feat(spatial): add SRID-aware geometry previews
This commit is contained in:
1 parent
ee26b2a580
commit
a6a072294a
57 files changed
+2771
-384
No files matched your search
@@ -0,0 +1,40 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { renderGeometryFeaturesIndependently } from "@/lib/dataGrid/geometryLayerPreview";
|
||||
|
||||
describe("renderGeometryFeaturesIndependently", () => {
|
||||
it("keeps valid mixed-SRID layers when other features are unsupported or throw", () => {
|
||||
const added: string[] = [];
|
||||
const errors: unknown[] = [];
|
||||
const summary = renderGeometryFeaturesIndependently(
|
||||
[
|
||||
{ id: "wgs84", srid: 4326 },
|
||||
{ id: "unknown", srid: null },
|
||||
{ id: "broken", srid: 3857 },
|
||||
{ id: "mercator", srid: 3857 },
|
||||
],
|
||||
(feature) => {
|
||||
if (feature.srid === null) return null;
|
||||
if (feature.id === "broken") throw new Error("invalid geometry");
|
||||
return { layer: feature.id, srid: feature.srid };
|
||||
},
|
||||
(layer) => added.push(layer),
|
||||
(error) => errors.push(error),
|
||||
);
|
||||
|
||||
expect(added).toEqual(["wgs84", "mercator"]);
|
||||
expect(summary).toEqual({ rendered: 2, skipped: 2, srids: [3857, 4326] });
|
||||
expect(errors).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("reports an entirely unsupported result without adding layers", () => {
|
||||
const summary = renderGeometryFeaturesIndependently(
|
||||
[null, 4490],
|
||||
() => null,
|
||||
() => {
|
||||
throw new Error("must not add a layer");
|
||||
},
|
||||
);
|
||||
|
||||
expect(summary).toEqual({ rendered: 0, skipped: 2, srids: [] });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildGeometryMapFeatureCollection } from "@/lib/dataGrid/geometryMapPreview";
|
||||
import type { PreviewActionContext } from "@/lib/dataGrid/resultPreviewRegistry";
|
||||
|
||||
function context(): PreviewActionContext {
|
||||
return {
|
||||
result: {
|
||||
columns: ["shape", "name"],
|
||||
column_types: ["geometry", "text"],
|
||||
column_sortables: [],
|
||||
spatial_columns: [{ column_index: 0, srid: 4326 }],
|
||||
rows: [
|
||||
["POINT(116.397 39.908)", "wgs84"],
|
||||
["POINT(12957254.77 4852618.61)", "mercator"],
|
||||
["POINT(1 2)", "unknown"],
|
||||
],
|
||||
affected_rows: 0,
|
||||
execution_time_ms: 1,
|
||||
truncated: false,
|
||||
has_more: false,
|
||||
},
|
||||
selectedRowIds: [],
|
||||
displayRowRefs: [
|
||||
{ id: 20, sourceIndex: 1, isNew: false },
|
||||
{ id: 10, sourceIndex: 0, isNew: false },
|
||||
{ id: 30, sourceIndex: 2, isNew: false },
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
describe("buildGeometryMapFeatureCollection", () => {
|
||||
it("exposes the detected layer SRID and binds row properties by sourceIndex", () => {
|
||||
const collection = buildGeometryMapFeatureCollection(context());
|
||||
|
||||
expect(collection?.detectedSrid).toBe(4326);
|
||||
expect(collection?.features.map((feature) => feature.properties.name)).toEqual(["mercator", "wgs84", "unknown"]);
|
||||
});
|
||||
|
||||
it("reports detectedSrid null when spatial metadata is absent", () => {
|
||||
const ctx = context();
|
||||
ctx.result.spatial_columns = undefined;
|
||||
|
||||
const collection = buildGeometryMapFeatureCollection(ctx);
|
||||
expect(collection?.detectedSrid).toBeNull();
|
||||
});
|
||||
|
||||
it("binds each feature to its own per-cell SRID when the column mixes SRIDs", () => {
|
||||
const ctx = context();
|
||||
ctx.result.spatial_columns = [{ column_index: 0, srid: 4326 }];
|
||||
// Per-cell SRIDs, parallel to rows: wgs84=4326, mercator=3857, unknown=null.
|
||||
ctx.result.spatial_values = [
|
||||
[4326, null],
|
||||
[3857, null],
|
||||
[null, null],
|
||||
];
|
||||
|
||||
const collection = buildGeometryMapFeatureCollection(ctx);
|
||||
expect(collection?.features.map((feature) => feature.properties._srid)).toEqual([3857, 4326, null]);
|
||||
});
|
||||
|
||||
it("prefers per-cell SRIDs over column-level hints", () => {
|
||||
const ctx = context();
|
||||
ctx.result.spatial_columns = [{ column_index: 0, srid: 3857 }];
|
||||
ctx.result.spatial_values = [
|
||||
[4326, null],
|
||||
[null, null],
|
||||
[null, null],
|
||||
];
|
||||
|
||||
const collection = buildGeometryMapFeatureCollection(ctx);
|
||||
// wgs84 row carries its own 4326 even though the column hint says 3857.
|
||||
expect(collection?.features.find((f) => f.properties.name === "wgs84")?.properties._srid).toBe(4326);
|
||||
});
|
||||
|
||||
it("uses the column-level hint only for legacy results without per-cell metadata", () => {
|
||||
const ctx = context();
|
||||
ctx.result.spatial_columns = [{ column_index: 0, srid: 3857 }];
|
||||
ctx.result.spatial_values = undefined;
|
||||
|
||||
const collection = buildGeometryMapFeatureCollection(ctx);
|
||||
expect(collection?.features.map((feature) => feature.properties._srid)).toEqual([3857, 3857, 3857]);
|
||||
});
|
||||
|
||||
it("deduplicates geometry by SRID and WKT", () => {
|
||||
const ctx = context();
|
||||
ctx.result.rows = [
|
||||
["POINT(1 2)", "wgs84"],
|
||||
["POINT(1 2)", "mercator"],
|
||||
["POINT(1 2)", "duplicate wgs84"],
|
||||
];
|
||||
ctx.result.spatial_values = [
|
||||
[4326, null],
|
||||
[3857, null],
|
||||
[4326, null],
|
||||
];
|
||||
|
||||
const collection = buildGeometryMapFeatureCollection(ctx);
|
||||
expect(collection?.features.map((feature) => feature.properties._srid)).toEqual([3857, 4326]);
|
||||
expect(collection?.features.map((feature) => feature.properties.name)).toEqual(["mercator", "wgs84"]);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { wktToGeoJson } from "@/lib/dataGrid/geometryPreview";
|
||||
import { parseWktGeometry, renderGeometryOnCanvas, wktToGeoJson } from "@/lib/dataGrid/geometryPreview";
|
||||
|
||||
describe("wktToGeoJson", () => {
|
||||
it("preserves polygon interior rings", () => {
|
||||
@@ -51,4 +51,45 @@ describe("wktToGeoJson", () => {
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("defensively strips an old EWKT prefix", () => {
|
||||
expect(wktToGeoJson("SRID=4326;POINT(116.397 39.908)")).toEqual({
|
||||
type: "Point",
|
||||
coordinates: [116.397, 39.908],
|
||||
});
|
||||
expect(parseWktGeometry("SRID=3857;POINT(1 2)")?.type).toBe("POINT");
|
||||
});
|
||||
|
||||
it("rejects a geometry collection when any member cannot be parsed", () => {
|
||||
expect(wktToGeoJson("GEOMETRYCOLLECTION(POINT(1 2),NOT_A_GEOMETRY(3 4))")).toBeNull();
|
||||
});
|
||||
|
||||
it("fills polygon holes with the even-odd rule", () => {
|
||||
const fillRules: string[] = [];
|
||||
const context = {
|
||||
clearRect() {},
|
||||
beginPath() {},
|
||||
moveTo() {},
|
||||
lineTo() {},
|
||||
closePath() {},
|
||||
stroke() {},
|
||||
arc() {},
|
||||
fill(rule?: string) {
|
||||
if (rule) fillRules.push(rule);
|
||||
},
|
||||
fillStyle: "",
|
||||
strokeStyle: "",
|
||||
font: "",
|
||||
textAlign: "",
|
||||
lineWidth: 0,
|
||||
lineJoin: "",
|
||||
lineCap: "",
|
||||
fillText() {},
|
||||
} as unknown as CanvasRenderingContext2D;
|
||||
const canvas = { width: 400, height: 280, getContext: () => context } as unknown as HTMLCanvasElement;
|
||||
const geometry = parseWktGeometry("POLYGON((0 0,10 0,10 10,0 10,0 0),(2 2,8 2,8 8,2 8,2 2))");
|
||||
expect(geometry).not.toBeNull();
|
||||
renderGeometryOnCanvas(canvas, geometry!);
|
||||
expect(fillRules).toContain("evenodd");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { describe, expect, it } from "vitest";
|
||||
import L from "leaflet";
|
||||
import { createBuiltInCoordsToLatLng, prepareCoordsToLatLng } from "@/lib/dataGrid/geometryProjection";
|
||||
|
||||
describe("geometry projection", () => {
|
||||
it("maps equivalent EPSG:4326 and EPSG:3857 points to the same location", () => {
|
||||
const latLng = L.latLng(39.908, 116.397);
|
||||
const projected = L.CRS.EPSG3857.project(latLng);
|
||||
const from4326 = createBuiltInCoordsToLatLng(4326, L)!([116.397, 39.908]);
|
||||
const from3857 = createBuiltInCoordsToLatLng(3857, L)!([projected.x, projected.y]);
|
||||
|
||||
expect(from3857.lat).toBeCloseTo(from4326.lat, 8);
|
||||
expect(from3857.lng).toBeCloseTo(from4326.lng, 8);
|
||||
});
|
||||
|
||||
it("projects a CGCS2000 zone-40 (EPSG:4528) easting near 120E", async () => {
|
||||
const toLatLng = await prepareCoordsToLatLng(4528, L);
|
||||
expect(toLatLng).not.toBeNull();
|
||||
const ll = toLatLng!([40_500_000, 2_600_000]); // zone-40 false easting, ~lon 120
|
||||
|
||||
expect(ll.lng).toBeCloseTo(120, 1);
|
||||
expect(ll.lat).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it("returns no converter for missing and unsupported spatial references", async () => {
|
||||
expect(createBuiltInCoordsToLatLng(null, L)).toBeNull();
|
||||
await expect(prepareCoordsToLatLng(2154, L)).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { getSpatialReference, SHORTLIST_SRIDS } from "@/lib/dataGrid/spatialReferenceCatalog";
|
||||
|
||||
describe("spatialReferenceCatalog", () => {
|
||||
it("resolves WGS84 and Web Mercator natively", () => {
|
||||
expect(getSpatialReference(4326)?.kind).toBe("lnglat");
|
||||
expect(getSpatialReference(3857)?.kind).toBe("webmercator");
|
||||
});
|
||||
|
||||
it("resolves CGCS2000 3-degree zone 40 (4528) with false easting 40500000", () => {
|
||||
const entry = getSpatialReference(4528);
|
||||
expect(entry?.kind).toBe("proj4");
|
||||
expect(entry?.proj4).toContain("+lon_0=120");
|
||||
expect(entry?.proj4).toContain("+x_0=40500000 ");
|
||||
});
|
||||
|
||||
it("resolves CGCS2000 3-degree CM 120E (4549) with false easting 500000", () => {
|
||||
const entry = getSpatialReference(4549);
|
||||
expect(entry?.proj4).toContain("+lon_0=120");
|
||||
expect(entry?.proj4).toContain("+x_0=500000 ");
|
||||
});
|
||||
|
||||
it("resolves CGCS2000 3-degree CM 114E (4547) with false easting 500000", () => {
|
||||
const entry = getSpatialReference(4547);
|
||||
expect(entry?.proj4).toContain("+lon_0=114");
|
||||
expect(entry?.proj4).toContain("+x_0=500000 ");
|
||||
});
|
||||
|
||||
it("treats CGCS2000 geographic (4490) as lng/lat", () => {
|
||||
expect(getSpatialReference(4490)?.kind).toBe("lnglat");
|
||||
});
|
||||
|
||||
it("returns null for codes outside the offline subset", () => {
|
||||
expect(getSpatialReference(2154)).toBeNull();
|
||||
});
|
||||
|
||||
it("shortlist starts with 4326 and 3857", () => {
|
||||
expect(SHORTLIST_SRIDS.slice(0, 2)).toEqual([4326, 3857]);
|
||||
});
|
||||
});
|
||||
@@ -144,6 +144,25 @@ describe("tab result cache statement execution metadata", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves spatial metadata", () => {
|
||||
const encoded = encodeTabResultSnapshot({
|
||||
result: {
|
||||
columns: ["geom"],
|
||||
column_types: ["geometry"],
|
||||
spatial_columns: [{ column_index: 0, srid: 4326 }],
|
||||
spatial_values: [[4326], [3857], [null]],
|
||||
rows: [["POINT(116.397 39.908)"], ["POINT(12957255 4852583)"], [null]],
|
||||
affected_rows: 0,
|
||||
execution_time_ms: 1,
|
||||
},
|
||||
cachedAt: 1,
|
||||
});
|
||||
|
||||
const result = decodeTabResultSnapshot(encoded).result;
|
||||
expect(result?.spatial_columns).toEqual([{ column_index: 0, srid: 4326 }]);
|
||||
expect(result?.spatial_values).toEqual([[4326], [3857], [null]]);
|
||||
});
|
||||
|
||||
it("restores multi-result, pagination, local-sort, and editable metadata fixtures", () => {
|
||||
const restored = decodeTabResultSnapshot(encodeTabResultSnapshot(queryResultLifecycleSnapshot()));
|
||||
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
export interface PreparedGeometryLayer<TLayer> {
|
||||
layer: TLayer;
|
||||
srid: number;
|
||||
}
|
||||
|
||||
export interface GeometryLayerRenderSummary {
|
||||
rendered: number;
|
||||
skipped: number;
|
||||
srids: number[];
|
||||
}
|
||||
|
||||
/** Render features independently so one malformed geometry cannot hide valid layers. */
|
||||
export function renderGeometryFeaturesIndependently<TFeature, TLayer>(features: readonly TFeature[], prepareLayer: (feature: TFeature) => PreparedGeometryLayer<TLayer> | null, addLayer: (layer: TLayer) => void, onError?: (error: unknown) => void): GeometryLayerRenderSummary {
|
||||
let rendered = 0;
|
||||
let skipped = 0;
|
||||
const srids = new Set<number>();
|
||||
|
||||
for (const feature of features) {
|
||||
try {
|
||||
const prepared = prepareLayer(feature);
|
||||
if (!prepared) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
addLayer(prepared.layer);
|
||||
rendered++;
|
||||
srids.add(prepared.srid);
|
||||
} catch (error) {
|
||||
skipped++;
|
||||
onError?.(error);
|
||||
}
|
||||
}
|
||||
|
||||
return { rendered, skipped, srids: Array.from(srids).sort((a, b) => a - b) };
|
||||
}
|
||||
@@ -1,8 +1,21 @@
|
||||
import { Map as MapIcon } from "@lucide/vue";
|
||||
import { registerPreviewAction } from "@/lib/dataGrid/resultPreviewRegistry";
|
||||
import { wktToGeoJson } from "@/lib/dataGrid/geometryPreview";
|
||||
import { registerPreviewAction, type PreviewActionContext } from "@/lib/dataGrid/resultPreviewRegistry";
|
||||
import { wktToGeoJson, type GeoJsonGeometry } from "@/lib/dataGrid/geometryPreview";
|
||||
import LayerPreviewDialog from "@/components/grid/LayerPreviewDialog.vue";
|
||||
|
||||
export interface GeometryMapFeature {
|
||||
type: "Feature";
|
||||
geometry: GeoJsonGeometry;
|
||||
properties: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface GeometryMapFeatureCollection {
|
||||
type: "FeatureCollection";
|
||||
features: GeometryMapFeature[];
|
||||
/** First non-null SRID among rendered features' columns, or null if unknown. */
|
||||
detectedSrid: number | null;
|
||||
}
|
||||
|
||||
registerPreviewAction({
|
||||
id: "geometry-map-preview",
|
||||
label: "grid.layerPreview",
|
||||
@@ -17,59 +30,63 @@ registerPreviewAction({
|
||||
});
|
||||
},
|
||||
execute(ctx) {
|
||||
const geomIndices = geometryColumnIndices(ctx.result.column_types);
|
||||
if (geomIndices.length === 0) return null;
|
||||
|
||||
const features: Record<string, any>[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
for (const ref of ctx.displayRowRefs) {
|
||||
if (ref.isNew) continue;
|
||||
// Only include selected rows if there's an active selection
|
||||
if (ctx.selectedRowIds.length > 0 && !ctx.selectedRowIds.includes(ref.id)) continue;
|
||||
const row = ctx.result.rows[ref.sourceIndex];
|
||||
if (!row) continue;
|
||||
for (const colIdx of geomIndices) {
|
||||
const raw = row[colIdx];
|
||||
if (raw === null || raw === undefined) continue;
|
||||
const wkt = String(raw);
|
||||
if (wkt.startsWith("0x") || seen.has(wkt)) continue;
|
||||
seen.add(wkt);
|
||||
const geom = wktToGeoJson(wkt);
|
||||
if (geom) {
|
||||
// Include all non-geometry column values as properties for labelling.
|
||||
const props: Record<string, any> = {
|
||||
_column: ctx.result.columns[colIdx],
|
||||
_row: ref.sourceIndex,
|
||||
};
|
||||
for (let c = 0; c < ctx.result.columns.length; c++) {
|
||||
if (geomIndices.includes(c)) continue; // skip geometry columns
|
||||
const colName = ctx.result.columns[c] ?? `col_${c}`;
|
||||
const val = row[c];
|
||||
props[colName] = val ?? null;
|
||||
}
|
||||
features.push({
|
||||
type: "Feature",
|
||||
geometry: geom,
|
||||
properties: props,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (features.length === 0) return null;
|
||||
|
||||
const fc = { type: "FeatureCollection", features };
|
||||
const featureCollection = buildGeometryMapFeatureCollection(ctx);
|
||||
if (!featureCollection) return null;
|
||||
|
||||
return {
|
||||
component: LayerPreviewDialog,
|
||||
props: {
|
||||
geojson: JSON.stringify(fc),
|
||||
geojson: JSON.stringify(featureCollection),
|
||||
},
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
export function buildGeometryMapFeatureCollection(ctx: PreviewActionContext): GeometryMapFeatureCollection | null {
|
||||
const geomIndices = geometryColumnIndices(ctx.result.column_types);
|
||||
if (geomIndices.length === 0) return null;
|
||||
|
||||
const features: GeometryMapFeature[] = [];
|
||||
const seen = new Set<string>();
|
||||
const sridByColumn = new Map<number, number | null>((ctx.result.spatial_columns ?? []).map((entry) => [entry.column_index, entry.srid]));
|
||||
const spatialValues = ctx.result.spatial_values;
|
||||
let detectedSrid: number | null = null;
|
||||
|
||||
for (const ref of ctx.displayRowRefs) {
|
||||
if (ref.isNew) continue;
|
||||
if (ctx.selectedRowIds.length > 0 && !ctx.selectedRowIds.includes(ref.id)) continue;
|
||||
const row = ctx.result.rows[ref.sourceIndex];
|
||||
if (!row) continue;
|
||||
for (const colIdx of geomIndices) {
|
||||
const raw = row[colIdx];
|
||||
if (raw === null || raw === undefined) continue;
|
||||
const wkt = String(raw);
|
||||
if (wkt.startsWith("0x")) continue;
|
||||
const srid = spatialValues === undefined ? (sridByColumn.get(colIdx) ?? null) : (spatialValues[ref.sourceIndex]?.[colIdx] ?? null);
|
||||
const geometryKey = JSON.stringify([srid, wkt]);
|
||||
if (seen.has(geometryKey)) continue;
|
||||
seen.add(geometryKey);
|
||||
const geometry = wktToGeoJson(wkt);
|
||||
if (!geometry) continue;
|
||||
if (detectedSrid == null && srid != null) detectedSrid = srid;
|
||||
|
||||
const properties: Record<string, unknown> = {
|
||||
_column: ctx.result.columns[colIdx],
|
||||
_row: ref.sourceIndex,
|
||||
_srid: srid,
|
||||
};
|
||||
for (let c = 0; c < ctx.result.columns.length; c++) {
|
||||
if (geomIndices.includes(c)) continue;
|
||||
const columnName = ctx.result.columns[c] ?? `col_${c}`;
|
||||
properties[columnName] = row[c] ?? null;
|
||||
}
|
||||
features.push({ type: "Feature", geometry, properties });
|
||||
}
|
||||
}
|
||||
|
||||
return features.length > 0 ? { type: "FeatureCollection", features, detectedSrid } : null;
|
||||
}
|
||||
|
||||
function geometryColumnIndices(columnTypes: readonly string[] | undefined): number[] {
|
||||
if (!columnTypes) return [];
|
||||
const indices: number[] = [];
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
type Coord = [number, number];
|
||||
export type Coord = [number, number];
|
||||
|
||||
interface GeometryGroup {
|
||||
export interface ParsedWktGeometry {
|
||||
type: string;
|
||||
groups: GeometryGroup[];
|
||||
coordinates: Coord[];
|
||||
}
|
||||
|
||||
export interface GeometryGroup {
|
||||
coords: Coord[];
|
||||
children: GeometryGroup[];
|
||||
}
|
||||
@@ -112,20 +118,18 @@ function extractCoords(g: GeometryGroup): Coord[] {
|
||||
function drawPolygonRings(ctx: CanvasRenderingContext2D, group: GeometryGroup, mapX: (v: number) => number, mapY: (v: number) => number) {
|
||||
// group.children contains ring groups
|
||||
const rings = group.children.length > 0 ? group.children : [group];
|
||||
let ringIndex = 0;
|
||||
ctx.beginPath();
|
||||
for (const ringGroup of rings) {
|
||||
const coords = extractCoords(ringGroup);
|
||||
if (coords.length < 2) continue;
|
||||
ctx.beginPath();
|
||||
ctx.moveTo(mapX(coords[0][0]), mapY(coords[0][1]));
|
||||
for (let j = 1; j < coords.length; j++) {
|
||||
ctx.lineTo(mapX(coords[j][0]), mapY(coords[j][1]));
|
||||
}
|
||||
ctx.closePath();
|
||||
if (ringIndex === 0) ctx.fill();
|
||||
ctx.stroke();
|
||||
ringIndex++;
|
||||
}
|
||||
ctx.fill("evenodd");
|
||||
ctx.stroke();
|
||||
}
|
||||
|
||||
function drawGroups(ctx: CanvasRenderingContext2D, groups: GeometryGroup[], type: string, mapX: (v: number) => number, mapY: (v: number) => number) {
|
||||
@@ -201,12 +205,72 @@ function detectWktType(wkt: string): string {
|
||||
return m ? m[1].toUpperCase() : "GEOMETRYCOLLECTION";
|
||||
}
|
||||
|
||||
function cleanWktInput(wkt: string): string {
|
||||
const trimmed = wkt.trim();
|
||||
const ewkt = trimmed.match(/^SRID=\d+\s*;\s*/i);
|
||||
return ewkt ? trimmed.slice(ewkt[0].length).trim() : trimmed;
|
||||
}
|
||||
|
||||
// EWKB parsing on the backend can fall back to hex for unsupported geometry types
|
||||
// (e.g. TIN, Triangle, CircularString). Don't attempt to render hex as WKT.
|
||||
export function isHexGeometry(value: string): boolean {
|
||||
return value.startsWith("0x");
|
||||
}
|
||||
|
||||
export function parseWktGeometry(wkt: string): ParsedWktGeometry | null {
|
||||
const cleaned = cleanWktInput(wkt);
|
||||
if (!cleaned || isHexGeometry(cleaned)) return null;
|
||||
const type = detectWktType(cleaned);
|
||||
const tokens = tokenize(cleaned);
|
||||
const { groups } = parseGroups(tokens, 0);
|
||||
const coordinates = flattenCoords(groups).filter(([x, y]) => Number.isFinite(x) && Number.isFinite(y));
|
||||
return groups.length > 0 || /\bEMPTY\b/i.test(cleaned) ? { type, groups, coordinates } : null;
|
||||
}
|
||||
|
||||
export function renderGeometryOnCanvas(canvas: HTMLCanvasElement, geometry: ParsedWktGeometry): void {
|
||||
const allCoords = geometry.coordinates;
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
const W = canvas.width;
|
||||
const H = canvas.height;
|
||||
const pad = 20;
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
if (allCoords.length === 0) {
|
||||
ctx.fillStyle = "#888";
|
||||
ctx.font = "12px sans-serif";
|
||||
ctx.textAlign = "center";
|
||||
ctx.fillText("Empty geometry", W / 2, H / 2);
|
||||
return;
|
||||
}
|
||||
let minX = Infinity,
|
||||
maxX = -Infinity,
|
||||
minY = Infinity,
|
||||
maxY = -Infinity;
|
||||
for (const [x, y] of allCoords) {
|
||||
minX = Math.min(minX, x);
|
||||
maxX = Math.max(maxX, x);
|
||||
minY = Math.min(minY, y);
|
||||
maxY = Math.max(maxY, y);
|
||||
}
|
||||
if (minX === maxX && minY === maxY) {
|
||||
minX -= 1;
|
||||
maxX += 1;
|
||||
minY -= 1;
|
||||
maxY += 1;
|
||||
}
|
||||
const scale = Math.min((W - pad * 2) / (maxX - minX || 1), (H - pad * 2) / (maxY - minY || 1));
|
||||
const midX = (minX + maxX) / 2;
|
||||
const midY = (minY + maxY) / 2;
|
||||
const mapX = (x: number) => (x - midX) * scale + W / 2;
|
||||
const mapY = (y: number) => -(y - midY) * scale + H / 2;
|
||||
ctx.strokeStyle = "#3b82f6";
|
||||
ctx.fillStyle = "rgba(59, 130, 246, 0.15)";
|
||||
ctx.lineWidth = 1.5;
|
||||
ctx.lineJoin = "round";
|
||||
ctx.lineCap = "round";
|
||||
drawGroups(ctx, geometry.groups, geometry.type, mapX, mapY);
|
||||
}
|
||||
|
||||
export function renderWktOnCanvas(canvas: HTMLCanvasElement, wkt: string): void {
|
||||
if (isHexGeometry(wkt)) {
|
||||
const ctx = canvas.getContext("2d");
|
||||
@@ -219,70 +283,15 @@ export function renderWktOnCanvas(canvas: HTMLCanvasElement, wkt: string): void
|
||||
return;
|
||||
}
|
||||
|
||||
const type = detectWktType(wkt);
|
||||
const tokens = tokenize(wkt);
|
||||
const { groups } = parseGroups(tokens, 0);
|
||||
const allCoords = flattenCoords(groups);
|
||||
|
||||
const ctx = canvas.getContext("2d");
|
||||
if (!ctx) return;
|
||||
|
||||
const W = canvas.width;
|
||||
const H = canvas.height;
|
||||
const pad = 20;
|
||||
|
||||
ctx.clearRect(0, 0, W, H);
|
||||
|
||||
if (allCoords.length === 0) {
|
||||
ctx.fillStyle = "#888";
|
||||
ctx.font = "12px sans-serif";
|
||||
ctx.textAlign = "center";
|
||||
ctx.fillText("Empty geometry", W / 2, H / 2);
|
||||
return;
|
||||
}
|
||||
|
||||
let minX = Infinity,
|
||||
maxX = -Infinity,
|
||||
minY = Infinity,
|
||||
maxY = -Infinity;
|
||||
for (const [x, y] of allCoords) {
|
||||
if (x < minX) minX = x;
|
||||
if (x > maxX) maxX = x;
|
||||
if (y < minY) minY = y;
|
||||
if (y > maxY) maxY = y;
|
||||
}
|
||||
|
||||
if (minX === maxX && minY === maxY) {
|
||||
minX -= 1;
|
||||
maxX += 1;
|
||||
minY -= 1;
|
||||
maxY += 1;
|
||||
}
|
||||
|
||||
const rangeX = maxX - minX || 1;
|
||||
const rangeY = maxY - minY || 1;
|
||||
const scale = Math.min((W - pad * 2) / rangeX, (H - pad * 2) / rangeY);
|
||||
|
||||
const midX = (minX + maxX) / 2;
|
||||
const midY = (minY + maxY) / 2;
|
||||
|
||||
const mapX = (x: number) => (x - midX) * scale + W / 2;
|
||||
const mapY = (y: number) => -(y - midY) * scale + H / 2;
|
||||
|
||||
ctx.strokeStyle = "#3b82f6";
|
||||
ctx.fillStyle = "rgba(59, 130, 246, 0.15)";
|
||||
ctx.lineWidth = 1.5;
|
||||
ctx.lineJoin = "round";
|
||||
ctx.lineCap = "round";
|
||||
|
||||
drawGroups(ctx, groups, type, mapX, mapY);
|
||||
const geometry = parseWktGeometry(wkt);
|
||||
if (geometry) renderGeometryOnCanvas(canvas, geometry);
|
||||
}
|
||||
|
||||
/** GeoJSON geometry type. */
|
||||
export interface GeoJsonGeometry {
|
||||
type: string;
|
||||
coordinates?: any;
|
||||
geometries?: (GeoJsonGeometry | null)[];
|
||||
geometries?: GeoJsonGeometry[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -290,10 +299,11 @@ export interface GeoJsonGeometry {
|
||||
* Returns `null` for binary (hex) geometries or parse failures.
|
||||
*/
|
||||
export function wktToGeoJson(wkt: string): GeoJsonGeometry | null {
|
||||
if (isHexGeometry(wkt)) return null;
|
||||
const type = detectWktType(wkt);
|
||||
if (type === "GEOMETRYCOLLECTION") return geometryCollectionToGeoJson(wkt);
|
||||
const tokens = tokenize(wkt);
|
||||
const cleaned = cleanWktInput(wkt);
|
||||
if (isHexGeometry(cleaned)) return null;
|
||||
const type = detectWktType(cleaned);
|
||||
if (type === "GEOMETRYCOLLECTION") return geometryCollectionToGeoJson(cleaned);
|
||||
const tokens = tokenize(cleaned);
|
||||
const { groups } = parseGroups(tokens, 0);
|
||||
if (groups.length === 0) return null;
|
||||
try {
|
||||
@@ -369,9 +379,11 @@ function geometryCollectionToGeoJson(wkt: string): GeoJsonGeometry | null {
|
||||
const content = inner.slice(1, -1).trim();
|
||||
if (!content) return null;
|
||||
const parts = splitGeomCollectionMembers(content);
|
||||
const geometries = parts.map((part) => wktToGeoJson(part));
|
||||
if (geometries.some((geometry) => geometry === null)) return null;
|
||||
return {
|
||||
type: "GeometryCollection",
|
||||
geometries: parts.map((p) => wktToGeoJson(p)),
|
||||
geometries: geometries as GeoJsonGeometry[],
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import type L from "leaflet";
|
||||
import type { Coord } from "@/lib/dataGrid/geometryPreview";
|
||||
import { getSpatialReference } from "@/lib/dataGrid/spatialReferenceCatalog";
|
||||
|
||||
export type CoordinateToLatLng = (coord: Coord) => L.LatLng;
|
||||
|
||||
type CoordinateTransform = (coord: Coord) => Coord;
|
||||
|
||||
const transformPromises = new Map<number, Promise<CoordinateTransform>>();
|
||||
|
||||
export function createBuiltInCoordsToLatLng(srid: number | null | undefined, leaflet: typeof L): CoordinateToLatLng | null {
|
||||
if (srid == null) return null;
|
||||
const entry = getSpatialReference(srid);
|
||||
if (entry?.kind === "lnglat") return (coord) => leaflet.latLng(coord[1], coord[0]);
|
||||
if (entry?.kind === "webmercator") return (coord) => leaflet.CRS.EPSG3857.unproject(leaflet.point(coord[0], coord[1]));
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function prepareCoordsToLatLng(srid: number | null | undefined, leaflet: typeof L): Promise<CoordinateToLatLng | null> {
|
||||
const builtIn = createBuiltInCoordsToLatLng(srid, leaflet);
|
||||
if (builtIn) return builtIn;
|
||||
if (srid == null) return null;
|
||||
const entry = getSpatialReference(srid);
|
||||
if (!entry || entry.kind !== "proj4" || !entry.proj4) return null;
|
||||
|
||||
let transformPromise = transformPromises.get(srid);
|
||||
if (!transformPromise) {
|
||||
transformPromise = loadCoordinateTransform(srid, entry.proj4);
|
||||
transformPromises.set(srid, transformPromise);
|
||||
transformPromise.catch(() => transformPromises.delete(srid));
|
||||
}
|
||||
const transform = await transformPromise;
|
||||
return (coord) => {
|
||||
const [longitude, latitude] = transform(coord);
|
||||
return leaflet.latLng(latitude, longitude);
|
||||
};
|
||||
}
|
||||
|
||||
async function loadCoordinateTransform(srid: number, definition: string): Promise<CoordinateTransform> {
|
||||
const { default: proj4 } = await import("proj4");
|
||||
const source = `EPSG:${srid}`;
|
||||
proj4.defs(source, definition);
|
||||
const converter = proj4(source, "EPSG:4326");
|
||||
return ([x, y]) => {
|
||||
const [longitude, latitude] = converter.forward([x, y]);
|
||||
return [longitude, latitude];
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
export interface SpatialReferenceEntry {
|
||||
srid: number;
|
||||
label: string;
|
||||
kind: "lnglat" | "webmercator" | "proj4";
|
||||
/** proj4 definition string for kind === "proj4". */
|
||||
proj4?: string;
|
||||
}
|
||||
|
||||
const GRS80 = "+ellps=GRS80 +towgs84=0,0,0 +units=m +no_defs";
|
||||
|
||||
/** CGCS2000 Gauss-Kruger definitions follow the official EPSG parameters. */
|
||||
function gaussKruger(lon0: number, falseEasting: number): string {
|
||||
return `+proj=tmerc +lat_0=0 +lon_0=${lon0} +k=1 +x_0=${falseEasting} +y_0=0 ${GRS80}`;
|
||||
}
|
||||
|
||||
const entries = new Map<number, SpatialReferenceEntry>();
|
||||
|
||||
function add(entry: SpatialReferenceEntry) {
|
||||
entries.set(entry.srid, entry);
|
||||
}
|
||||
|
||||
// Geographic / native
|
||||
add({ srid: 4326, label: "WGS 84 (EPSG:4326)", kind: "lnglat" });
|
||||
add({ srid: 4490, label: "CGCS2000 geographic (EPSG:4490)", kind: "lnglat" });
|
||||
add({ srid: 3857, label: "Web Mercator (EPSG:3857)", kind: "webmercator" });
|
||||
add({ srid: 3395, label: "World Mercator (EPSG:3395)", kind: "proj4", proj4: `+proj=merc +lon_0=0 +k=1 +x_0=0 +y_0=0 ${GRS80}` });
|
||||
|
||||
// CGCS2000 3-degree Gauss-Kruger, ZONE-numbered series: EPSG 4513..4533, zones 25..45.
|
||||
// x_0 = zone*1e6 + 500000 — the leading digits encode the zone (e.g. 4528 = zone 40, x_0=40500000).
|
||||
for (let code = 4513; code <= 4533; code++) {
|
||||
const zone = 25 + (code - 4513);
|
||||
add({ srid: code, label: `CGCS2000 3-degree GK zone ${zone} · CM ${zone * 3}E (EPSG:${code})`, kind: "proj4", proj4: gaussKruger(zone * 3, zone * 1_000_000 + 500_000) });
|
||||
}
|
||||
// CGCS2000 3-degree Gauss-Kruger, CM (no zone prefix) series: EPSG 4534..4554, CM 75E..135E, x_0=500000
|
||||
// (e.g. 4547 = CM 114E, 4549 = CM 120E).
|
||||
for (let code = 4534; code <= 4554; code++) {
|
||||
const lon0 = 75 + (code - 4534) * 3;
|
||||
add({ srid: code, label: `CGCS2000 3-degree GK CM ${lon0}E (EPSG:${code})`, kind: "proj4", proj4: gaussKruger(lon0, 500000) });
|
||||
}
|
||||
// CGCS2000 6-degree Gauss-Kruger, ZONE-numbered series: EPSG 4491..4501, zones 13..23.
|
||||
// x_0 = zone*1e6 + 500000.
|
||||
for (let code = 4491; code <= 4501; code++) {
|
||||
const zone = 13 + (code - 4491);
|
||||
add({ srid: code, label: `CGCS2000 6-degree GK zone ${zone} · CM ${zone * 6 - 3}E (EPSG:${code})`, kind: "proj4", proj4: gaussKruger(zone * 6 - 3, zone * 1_000_000 + 500_000) });
|
||||
}
|
||||
// CGCS2000 6-degree Gauss-Kruger, CM (no zone prefix) series: EPSG 4502..4512, CM 75E..135E, x_0=500000
|
||||
for (let code = 4502; code <= 4512; code++) {
|
||||
const lon0 = 75 + (code - 4502) * 6;
|
||||
add({ srid: code, label: `CGCS2000 6-degree GK CM ${lon0}E (EPSG:${code})`, kind: "proj4", proj4: gaussKruger(lon0, 500000) });
|
||||
}
|
||||
|
||||
export function getSpatialReference(srid: number): SpatialReferenceEntry | null {
|
||||
return entries.get(srid) ?? null;
|
||||
}
|
||||
|
||||
/** Curated dropdown order: WGS84, Web Mercator, then common CGCS2000 zones. */
|
||||
export const SHORTLIST_SRIDS: number[] = [4326, 3857, 4490, 4528, 4549, 4526, 4547];
|
||||
@@ -46,6 +46,8 @@ export interface TabResultSnapshot {
|
||||
|
||||
interface ColumnarQueryResult {
|
||||
columns: string[];
|
||||
spatial_columns?: QueryResult["spatial_columns"];
|
||||
spatial_values?: QueryResult["spatial_values"];
|
||||
execution_error?: true;
|
||||
statement_index?: number;
|
||||
column_types?: string[];
|
||||
@@ -324,6 +326,8 @@ function stripSessionIds(result: QueryResult | undefined): QueryResult | undefin
|
||||
execution_error: result.execution_error,
|
||||
statement_index: result.statement_index,
|
||||
column_types: result.column_types ? [...result.column_types] : undefined,
|
||||
spatial_columns: result.spatial_columns?.map((entry) => ({ column_index: entry.column_index, srid: entry.srid })),
|
||||
spatial_values: result.spatial_values?.map((row) => [...row]),
|
||||
rows: result.rows.map((row) => [...row]),
|
||||
mongo_documents: result.mongo_documents ? clonePlain(result.mongo_documents) : undefined,
|
||||
mongo_copy_documents: result.mongo_copy_documents ? clonePlain(result.mongo_copy_documents) : undefined,
|
||||
@@ -363,6 +367,8 @@ function toColumnarResult(result: QueryResult | undefined): ColumnarQueryResult
|
||||
execution_error: result.execution_error,
|
||||
statement_index: result.statement_index,
|
||||
column_types: result.column_types ? [...result.column_types] : undefined,
|
||||
spatial_columns: result.spatial_columns?.map((entry) => ({ column_index: entry.column_index, srid: entry.srid })),
|
||||
spatial_values: result.spatial_values?.map((row) => [...row]),
|
||||
columnValues,
|
||||
rowCount: result.rows.length,
|
||||
mongo_documents: result.mongo_documents ? clonePlain(result.mongo_documents) : undefined,
|
||||
@@ -386,6 +392,8 @@ function fromColumnarResult(result: ColumnarQueryResult | undefined): QueryResul
|
||||
execution_error: result.execution_error,
|
||||
statement_index: result.statement_index,
|
||||
column_types: result.column_types ? [...result.column_types] : undefined,
|
||||
spatial_columns: result.spatial_columns?.map((entry) => ({ column_index: entry.column_index, srid: entry.srid })),
|
||||
spatial_values: result.spatial_values?.map((row) => [...row]),
|
||||
rows,
|
||||
mongo_documents: result.mongo_documents ? clonePlain(result.mongo_documents) : undefined,
|
||||
mongo_copy_documents: result.mongo_copy_documents ? clonePlain(result.mongo_copy_documents) : undefined,
|
||||
|
||||
Reference in new issue
Block a user