forked from opengeos/GeoLibre
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.ts
More file actions
1933 lines (1863 loc) · 79.4 KB
/
Copy pathstore.ts
File metadata and controls
1933 lines (1863 loc) · 79.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { FeatureCollection } from "geojson";
import { v4 as uuidv4 } from "uuid";
import { create } from "zustand";
import { shallow } from "zustand/shallow";
import { temporal } from "zundo";
import {
getHistoryCoalesceMs,
getMaxHistoryFeatureCount,
leadingDebounce,
trimHistoryBySize,
} from "./history";
import {
applyProjectToStore,
type CreateProjectOptions,
createDefaultMapView,
createEmptyProject,
DEFAULT_PROJECT_NAME,
} from "./project";
import { DEFAULT_LAYER_GROUP_OPACITY, normalizeGroupContiguity } from "./layer-groups";
import {
DEFAULT_BASEMAP,
DEFAULT_DASHBOARD_COLUMNS,
DEFAULT_LAYER_STYLE,
DEFAULT_LEGEND_CONFIG,
DEFAULT_MAP_GRID_LAYOUT,
DEFAULT_PROJECT_PREFERENCES,
MAX_MAP_GRID_DIM,
DEFAULT_STORY_MAP,
MAX_DASHBOARD_COLUMNS,
MAX_PROCESSING_HISTORY,
MIN_DASHBOARD_COLUMNS,
type AddTileLayerOptions,
type CollaborationChatMessage,
type CollaborationParticipant,
type CollaborationPresence,
type CollaborationState,
type DashboardWidget,
type GeoLibreLayer,
type GeoLibreProject,
type LayerGroup,
type AttributeFormConfig,
type LayerJoin,
type LayerVirtualField,
type LayerStyle,
type LegendConfig,
type MapGridLayout,
type MapViewState,
type ProcessingModel,
type ProcessingRerunRequest,
type ProcessingRun,
type SecondaryMapView,
type ProjectPluginState,
type ProjectPreferences,
type RecentProjectEntry,
type StoryChapter,
type StoryMap,
type StyleLibraryEntry,
} from "./types";
import { hasSimpleStyleProperties } from "./vector-color";
import {
applyCopiedLayerStyle,
type CopiedLayerStyle,
extractCopiedLayerStyle,
} from "./layer-style-clipboard";
import { applyJoinsToLayer, cascadeLayerJoinRefresh, reapplyLayerJoins } from "./joins";
import {
DEFAULT_ELLIPSOID_ID,
getPlanetaryBasemapByStyleUrl,
setActiveEllipsoidId,
} from "./ellipsoids";
import type { PlanetaryBasemap } from "./ellipsoids";
export type ConversionToolKind =
| "vector-to-vector"
| "vector-to-geoparquet"
| "vector-to-flatgeobuf"
| "vector-to-shapefile"
| "vector-to-geopackage"
| "csv-to-geoparquet"
| "vector-to-pmtiles"
| "raster-to-pmtiles"
| "raster-to-cog";
/**
* Identifiers of the vector processing tools. Kept in sync by hand with the
* `id` fields of `VECTOR_TOOLS` in `@geolibre/processing` (`vector-tools.ts`);
* deriving the type there would create a core -> processing circular import.
*/
export type VectorToolKind =
| "buffer"
| "centroids"
| "convex-hull"
| "dissolve"
| "bounding-box"
| "simplify"
| "clip"
| "intersection"
| "difference"
| "union"
| "spatial-join"
| "attribute-join"
| "select-by-value"
| "select-by-location"
| "random-extract"
| "reproject"
| "explode"
| "aggregate"
| "smooth"
| "grid"
| "voronoi"
| "cell-sectors"
| "h3-grid"
| "h3-bin-points"
| "trajectory-speed"
| "detect-stops"
| "space-time-proximity"
| "check-validity"
| "fix-geometries"
| "check-topology-rules"
| "fix-topology";
/** Identifiers of the network-analysis tools (`NETWORK_TOOLS` ids). */
export type NetworkToolKind = "isochrone" | "od-matrix" | "sequential-route";
/** Identifiers of the spatial-statistics tools (`STATISTICS_TOOLS` ids). */
export type StatisticsToolKind =
| "global-morans-i"
| "local-morans-i"
| "getis-ord-gi"
| "average-nearest-neighbor"
| "kernel-density"
| "emerging-hot-spot";
/**
* Identifiers of the raster processing tools. Kept in sync by hand with the
* `id` fields of `RASTER_TOOLS` in `@geolibre/processing` (`raster-tools.ts`);
* deriving the type there would create a core -> processing circular import.
*/
export type RasterToolKind =
| "hillshade"
| "slope"
| "aspect"
| "reproject"
| "resample"
| "clip-extent"
| "clip-mask"
| "polygonize"
| "contour"
| "interpolate"
| "zonal"
| "raster-calc"
| "spectral-index"
| "reclassify"
| "mosaic"
| "focal";
/**
* Latest live device-GPS fix published by the GPS Tracking tool (issue #1316),
* read by the status bar readout. Device state, not project state: excluded
* from undo history (partialize never lists it) and from project files, and
* deliberately left untouched on project switches.
*/
export interface GpsStatusFix {
lng: number;
lat: number;
/** Horizontal accuracy radius in meters. */
accuracy: number;
/** Ground speed in m/s, or null when the device doesn't report one. */
speed: number | null;
/** Fix time in epoch milliseconds. */
timestamp: number;
}
export interface AppState {
projectName: string;
projectPath: string | null;
projectGeneration: number;
isDirty: boolean;
mapView: MapViewState;
basemapStyleUrl: string;
basemapVisible: boolean;
basemapOpacity: number;
layers: GeoLibreLayer[];
layerGroups: LayerGroup[];
preferences: ProjectPreferences;
projectPlugins: ProjectPluginState | null;
legend: LegendConfig;
storymap: StoryMap | null;
/** Saved processing pipelines (batch/model chaining; issue #344). */
models: ProcessingModel[];
/**
* App-level Style Manager library (issue #1294). Lives outside the project
* lifecycle: never serialized into the project file, untouched by
* newProject/loadProject, and persisted by the desktop app (IndexedDB).
*/
styleLibrary: StyleLibraryEntry[];
/**
* Project-scoped Style Manager entries (issue #1294), serialized into the
* `.geolibre.json` `styleLibrary` array and replaced on project load.
*/
projectStyleLibrary: StyleLibraryEntry[];
/** Recorded processing tool runs, oldest first (Processing History; #1292). */
processingHistory: ProcessingRun[];
/** Saved Dashboard panel chart widgets (issue #401). */
widgets: DashboardWidget[];
/** Number of columns in the Dashboard widget grid. */
dashboardColumns: number;
/**
* Multi-map grid layout (issue: split/grid view). A 1x1 grid is the normal
* single-map workspace. `rows * cols` panes are shown; pane 0 is the primary
* map driven by `mapView` / `basemap*`, panes 1.. are `secondaryMapViews`.
*/
mapLayout: MapGridLayout;
/**
* Secondary map panes (everything past the primary pane). The store keeps
* exactly `rows * cols - 1` entries in sync with `mapLayout`.
*/
secondaryMapViews: SecondaryMapView[];
/** User-entered label for the primary pane (shown only in multi-map mode). */
primaryMapLabel: string;
selectedLayerId: string | null;
selectedFeatureId: string | null;
/**
* Full set of selected feature ids. The attribute table extends the single
* selection to many rows via Ctrl/Cmd (toggle) and Shift (range). The anchor
* — `selectedFeatureId` — is the primary/last-clicked feature used for map
* fit, DuckDB highlight, and scripting, and is always one of these ids (or
* `null` when the set is empty). A single click leaves exactly one id here.
*/
selectedFeatureIds: string[];
identifyLayerId: string | null;
pointerCoords: [number, number] | null;
/** Live GPS fix for the status bar, or null while GPS tracking is off. */
gpsStatus: GpsStatusFix | null;
metadata: Record<string, unknown>;
recentProjects: RecentProjectEntry[];
attributeFilter: string;
// Ephemeral live-collaboration session state (issue #307). Deliberately
// excluded from the project file (project.ts never reads it) and from undo
// history (partialize never lists it).
collaboration: CollaborationState;
ui: {
processingOpen: boolean;
/**
* Tool id to preselect when the Whitebox toolbox dialog opens, set when the
* user picks a specific tool from the Processing menu's category submenus.
* Consumed and cleared by ProcessingDialog. Null means "no preselection".
*/
processingInitialTool: string | null;
conversionOpen: ConversionToolKind | null;
vectorToolOpen: VectorToolKind | null;
networkToolOpen: NetworkToolKind | null;
statisticsToolOpen: StatisticsToolKind | null;
rasterToolOpen: RasterToolKind | null;
segmentationOpen: boolean;
objectDetectionOpen: boolean;
segmentEverythingOpen: boolean;
geocodeOpen: boolean;
sqlWorkspaceOpen: boolean;
loadEditorFeaturesOpen: boolean;
// Store layer preselected in the "Load Features into Editor" dialog when it
// is opened from a layer's context menu, or null when opened without a target.
loadEditorFeaturesLayerId: string | null;
pythonConsoleOpen: boolean;
notebookOpen: boolean;
assistantOpen: boolean;
attributeTableOpen: boolean;
/** Whether the Raster Attribute Table bottom panel is open (issue #1307). */
rasterAttributeTableOpen: boolean;
dashboardOpen: boolean;
storymapPanelOpen: boolean;
storymapPresenting: boolean;
// True when the active presentation was launched from the editor, so exiting
// it reopens the Story Map editor instead of dropping to the bare map
// (#918). Auto-presented projects (opened for viewing) leave this false.
storymapReturnToEditor: boolean;
// Id of the chapter currently being composed on the live map. When set, the
// Story Map dialog is hidden so the user can pan/zoom/tilt the real map and
// save the resulting camera back into this chapter (issue #775).
storymapComposingId: string | null;
modelBuilderOpen: boolean;
/** Style Manager dialog visibility (issue #1294). */
styleManagerOpen: boolean;
/** Processing History panel visibility (#1292). */
processingHistoryOpen: boolean;
/** Select by Expression dialog visibility (#1314). */
selectByExpressionOpen: boolean;
// Layer preselected in the Select by Expression dialog when it is opened
// from a layer's context menu, or null when opened without a target.
// Deliberately not selectLayer(): that would clear the live selection the
// dialog's add/remove/intersect modes need to combine with.
selectByExpressionLayerId: string | null;
/** Select by Location dialog visibility (#1314). */
selectByLocationOpen: boolean;
/** Same contract as `selectByExpressionLayerId`, for Select by Location. */
selectByLocationLayerId: string | null;
/**
* Pending "re-run from History" request. Written by the History panel just
* before it opens the target processing dialog; consumed and cleared by
* that dialog once it has pre-filled its parameter form. Null when idle.
*/
processingRerun: ProcessingRerunRequest | null;
zoomToSelectedFeature: boolean;
// Live-collaboration dialog visibility. Lifted into the store (rather than
// local toolbar state) so the on-canvas session-status badge can reopen the
// Collaborate dialog from outside the toolbar's component tree (#754).
collaborateDialogOpen: boolean;
};
setPointerCoords: (coords: [number, number] | null) => void;
setGpsStatus: (fix: GpsStatusFix | null) => void;
setCollaboration: (patch: Partial<CollaborationState>) => void;
updateCollaborationPresence: (clientId: string, presence: CollaborationPresence | null) => void;
/** Append a chat message to the session log (bounded; #754). */
addCollaborationChat: (message: CollaborationChatMessage) => void;
resetCollaboration: () => void;
setMapView: (view: Partial<MapViewState>, markDirty?: boolean) => void;
/**
* Resize the map grid. Clamps `rows`/`cols` into range and grows/shrinks
* `secondaryMapViews` so it always holds `rows * cols - 1` panes; new panes
* clone the primary map's current camera and basemap.
*/
setMapGrid: (rows: number, cols: number) => void;
/** Toggle synchronized camera across all panes. */
setSyncView: (syncView: boolean) => void;
/** Patch one secondary pane's camera by id (no-op if the id is unknown). */
setSecondaryMapView: (id: string, view: Partial<MapViewState>, markDirty?: boolean) => void;
/**
* Override a layer's visibility in one secondary pane (no-op if the pane id is
* unknown). The override forces the layer visible/hidden in that pane only,
* independent of the primary map's visibility.
*/
setSecondaryLayerVisibility: (id: string, layerId: string, visible: boolean) => void;
/** Set the primary pane's custom label. */
setPrimaryMapLabel: (label: string) => void;
/** Set one secondary pane's custom label (no-op if the id is unknown). */
setSecondaryMapLabel: (id: string, label: string) => void;
/**
* Switch one secondary pane between the 2D map and the 3D globe (no-op if the
* id is unknown or the kind is unchanged).
*/
setSecondaryViewKind: (id: string, viewKind: NonNullable<SecondaryMapView["viewKind"]>) => void;
/** Remove one secondary pane and collapse the grid back toward 1x1. */
removeSecondaryMapView: (id: string) => void;
setBasemapStyleUrl: (url: string) => void;
/**
* Apply a planetary basemap and sync the project's ellipsoid to the body it
* depicts, so measurements and the globe control use that body's radius. Used
* by both the basemap picker and the Layers-panel planet switcher.
*/
applyPlanetaryBasemap: (basemap: PlanetaryBasemap) => void;
/**
* Return to Earth: apply `styleUrl` (typically the Earth basemap that was
* active before a planet was selected, e.g. Liberty) and reset the ellipsoid
* to Earth. Used when a planet is deselected in the switcher.
*/
restoreEarthBasemap: (styleUrl: string) => void;
setBasemapVisible: (visible: boolean) => void;
setBasemapOpacity: (opacity: number) => void;
setPreferences: (preferences: ProjectPreferences) => void;
setLegend: (legend: LegendConfig) => void;
setProjectPlugins: (projectPlugins: ProjectPluginState | null, shouldMarkDirty?: boolean) => void;
selectLayer: (id: string | null) => void;
selectFeature: (id: string | null) => void;
/**
* Replace the multi-selection with `ids`. The anchor (`selectedFeatureId`)
* becomes `anchorId` when provided, otherwise the last id in the list (or
* `null` when the list is empty).
*/
selectFeatures: (ids: string[], anchorId?: string | null) => void;
setIdentifyLayer: (id: string | null) => void;
setAttributeFilter: (filter: string) => void;
setProcessingOpen: (open: boolean) => void;
setProcessingInitialTool: (toolId: string | null) => void;
setConversionOpen: (kind: ConversionToolKind | null) => void;
setVectorToolOpen: (kind: VectorToolKind | null) => void;
setNetworkToolOpen: (kind: NetworkToolKind | null) => void;
setStatisticsToolOpen: (kind: StatisticsToolKind | null) => void;
setRasterToolOpen: (kind: RasterToolKind | null) => void;
setSegmentationOpen: (open: boolean) => void;
setObjectDetectionOpen: (open: boolean) => void;
setSegmentEverythingOpen: (open: boolean) => void;
setGeocodeOpen: (open: boolean) => void;
setSqlWorkspaceOpen: (open: boolean) => void;
setLoadEditorFeaturesOpen: (open: boolean, layerId?: string | null) => void;
setPythonConsoleOpen: (open: boolean) => void;
setNotebookOpen: (open: boolean) => void;
setAssistantOpen: (open: boolean) => void;
setAttributeTableOpen: (open: boolean) => void;
setRasterAttributeTableOpen: (open: boolean) => void;
setDashboardOpen: (open: boolean) => void;
setStorymapPanelOpen: (open: boolean) => void;
setStorymapPresenting: (presenting: boolean, returnToEditor?: boolean) => void;
setStorymapComposing: (chapterId: string | null) => void;
setModelBuilderOpen: (open: boolean) => void;
setProcessingHistoryOpen: (open: boolean) => void;
/** Open/close Select by Expression, optionally preselecting a target layer. */
setSelectByExpressionOpen: (open: boolean, layerId?: string | null) => void;
/** Open/close Select by Location, optionally preselecting a target layer. */
setSelectByLocationOpen: (open: boolean, layerId?: string | null) => void;
setProcessingRerun: (request: ProcessingRerunRequest | null) => void;
setCollaborateDialogOpen: (open: boolean) => void;
setZoomToSelectedFeature: (enabled: boolean) => void;
setStyleManagerOpen: (open: boolean) => void;
/**
* Replace the app-level style library wholesale. Used by the persistence
* layer on startup and by bundle imports.
*/
setStyleLibrary: (entries: StyleLibraryEntry[]) => void;
/**
* Insert or replace (matching by `id`) a Style Manager entry in the given
* scope. Scope-local, like {@link deleteStyleLibraryEntry}: the other
* scope's list is never touched, since a same id there can belong to an
* unrelated entry after loading a project authored elsewhere. Project-scope
* saves mark the project dirty.
*/
saveStyleLibraryEntry: (entry: StyleLibraryEntry, scope?: "app" | "project") => void;
/**
* Remove a Style Manager entry by id. When `scope` is given only that list
* is touched — the two scopes can legitimately hold the same id after
* loading a project authored elsewhere, and deleting a project entry must
* not erase a local app-library style (or vice versa). Omitting `scope`
* removes the id from both lists.
*/
deleteStyleLibraryEntry: (id: string, scope?: "app" | "project") => void;
/** Insert a new model or replace an existing one matching by `id`. */
saveModel: (model: ProcessingModel) => void;
/** Remove a saved model by id. */
deleteModel: (id: string) => void;
/** Append a processing run to the history (bounded, de-duped by id; #1292). */
addProcessingRun: (run: ProcessingRun) => void;
/** Patch a recorded run by id (no-op if absent), e.g. to add output layers. */
updateProcessingRun: (id: string, patch: Partial<Omit<ProcessingRun, "id">>) => void;
/** Drop all recorded processing runs. */
clearProcessingHistory: () => void;
/** Append a new dashboard widget. */
addWidget: (widget: DashboardWidget) => void;
/** Patch an existing dashboard widget by id (no-op if absent). Merges, so an
* omitted key keeps its current value; use replaceWidget to clear one. */
updateWidget: (id: string, patch: Partial<Omit<DashboardWidget, "id">>) => void;
/** Swap an existing dashboard widget for a complete new record, keeping its
* id and position (no-op if absent). Unlike updateWidget this does not merge,
* so fields the caller omits are cleared — what the widget editor needs to
* persist an emptied title, color, prefix, or suffix. */
replaceWidget: (id: string, widget: Omit<DashboardWidget, "id">) => void;
/** Remove a dashboard widget by id. */
removeWidget: (id: string) => void;
/** Move a widget to a new index, clamped into range, preserving the rest. */
moveWidget: (id: string, toIndex: number) => void;
/** Set the Dashboard widget-grid column count (clamped into range). */
setDashboardColumns: (columns: number) => void;
setStorymap: (storymap: StoryMap | null) => void;
updateStorymapSettings: (patch: Partial<Omit<StoryMap, "chapters">>) => void;
addStoryChapter: (chapter: StoryChapter, atIndex?: number) => void;
updateStoryChapter: (id: string, patch: Partial<StoryChapter>) => void;
removeStoryChapter: (id: string) => void;
moveStoryChapter: (id: string, targetIndex: number) => void;
newProject: (options?: CreateProjectOptions & { name?: string }) => void;
loadProject: (
project: GeoLibreProject,
path?: string | null,
options?: { rememberRecent?: boolean; presenting?: boolean },
) => void;
setProjectPath: (path: string | null) => void;
setProjectName: (name: string) => void;
setRecentProjects: (projects: RecentProjectEntry[]) => void;
rememberRecentProject: (entry: RecentProjectEntry) => void;
forgetRecentProject: (path: string) => void;
clearRecentProjects: () => void;
markSaved: () => void;
addLayer: (layer: GeoLibreLayer, beforeLayerId?: string | null) => void;
removeLayer: (id: string) => void;
updateLayer: (id: string, patch: Partial<GeoLibreLayer>) => void;
setLayerVisibility: (id: string, visible: boolean) => void;
setLayerOpacity: (id: string, opacity: number) => void;
setLayerStyle: (id: string, style: Partial<LayerStyle>) => void;
/**
* Transient clipboard holding a layer's symbology, captured by
* {@link copyLayerStyle} and applied by {@link pasteLayerStyle} (copy/paste
* styles, issue #1339). Runtime-only: excluded from undo history
* (`partialize` never lists it) and from the saved project. `null` until a
* style is copied this session. Cleared by `newProject`/`loadProject` so a
* paste can't apply an entry from a different project; it deliberately
* survives undo/redo within a project (it holds a deep snapshot, not a live
* layer reference, so a paste stays valid even if the source layer is undone
* away — only the displayed source name may then be stale).
*/
copiedLayerStyle: CopiedLayerStyle | null;
/**
* Snapshot the given layer's style into {@link copiedLayerStyle} so it can be
* pasted onto a compatible layer. No-op when the layer is missing or has no
* copyable symbology (leaving any prior clipboard entry untouched). Returns
* `true` when a style was captured, so callers can skip the confirmation on a
* no-op.
*/
copyLayerStyle: (id: string) => boolean;
/**
* Apply the {@link copiedLayerStyle} clipboard entry onto the given layer.
* No-op when the clipboard is empty, the layer is missing, or the entry's
* style family does not match the target layer's. Returns `true` when the
* style was applied, so callers can skip the confirmation on a no-op.
*/
pasteLayerStyle: (id: string) => boolean;
/**
* Replace a layer's persistent attribute joins and immediately re-derive its
* joined columns (strip what the previous joins added, apply the new list).
* Pass an empty array to detach every join and restore the base attributes.
*/
setLayerJoins: (id: string, joins: LayerJoin[]) => void;
/**
* Replace the layer's Attribute Form designer configuration (per-field edit
* widgets, constraints, conditional visibility). Pass `undefined` to remove
* the form config entirely.
*/
setLayerAttributeForm: (id: string, attributeForm: AttributeFormConfig | undefined) => void;
/**
* Replace a layer's virtual fields and immediately re-derive its computed
* columns (strip what the previous fields added, evaluate the new list).
* Pass an empty array to detach every virtual field.
*/
setLayerVirtualFields: (id: string, fields: LayerVirtualField[]) => void;
reorderLayer: (id: string, direction: "up" | "down") => void;
moveLayer: (id: string, targetIndex: number) => void;
addGeoJsonLayer: (
name: string,
geojson: FeatureCollection,
sourcePath?: string,
beforeLayerId?: string | null,
) => string;
/**
* Add a georeferenced image overlay (a MapLibre `image` source rendered as a
* raster layer) from an image URL and its four corner coordinates, and return
* its id. Used for KML/KMZ `<GroundOverlay>` imports; the layer persists and
* renders exactly like a Raster Georeferencer overlay. Corners are `[lng,
* lat]` in top-left, top-right, bottom-right, bottom-left order.
*/
addImageOverlayLayer: (
name: string,
source: { url: string; coordinates: [number, number][] },
options?: {
opacity?: number;
bounds?: [number, number, number, number];
sourcePath?: string;
/** Initial visibility (default true); a time-slider frame past the first
* starts hidden. */
visible?: boolean;
/** Epoch-ms time bounds of a KML `<TimeSpan>`/`<TimeStamp>` frame; the
* Time Slider toggles this frame's visibility by the current date. */
timeSpan?: { begin: number | null; end: number | null };
},
beforeLayerId?: string | null,
) => string;
/**
* Add a native raster tile layer (XYZ, WMS, or WMTS) from one or more tile
* URL templates and return its id. The layer appears in the Layers panel and
* persists with the project exactly like a layer added through the Add Data
* dialog, so callers (e.g. an external plugin) do not have to touch MapLibre
* directly. See {@link AddTileLayerOptions}.
*/
addTileLayer: (
name: string,
options: AddTileLayerOptions,
beforeLayerId?: string | null,
) => string;
addLayerGroup: (name?: string, layerIds?: string[]) => string;
removeLayerGroup: (id: string, options?: { removeChildren?: boolean }) => void;
renameLayerGroup: (id: string, name: string) => void;
setLayerGroupVisibility: (id: string, visible: boolean) => void;
setLayerGroupOpacity: (id: string, opacity: number) => void;
toggleLayerGroupCollapsed: (id: string) => void;
moveLayerToGroup: (
layerId: string,
groupId: string | null,
beforeLayerId?: string | null,
) => void;
reorderLayerGroup: (id: string, direction: "up" | "down") => void;
}
const MAX_RECENT_PROJECTS = 10;
/**
* A fresh, inactive collaboration slice (no live session). Frozen (like
* DEFAULT_LEGEND_CONFIG) to guard against accidental in-place mutation; store
* actions always produce new objects via spread, so the frozen default is only
* ever read.
*/
export const DEFAULT_COLLABORATION_STATE: CollaborationState = Object.freeze({
isActive: false,
connecting: false,
sessionId: null,
clientId: null,
role: null,
mode: "co-edit",
selfName: "",
selfColor: "",
participants: Object.freeze([] as CollaborationParticipant[]) as CollaborationParticipant[],
presence: Object.freeze({} as Record<string, CollaborationPresence>) as Record<
string,
CollaborationPresence
>,
followHost: false,
chat: Object.freeze([] as CollaborationChatMessage[]) as CollaborationChatMessage[],
error: null,
});
// Cap the in-store chat log so a long session can't grow it without bound. This
// is intentionally larger than the relay's persisted history (50): the live
// session accumulates messages locally, while the relay only retains the tail
// for late joiners.
const MAX_COLLABORATION_CHAT = 200;
/** Derive a human-friendly display name from a file path or URL. */
export function projectPathLabel(path: string): string {
return path.split(/[/\\]/).pop() || path;
}
function normalizeRecentProjects(projects: RecentProjectEntry[]): RecentProjectEntry[] {
const seen = new Set<string>();
const normalized: RecentProjectEntry[] = [];
for (const project of projects) {
const path = project.path.trim();
if (!path || seen.has(path)) continue;
const name = project.name.trim() || projectPathLabel(path);
normalized.push({
path,
name,
openedAt: project.openedAt || new Date().toISOString(),
});
seen.add(path);
}
return normalized.slice(0, MAX_RECENT_PROJECTS);
}
/**
* Pick the lowest `Group N` name not already taken, so default names stay
* unique while still preferring small numbers — starting the search at 1 (not
* `length + 1`) avoids skipping free low numbers when some groups carry custom
* names. Group counts are small, so the linear scan is negligible.
*/
function nextDefaultGroupName(groups: LayerGroup[]): string {
const existing = new Set(groups.map((g) => g.name));
let n = 1;
while (existing.has(`Group ${n}`)) n++;
return `Group ${n}`;
}
/**
* Compare two `layerGroups` arrays for undo-history purposes, ignoring the
* `collapsed` flag so expand/collapse (a UI-panel preference) never records a
* history entry. Every other field — order, name, visibility, opacity — is
* still compared, so real edits are tracked.
*/
function layerGroupsEqualForHistory(a: LayerGroup[], b: LayerGroup[]): boolean {
if (a.length !== b.length) return false;
for (let i = 0; i < a.length; i++) {
const x = a[i];
const y = b[i];
if (x === y) continue;
if (x.id !== y.id || x.name !== y.name || x.visible !== y.visible || x.opacity !== y.opacity) {
return false;
}
}
return true;
}
/** True when two camera states have identical center/zoom/bearing/pitch. */
function sameCamera(a: MapViewState, b: MapViewState): boolean {
return (
a.center[0] === b.center[0] &&
a.center[1] === b.center[1] &&
a.zoom === b.zoom &&
a.bearing === b.bearing &&
a.pitch === b.pitch
);
}
/** Clamp a requested grid row/column count into the supported [1, MAX] range. */
function clampGridDim(value: number): number {
if (!Number.isFinite(value)) return 1;
return Math.max(1, Math.min(MAX_MAP_GRID_DIM, Math.floor(value)));
}
/**
* Pick a grid that holds at least `total` panes within the supported
* `MAX_MAP_GRID_DIM x MAX_MAP_GRID_DIM` bound, minimizing empty cells first and
* then preferring a column count close to (and, on ties, no smaller than)
* `preferredCols` so removing a pane keeps the layout's orientation. Used when
* collapsing the grid after a pane is removed.
*
* Bounding both dimensions matters: a prime `total` (e.g. 5 panes left after
* removing one from a 2x3 grid) has no gap-free factor pair inside the bound, so
* the only gap-free options (1x5 / 5x1) would exceed `MAX_MAP_GRID_DIM`. In that
* case we accept the smallest bounded grid with one empty trailing cell (2x3)
* rather than returning an out-of-range dimension.
*/
function fitGrid(total: number, preferredCols: number): { rows: number; cols: number } {
if (total <= 1) return { rows: 1, cols: 1 };
let best: { rows: number; cols: number; empty: number; score: number } | null = null;
for (let rows = 1; rows <= MAX_MAP_GRID_DIM; rows++) {
for (let cols = 1; cols <= MAX_MAP_GRID_DIM; cols++) {
const capacity = rows * cols;
if (capacity < total) continue;
const empty = capacity - total;
const score = Math.abs(cols - preferredCols);
// Fewest empty cells wins; then the column count closest to
// preferredCols; then, on a tie, the larger column count (favoring wider,
// side-by-side layouts over tall ones).
const better =
best === null ||
empty < best.empty ||
(empty === best.empty &&
(score < best.score || (score === best.score && cols > best.cols)));
if (better) best = { rows, cols, empty, score };
}
}
return best ? { rows: best.rows, cols: best.cols } : { rows: 1, cols: 1 };
}
/** Cancels the active history coalesce window (assigned by zundo's handleSet). */
let cancelHistoryCoalesce: () => void = () => {};
/**
* Drop the oldest undo snapshots once their combined feature payload exceeds the
* configured budget, bounding the memory held by history when a large vector
* layer is edited repeatedly (issue #341). Called after a snapshot is appended.
* Operates on the live temporal store directly; this never touches the main
* store, so it does not itself record a history entry.
*/
function pruneHistoryBySize(): void {
const temporalStore = useAppStore.temporal;
const { pastStates } = temporalStore.getState();
const trimmed = trimHistoryBySize(pastStates, getMaxHistoryFeatureCount());
if (trimmed.length !== pastStates.length) {
temporalStore.setState({ pastStates: trimmed });
}
}
export const useAppStore = create<AppState>()(
temporal(
(set, get) => ({
projectName: DEFAULT_PROJECT_NAME,
projectPath: null,
projectGeneration: 0,
isDirty: false,
mapView: createDefaultMapView(),
basemapStyleUrl: DEFAULT_BASEMAP,
basemapVisible: true,
basemapOpacity: 1,
layers: [],
layerGroups: [],
preferences: DEFAULT_PROJECT_PREFERENCES,
projectPlugins: null,
legend: { ...DEFAULT_LEGEND_CONFIG },
storymap: null,
models: [],
styleLibrary: [],
projectStyleLibrary: [],
processingHistory: [],
widgets: [],
dashboardColumns: DEFAULT_DASHBOARD_COLUMNS,
mapLayout: { ...DEFAULT_MAP_GRID_LAYOUT },
secondaryMapViews: [],
primaryMapLabel: "",
copiedLayerStyle: null,
selectedLayerId: null,
selectedFeatureId: null,
selectedFeatureIds: [],
identifyLayerId: null,
pointerCoords: null,
gpsStatus: null,
metadata: {},
recentProjects: [],
attributeFilter: "",
collaboration: DEFAULT_COLLABORATION_STATE,
ui: {
processingOpen: false,
processingInitialTool: null,
conversionOpen: null,
vectorToolOpen: null,
networkToolOpen: null,
statisticsToolOpen: null,
rasterToolOpen: null,
segmentationOpen: false,
objectDetectionOpen: false,
segmentEverythingOpen: false,
geocodeOpen: false,
sqlWorkspaceOpen: false,
loadEditorFeaturesOpen: false,
loadEditorFeaturesLayerId: null,
pythonConsoleOpen: false,
notebookOpen: false,
assistantOpen: false,
attributeTableOpen: false,
rasterAttributeTableOpen: false,
dashboardOpen: false,
storymapPanelOpen: false,
storymapPresenting: false,
storymapReturnToEditor: false,
storymapComposingId: null,
modelBuilderOpen: false,
styleManagerOpen: false,
processingHistoryOpen: false,
selectByExpressionOpen: false,
selectByExpressionLayerId: null,
selectByLocationOpen: false,
selectByLocationLayerId: null,
processingRerun: null,
zoomToSelectedFeature: false,
collaborateDialogOpen: false,
},
setPointerCoords: (coords) => set({ pointerCoords: coords }),
setGpsStatus: (fix) => set({ gpsStatus: fix }),
setCollaboration: (patch) =>
set((s) => ({ collaboration: { ...s.collaboration, ...patch } })),
// Add or remove a single remote participant's presence without rebuilding
// the whole map on every cursor move. Passing `null` drops the entry (on
// participant leave).
updateCollaborationPresence: (clientId, presence) =>
set((s) => {
const next = { ...s.collaboration.presence };
if (presence === null) {
delete next[clientId];
} else {
next[clientId] = presence;
}
return { collaboration: { ...s.collaboration, presence: next } };
}),
addCollaborationChat: (message) =>
set((s) => {
// Default to [] in case an older relay left the slice undefined.
const current = s.collaboration.chat ?? [];
// Ignore a duplicate id: the server broadcasts to the sender too, and a
// reconnect can replay recent history, so de-dupe defensively.
if (current.some((m) => m.id === message.id)) return s;
const chat = [...current, message].slice(-MAX_COLLABORATION_CHAT);
return { collaboration: { ...s.collaboration, chat } };
}),
resetCollaboration: () =>
// Also close the Collaborate dialog: an unexpected disconnect resets the
// slice without a user-initiated leave(), and leaving the dialog open
// would drop the user onto the start/join form with no context.
set((s) => ({
collaboration: DEFAULT_COLLABORATION_STATE,
ui: { ...s.ui, collaborateDialogOpen: false },
})),
setMapView: (view, markDirty = false) =>
set((s) => ({
mapView: { ...s.mapView, ...view },
isDirty: markDirty || s.isDirty,
})),
setMapGrid: (rows, cols) =>
set((s) => {
const clampedRows = clampGridDim(rows);
const clampedCols = clampGridDim(cols);
const desiredSecondary = clampedRows * clampedCols - 1;
let secondaryMapViews = s.secondaryMapViews;
if (desiredSecondary < secondaryMapViews.length) {
secondaryMapViews = secondaryMapViews.slice(0, desiredSecondary);
} else if (desiredSecondary > secondaryMapViews.length) {
const additions: SecondaryMapView[] = [];
for (let i = secondaryMapViews.length; i < desiredSecondary; i++) {
// New panes start as a clone of the primary map's camera and (by
// having no overrides) inherit its layer visibility, so the
// comparison begins from the same view the user is looking at.
additions.push({
id: uuidv4(),
view: { ...s.mapView },
layerVisibility: {},
});
}
secondaryMapViews = [...secondaryMapViews, ...additions];
}
return {
mapLayout: {
...s.mapLayout,
rows: clampedRows,
cols: clampedCols,
},
secondaryMapViews,
isDirty: true,
};
}),
setSyncView: (syncView) =>
set((s) => ({
mapLayout: { ...s.mapLayout, syncView },
isDirty: true,
})),
setSecondaryMapView: (id, view, markDirty = false) =>
set((s) => {
let changed = false;
const secondaryMapViews = s.secondaryMapViews.map((pane) => {
if (pane.id !== id) return pane;
const merged = { ...pane.view, ...view };
// Skip value-identical writes: a programmatic `applyView` (camera
// sync, initial load) fires "moveend" too, so without this guard
// each pane re-stores the same camera it was just given, churning a
// new `secondaryMapViews` array and re-rendering every subscriber.
if (sameCamera(pane.view, merged)) return pane;
changed = true;
return { ...pane, view: merged };
});
if (!changed) return s;
return {
secondaryMapViews,
isDirty: markDirty || s.isDirty,
};
}),
setSecondaryLayerVisibility: (id, layerId, visible) =>
set((s) => {
let changed = false;
const secondaryMapViews = s.secondaryMapViews.map((pane) => {
if (pane.id !== id) return pane;
changed = true;
return {
...pane,
layerVisibility: { ...pane.layerVisibility, [layerId]: visible },
};
});
if (!changed) return s;
return { secondaryMapViews, isDirty: true };
}),
setPrimaryMapLabel: (label) => set({ primaryMapLabel: label, isDirty: true }),
setSecondaryMapLabel: (id, label) =>
set((s) => {
let changed = false;
const secondaryMapViews = s.secondaryMapViews.map((pane) => {
if (pane.id !== id) return pane;
changed = true;
return { ...pane, label };
});
if (!changed) return s;
return { secondaryMapViews, isDirty: true };
}),
setSecondaryViewKind: (id, viewKind) =>
set((s) => {
let changed = false;
const secondaryMapViews = s.secondaryMapViews.map((pane) => {
if (pane.id !== id) return pane;
// Treat an absent viewKind as "maplibre" so switching a legacy pane
// to maplibre is a no-op rather than a churned array.
if ((pane.viewKind ?? "maplibre") === viewKind) return pane;
changed = true;
return { ...pane, viewKind };
});
if (!changed) return s;
return { secondaryMapViews, isDirty: true };
}),
removeSecondaryMapView: (id) =>
set((s) => {
const secondaryMapViews = s.secondaryMapViews.filter((pane) => pane.id !== id);
if (secondaryMapViews.length === s.secondaryMapViews.length) {
return s;
}
// Collapse to a gap-free grid that fits the remaining panes, keeping
// the layout's orientation as close as possible to the current one.
const total = secondaryMapViews.length + 1;
const { rows, cols } = fitGrid(total, s.mapLayout.cols);
return {
secondaryMapViews,
mapLayout: { ...s.mapLayout, rows, cols },
isDirty: true,
};
}),
setBasemapStyleUrl: (url) => set({ basemapStyleUrl: url, isDirty: true }),
applyPlanetaryBasemap: (basemap) =>
set((state) => ({
basemapStyleUrl: basemap.styleUrl,
preferences:
state.preferences.map.ellipsoidId === basemap.ellipsoidId
? state.preferences
: {
...state.preferences,
map: {
...state.preferences.map,
ellipsoidId: basemap.ellipsoidId,
},
},
isDirty: true,
})),
restoreEarthBasemap: (styleUrl) =>
set((state) => ({
basemapStyleUrl: styleUrl,
preferences:
state.preferences.map.ellipsoidId === DEFAULT_ELLIPSOID_ID
? state.preferences
: {
...state.preferences,
map: {