-
-
Notifications
You must be signed in to change notification settings - Fork 628
Expand file tree
/
Copy pathAttributeTable.tsx
More file actions
2328 lines (2224 loc) · 93.3 KB
/
Copy pathAttributeTable.tsx
File metadata and controls
2328 lines (2224 loc) · 93.3 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 { useTranslation } from "react-i18next";
import {
attributeLinkUrl,
coerceAttributeFormValue,
isDuckDBQueryLayer,
useAppStore,
validateAttributeFormValues,
type AttributeFormConfig,
type AttributeFormFieldConfig,
type AttributeFormFieldError,
} from "@geolibre/core";
import {
getDuckDBLayerRows,
getGeometryEditTargetLayerId,
subscribeGeometryEdit,
updateDuckDBLayerRows,
type DuckDBAttributeRow,
} from "@geolibre/plugins";
import type { MapController } from "@geolibre/map";
import type { GeoJSONSource } from "maplibre-gl";
import {
Button,
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DropdownMenu,
DropdownMenuCheckboxItem,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuSeparator,
DropdownMenuTrigger,
Input,
Label,
ScrollArea,
Select,
Textarea,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@geolibre/ui";
import { useVirtualizer } from "@tanstack/react-virtual";
import type { Feature, FeatureCollection } from "geojson";
import {
ArrowDown,
ArrowLeft,
ArrowRight,
ArrowUp,
Calculator,
ChartColumn,
Columns3,
Download,
EyeOff,
LayoutDashboard,
MoreHorizontal,
MousePointerSquareDashed,
Pencil,
PanelBottomClose,
PanelBottomOpen,
Plus,
RotateCcw,
Save,
Sigma,
SquareFunction,
TableProperties,
Telescope,
Trash2,
X,
} from "lucide-react";
import {
type MouseEvent as ReactMouseEvent,
type RefObject,
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
} from "react";
import { isTauri } from "../../lib/tauri-io";
import {
addColumn,
calculateField,
deleteColumn,
getColumnSettings,
hiddenColumns,
moveColumn,
showAllColumns,
toggleColumnHidden,
renameColumn,
visibleColumns,
type ColumnMoveDirection,
type NewColumnType,
inferColumnTypes,
} from "../../lib/attribute-columns";
import {
coerceComputedValue,
compileExpression,
EXPRESSION_HELPERS,
fieldReference,
type CalcOutputType,
} from "../../lib/attribute-expression";
import { attributeFormErrorMessage } from "../../lib/attribute-form-messages";
import { computeRowSelection } from "../../lib/attribute-selection";
import { RESERVED_PROPERTY_KEYS } from "../../lib/field-collection";
import {
AREA_UNITS,
detectGeometryFamilies,
DISTANCE_UNITS,
UNIT_SYMBOLS,
type GeometryMetric,
} from "../../lib/geometry-measure";
import { AttributeChartDialog } from "./AttributeChartDialog";
import { AttributeStatsDialog } from "./AttributeStatsDialog";
import { ColumnExplorerDialog } from "./ColumnExplorerDialog";
import {
exportVectorLayer,
formatAttributeValue,
geojsonVectorSourceId,
kmlExportErrorMessage,
sanitizeExportFileName,
shapefileFieldWarnings,
type VectorExportFormat,
} from "../../lib/vector-export";
import { PANEL_RESIZE_END_EVENT, PANEL_RESIZE_START_EVENT } from "../../lib/panel-resize";
import { openExternalLink } from "../../lib/open-external";
type SortDirection = "asc" | "desc";
type SortKey = "__featureId" | string;
type ColumnWidths = Record<string, number>;
type AttributeDrafts = Record<string, Record<string, string>>;
type AttributeTableRow = {
featureId: string;
properties: Record<string, unknown>;
};
/** Reserved inline-image property keys (photo thumbnail + full-resolution) that
* hold data URLs, so they are hidden from the attribute table's columns. */
const RESERVED_IMAGE_KEYS = new Set<string>(RESERVED_PROPERTY_KEYS);
const DEFAULT_FEATURE_ID_COLUMN_WIDTH = 72;
const DEFAULT_ATTRIBUTE_COLUMN_WIDTH = 160;
const MIN_FEATURE_ID_COLUMN_WIDTH = 48;
const MAX_FEATURE_ID_COLUMN_WIDTH = 180;
const MIN_ATTRIBUTE_COLUMN_WIDTH = 72;
const MAX_ATTRIBUTE_COLUMN_WIDTH = 520;
// Estimated row height used to size the virtualizer before real rows are
// measured. View-mode rows are ~37px; edit-mode rows (with an Input) are taller
// and are corrected by measureElement once rendered.
const ESTIMATED_ROW_HEIGHT = 37;
const DEFAULT_TABLE_HEIGHT = 192;
const MIN_TABLE_HEIGHT = 96;
const MAX_TABLE_HEIGHT = 520;
function compareAttributeValues(a: unknown, b: unknown): number {
if (a == null && b == null) return 0;
if (a == null) return -1;
if (b == null) return 1;
if (typeof a === "number" && typeof b === "number") return a - b;
const aNumber = Number(a);
const bNumber = Number(b);
if (Number.isFinite(aNumber) && Number.isFinite(bNumber)) {
return aNumber - bNumber;
}
return String(a).localeCompare(String(b), undefined, {
numeric: true,
sensitivity: "base",
});
}
function parseAttributeDraft(draft: string, previousValue: unknown, columnType?: string): unknown {
if (draft.trim() === "") return null;
// An empty cell carries no type of its own, so fall back to what the rest of
// the column holds; only a column with no values anywhere keeps the raw string.
if (previousValue == null) {
if (columnType === "number") {
const nextValue = Number(draft);
return Number.isFinite(nextValue) ? nextValue : draft;
}
if (columnType === "boolean") {
const normalized = draft.trim().toLowerCase();
if (normalized === "true") return true;
if (normalized === "false") return false;
return draft;
}
return draft;
}
if (typeof previousValue === "number") {
const nextValue = Number(draft);
return Number.isFinite(nextValue) ? nextValue : draft;
}
if (typeof previousValue === "boolean") {
const normalized = draft.trim().toLowerCase();
if (normalized === "true") return true;
if (normalized === "false") return false;
return draft;
}
if (typeof previousValue === "object") {
try {
return JSON.parse(draft);
} catch {
return draft;
}
}
return draft;
}
function isInvalidObjectDraft(draft: string, previousValue: unknown): boolean {
if (typeof previousValue !== "object" || previousValue == null) return false;
if (draft.trim() === "") return false;
try {
JSON.parse(draft);
return false;
} catch {
return true;
}
}
function hasDraftEdits(drafts: AttributeDrafts): boolean {
return Object.values(drafts).some((columns) => Object.keys(columns).length > 0);
}
function applyDraftsToFeatures(
features: Feature[],
drafts: AttributeDrafts,
formFields?: Map<string, AttributeFormFieldConfig>,
): Feature[] {
// Derived from the whole collection, so an edit to an empty cell adopts the
// column's type rather than the cell's (absent) one.
const columnTypes = inferColumnTypes(features.map((feature) => feature.properties));
return features.map((feature, index) => {
const featureId = String(feature.id ?? index);
const rowDrafts = drafts[featureId];
if (!rowDrafts) return feature;
const properties = { ...(feature.properties ?? {}) };
for (const [column, draft] of Object.entries(rowDrafts)) {
const previousValue = feature.properties?.[column];
// Skip drafts that are invalid JSON for an object-typed cell so we never
// persist or export a type-corrupted value; the existing value is kept.
if (isInvalidObjectDraft(draft, previousValue)) continue;
// A column with an Attribute Form widget coerces by widget type (a
// number widget stores a number even into a previously-null cell);
// unconfigured columns keep the previous-value type inference.
const config = formFields?.get(column);
properties[column] = config
? coerceAttributeFormValue(config, draft)
: parseAttributeDraft(draft, previousValue, columnTypes?.get(column));
}
return { ...feature, properties };
});
}
/**
* Validate drafted rows against the layer's Attribute Form config. Only edits
* that introduce (or keep, on an edited field) a violation are reported —
* pre-existing violations on untouched fields never block an unrelated edit.
* Iterates the drafts (few rows), not the whole table; `featureById` is the
* memoized feature index so no per-keystroke full scan happens here. Returns
* featureId → field → error for every blocking violation.
*/
function computeFormDraftErrors(
form: AttributeFormConfig | undefined,
drafts: AttributeDrafts,
featureById: Map<string, Feature> | null,
): Record<string, Record<string, AttributeFormFieldError>> {
const result: Record<string, Record<string, AttributeFormFieldError>> = {};
if (!form?.fields.length || !featureById || !hasDraftEdits(drafts)) {
return result;
}
const formFields = new Map(form.fields.map((entry) => [entry.field, entry]));
for (const [featureId, rowDrafts] of Object.entries(drafts)) {
if (Object.keys(rowDrafts).length === 0) continue;
const feature = featureById.get(featureId);
if (!feature) continue;
const properties = (feature.properties ?? {}) as Record<string, unknown>;
const candidate = { ...properties };
for (const [column, draft] of Object.entries(rowDrafts)) {
const previousValue = properties[column];
if (isInvalidObjectDraft(draft, previousValue)) continue;
const config = formFields.get(column);
candidate[column] = config
? coerceAttributeFormValue(config, draft)
: parseAttributeDraft(draft, previousValue);
}
const validation = validateAttributeFormValues(form, candidate, {
feature,
});
if (validation.ok) continue;
const baseline = validateAttributeFormValues(form, properties, {
feature,
});
const rowErrors: Record<string, AttributeFormFieldError> = {};
for (const [field, error] of Object.entries(validation.errors)) {
if (rowDrafts[field] !== undefined || !baseline.errors[field]) {
rowErrors[field] = error;
}
}
if (Object.keys(rowErrors).length > 0) result[featureId] = rowErrors;
}
return result;
}
function duckDBRowsToAttributeRows(rows: DuckDBAttributeRow[]): AttributeTableRow[] {
return rows.map((row) => ({
featureId: row.featureId,
properties: row.properties,
}));
}
function applyDraftsToDuckDBRows(
rows: AttributeTableRow[],
drafts: AttributeDrafts,
): Record<string, Record<string, unknown>> {
const rowById = new Map(rows.map((row) => [row.featureId, row]));
const updates: Record<string, Record<string, unknown>> = {};
// Same column-level inference as the GeoJSON path, over the query's rows.
const columnTypes = inferColumnTypes(rows.map((row) => row.properties));
for (const [featureId, rowDrafts] of Object.entries(drafts)) {
const row = rowById.get(featureId);
if (!row) continue;
const properties: Record<string, unknown> = {};
for (const [column, draft] of Object.entries(rowDrafts)) {
const previousValue = row.properties[column];
if (isInvalidObjectDraft(draft, previousValue)) continue;
properties[column] = parseAttributeDraft(draft, previousValue, columnTypes.get(column));
}
if (Object.keys(properties).length > 0) updates[featureId] = properties;
}
return updates;
}
interface AttributeTableProps {
mapControllerRef: RefObject<MapController | null>;
}
export function AttributeTable({ mapControllerRef }: AttributeTableProps) {
const { t } = useTranslation();
// Column order is visual: in a right-to-left layout the first column renders
// rightmost, so the move-left/right actions and their guards swap.
const isRtl = document.documentElement.dir === "rtl";
const tableSectionRef = useRef<HTMLElement>(null);
const tableResizeGuideRef = useRef<HTMLDivElement>(null);
// The Radix ScrollArea viewport, used as the virtualizer's scroll container.
const scrollViewportRef = useRef<HTMLDivElement>(null);
const selectedLayerId = useAppStore((s) => s.selectedLayerId);
const layers = useAppStore((s) => s.layers);
const attributeFilter = useAppStore((s) => s.attributeFilter);
const setAttributeFilter = useAppStore((s) => s.setAttributeFilter);
const selectedFeatureId = useAppStore((s) => s.selectedFeatureId);
const selectedFeatureIds = useAppStore((s) => s.selectedFeatureIds);
const selectFeature = useAppStore((s) => s.selectFeature);
const selectFeatures = useAppStore((s) => s.selectFeatures);
const attributeTableOpen = useAppStore((s) => s.ui.attributeTableOpen);
const setAttributeTableOpen = useAppStore((s) => s.setAttributeTableOpen);
const setDashboardOpen = useAppStore((s) => s.setDashboardOpen);
const updateLayer = useAppStore((s) => s.updateLayer);
const zoomToSelectedFeature = useAppStore((s) => s.ui.zoomToSelectedFeature);
const setZoomToSelectedFeature = useAppStore((s) => s.setZoomToSelectedFeature);
const [sort, setSort] = useState<{
key: SortKey;
direction: SortDirection;
}>({
key: "__featureId",
direction: "asc",
});
const [columnWidths, setColumnWidths] = useState<ColumnWidths>({});
// "all" shows every feature; "selected" restricts the table to the current
// multi-selection (the Show All / Show Selected dropdown).
const [featureView, setFeatureView] = useState<"all" | "selected">("all");
const [tableHeight, setTableHeight] = useState(DEFAULT_TABLE_HEIGHT);
// Collapsed shows only the toolbar header, hiding the table body, while the
// panel stays open. Distinct from closing the panel entirely (the X button).
const [collapsed, setCollapsed] = useState(false);
const [isEditing, setIsEditing] = useState(false);
const [drafts, setDrafts] = useState<AttributeDrafts>({});
const [exportError, setExportError] = useState<string | null>(null);
const [exportWarning, setExportWarning] = useState<string | null>(null);
const deferTableResize = isTauri();
const [loadingVectorGeojson, setLoadingVectorGeojson] = useState(false);
// Inline field-rename editing in a column header.
const [editingColumn, setEditingColumn] = useState<string | null>(null);
const [editingColumnName, setEditingColumnName] = useState("");
// Set true by Escape/commit so the input's blur does not re-commit a rename
// from a stale closure (mirrors LayerPanel's rename guard).
const suppressColumnBlurRef = useRef(false);
const [columnPendingDelete, setColumnPendingDelete] = useState<string | null>(null);
// New-field creation dialog state.
const [addingColumn, setAddingColumn] = useState(false);
const [newColumnName, setNewColumnName] = useState("");
const [newColumnType, setNewColumnType] = useState<NewColumnType>("text");
const [newColumnDefault, setNewColumnDefault] = useState("");
// Charts dialog state.
const [chartOpen, setChartOpen] = useState(false);
// Field-statistics dialog state.
const [statsOpen, setStatsOpen] = useState(false);
// Column-explorer dialog state.
const [explorerOpen, setExplorerOpen] = useState(false);
// Field-calculator dialog state.
const [calcOpen, setCalcOpen] = useState(false);
const [calcMode, setCalcMode] = useState<"update" | "create">("update");
const [calcTargetField, setCalcTargetField] = useState("");
const [calcNewName, setCalcNewName] = useState("");
const [calcOutputType, setCalcOutputType] = useState<CalcOutputType>("auto");
const [calcExpression, setCalcExpression] = useState("");
const [calcSelectedOnly, setCalcSelectedOnly] = useState(false);
const [calcError, setCalcError] = useState<string | null>(null);
// Geometry-measurement helper inside the calculator: which metric and unit the
// "Insert" button builds a `$length/$perimeter/$area(...)` snippet from.
const [calcGeomMetric, setCalcGeomMetric] = useState<GeometryMetric>("length");
const [calcGeomUnit, setCalcGeomUnit] = useState<string>("meters");
const calcExpressionRef = useRef<HTMLTextAreaElement>(null);
const layer = layers.find((l) => l.id === selectedLayerId);
const hasLayer = Boolean(layer);
// Columns materialized by persistent joins are derived data: every save
// re-derives them from the join table, so an edit, rename, or delete here
// would be silently undone. Render them read-only instead.
const joinDerivedColumns = useMemo(
() => new Set((layer?.joins ?? []).flatMap((join) => join.addedFields ?? [])),
[layer?.joins],
);
// Same for columns computed by virtual fields (expression-backed, re-derived
// on every data change): read-only here, managed in Layer properties.
const virtualFieldColumns = useMemo(
() =>
new Set(
(layer?.virtualFields ?? []).flatMap((field) =>
field.addedField ? [field.addedField] : [],
),
),
[layer?.virtualFields],
);
const derivedColumns = useMemo(
() => new Set([...joinDerivedColumns, ...virtualFieldColumns]),
[joinDerivedColumns, virtualFieldColumns],
);
const features = layer?.geojson?.features ?? [];
const isDuckDBLayer = isDuckDBQueryLayer(layer);
const duckdbRows = layer && isDuckDBLayer ? getDuckDBLayerRows(layer.id) : [];
const attributeRows: AttributeTableRow[] = isDuckDBLayer
? duckDBRowsToAttributeRows(duckdbRows)
: features.map((feature, index) => ({
featureId: String(feature.id ?? index),
properties: (feature.properties ?? {}) as Record<string, unknown>,
}));
const hasAttributeSource = Boolean(layer?.geojson || isDuckDBLayer);
// Add Vector Layer (geojson-mode) layers render from a MapLibre source the
// control owns, and their `layer.geojson` is dropped when a project is saved.
// Edits made here would neither redraw on the map nor survive a save, so the
// attribute table is read-only for them.
const isReadOnlyVectorLayer = geojsonVectorSourceId(layer) !== null;
// While this layer's geometry is being edited in place, attribute edits would
// race the editor's geometry write-back, so the inline editor is disabled.
const geometryEditLayerId = useSyncExternalStore(
subscribeGeometryEdit,
getGeometryEditTargetLayerId,
);
const isGeometryEditing = layer != null && geometryEditLayerId === layer.id;
// Vector layers added via the Add Vector Layer control keep their features in
// a MapLibre GeoJSON source rather than in `layer.geojson`. Read the data back
// from the map once so the table (and export) can use it like any other
// vector layer. Tiles-mode vector layers are not handled here.
useEffect(() => {
if (!layer || layer.geojson) {
setLoadingVectorGeojson(false);
return;
}
const sourceId = geojsonVectorSourceId(layer);
if (!sourceId) {
setLoadingVectorGeojson(false);
return;
}
const source = mapControllerRef.current?.getMap()?.getSource(sourceId) as
| GeoJSONSource
| undefined;
if (!source || typeof source.getData !== "function") {
// Reset here too: a prior run may have left the indicator true, and this
// early return would otherwise leave it stuck after a layer switch.
setLoadingVectorGeojson(false);
return;
}
let cancelled = false;
const layerId = layer.id;
setLoadingVectorGeojson(true);
source
.getData()
.then((data) => {
if (cancelled) return;
if (
data &&
typeof data === "object" &&
(data as { type?: string }).type === "FeatureCollection"
) {
updateLayer(layerId, { geojson: data as FeatureCollection });
}
})
.catch(() => {
// Best-effort: a source that cannot return data leaves the table in its
// existing "requires a vector layer" empty state.
})
.finally(() => {
if (!cancelled) setLoadingVectorGeojson(false);
});
return () => {
cancelled = true;
};
}, [layer, mapControllerRef, updateLayer]);
const hasEdits = hasDraftEdits(drafts);
const hasInvalidDrafts = attributeRows.some((row) => {
const rowDrafts = drafts[row.featureId];
if (!rowDrafts) return false;
return Object.entries(rowDrafts).some(([column, draft]) =>
isInvalidObjectDraft(draft, row.properties[column]),
);
});
// Attribute Form designer config: per-column edit widgets plus constraint
// validation of drafted rows. DuckDB layers keep the plain text editor —
// the designer is only offered for store-backed geojson layers.
const attributeForm = isDuckDBLayer ? undefined : layer?.attributeForm;
const formFields = useMemo(
() => new Map((attributeForm?.fields ?? []).map((entry) => [entry.field, entry])),
[attributeForm],
);
// Feature index for validation, rebuilt only when the layer data (not a
// draft keystroke) changes; null when no form config is active.
const formFeatureIndex = useMemo(() => {
if (!attributeForm?.fields.length) return null;
const geojsonFeatures = layer?.geojson?.features ?? [];
return new Map(
geojsonFeatures.map((feature, index): [string, Feature] => [
String(feature.id ?? index),
feature,
]),
);
}, [attributeForm, layer?.geojson]);
const formDraftErrors = useMemo(
() => computeFormDraftErrors(attributeForm, drafts, formFeatureIndex),
[attributeForm, drafts, formFeatureIndex],
);
const hasFormErrors = Object.keys(formDraftErrors).length > 0;
useEffect(() => {
setIsEditing(false);
setDrafts({});
// Clear column-management state too, so a rename input or pending delete
// started on the previous layer cannot apply to a same-named column on the
// newly selected layer. Suppress the rename Input's onBlur first: clearing
// editingColumn unmounts it, which fires onBlur -> commitColumnRename with
// the old column but the new layer, so the guard must already be set.
suppressColumnBlurRef.current = true;
setEditingColumn(null);
setEditingColumnName("");
setColumnPendingDelete(null);
setAddingColumn(false);
setNewColumnName("");
setNewColumnType("text");
setNewColumnDefault("");
setCalcOpen(false);
setCalcExpression("");
setCalcError(null);
setCalcSelectedOnly(false);
}, [selectedLayerId, hasLayer, isGeometryEditing]);
// If the selected feature is cleared while the calculator is open, drop the
// "selected only" flag too: leaving it checked-but-disabled would mislead the
// user, and the submit guard would silently widen the scope to all features.
useEffect(() => {
if (!selectedFeatureId) setCalcSelectedOnly(false);
}, [selectedFeatureId]);
// Always reopen the table expanded: a panel left collapsed before it was
// closed should not reappear collapsed the next time it is opened.
useEffect(() => {
if (!attributeTableOpen) setCollapsed(false);
}, [attributeTableOpen]);
// "Show Selected Features" over an empty selection is a blank table; fall back
// to showing everything once nothing is selected (e.g. after clearing or
// switching layers).
useEffect(() => {
if (selectedFeatureIds.length === 0) setFeatureView("all");
}, [selectedFeatureIds.length]);
// O(1) lookups for the multi-selection while rendering thousands of rows.
const selectedIdSet = useMemo(() => new Set(selectedFeatureIds), [selectedFeatureIds]);
const filterLower = attributeFilter.toLowerCase();
const filtered = attributeRows.filter(({ properties, featureId }) => {
// "Show Selected Features" restricts the table to the current selection.
if (featureView === "selected" && !selectedIdSet.has(featureId)) return false;
if (!filterLower) return true;
const props = JSON.stringify(properties).toLowerCase();
return featureId.includes(filterLower) || props.includes(filterLower);
});
const sorted = [...filtered].sort((a, b) => {
const aValue = sort.key === "__featureId" ? a.featureId : a.properties[sort.key];
const bValue = sort.key === "__featureId" ? b.featureId : b.properties[sort.key];
const result = compareAttributeValues(aValue, bValue);
return sort.direction === "asc" ? result : -result;
});
// Row selection with keyboard modifiers (plain / Ctrl-toggle / Shift-range /
// Shift+Ctrl merge). The branching lives in the pure `computeRowSelection`
// helper so it can be unit-tested; here we just feed it the current state.
const handleRowClick = (featureId: string, event: ReactMouseEvent<HTMLTableRowElement>) => {
const additive = event.ctrlKey || event.metaKey;
const range = event.shiftKey;
const { ids, anchor } = computeRowSelection({
featureId,
sortedIds: sorted.map((row) => row.featureId),
selectedIds: selectedFeatureIds,
anchorId: selectedFeatureId,
additive,
range,
});
// A plain click ("make this the sole selection") while reviewing the
// "Show Selected" subset would otherwise shrink the table to that one row.
// Drop back to "Show All" so the pick lands in the full table instead of
// stranding the user on a single-row view. Modifier clicks are deliberate
// refinements of the shown set, so they stay in the selected view.
if (!additive && !range && featureView === "selected") {
setFeatureView("all");
}
selectFeatures(ids, anchor);
};
// Row virtualization: only the rows in (and just around) the viewport are
// mounted, so opening the table on a layer with tens of thousands of features
// no longer builds that many DOM nodes at once. Sorting/filtering above still
// operate over the full data model; the virtualizer only governs rendering.
const rowVirtualizer = useVirtualizer({
count: sorted.length,
getScrollElement: () => scrollViewportRef.current,
estimateSize: () => ESTIMATED_ROW_HEIGHT,
// Key by feature id so measured heights stay attached to the right row when
// the sort/filter reorders the list. getItemKey is only called with indices
// in [0, count), so sorted[index] is always defined.
getItemKey: (index) => sorted[index].featureId,
// A small cushion of off-screen rows: enough to cover the sticky header's
// ~1-row offset (the virtualizer measures from the scroll container top) and
// to avoid blank gaps during fast scrolling, without keeping many extra rows
// mounted.
overscan: 8,
});
const virtualRows = rowVirtualizer.getVirtualItems();
const virtualTotalSize = rowVirtualizer.getTotalSize();
// Spacer rows above/below the rendered window reserve the scroll height of the
// off-screen rows while keeping the native <table> column layout intact.
const paddingTop = virtualRows.length > 0 ? virtualRows[0].start : 0;
const paddingBottom =
virtualRows.length > 0 ? virtualTotalSize - virtualRows[virtualRows.length - 1].end : 0;
// Bring the selected feature's row into view. With virtualization the row may
// be unmounted (e.g. when a feature is picked on the map), so a plain CSS
// highlight would be invisible; scroll the virtualizer to it instead. "auto"
// alignment leaves an already-visible row untouched, so this stays unobtrusive
// even when it re-runs on every filter keystroke. Re-runs when the table opens
// (the viewport is null while closed, so scrollToIndex is a no-op then), when
// the sort changes, when the row count changes (so the scroll fires once rows
// materialize asynchronously for Add Vector Layer layers), and when the filter
// text changes (two different filters can yield the same row count yet a
// different position for the selected row).
useEffect(() => {
if (!attributeTableOpen || !selectedFeatureId) return;
const index = sorted.findIndex((row) => row.featureId === selectedFeatureId);
if (index >= 0) rowVirtualizer.scrollToIndex(index, { align: "auto" });
// `sorted`/`rowVirtualizer` are rebuilt every render and so are intentionally
// excluded; the dependencies below are the inputs that actually change which
// row (if any) the selected feature occupies and warrant a re-scroll.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [
selectedFeatureId,
selectedLayerId,
attributeTableOpen,
sort,
sorted.length,
attributeFilter,
]);
const propKeys = new Set<string>();
for (const row of attributeRows) {
for (const k of Object.keys(row.properties)) {
// The inline photo/full-resolution image keys are multi-KB-to-MB data
// URLs (the map popup and Identify render them as thumbnails instead); a
// table cell would dump the raw base64 as text and jank on large photos.
if (!RESERVED_IMAGE_KEYS.has(k)) propKeys.add(k);
}
}
const discoveredColumns = Array.from(propKeys);
const columnSettings = getColumnSettings(layer);
// Columns rendered in the table, honoring saved order and hidden state.
const columns = visibleColumns(discoveredColumns, columnSettings);
const hiddenCols = hiddenColumns(discoveredColumns, columnSettings);
const hiddenColSet = new Set(hiddenCols);
const tableColumns = ["__featureId", ...columns];
// Column management mutates layer.geojson/style/metadata, so it is offered
// only for in-store, editable GeoJSON layers — not DuckDB query results or
// Add Vector Layer layers (whose geojson is not persisted).
const canManageColumns = Boolean(layer?.geojson) && !isDuckDBLayer && !isReadOnlyVectorLayer;
const columnWidth = (key: SortKey) =>
columnWidths[key] ??
(key === "__featureId" ? DEFAULT_FEATURE_ID_COLUMN_WIDTH : DEFAULT_ATTRIBUTE_COLUMN_WIDTH);
const tableWidth = tableColumns.reduce((width, column) => width + columnWidth(column), 0);
const columnWidthLimits = (key: SortKey) =>
key === "__featureId"
? {
max: MAX_FEATURE_ID_COLUMN_WIDTH,
min: MIN_FEATURE_ID_COLUMN_WIDTH,
}
: {
max: MAX_ATTRIBUTE_COLUMN_WIDTH,
min: MIN_ATTRIBUTE_COLUMN_WIDTH,
};
const startColumnResize = (key: SortKey, event: ReactMouseEvent<HTMLDivElement>) => {
event.preventDefault();
event.stopPropagation();
const startX = event.clientX;
const startWidth = columnWidth(key);
const { min, max } = columnWidthLimits(key);
// The handle sits at the column's logical inline-end (`-end-2`) — the right
// edge in LTR, the left edge in RTL. clientX still increases to the right in
// both, so invert the delta under RTL: dragging the (left-side) RTL handle
// outward lowers clientX but should widen the column.
const directionSign = getComputedStyle(event.currentTarget).direction === "rtl" ? -1 : 1;
const onMouseMove = (moveEvent: MouseEvent) => {
const nextWidth = Math.min(
max,
Math.max(min, startWidth + directionSign * (moveEvent.clientX - startX)),
);
setColumnWidths((current) => ({ ...current, [key]: nextWidth }));
};
const onMouseUp = () => {
window.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
};
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mouseup", onMouseUp);
};
const startTableResize = (event: ReactMouseEvent<HTMLDivElement>) => {
event.preventDefault();
event.stopPropagation();
const startY = event.clientY;
const startHeight = tableHeight;
let nextHeight = startHeight;
let resizeFrame: number | null = null;
const previousCursor = document.body.style.cursor;
const previousUserSelect = document.body.style.userSelect;
document.body.style.cursor = "row-resize";
document.body.style.userSelect = "none";
window.dispatchEvent(new Event(PANEL_RESIZE_START_EVENT));
const onMouseMove = (moveEvent: MouseEvent) => {
const availableHeight = Math.max(MIN_TABLE_HEIGHT, window.innerHeight - 180);
const maxHeight = Math.min(MAX_TABLE_HEIGHT, availableHeight);
nextHeight = Math.min(
maxHeight,
Math.max(MIN_TABLE_HEIGHT, startHeight + startY - moveEvent.clientY),
);
if (resizeFrame !== null) return;
resizeFrame = window.requestAnimationFrame(() => {
resizeFrame = null;
if (deferTableResize) {
if (tableResizeGuideRef.current) {
tableResizeGuideRef.current.style.top = `${startY + startHeight - nextHeight}px`;
tableResizeGuideRef.current.classList.remove("hidden");
}
return;
}
if (tableSectionRef.current) {
tableSectionRef.current.style.height = `${nextHeight}px`;
}
});
};
const onMouseUp = () => {
window.removeEventListener("mousemove", onMouseMove);
window.removeEventListener("mouseup", onMouseUp);
if (resizeFrame !== null) {
window.cancelAnimationFrame(resizeFrame);
resizeFrame = null;
}
if (tableSectionRef.current) {
tableSectionRef.current.style.height = `${nextHeight}px`;
}
tableResizeGuideRef.current?.classList.add("hidden");
setTableHeight(nextHeight);
window.dispatchEvent(new Event(PANEL_RESIZE_END_EVENT));
document.body.style.cursor = previousCursor;
document.body.style.userSelect = previousUserSelect;
};
window.addEventListener("mousemove", onMouseMove);
window.addEventListener("mouseup", onMouseUp);
};
const toggleSort = (key: SortKey) => {
setSort((current) => ({
key,
direction: current.key === key && current.direction === "asc" ? "desc" : "asc",
}));
};
const renderSortIcon = (key: SortKey) => {
if (sort.key !== key) return null;
return sort.direction === "asc" ? (
<ArrowUp className="h-3.5 w-3.5" />
) : (
<ArrowDown className="h-3.5 w-3.5" />
);
};
// Localize an Attribute Form validation error for a cell tooltip.
const formErrorText = (error: AttributeFormFieldError): string =>
attributeFormErrorMessage(t, error);
const updateCellDraft = (
featureId: string,
column: string,
value: string,
previousValue: unknown,
) => {
setDrafts((current) => {
const next = { ...current };
const row = { ...(next[featureId] ?? {}) };
if (value === formatAttributeValue(previousValue)) {
delete row[column];
} else {
row[column] = value;
}
if (Object.keys(row).length === 0) {
delete next[featureId];
} else {
next[featureId] = row;
}
return next;
});
};
const cancelEditing = () => {
setIsEditing(false);
setDrafts({});
};
const toggleEditing = () => {
if (isEditing && !hasEdits) {
setIsEditing(false);
return;
}
if (!isEditing) {
setIsEditing(true);
}
};
const saveDrafts = () => {
if (!layer || !hasEdits || hasInvalidDrafts || hasFormErrors) return;
if (isDuckDBLayer) {
updateDuckDBLayerRows(layer.id, applyDraftsToDuckDBRows(attributeRows, drafts));
setIsEditing(false);
setDrafts({});
return;
}
if (!layer.geojson) return;
const geojson = {
...layer.geojson,
features: applyDraftsToFeatures(layer.geojson.features, drafts, formFields),
};
updateLayer(layer.id, { geojson });
setIsEditing(false);
setDrafts({});
};
const geojsonWithDrafts = () => {
if (!layer?.geojson) return null;
return {
...layer.geojson,
features: applyDraftsToFeatures(layer.geojson.features, drafts, formFields),
};
};
const exportLayer = async (format: VectorExportFormat) => {
if (!layer?.geojson) return;
try {
setExportError(null);
setExportWarning(null);
const exportGeojson = geojsonWithDrafts();
if (!exportGeojson) return;
const baseName = sanitizeExportFileName(layer.name);
const savedPath = await exportVectorLayer(exportGeojson, format, baseName, layer.name);
// Surface Shapefile field-name limitations (10-char truncation and any
// resulting collisions) only when a file was actually written; a null
// path means the user cancelled the save dialog.
if (savedPath !== null && format === "shapefile") {
const warnings = shapefileFieldWarnings(exportGeojson);
setExportWarning(warnings.length > 0 ? warnings.join(" ") : null);
}
} catch (error) {
console.error("Failed to export attribute table", error);
setExportError(
kmlExportErrorMessage(error, t) ??
(error instanceof Error ? error.message : t("attributeTable.exportFailed")),
);
}
};
const beginColumnRename = (col: string) => {
suppressColumnBlurRef.current = false;
setEditingColumn(col);
setEditingColumnName(col);
};
const cancelColumnRename = () => {
suppressColumnBlurRef.current = true;
setEditingColumn(null);
setEditingColumnName("");
};
const commitColumnRename = () => {
if (suppressColumnBlurRef.current || !editingColumn || !layer) {
suppressColumnBlurRef.current = false;
return;
}
suppressColumnBlurRef.current = true;
const oldKey = editingColumn;
// Normalize the key here so the view-state updates below use exactly what
// renameColumn writes. (renameColumn also trims defensively for other
// callers; passing the already-trimmed value keeps the two in agreement.)
const newKey = editingColumnName.trim();
const patch = renameColumn(layer, discoveredColumns, oldKey, newKey);
if (patch) {
updateLayer(layer.id, patch);
// Keep view state pointing at the renamed column.
setColumnWidths((current) => {
if (!(oldKey in current)) return current;
const { [oldKey]: width, ...rest } = current;
return { ...rest, [newKey]: width };
});
setSort((current) => (current.key === oldKey ? { ...current, key: newKey } : current));
}
// Always close the editor when committing, even on a no-op (empty,
// unchanged, or a name that collides with an existing — possibly hidden —
// column); the original name is kept. This matches the layer-rename UX in
// LayerPanel. Use Escape to cancel.
setEditingColumn(null);
setEditingColumnName("");
};
const handleToggleHidden = (col: string) => {
if (!layer) return;
updateLayer(layer.id, toggleColumnHidden(layer, col));
};
const handleShowAllColumns = () => {
if (!layer) return;
updateLayer(layer.id, showAllColumns(layer));