Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

feat: add GeoJSON export for tables and dataframes (#11116)

Kiran Gadhave143b4cf7e838
diff --git a/frontend/plugins.openapi.yaml b/frontend/plugins.openapi.yaml
index 8d8edb453f..44ef17f724 100644
--- a/frontend/plugins.openapi.yaml
+++ b/frontend/plugins.openapi.yaml
@@ -665,6 +665,64 @@ paths:
responses:
"204":
description: Accepted.
+ /plugins/marimo-dataframe/functions/download_geojson/input:
+ summary: marimo-dataframe download_geojson input
+ get:
+ operationId: read_marimo_dataframe_download_geojson_input
+ summary: Read marimo-dataframe download_geojson input
+ tags:
+ - rpc-input
+ responses:
+ "200":
+ description: marimo-dataframe download_geojson input accepted by a plugin
+ consumer.
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/marimo-dataframe.download_geojson.input"
+ put:
+ operationId: write_marimo_dataframe_download_geojson_input
+ summary: Write marimo-dataframe download_geojson input
+ tags:
+ - rpc-input
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/marimo-dataframe.download_geojson.input"
+ responses:
+ "204":
+ description: Accepted.
+ /plugins/marimo-dataframe/functions/download_geojson/output:
+ summary: marimo-dataframe download_geojson output
+ get:
+ operationId: read_marimo_dataframe_download_geojson_output
+ summary: Read marimo-dataframe download_geojson output
+ tags:
+ - rpc-output
+ responses:
+ "200":
+ description: marimo-dataframe download_geojson output accepted by a plugin
+ consumer.
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/marimo-dataframe.download_geojson.output"
+ put:
+ operationId: write_marimo_dataframe_download_geojson_output
+ summary: Write marimo-dataframe download_geojson output
+ tags:
+ - rpc-output
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/marimo-dataframe.download_geojson.output"
+ responses:
+ "204":
+ description: Accepted.
/plugins/marimo-dataframe/functions/get_column_values/input:
summary: marimo-dataframe get_column_values input
get:
@@ -2269,6 +2327,62 @@ paths:
responses:
"204":
description: Accepted.
+ /plugins/marimo-table/functions/download_geojson/input:
+ summary: marimo-table download_geojson input
+ get:
+ operationId: read_marimo_table_download_geojson_input
+ summary: Read marimo-table download_geojson input
+ tags:
+ - rpc-input
+ responses:
+ "200":
+ description: marimo-table download_geojson input accepted by a plugin consumer.
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/marimo-table.download_geojson.input"
+ put:
+ operationId: write_marimo_table_download_geojson_input
+ summary: Write marimo-table download_geojson input
+ tags:
+ - rpc-input
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/marimo-table.download_geojson.input"
+ responses:
+ "204":
+ description: Accepted.
+ /plugins/marimo-table/functions/download_geojson/output:
+ summary: marimo-table download_geojson output
+ get:
+ operationId: read_marimo_table_download_geojson_output
+ summary: Read marimo-table download_geojson output
+ tags:
+ - rpc-output
+ responses:
+ "200":
+ description: marimo-table download_geojson output accepted by a plugin consumer.
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/marimo-table.download_geojson.output"
+ put:
+ operationId: write_marimo_table_download_geojson_output
+ summary: Write marimo-table download_geojson output
+ tags:
+ - rpc-output
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/marimo-table.download_geojson.output"
+ responses:
+ "204":
+ description: Accepted.
/plugins/marimo-table/functions/get_column_summaries/input:
summary: marimo-table get_column_summaries input
get:
@@ -3258,13 +3372,6 @@ components:
marimo-dataframe.download_as.input:
type: object
properties:
- format:
- type: string
- enum:
- - csv
- - json
- - parquet
- - tsv
geometry_column:
type:
- string
@@ -3278,6 +3385,13 @@ components:
type: string
ensure_ascii:
type: boolean
+ format:
+ type: string
+ enum:
+ - csv
+ - json
+ - parquet
+ - tsv
required:
- format
marimo-dataframe.download_as.output:
@@ -3316,6 +3430,66 @@ components:
required:
- url
- filename
+ marimo-dataframe.download_geojson.input:
+ type: object
+ properties:
+ geometry_column:
+ type:
+ - string
+ - "null"
+ options:
+ type: object
+ properties:
+ separator:
+ type: string
+ encoding:
+ type: string
+ ensure_ascii:
+ type: boolean
+ format:
+ type: string
+ const: geojson
+ required:
+ - format
+ marimo-dataframe.download_geojson.output:
+ type: object
+ properties:
+ url:
+ type: string
+ filename:
+ type: string
+ error:
+ type:
+ - string
+ - "null"
+ missing_packages:
+ anyOf:
+ - type: array
+ items:
+ type: string
+ - type: "null"
+ code:
+ anyOf:
+ - anyOf:
+ - type: string
+ enum:
+ - geometry_required
+ - invalid_geometry
+ - invalid_metadata
+ - unsupported_representation
+ - unsupported_version
+ - missing_packages
+ - conversion_failed
+ - type: "null"
+ - type: string
+ const: missing_crs
+ column:
+ type:
+ - string
+ - "null"
+ required:
+ - url
+ - filename
marimo-dataframe.get_column_values.input:
type: object
properties:
@@ -4836,13 +5010,6 @@ components:
marimo-table.download_as.input:
type: object
properties:
- format:
- type: string
- enum:
- - csv
- - json
- - parquet
- - tsv
geometry_column:
type:
- string
@@ -4856,6 +5023,13 @@ components:
type: string
ensure_ascii:
type: boolean
+ format:
+ type: string
+ enum:
+ - csv
+ - json
+ - parquet
+ - tsv
required:
- format
marimo-table.download_as.output:
@@ -4894,6 +5068,66 @@ components:
required:
- url
- filename
+ marimo-table.download_geojson.input:
+ type: object
+ properties:
+ geometry_column:
+ type:
+ - string
+ - "null"
+ options:
+ type: object
+ properties:
+ separator:
+ type: string
+ encoding:
+ type: string
+ ensure_ascii:
+ type: boolean
+ format:
+ type: string
+ const: geojson
+ required:
+ - format
+ marimo-table.download_geojson.output:
+ type: object
+ properties:
+ url:
+ type: string
+ filename:
+ type: string
+ error:
+ type:
+ - string
+ - "null"
+ missing_packages:
+ anyOf:
+ - type: array
+ items:
+ type: string
+ - type: "null"
+ code:
+ anyOf:
+ - anyOf:
+ - type: string
+ enum:
+ - geometry_required
+ - invalid_geometry
+ - invalid_metadata
+ - unsupported_representation
+ - unsupported_version
+ - missing_packages
+ - conversion_failed
+ - type: "null"
+ - type: string
+ const: missing_crs
+ column:
+ type:
+ - string
+ - "null"
+ required:
+ - url
+ - filename
marimo-table.get_column_summaries.input:
type: object
properties: {}
diff --git a/frontend/src/components/data-table/__tests__/export-actions.test.tsx b/frontend/src/components/data-table/__tests__/export-actions.test.tsx
index 695dc2de36..e009fd378a 100644
--- a/frontend/src/components/data-table/__tests__/export-actions.test.tsx
+++ b/frontend/src/components/data-table/__tests__/export-actions.test.tsx
@@ -96,6 +96,7 @@ const geometryMetadata: ExportMetadata = {
default_geometry_column: "location",
formats: {
parquet: { available: true, reason: null, missing_packages: [] },
+ geojson: { available: true, reason: null, missing_packages: [] },
},
};
@@ -1183,3 +1184,576 @@ describe("ExportActions clipboard geometry", () => {
},
);
});
+
+describe("ExportActions GeoJSON", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ downloadAs.mockResolvedValue({
+ url: "https://example.test/export",
+ filename: "table.source",
+ });
+ });
+
+ const metadataWithCrs: ExportMetadata = {
+ ...geometryMetadata,
+ geometry_columns: [
+ geometryMetadata.geometry_columns[0],
+ { name: "boundary", encoding: "objects", crs: "EPSG:3857" },
+ ],
+ };
+
+ it("hides GeoJSON for ordinary sources", async () => {
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue({
+ geometry_columns: [],
+ primary_geometry_column: null,
+ default_geometry_column: null,
+ formats: {},
+ }),
+ });
+ await openDialog();
+ expect(screen.queryByTestId("export-row-geojson")).not.toBeInTheDocument();
+ });
+
+ it("downloads GeoJSON without PyArrow", async () => {
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue({
+ ...geometryMetadata,
+ formats: {
+ ...geometryMetadata.formats,
+ parquet: {
+ available: false,
+ reason: "GeoParquet export requires pyarrow.",
+ missing_packages: ["pyarrow"],
+ },
+ },
+ }),
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Download GeoJSON" }),
+ );
+ expect(screen.getByRole("button", { name: "Copy GeoJSON" })).toBeEnabled();
+ await waitFor(() => {
+ expect(downloadByURL).toHaveBeenCalledWith(
+ "https://example.test/export?download=1&filename=table.geojson",
+ "table.geojson",
+ );
+ });
+ expect(downloadAs).toHaveBeenCalledWith({
+ format: "geojson",
+ geometry_column: "location",
+ });
+ expect(copyToClipboard).not.toHaveBeenCalled();
+ });
+
+ it("shares the geometry choice and disables only GeoJSON for a missing CRS", async () => {
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue(geometryMetadata),
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "GeoJSON options" }),
+ );
+ expect(
+ screen.getByRole("group", { name: "GeoJSON options" }),
+ ).toHaveTextContent(/longitude and latitude/);
+ expect(
+ screen.getByRole("group", { name: "GeoJSON options" }),
+ ).toHaveTextContent(/complete WKT/);
+ selectGeometry("boundary");
+ expect(
+ screen.getByRole("button", { name: "Download GeoJSON" }),
+ ).toBeDisabled();
+ expect(
+ screen.getByRole("button", { name: "Download GeoParquet" }),
+ ).toBeEnabled();
+ expect(screen.getByRole("button", { name: "Download JSON" })).toBeEnabled();
+ expect(screen.getByRole("button", { name: "Download CSV" })).toBeEnabled();
+ expect(screen.getByTestId("export-row-geojson")).toHaveTextContent(
+ "Declare its source CRS in Python",
+ );
+ fireEvent.click(screen.getByRole("button", { name: "GeoParquet options" }));
+ expect(
+ screen.getByRole("combobox", { name: "Primary geometry" }),
+ ).toHaveDisplayValue("boundary");
+ selectGeometry("location");
+ expect(
+ screen.getByRole("button", { name: "Download GeoJSON" }),
+ ).toBeEnabled();
+ expect(screen.getByTestId("export-summary-geojson")).toHaveTextContent(
+ "location",
+ );
+ });
+
+ it("allows a known-CRS alternative when the default has no CRS", async () => {
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue({
+ ...geometryMetadata,
+ default_geometry_column: "boundary",
+ primary_geometry_column: "boundary",
+ }),
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "GeoJSON options" }),
+ );
+ expect(
+ screen.getByRole("button", { name: "Download GeoJSON" }),
+ ).toBeDisabled();
+ selectGeometry("location");
+ fireEvent.click(screen.getByRole("button", { name: "Download GeoJSON" }));
+ await waitFor(() =>
+ expect(downloadAs).toHaveBeenCalledWith({
+ format: "geojson",
+ geometry_column: "location",
+ }),
+ );
+ });
+
+ it("requires a choice for ambiguous sources", async () => {
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue({
+ ...metadataWithCrs,
+ primary_geometry_column: null,
+ default_geometry_column: null,
+ }),
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "GeoJSON options" }),
+ );
+ expect(
+ screen.getByRole("button", { name: "Download GeoJSON" }),
+ ).toBeDisabled();
+ selectGeometry("boundary");
+ fireEvent.click(screen.getByRole("button", { name: "Download GeoJSON" }));
+ await waitFor(() =>
+ expect(downloadAs).toHaveBeenCalledWith({
+ format: "geojson",
+ geometry_column: "boundary",
+ }),
+ );
+ });
+
+ it("preserves an empty geometry name", async () => {
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue({
+ ...geometryMetadata,
+ geometry_columns: [{ name: "", encoding: "objects", crs: "EPSG:4326" }],
+ primary_geometry_column: "",
+ default_geometry_column: "",
+ }),
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Download GeoJSON" }),
+ );
+ await waitFor(() =>
+ expect(downloadAs).toHaveBeenCalledWith({
+ format: "geojson",
+ geometry_column: "",
+ }),
+ );
+ });
+
+ it.each(["missing_crs", "conversion_failed"] as const)(
+ "keeps choices after %s and retries",
+ async (code) => {
+ downloadAs.mockResolvedValueOnce({
+ url: "",
+ filename: "",
+ code,
+ error: "Geometry export failed.",
+ });
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue(metadataWithCrs),
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "GeoJSON options" }),
+ );
+ selectGeometry("boundary");
+ fireEvent.click(screen.getByRole("button", { name: "Download GeoJSON" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Geometry export failed.",
+ );
+ expect(downloadByURL).not.toHaveBeenCalled();
+ expect(
+ screen.getByRole("combobox", { name: "Primary geometry" }),
+ ).toHaveDisplayValue("boundary");
+ fireEvent.click(screen.getByRole("button", { name: "Download GeoJSON" }));
+ await waitFor(() => expect(downloadByURL).toHaveBeenCalled());
+ expect(downloadAs).toHaveBeenLastCalledWith({
+ format: "geojson",
+ geometry_column: "boundary",
+ });
+ },
+ );
+
+ it("refreshes metadata and keeps the geometry choice after installation", async () => {
+ const getExportMetadata = vi.fn().mockResolvedValue(metadataWithCrs);
+ downloadAs.mockResolvedValueOnce({
+ url: "",
+ filename: "",
+ code: "missing_packages",
+ error: "GeoJSON requires geopandas.",
+ missing_packages: ["geopandas"],
+ });
+ renderExportActions({ getExportMetadata });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "GeoJSON options" }),
+ );
+ selectGeometry("boundary");
+ fireEvent.click(screen.getByRole("button", { name: "Download GeoJSON" }));
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Install geopandas" }),
+ );
+ await act(async () => mocks.handleInstallPackages.mock.calls[0][1]());
+ await waitFor(() => expect(downloadByURL).toHaveBeenCalled());
+ expect(getExportMetadata).toHaveBeenCalledTimes(2);
+ expect(downloadAs).toHaveBeenLastCalledWith({
+ format: "geojson",
+ geometry_column: "boundary",
+ });
+ });
+
+ it.each(["missing-package", "missing-crs", "obsolete-choice"] as const)(
+ "does not retry after installation with %s",
+ async (prerequisite) => {
+ const getExportMetadata = vi.fn().mockResolvedValue(metadataWithCrs);
+ downloadAs.mockResolvedValueOnce({
+ url: "",
+ filename: "",
+ code: "missing_packages",
+ missing_packages: ["geopandas"],
+ });
+ renderExportActions({ getExportMetadata });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "GeoJSON options" }),
+ );
+ selectGeometry("boundary");
+ fireEvent.click(screen.getByRole("button", { name: "Download GeoJSON" }));
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Install geopandas" }),
+ );
+ getExportMetadata.mockResolvedValue(
+ prerequisite === "missing-package"
+ ? {
+ ...metadataWithCrs,
+ formats: {
+ geojson: {
+ available: false,
+ reason: "GeoJSON requires geopandas.",
+ missing_packages: ["geopandas"],
+ },
+ },
+ }
+ : prerequisite === "missing-crs"
+ ? geometryMetadata
+ : {
+ ...geometryMetadata,
+ geometry_columns: [geometryMetadata.geometry_columns[0]],
+ },
+ );
+ await act(async () => mocks.handleInstallPackages.mock.calls[0][1]());
+ expect(downloadAs).toHaveBeenCalledTimes(1);
+ expect(downloadByURL).not.toHaveBeenCalled();
+ expect(screen.queryByRole("alert") !== null).toBe(
+ prerequisite === "obsolete-choice",
+ );
+ expect(
+ screen.getByRole("combobox", { name: "Primary geometry" }),
+ ).toHaveDisplayValue(
+ prerequisite === "obsolete-choice" ? "location" : "boundary",
+ );
+ expect(
+ screen.getByRole("button", { name: "Download GeoJSON" }),
+ ).toHaveProperty("disabled", prerequisite !== "obsolete-choice");
+ },
+ );
+
+ it("rejects an obsolete choice after a source change", async () => {
+ const getExportMetadata = vi.fn().mockResolvedValue(metadataWithCrs);
+ const { rerenderExportActions } = renderExportActions({
+ getExportMetadata,
+ metadataSource: "first",
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "GeoJSON options" }),
+ );
+ selectGeometry("boundary");
+ getExportMetadata.mockResolvedValue({
+ ...geometryMetadata,
+ geometry_columns: [geometryMetadata.geometry_columns[0]],
+ });
+ rerenderExportActions({ getExportMetadata, metadataSource: "second" });
+ await waitFor(() =>
+ expect(screen.getByTestId("export-summary-geojson")).toHaveTextContent(
+ "location",
+ ),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Download GeoJSON" }));
+ await waitFor(() =>
+ expect(downloadAs).toHaveBeenCalledWith({
+ format: "geojson",
+ geometry_column: "location",
+ }),
+ );
+ });
+
+ it("keeps a WASM data URL unchanged", async () => {
+ downloadAs.mockResolvedValue({
+ url: "data:application/geo+json;base64,e30=",
+ filename: "table",
+ });
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue(geometryMetadata),
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Download GeoJSON" }),
+ );
+ await waitFor(() =>
+ expect(downloadByURL).toHaveBeenCalledWith(
+ "data:application/geo+json;base64,e30=",
+ "table.geojson",
+ ),
+ );
+ });
+
+ it("hides package installation in read mode", async () => {
+ renderExportActions(
+ {
+ getExportMetadata: vi.fn().mockResolvedValue({
+ ...geometryMetadata,
+ formats: {
+ geojson: {
+ available: false,
+ reason: "GeoJSON requires geopandas.",
+ missing_packages: ["geopandas"],
+ },
+ },
+ }),
+ },
+ null,
+ "read",
+ );
+ await openDialog();
+ expect(
+ await screen.findByText(
+ "GeoJSON export isn't available in this notebook",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole("button", { name: /Install/ }),
+ ).not.toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Download GeoJSON" }),
+ ).toBeDisabled();
+ });
+
+ it("respects the host size limit for geometry sources", () => {
+ renderExportActions(
+ {
+ getExportMetadata: vi.fn().mockResolvedValue(geometryMetadata),
+ sizeBytes: 101,
+ },
+ { limitBytes: 100, unavailableMessage: "Export is too large." },
+ );
+ expect(screen.getByTestId("export-button")).toBeDisabled();
+ fireEvent.click(screen.getByTestId("export-button"));
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(downloadAs).not.toHaveBeenCalled();
+ });
+});
+
+describe("ExportActions GeoJSON clipboard", () => {
+ const metadata: ExportMetadata = {
+ ...geometryMetadata,
+ geometry_columns: [
+ geometryMetadata.geometry_columns[0],
+ { name: "boundary", encoding: "objects", crs: "EPSG:3857" },
+ ],
+ };
+ const payload = `{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"Point","coordinates":[20,5]},"properties":{"large":9007199254740993,"secondary":${JSON.stringify(LONG_GEOMETRY_WKT)}}}]}`;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ downloadAs.mockResolvedValue({
+ url: "https://example.test/export",
+ filename: "table.geojson",
+ });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn().mockResolvedValue({
+ ok: true,
+ text: vi.fn().mockResolvedValue(payload),
+ }),
+ );
+ });
+
+ afterEach(() => vi.unstubAllGlobals());
+
+ it("copies the exact FeatureCollection with the selected geometry", async () => {
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue(metadata),
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "GeoJSON options" }),
+ );
+ selectGeometry("boundary");
+ fireEvent.click(screen.getByRole("button", { name: "Copy GeoJSON" }));
+ await waitFor(() => expect(copyToClipboard).toHaveBeenCalledWith(payload));
+ expect(downloadAs).toHaveBeenCalledWith({
+ format: "geojson",
+ geometry_column: "boundary",
+ });
+ expect(downloadByURL).not.toHaveBeenCalled();
+ expect(toast).toHaveBeenCalledWith({ title: "Copied to clipboard" });
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it.each([
+ { name: "a missing CRS", metadata: geometryMetadata, choice: "boundary" },
+ {
+ name: "an ambiguous geometry",
+ metadata: {
+ ...metadata,
+ primary_geometry_column: null,
+ default_geometry_column: null,
+ },
+ choice: null,
+ },
+ {
+ name: "missing packages",
+ metadata: {
+ ...metadata,
+ formats: {
+ geojson: {
+ available: false,
+ reason: "Install geopandas.",
+ missing_packages: ["geopandas"],
+ },
+ },
+ },
+ choice: "location",
+ },
+ ])("disables copy for $name", async ({ metadata, choice }) => {
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue(metadata),
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "GeoJSON options" }),
+ );
+ if (choice !== null) {
+ selectGeometry(choice);
+ }
+ expect(screen.getByRole("button", { name: "Copy GeoJSON" })).toBeDisabled();
+ fireEvent.click(screen.getByRole("button", { name: "Copy GeoJSON" }));
+ expect(downloadAs).not.toHaveBeenCalled();
+ expect(copyToClipboard).not.toHaveBeenCalled();
+ });
+
+ it("preserves the copy destination and geometry after installation", async () => {
+ downloadAs.mockResolvedValueOnce({
+ url: "",
+ filename: "",
+ code: "missing_packages",
+ missing_packages: ["geopandas"],
+ });
+ const getExportMetadata = vi.fn().mockResolvedValue(metadata);
+ renderExportActions({ getExportMetadata });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "GeoJSON options" }),
+ );
+ selectGeometry("boundary");
+ fireEvent.click(screen.getByRole("button", { name: "Copy GeoJSON" }));
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Install geopandas" }),
+ );
+ expect(copyToClipboard).not.toHaveBeenCalled();
+ await act(async () => mocks.handleInstallPackages.mock.calls[0][1]());
+ await waitFor(() => expect(copyToClipboard).toHaveBeenCalledWith(payload));
+ expect(downloadAs).toHaveBeenLastCalledWith({
+ format: "geojson",
+ geometry_column: "boundary",
+ });
+ expect(getExportMetadata).toHaveBeenCalledTimes(2);
+ expect(downloadByURL).not.toHaveBeenCalled();
+ });
+
+ it("preserves the choice after a backend failure", async () => {
+ downloadAs.mockResolvedValueOnce({
+ url: "",
+ filename: "",
+ code: "conversion_failed",
+ error: "Invalid geometry.",
+ });
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue(metadata),
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "GeoJSON options" }),
+ );
+ selectGeometry("boundary");
+ fireEvent.click(screen.getByRole("button", { name: "Copy GeoJSON" }));
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "Failed to copy to clipboard",
+ );
+ expect(copyToClipboard).not.toHaveBeenCalled();
+ expect(
+ screen.getByRole("combobox", { name: "Primary geometry" }),
+ ).toHaveDisplayValue("boundary");
+ fireEvent.click(screen.getByRole("button", { name: "Copy GeoJSON" }));
+ await waitFor(() => expect(copyToClipboard).toHaveBeenCalledWith(payload));
+ });
+
+ it("reports clipboard rejection in the GeoJSON row", async () => {
+ vi.mocked(copyToClipboard).mockRejectedValueOnce(
+ new Error("Clipboard blocked"),
+ );
+ renderExportActions({
+ getExportMetadata: vi.fn().mockResolvedValue(metadata),
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Copy GeoJSON" }),
+ );
+ const alert = await screen.findByRole("alert");
+ expect(screen.getByTestId("export-row-geojson")).toContainElement(alert);
+ expect(alert).toHaveTextContent("Clipboard blocked");
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ });
+
+ it("does not copy a late response after the source changes", async () => {
+ let resolveText: (value: string) => void = () => undefined;
+ const text = vi.fn().mockReturnValue(
+ new Promise<string>((resolve) => {
+ resolveText = resolve;
+ }),
+ );
+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({ ok: true, text }));
+ const getExportMetadata = vi.fn().mockResolvedValue(metadata);
+ const { rerenderExportActions } = renderExportActions({
+ getExportMetadata,
+ metadataSource: "first",
+ });
+ await openDialog();
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Copy GeoJSON" }),
+ );
+ await waitFor(() => expect(text).toHaveBeenCalled());
+ rerenderExportActions({ getExportMetadata, metadataSource: "second" });
+ await act(async () => resolveText(payload));
+ expect(copyToClipboard).not.toHaveBeenCalled();
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ });
+});
diff --git a/frontend/src/components/data-table/__tests__/schemas.test.ts b/frontend/src/components/data-table/__tests__/schemas.test.ts
new file mode 100644
index 0000000000..6289b8f5f3
--- /dev/null
+++ b/frontend/src/components/data-table/__tests__/schemas.test.ts
@@ -0,0 +1,57 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { describe, expect, it } from "vitest";
+import {
+ DownloadAsSchema,
+ DownloadGeoJSONSchema,
+ GetExportMetadataSchema,
+} from "../schemas";
+
+describe("geometry export contracts", () => {
+ it("keeps the existing download_as formats unchanged", () => {
+ for (const format of ["csv", "tsv", "json", "parquet"]) {
+ expect(DownloadAsSchema.input.parse({ format })).toEqual({ format });
+ }
+ expect(
+ DownloadAsSchema.input.safeParse({ format: "geojson" }).success,
+ ).toBe(false);
+ });
+ it.each([undefined, "geom_b", ""])(
+ "accepts a GeoJSON request with geometry %s",
+ (geometry_column) => {
+ const request = { format: "geojson", geometry_column };
+ expect(DownloadGeoJSONSchema.input.parse(request)).toEqual(request);
+ },
+ );
+
+ it("accepts a missing CRS response for an unnamed geometry", () => {
+ const response = {
+ url: "",
+ filename: "",
+ code: "missing_crs",
+ column: "",
+ error: "Declare a CRS.",
+ };
+ expect(DownloadGeoJSONSchema.output.parse(response)).toEqual(response);
+ });
+
+ it("accepts GeoJSON support when the default geometry has no CRS", () => {
+ const metadata = {
+ geometry_columns: [
+ { name: "", encoding: "objects", crs: null },
+ { name: "alternate", encoding: "objects", crs: "EPSG:4326" },
+ ],
+ primary_geometry_column: "",
+ default_geometry_column: "",
+ formats: {
+ geojson: { available: true, reason: null, missing_packages: [] },
+ parquet: {
+ available: false,
+ reason: "GeoParquet export requires pyarrow.",
+ missing_packages: ["pyarrow"],
+ },
+ },
+ };
+ expect(GetExportMetadataSchema.output.parse(metadata)).toEqual(metadata);
+ });
+});
diff --git a/frontend/src/components/data-table/export-actions.tsx b/frontend/src/components/data-table/export-actions.tsx
index 5047d30711..3e55f962cb 100644
--- a/frontend/src/components/data-table/export-actions.tsx
+++ b/frontend/src/components/data-table/export-actions.tsx
@@ -10,6 +10,7 @@ import {
DownloadIcon,
FileTextIcon,
InfoIcon,
+ MapIcon,
TableIcon,
} from "lucide-react";
import React from "react";
@@ -81,6 +82,14 @@ const EXPORT_OPTIONS = [
canDownload: true,
canCopy: false,
},
+ {
+ label: "GeoJSON",
+ format: "geojson",
+ description: "Geometry in longitude and latitude",
+ icon: MapIcon,
+ canDownload: true,
+ canCopy: true,
+ },
{
label: "Markdown",
format: "markdown",
@@ -93,6 +102,10 @@ const EXPORT_OPTIONS = [
type ExportFormat = (typeof EXPORT_OPTIONS)[number]["format"];
type CopyFormat = Exclude<ExportFormat, "parquet">;
+type GeographicFormat = "parquet" | "geojson";
+
+const isGeographic = (format: ExportFormat): format is GeographicFormat =>
+ format === "parquet" || format === "geojson";
type ExportAction =
| { destination: "download"; format: DownloadFormat }
| { destination: "copy"; format: CopyFormat };
@@ -117,6 +130,7 @@ const COPY_SOURCE_FORMAT: Record<CopyFormat, DownloadFormat> = {
csv: "csv",
tsv: "tsv",
json: "json",
+ geojson: "geojson",
markdown: "json",
};
@@ -191,6 +205,7 @@ function requestOptions(
}
break;
case "parquet":
+ case "geojson":
break;
default:
logNever(format);
@@ -221,6 +236,7 @@ function settingsSummary(
? "Escapes non-ASCII"
: "Keeps non-ASCII";
case "parquet":
+ case "geojson":
case "markdown":
return null;
default:
@@ -241,7 +257,10 @@ export interface ExportActionProps {
sizeBytesIsLoading?: boolean;
}
-const labelForFormat = (format: ExportFormat, hasGeometry = false): string =>
+const labelForFormat = (
+ format: ExportFormat | DownloadFormat,
+ hasGeometry = false,
+): string =>
format === "parquet" && hasGeometry
? "GeoParquet"
: (EXPORT_OPTIONS.find((option) => option.format === format)?.label ??
@@ -270,7 +289,7 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
);
const hasGeometry = !!metadata?.geometry_columns.length;
const [expandedFormat, setExpandedFormat] = React.useState<
- ConfigurableFormat | "parquet" | null
+ ConfigurableFormat | GeographicFormat | null
>(null);
const triggerRef = React.useRef<HTMLButtonElement>(null);
const dialogRef = React.useRef<HTMLDivElement>(null);
@@ -380,7 +399,7 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
const request = {
format,
...(options ? { options } : {}),
- ...(format === "parquet" && geometryColumn !== null
+ ...(isGeographic(format) && geometryColumn !== null
? { geometry_column: geometryColumn }
: {}),
};
@@ -481,6 +500,7 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
switch (format) {
case "tsv":
case "csv":
+ case "geojson":
text = await fetchText(result.url);
break;
case "json": {
@@ -498,6 +518,9 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
return;
}
+ if (actionId !== latestActionId.current) {
+ return;
+ }
await copyToClipboard(text);
toast({
title: "Copied to clipboard",
@@ -531,7 +554,7 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
};
const retryAfterInstall = async (action: ExportAction) => {
- if (action.format === "parquet" && getExportMetadata) {
+ if (isGeographic(action.format) && getExportMetadata) {
const actionId = latestActionId.current;
let result: ExportMetadata;
try {
@@ -547,7 +570,7 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
}
setMetadata(result);
setMetadataError(null);
- if (result.formats.parquet?.available === false) {
+ if (result.formats[action.format]?.available === false) {
setFailure(null);
return;
}
@@ -570,15 +593,21 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
if (result.geometry_columns.length > 0 && geometryColumn === null) {
return;
}
+ if (
+ action.format === "geojson" &&
+ !result.geometry_columns.find(
+ (column) => column.name === geometryColumn,
+ )?.crs
+ ) {
+ setFailure(null);
+ return;
+ }
}
retryAction(action);
};
const toggleExpanded = (format: ExportFormat) => {
- if (
- !isConfigurable(format) &&
- !(format === "parquet" && metadata?.geometry_columns.length)
- ) {
+ if (!isConfigurable(format) && !(isGeographic(format) && hasGeometry)) {
return;
}
setExpandedFormat((current) => (current === format ? null : format));
@@ -624,12 +653,13 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
aria-label="Export formats"
className="list-none overflow-hidden rounded-md border divide-y"
>
- {EXPORT_OPTIONS.map((option) => {
+ {EXPORT_OPTIONS.filter(
+ (option) => option.format !== "geojson" || hasGeometry,
+ ).map((option) => {
const optionLabel = labelForFormat(option.format, hasGeometry);
const configurableFormat =
isConfigurable(option.format) ||
- (option.format === "parquet" &&
- !!metadata?.geometry_columns.length)
+ (isGeographic(option.format) && hasGeometry)
? option.format
: null;
const expanded =
@@ -639,7 +669,7 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
const rowFailure =
failure?.action.format === option.format ? failure : null;
const summary =
- option.format === "parquet" && metadata?.geometry_columns.length
+ isGeographic(option.format) && hasGeometry
? geometryColumn === ""
? "(unnamed geometry)"
: (geometryColumn ?? "Choose geometry")
@@ -648,25 +678,42 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
metadata?.geometry_columns.findIndex(
(column) => column.name === geometryColumn,
) ?? -1;
- const parquetEligibility =
- option.format === "parquet"
- ? metadata?.formats.parquet
- : undefined;
+ const eligibility = isGeographic(option.format)
+ ? metadata?.formats[option.format]
+ : undefined;
+ const selectedGeometry =
+ metadata?.geometry_columns[selectedGeometryIndex];
+ const missingCrs =
+ option.format === "geojson" &&
+ selectedGeometry !== undefined &&
+ !selectedGeometry.crs;
+ const geometryReason = metadataError
+ ? `Could not load geometry options: ${metadataError}`
+ : (eligibility?.reason ??
+ (hasGeometry && geometryColumn === null
+ ? `Choose a primary geometry column to export ${optionLabel}.`
+ : missingCrs
+ ? `Geometry column ${geometryColumn === "" ? "(unnamed geometry)" : geometryColumn} needs a CRS for GeoJSON export. Declare its source CRS in Python before exporting.`
+ : null));
const missingPackageFailure =
rowFailure?.kind === "missing-packages" ? rowFailure : null;
const missingPackages =
missingPackageFailure?.packages ??
- (parquetEligibility?.available === false
- ? parquetEligibility.missing_packages
+ (eligibility?.available === false
+ ? eligibility.missing_packages
: []);
- const parquetUnavailable =
- option.format === "parquet" &&
+ const geographicUnavailable =
+ isGeographic(option.format) &&
((!!getExportMetadata && !metadata) ||
metadataLoading ||
!!metadataError ||
- parquetEligibility?.available === false ||
+ eligibility?.available === false ||
+ missingCrs ||
(!!metadata?.geometry_columns.length &&
geometryColumn === null));
+ const copyUnavailable =
+ isGeographic(option.format) &&
+ (geographicUnavailable || missingPackages.length > 0);
return (
<li
key={option.format}
@@ -737,12 +784,12 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
aria-label={`Download ${optionLabel}`}
disabled={
!option.canDownload ||
- parquetUnavailable ||
+ geographicUnavailable ||
missingPackages.length > 0
}
onClick={
option.canDownload &&
- !parquetUnavailable &&
+ !geographicUnavailable &&
missingPackages.length === 0
? () => {
void handleDownload(option.format);
@@ -767,9 +814,9 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
variant="ghost"
size="icon"
aria-label={`Copy ${optionLabel}`}
- disabled={!option.canCopy}
+ disabled={!option.canCopy || copyUnavailable}
onClick={
- option.canCopy
+ option.canCopy && !copyUnavailable
? () => {
void handleCopyAction(option.format);
}
@@ -788,11 +835,18 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
className="grid grid-cols-2 gap-3 border-t bg-muted/50 px-3.5 py-3.5 pl-[52px]"
>
<legend className="sr-only">{optionLabel} options</legend>
- {configurableFormat === "parquet" ? (
+ {isGeographic(configurableFormat) && (
+ <p className="col-span-2 text-xs text-muted-foreground">
+ {configurableFormat === "geojson"
+ ? "Reproject the selected geometry to longitude and latitude (WGS 84). Keep other geometry columns as complete WKT in their source coordinates."
+ : "Use the selected column as the primary geometry. Preserve all geometry columns and their coordinate reference systems (CRS)."}
+ </p>
+ )}
+ {isGeographic(configurableFormat) ? (
<SettingField
id="export-primary-geometry"
label="Primary geometry"
- help="Geometry column to use as the primary geometry in the GeoParquet file."
+ help={`Geometry column to use as the primary geometry in the ${optionLabel} file.`}
>
<NativeSelect
id="export-primary-geometry"
@@ -824,19 +878,11 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
)}
</fieldset>
)}
- {option.format === "parquet" &&
+ {isGeographic(option.format) &&
missingPackages.length === 0 &&
- (parquetEligibility?.reason ||
- metadataError ||
- (!!metadata?.geometry_columns.length &&
- geometryColumn === null)) && (
+ geometryReason && (
<div className="flex items-center justify-between gap-2 border-t px-3 py-2 pl-[42px] text-xs text-muted-foreground">
- <span>
- {metadataError
- ? `Could not load geometry options: ${metadataError}`
- : (parquetEligibility?.reason ??
- "Choose a primary geometry column to export GeoParquet.")}
- </span>
+ <span>{geometryReason}</span>
{metadataError && (
<Button
type="button"
@@ -858,13 +904,16 @@ export const ExportActions: React.FC<ExportActionProps> = (props) => {
featureName={`${optionLabel} export`}
description={
missingPackageFailure?.description ??
- parquetEligibility?.reason
+ eligibility?.reason
}
onInstall={() => {
void retryAfterInstall(
missingPackageFailure?.action ?? {
destination: "download",
- format: "parquet",
+ format:
+ option.format === "geojson"
+ ? "geojson"
+ : "parquet",
},
);
}}
diff --git a/frontend/src/components/data-table/schemas.ts b/frontend/src/components/data-table/schemas.ts
index 99ef318488..1e41b0703c 100644
--- a/frontend/src/components/data-table/schemas.ts
+++ b/frontend/src/components/data-table/schemas.ts
@@ -3,7 +3,7 @@
import z from "zod";
import { rpc } from "@/plugins/core/rpc";
-export type DownloadFormat = "csv" | "json" | "parquet" | "tsv";
+export type DownloadFormat = "csv" | "json" | "parquet" | "tsv" | "geojson";
/**
* Per-request export options. Each field is optional. A missing field keeps
@@ -33,46 +33,69 @@ export type DownloadAsArgs = (req: DownloadAsRequest) => Promise<{
| "unsupported_representation"
| "unsupported_version"
| "missing_packages"
+ | "missing_crs"
| "conversion_failed"
| null;
column?: string | null;
}>;
+const DownloadRequestSchema = z.object({
+ geometry_column: z.string().nullish(),
+ options: z
+ .object({
+ separator: z.string().optional(),
+ encoding: z.string().optional(),
+ ensure_ascii: z.boolean().optional(),
+ })
+ .optional(),
+});
+
+const DownloadResponseSchema = z.object({
+ url: z.string(),
+ filename: z.string(),
+ error: z.string().nullish(),
+ missing_packages: z.array(z.string()).nullish(),
+ code: z
+ .enum([
+ "geometry_required",
+ "invalid_geometry",
+ "invalid_metadata",
+ "unsupported_representation",
+ "unsupported_version",
+ "missing_packages",
+ "conversion_failed",
+ ])
+ .nullish(),
+ column: z.string().nullish(),
+});
+
export const DownloadAsSchema = rpc
.input(
- z.object({
+ DownloadRequestSchema.extend({
format: z.enum(["csv", "json", "parquet", "tsv"]),
- geometry_column: z.string().nullish(),
- options: z
- .object({
- separator: z.string().optional(),
- encoding: z.string().optional(),
- ensure_ascii: z.boolean().optional(),
- })
- .optional(),
}),
)
+ .output(DownloadResponseSchema);
+
+export const DownloadGeoJSONSchema = rpc
+ .input(DownloadRequestSchema.extend({ format: z.literal("geojson") }))
.output(
- z.object({
- url: z.string(),
- filename: z.string(),
- error: z.string().nullish(),
- missing_packages: z.array(z.string()).nullish(),
- code: z
- .enum([
- "geometry_required",
- "invalid_geometry",
- "invalid_metadata",
- "unsupported_representation",
- "unsupported_version",
- "missing_packages",
- "conversion_failed",
- ])
- .nullish(),
- column: z.string().nullish(),
+ DownloadResponseSchema.extend({
+ code: z.union([
+ DownloadResponseSchema.shape.code,
+ z.literal("missing_crs"),
+ ]),
}),
);
+export type DownloadAsFunction = (
+ req: z.infer<typeof DownloadAsSchema.input>,
+) => Promise<z.infer<typeof DownloadAsSchema.output>>;
+
+export type DownloadGeoJSON = (
+ req: z.infer<typeof DownloadGeoJSONSchema.input>,
+) => Promise<z.infer<typeof DownloadGeoJSONSchema.output>>;
+
const ExportMetadataSchema = z.object({
geometry_columns: z.array(
z.object({
diff --git a/frontend/src/plugins/impl/DataTablePlugin.tsx b/frontend/src/plugins/impl/DataTablePlugin.tsx
index c21dcab556..0f015faadd 100644
--- a/frontend/src/plugins/impl/DataTablePlugin.tsx
+++ b/frontend/src/plugins/impl/DataTablePlugin.tsx
@@ -36,7 +36,10 @@ import { usePanelOwnership } from "@/components/data-table/hooks/use-panel-owner
import { LoadingTable } from "@/components/data-table/loading-table";
import {
type DownloadAsArgs,
+ type DownloadAsFunction,
DownloadAsSchema,
+ type DownloadGeoJSON,
+ DownloadGeoJSONSchema,
type GetExportMetadata,
GetExportMetadataSchema,
} from "@/components/data-table/schemas";
@@ -211,7 +214,8 @@ interface Data<T> {
// oxlint-disable-next-line typescript/consistent-type-definitions
type DataTableFunctions = {
- download_as: DownloadAsArgs;
+ download_as: DownloadAsFunction;
+ download_geojson: DownloadGeoJSON;
get_export_metadata: GetExportMetadata;
get_column_summaries: <T>(opts: {}) => Promise<ColumnSummaries<T>>;
search: <T>(req: {
@@ -305,6 +309,7 @@ export const DataTablePlugin = createPlugin<S>("marimo-table")
)
.withFunctions<DataTableFunctions>({
download_as: DownloadAsSchema,
+ download_geojson: DownloadGeoJSONSchema,
get_export_metadata: GetExportMetadataSchema,
get_column_summaries: rpc.input(z.looseObject({})).output(
z.object({
@@ -843,7 +848,8 @@ const DataTableComponent = ({
fieldTypes,
paginationState,
setPaginationState,
- download_as: downloadAs,
+ download_as,
+ download_geojson,
get_export_metadata: getExportMetadata,
columnSummaries,
className,
@@ -885,6 +891,15 @@ const DataTableComponent = ({
sizeBytesIsLoading?: boolean;
}): JSX.Element => {
const id = useId();
+ const downloadAs = useCallback<DownloadAsArgs>(
+ (request) => {
+ const { format, ...options } = request;
+ return format === "geojson"
+ ? download_geojson({ format, ...options })
+ : download_as({ format, ...options });
+ },
+ [download_as, download_geojson],
+ );
const { locale } = useLocale();
const [viewedRowIdx, setViewedRowIdx] = useState(0);
const { isPanelOpen, isAnyPanelOpen, togglePanel, panelType, setPanelType } =
diff --git a/frontend/src/plugins/impl/__tests__/DataTablePlugin.test.tsx b/frontend/src/plugins/impl/__tests__/DataTablePlugin.test.tsx
index 18f94a06ab..598dfaf669 100644
--- a/frontend/src/plugins/impl/__tests__/DataTablePlugin.test.tsx
+++ b/frontend/src/plugins/impl/__tests__/DataTablePlugin.test.tsx
@@ -4,11 +4,17 @@ import { Tooltip } from "radix-ui";
const TooltipProvider = Tooltip.Provider;
-import { act, render, screen, waitFor } from "@testing-library/react";
+import {
+ act,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
import { Provider } from "jotai";
import { beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { SetupMocks } from "@/__mocks__/common";
-import type { DownloadAsArgs } from "@/components/data-table/schemas";
+import type { DownloadAsFunction } from "@/components/data-table/schemas";
import type { FieldTypesWithExternalType } from "@/components/data-table/types";
import { store } from "@/core/state/jotai";
import {
@@ -19,6 +25,10 @@ import {
// Default to normal (non-static) mode; individual tests flip this on.
const mockIsStatic = vi.fn().mockReturnValue(false);
+vi.mock("@/utils/download", () => ({
+ downloadByURL: vi.fn(),
+ withLoadingToast: vi.fn(async (_title, callback) => callback()),
+}));
vi.mock("@/core/static/static-state", async (importOriginal) => {
const actual =
await importOriginal<typeof import("@/core/static/static-state")>();
@@ -30,9 +40,15 @@ beforeAll(() => {
});
describe("LoadingDataTableComponent", () => {
- it("keeps data columns when inferred types include a row header", async () => {
+ it("keeps data columns and routes each export to its RPC", async () => {
const host = document.createElement("div");
const data = JSON.stringify([{ index: "first", value: 1 }]);
+ const downloadAs = vi
+ .fn()
+ .mockResolvedValue({ url: "export", filename: "table.csv" });
+ const downloadGeoJSON = vi
+ .fn()
+ .mockResolvedValue({ url: "export", filename: "table.geojson" });
render(
<Provider store={store}>
@@ -43,7 +59,7 @@ describe("LoadingDataTableComponent", () => {
pagination={false}
pageSize={10}
selection={null}
- showDownload={false}
+ showDownload={true}
showFilters={false}
showColumnSummaries={false}
showDataTypes={false}
@@ -68,8 +84,22 @@ describe("LoadingDataTableComponent", () => {
cell_styles: null,
cell_hover_texts: null,
})}
- download_as={vi.fn() as DownloadAsArgs}
- get_export_metadata={vi.fn()}
+ download_as={downloadAs}
+ download_geojson={downloadGeoJSON}
+ get_export_metadata={vi.fn().mockResolvedValue({
+ geometry_columns: [
+ { name: "value", encoding: "objects", crs: "EPSG:4326" },
+ ],
+ primary_geometry_column: "value",
+ default_geometry_column: "value",
+ formats: {
+ geojson: {
+ available: true,
+ reason: null,
+ missing_packages: [],
+ },
+ },
+ })}
get_column_summaries={vi.fn()}
get_data_url={vi.fn() as GetDataUrl}
get_row_ids={vi.fn() as GetRowIds}
@@ -84,6 +114,26 @@ describe("LoadingDataTableComponent", () => {
screen.getByRole("columnheader", { name: "value" }),
).toBeInTheDocument();
});
+ fireEvent.click(screen.getByTestId("export-button"));
+ await screen.findByRole("dialog", { name: "Export table" });
+ await waitFor(() =>
+ expect(
+ screen.getByRole("button", { name: "Download GeoJSON" }),
+ ).toBeEnabled(),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Download GeoJSON" }));
+ await waitFor(() =>
+ expect(downloadGeoJSON).toHaveBeenCalledWith({
+ format: "geojson",
+ geometry_column: "value",
+ }),
+ );
+ expect(downloadAs).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Download CSV" }));
+ await waitFor(() =>
+ expect(downloadAs).toHaveBeenCalledWith({ format: "csv" }),
+ );
+ expect(downloadGeoJSON).toHaveBeenCalledTimes(1);
});
it("does not log duplicate keys when a pivot becomes empty", async () => {
@@ -123,7 +173,8 @@ describe("LoadingDataTableComponent", () => {
showSearch: false,
value: [] as (number | string | { rowId: string; columnName?: string })[],
setValue: vi.fn(),
- download_as: vi.fn() as DownloadAsArgs,
+ download_as: vi.fn() as DownloadAsFunction,
+ download_geojson: vi.fn(),
get_export_metadata: vi.fn(),
get_column_summaries: vi.fn(),
get_data_url: vi.fn() as GetDataUrl,
@@ -265,7 +316,8 @@ describe("LoadingDataTableComponent", () => {
showSearch: true,
value: [] as (number | string | { rowId: string; columnName?: string })[],
setValue,
- download_as: vi.fn() as DownloadAsArgs,
+ download_as: vi.fn() as DownloadAsFunction,
+ download_geojson: vi.fn(),
get_export_metadata: vi.fn(),
get_column_summaries: vi.fn().mockResolvedValue({
data: null,
@@ -382,7 +434,8 @@ describe("static notebook control suppression", () => {
cell_styles: null,
cell_hover_texts: null,
}),
- download_as: vi.fn() as DownloadAsArgs,
+ download_as: vi.fn() as DownloadAsFunction,
+ download_geojson: vi.fn(),
get_export_metadata: vi.fn(),
get_column_summaries: vi.fn().mockResolvedValue({
data: null,
diff --git a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
index 439a901cd9..886147372e 100644
--- a/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
+++ b/frontend/src/plugins/impl/data-frames/DataFramePlugin.tsx
@@ -12,8 +12,10 @@ import {
} from "react";
import { z } from "zod";
import {
- type DownloadAsArgs,
+ type DownloadAsFunction,
DownloadAsSchema,
+ type DownloadGeoJSON,
+ DownloadGeoJSONSchema,
type GetExportMetadata,
GetExportMetadataSchema,
} from "@/components/data-table/schemas";
@@ -84,7 +86,8 @@ type PluginFunctions = {
data: TableData<T>;
total_rows: number;
}>;
- download_as: DownloadAsArgs;
+ download_as: DownloadAsFunction;
+ download_geojson: DownloadGeoJSON;
get_export_metadata: GetExportMetadata;
get_size_bytes: (opts: Record<string, never>) => Promise<{
size_bytes?: number | null;
@@ -156,6 +159,7 @@ export const DataFramePlugin = createPlugin<S>("marimo-dataframe")
}),
),
download_as: DownloadAsSchema,
+ download_geojson: DownloadGeoJSONSchema,
get_export_metadata: GetExportMetadataSchema,
get_size_bytes: rpc
.input(z.object({}))
@@ -178,7 +182,7 @@ interface DataTableProps extends Data, PluginFunctions {
setValue: (value: S) => void;
host: HTMLElement;
showDownload: boolean;
- download_as: DownloadAsArgs;
+ download_as: DownloadAsFunction;
}
const EMPTY: Transformations = {
@@ -198,6 +202,7 @@ export const DataFrameComponent = memo(
get_column_values,
search,
download_as,
+ download_geojson,
get_export_metadata,
get_size_bytes,
host,
@@ -342,6 +347,7 @@ export const DataFrameComponent = memo(
rowHeaders={row_headers || Arrays.EMPTY}
showDownload={showDownload}
download_as={download_as}
+ download_geojson={download_geojson}
get_export_metadata={get_export_metadata}
get_size_bytes={get_size_bytes}
showSearch={false}
diff --git a/frontend/src/stories/dataframe.stories.tsx b/frontend/src/stories/dataframe.stories.tsx
index 0a3ec1f12e..68a3aceec0 100644
--- a/frontend/src/stories/dataframe.stories.tsx
+++ b/frontend/src/stories/dataframe.stories.tsx
@@ -42,6 +42,7 @@ export const DataFrame: StoryObj = {
host={document.body}
showDownload={false}
download_as={async () => ({ url: "", filename: "" })}
+ download_geojson={async () => ({ url: "", filename: "" })}
get_export_metadata={async () => ({
geometry_columns: [],
primary_geometry_column: null,
diff --git a/marimo/_plugins/ui/_impl/dataframes/dataframe.py b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
index 59595e9017..6d4d4de28c 100644
--- a/marimo/_plugins/ui/_impl/dataframes/dataframe.py
+++ b/marimo/_plugins/ui/_impl/dataframes/dataframe.py
@@ -28,6 +28,7 @@ from marimo._plugins.ui._impl.table import (
DownloadAsArgs,
DownloadAsOptions,
DownloadAsResponse,
+ DownloadGeoJSONArgs,
GetSizeBytesResponse,
SearchTableArgs,
SearchTableResponse,
@@ -235,6 +236,11 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):
arg_cls=DownloadAsArgs,
function=self._download_as,
),
+ Function(
+ name="download_geojson",
+ arg_cls=DownloadGeoJSONArgs,
+ function=self._download_geojson,
+ ),
Function(
name="get_export_metadata",
arg_cls=EmptyArgs,
@@ -363,13 +369,23 @@ class dataframe(UIElement[dict[str, Any], DataFrameType]):
return get_export_metadata(get_table_manager(self._value))
def _download_as(self, args: DownloadAsArgs) -> DownloadAsResponse:
+ return self._download(args)
+
+ def _download_geojson(
+ self, args: DownloadGeoJSONArgs
+ ) -> DownloadAsResponse:
+ return self._download(args)
+
+ def _download(
+ self, args: DownloadAsArgs | DownloadGeoJSONArgs
+ ) -> DownloadAsResponse:
"""Download the transformed dataframe in the specified format.
Downloads the dataframe with all current transformations applied.
Args:
- args (DownloadAsArgs): Arguments specifying the download format.
- format must be one of 'csv', 'tsv', 'json', or 'parquet'.
+ args (DownloadAsArgs | DownloadGeoJSONArgs): Arguments specifying
+ the download format and optional export settings.
Returns:
DownloadAsResponse: URL and filename for the downloaded file.
diff --git a/marimo/_plugins/ui/_impl/table.py b/marimo/_plugins/ui/_impl/table.py
index daf37bf282..42e2fa8a8c 100644
--- a/marimo/_plugins/ui/_impl/table.py
+++ b/marimo/_plugins/ui/_impl/table.py
@@ -143,6 +143,13 @@ class DownloadAsArgs:
geometry_column: str | None = None
+@dataclass
+class DownloadGeoJSONArgs:
+ format: Literal["geojson"]
+ options: DownloadAsOptions | None = None
+ geometry_column: str | None = None
+
+
@dataclass
class DownloadAsResponse:
url: str = ""
@@ -977,6 +984,11 @@ class table(
arg_cls=DownloadAsArgs,
function=self._download_as,
),
+ Function(
+ name="download_geojson",
+ arg_cls=DownloadGeoJSONArgs,
+ function=self._download_geojson,
+ ),
Function(
name="get_export_metadata",
arg_cls=EmptyArgs,
@@ -1079,6 +1091,16 @@ class table(
return get_export_metadata(self._manager)
def _download_as(self, args: DownloadAsArgs) -> DownloadAsResponse:
+ return self._download(args)
+
+ def _download_geojson(
+ self, args: DownloadGeoJSONArgs
+ ) -> DownloadAsResponse:
+ return self._download(args)
+
+ def _download(
+ self, args: DownloadAsArgs | DownloadGeoJSONArgs
+ ) -> DownloadAsResponse:
"""Download the table data in the specified format.
For cell-selection modes ("single-cell"/"multi-cell"), selection is
@@ -1094,9 +1116,8 @@ class table(
user to install the dependency and retry.
Args:
- args (DownloadAsArgs): The requested download format and
- optional per-request export options. The format must be
- one of `'csv'`, `'tsv'`, `'json'`, or `'parquet'`.
+ args (DownloadAsArgs | DownloadGeoJSONArgs): The requested
+ format and optional per-request export options.
Returns:
DownloadAsResponse: Either a success response with `url` and
diff --git a/marimo/_plugins/ui/_impl/tables/geometry_export.py b/marimo/_plugins/ui/_impl/tables/geometry_export.py
index a1ed9e113b..207057c668 100644
--- a/marimo/_plugins/ui/_impl/tables/geometry_export.py
+++ b/marimo/_plugins/ui/_impl/tables/geometry_export.py
@@ -2,6 +2,7 @@
from __future__ import annotations
import json
+import math
from dataclasses import dataclass, field
from io import BytesIO
from typing import TYPE_CHECKING, Any, Literal
@@ -31,6 +32,7 @@ GeometryExportErrorCode = Literal[
"unsupported_representation",
"unsupported_version",
"missing_packages",
+ "missing_crs",
"conversion_failed",
]
@@ -38,6 +40,8 @@ _MIN_GEOPANDAS_GEOPARQUET_VERSION = "0.14.1"
_GEOPANDAS_UPGRADE_MESSAGE = (
"Update geopandas to 0.14.1 or newer to export GeoParquet."
)
+_MIN_SHAPELY_GEOJSON_VERSION = "2.0"
+_SHAPELY_UPGRADE_MESSAGE = "Update shapely to 2.0 or newer to export GeoJSON."
class GeometryExportError(Exception):
@@ -115,6 +119,9 @@ class ExportMetadata:
def get_export_metadata(manager: TableManager[Any]) -> ExportMetadata:
"""Read geometry declarations without materializing source rows.
+ Format eligibility covers source support and dependencies. The chosen
+ geometry's CRS and values require separate checks.
+
Args:
manager (TableManager[Any]): Manager for the export source.
"""
@@ -161,38 +168,56 @@ def get_export_metadata(manager: TableManager[Any]) -> ExportMetadata:
]
is_supported_source = False
+ formats: dict[str, ExportFormatEligibility] = {}
if not is_supported_source:
- if source.implementation.is_pandas():
- reason = "This pandas table needs geopandas to export GeoParquet."
- missing_packages = ["geopandas"]
- elif source.implementation.is_pyarrow():
- reason = (
- "GeoParquet export from Arrow tables is not supported yet."
+ for format_name, label in (
+ ("parquet", "GeoParquet"),
+ ("geojson", "GeoJSON"),
+ ):
+ if source.implementation.is_pandas():
+ reason = (
+ f"This pandas table needs geopandas to export {label}."
+ )
+ missing_packages = ["geopandas"]
+ elif source.implementation.is_pyarrow():
+ reason = (
+ f"{label} export from Arrow tables is not supported yet."
+ )
+ missing_packages = []
+ else:
+ reason = (
+ f"{label} export is not supported for this table type."
+ )
+ missing_packages = []
+ formats[format_name] = ExportFormatEligibility(
+ available=False,
+ reason=reason,
+ missing_packages=missing_packages,
)
- missing_packages = []
- else:
- reason = "GeoParquet export is not supported for this table type."
- missing_packages = []
- parquet = ExportFormatEligibility(
- available=False,
- reason=reason,
- missing_packages=missing_packages,
- )
- elif not DependencyManager.geopandas.has_at_version(
- min_version=_MIN_GEOPANDAS_GEOPARQUET_VERSION, quiet=True
- ):
- parquet = ExportFormatEligibility(
- available=False,
- reason=_GEOPANDAS_UPGRADE_MESSAGE,
- )
- elif not DependencyManager.pyarrow.has():
- parquet = ExportFormatEligibility(
- available=False,
- reason="GeoParquet export requires pyarrow.",
- missing_packages=["pyarrow"],
- )
else:
- parquet = ExportFormatEligibility(available=True)
+ if DependencyManager.shapely.has_at_version(
+ min_version=_MIN_SHAPELY_GEOJSON_VERSION, quiet=True
+ ):
+ formats["geojson"] = ExportFormatEligibility(available=True)
+ else:
+ formats["geojson"] = ExportFormatEligibility(
+ available=False, reason=_SHAPELY_UPGRADE_MESSAGE
+ )
+ if not DependencyManager.geopandas.has_at_version(
+ min_version=_MIN_GEOPANDAS_GEOPARQUET_VERSION, quiet=True
+ ):
+ formats["parquet"] = ExportFormatEligibility(
+ available=False,
+ reason=_GEOPANDAS_UPGRADE_MESSAGE,
+ )
+ elif not DependencyManager.pyarrow.has():
+ formats["parquet"] = ExportFormatEligibility(
+ available=False,
+ reason="GeoParquet export requires pyarrow.",
+ missing_packages=["pyarrow"],
+ )
+ else:
+ formats["parquet"] = ExportFormatEligibility(available=True)
default = (
primary
@@ -203,7 +228,7 @@ def get_export_metadata(manager: TableManager[Any]) -> ExportMetadata:
geometry_columns=columns,
primary_geometry_column=primary,
default_geometry_column=default,
- formats={"parquet": parquet},
+ formats=formats,
)
@@ -236,6 +261,350 @@ def has_geometry_columns(manager: TableManager[Any]) -> bool:
)
+def serialize_geojson(
+ manager: TableManager[Any],
+ geometry_column: str | None,
+ ensure_ascii: bool = True,
+) -> bytes:
+ """Write selected geometry and ordinary JSON properties as RFC 7946.
+
+ Args:
+ manager (TableManager[Any]): Manager for the effective export rows.
+ geometry_column (str | None): Explicit geometry, if chosen.
+ ensure_ascii (bool, optional): Whether to escape non-ASCII text.
+
+ Raises:
+ GeometryExportError: If geometry or properties cannot be preserved.
+ """
+ if not has_geometry_columns(manager):
+ raise GeometryExportError(
+ "invalid_geometry"
+ if geometry_column is not None
+ else "geometry_required",
+ "GeoJSON export requires a declared geometry column.",
+ column=geometry_column,
+ )
+ if (
+ not isinstance(manager, NarwhalsTableManager)
+ or not manager.data.implementation.is_pandas()
+ ):
+ raise GeometryExportError(
+ "unsupported_representation",
+ "GeoJSON export from this table type is not supported yet.",
+ column=geometry_column,
+ )
+ try:
+ metadata = get_export_metadata(manager)
+ except Exception as e:
+ raise GeometryExportError(
+ "invalid_metadata", f"Could not read geometry metadata: {e}"
+ ) from e
+ names = {column.name for column in metadata.geometry_columns}
+ if geometry_column is not None and geometry_column not in names:
+ raise GeometryExportError(
+ "invalid_geometry",
+ f"{geometry_column!r} is not a geometry column in this table.",
+ column=geometry_column,
+ )
+ primary = (
+ geometry_column
+ if geometry_column is not None
+ else metadata.default_geometry_column
+ )
+ if primary is None:
+ raise GeometryExportError(
+ "geometry_required",
+ "Choose a geometry column for GeoJSON export.",
+ )
+ if not DependencyManager.geopandas.has():
+ raise GeometryExportError(
+ "missing_packages",
+ "This pandas table needs geopandas to export GeoJSON.",
+ missing_packages=["geopandas"],
+ )
+ if not DependencyManager.shapely.has_at_version(
+ min_version=_MIN_SHAPELY_GEOJSON_VERSION, quiet=True
+ ):
+ raise GeometryExportError(
+ "unsupported_version", _SHAPELY_UPGRADE_MESSAGE
+ )
+
+ import geopandas as gpd # type: ignore[import-not-found,import-untyped,unused-ignore]
+ from shapely.ops import orient # type: ignore[import-untyped]
+
+ from marimo._plugins.ui._impl.tables.pandas_table import (
+ PandasTableManagerFactory,
+ _index_level_names,
+ _trivial_range_index,
+ )
+
+ native = manager.as_frame().to_native()
+ if not native.columns.is_unique:
+ raise GeometryExportError(
+ "invalid_metadata", "GeoJSON export requires unique column names."
+ )
+ geometry = gpd.GeoSeries(native[primary].array, index=native.index)
+ exports_index = isinstance(
+ manager, PandasTableManagerFactory.create()
+ ) and not _trivial_range_index(native.index)
+ if geometry.crs is None:
+ raise GeometryExportError(
+ "missing_crs",
+ f"Geometry column {primary!r} needs a CRS for GeoJSON export. "
+ "Declare its source CRS in Python before exporting.",
+ column=primary,
+ )
+ try:
+ if any(getattr(value, "has_m", False) for value in geometry.array):
+ raise GeometryExportError(
+ "unsupported_representation",
+ f"Geometry column {primary!r} contains M coordinates.",
+ column=primary,
+ )
+ projected = geometry.to_crs(epsg=4326)
+ _validate_reprojection(geometry, projected, primary)
+ projected = gpd.GeoSeries(
+ [
+ orient(value, sign=1.0)
+ if value is not None
+ and value.geom_type
+ in ("Polygon", "MultiPolygon", "GeometryCollection")
+ else value
+ for value in projected.array
+ ],
+ index=projected.index,
+ crs=projected.crs,
+ )
+ export = gpd.GeoDataFrame(geometry=projected)
+ properties_manager = prepare_geometry_text_export(
+ manager.drop_columns([primary])
+ )
+ properties: list[dict[str, Any]]
+ if len(native.columns) == 1 and not exports_index:
+ properties = [{} for _ in range(len(native))]
+ else:
+ property_json = properties_manager.to_json_str(
+ strict_json=True, ensure_ascii=ensure_ascii
+ )
+ properties = json.loads(
+ property_json, parse_constant=_reject_json_constant
+ )
+ del property_json
+ if not isinstance(properties, list) or len(properties) != len(native):
+ raise ValueError("Property conversion changed the number of rows.")
+ expected_keys = set(native.columns) - {primary}
+ if exports_index:
+ expected_keys.update(
+ _index_level_names(native.index, expected_keys)
+ )
+ if any(
+ not isinstance(row, dict) or set(row) != expected_keys
+ for row in properties
+ ):
+ raise ValueError("Property conversion changed the column names.")
+ _validate_secondary_wkt(properties, native, names - {primary})
+ features = []
+ for feature, row, value in zip(
+ export.iterfeatures(drop_id=True),
+ properties,
+ projected.array,
+ strict=True,
+ ):
+ if value is not None and value.is_empty:
+ feature["geometry"] = (
+ {"type": "GeometryCollection", "geometries": []}
+ if value.geom_type == "GeometryCollection"
+ else {"type": value.geom_type, "coordinates": []}
+ )
+ expected_geometry = (
+ None
+ if value is None
+ else feature["geometry"]
+ if value.is_empty
+ else value.__geo_interface__
+ )
+ if (
+ set(feature) != {"type", "geometry", "properties"}
+ or feature["type"] != "Feature"
+ or feature["geometry"] != expected_geometry
+ ):
+ raise ValueError(
+ "Geometry serialization changed feature geometry."
+ )
+ if feature["geometry"] is not None:
+ _validate_geojson_geometry(feature["geometry"])
+ feature["properties"] = row
+ features.append(feature)
+ del properties
+ text = json.dumps(
+ {"type": "FeatureCollection", "features": features},
+ allow_nan=False,
+ ensure_ascii=ensure_ascii,
+ separators=(",", ":"),
+ )
+ del features, export, projected, geometry, properties_manager
+ return text.encode("utf-8")
+ except GeometryExportError:
+ raise
+ except Exception as e:
+ raise GeometryExportError(
+ "conversion_failed",
+ f"Could not export GeoJSON: {e}",
+ column=primary,
+ ) from e
+
+
+def _reject_json_constant(value: str) -> Any:
+ raise ValueError(f"Invalid JSON constant: {value}")
+
+
+def _validate_reprojection(source: Any, projected: Any, column: str) -> None:
+ import numpy as np
+ import shapely # type: ignore[import-untyped]
+
+ original_coordinates = shapely.get_coordinates(
+ source.array, include_z=True
+ )
+ projected_coordinates = shapely.get_coordinates(
+ projected.array, include_z=True
+ )
+ if (
+ not np.isfinite(original_coordinates[:, :2]).all()
+ or not np.isfinite(projected_coordinates[:, :2]).all()
+ or not np.array_equal(
+ shapely.get_num_coordinates(source.array),
+ shapely.get_num_coordinates(projected.array),
+ )
+ or not np.array_equal(
+ shapely.get_type_id(source.array),
+ shapely.get_type_id(projected.array),
+ )
+ or not np.array_equal(
+ shapely.has_z(source.array), shapely.has_z(projected.array)
+ )
+ ):
+ raise GeometryExportError(
+ "conversion_failed",
+ "Reprojection changed geometry structure or produced non-finite coordinates.",
+ column=column,
+ )
+ if source.crs != projected.crs:
+ restored = projected.to_crs(source.crs)
+ restored_coordinates = shapely.get_coordinates(
+ restored.array, include_z=True
+ )
+ if (
+ original_coordinates.shape != restored_coordinates.shape
+ or not np.allclose(
+ original_coordinates,
+ restored_coordinates,
+ rtol=1e-9,
+ atol=1e-8,
+ equal_nan=True,
+ )
+ ):
+ raise GeometryExportError(
+ "conversion_failed",
+ "Reprojection cannot preserve the source coordinates.",
+ column=column,
+ )
+
+
+def _validate_secondary_wkt(
+ properties: list[dict[str, Any]], source: Any, columns: set[str]
+) -> None:
+ import numpy as np
+ import shapely # type: ignore[import-untyped]
+
+ for column in columns:
+ original = source[column].array
+ text = [row[column] for row in properties]
+ if any(
+ value is not None and not isinstance(value, str) for value in text
+ ):
+ raise ValueError(f"WKT conversion lost geometry in {column!r}.")
+ restored = shapely.from_wkt(text)
+ if np.array_equal(shapely.to_wkb(original), shapely.to_wkb(restored)):
+ continue
+ coordinate_options = {"include_z": True}
+ if any(getattr(value, "has_m", False) for value in original):
+ coordinate_options["include_m"] = True
+ before = shapely.get_coordinates(original, **coordinate_options)
+ after = shapely.get_coordinates(restored, **coordinate_options)
+ tolerance = np.abs(before[:, :2]).max(initial=0) * 1e-15
+ if (
+ not np.all(
+ shapely.equals_exact(original, restored, tolerance=tolerance)
+ | (shapely.is_missing(original) & shapely.is_missing(restored))
+ )
+ or before.shape != after.shape
+ or not np.allclose(
+ before, after, rtol=1e-15, atol=0, equal_nan=True
+ )
+ ):
+ raise ValueError(f"WKT conversion lost geometry in {column!r}.")
+
+
+def _validate_geojson_geometry(geometry: dict[str, Any]) -> None:
+ from shapely.geometry import LinearRing # type: ignore[import-untyped]
+
+ def position(values: Any) -> None:
+ if len(values) not in (2, 3) or not all(
+ isinstance(value, (int, float))
+ and not isinstance(value, bool)
+ and math.isfinite(value)
+ for value in values
+ ):
+ raise ValueError(
+ "GeoJSON positions require two or three finite coordinates."
+ )
+ if not (-180 <= values[0] <= 180 and -90 <= values[1] <= 90):
+ raise ValueError(
+ "GeoJSON coordinates must be longitude and latitude."
+ )
+
+ def line(values: Any, minimum: int = 2) -> None:
+ if values and len(values) < minimum:
+ raise ValueError("GeoJSON line has too few positions.")
+ for values_at_position in values:
+ position(values_at_position)
+
+ def polygon(rings: Any) -> None:
+ for index, ring in enumerate(rings):
+ line(ring, minimum=4)
+ if (
+ not ring
+ or ring[0] != ring[-1]
+ or LinearRing(ring).is_ccw != (index == 0)
+ ):
+ raise ValueError(
+ "GeoJSON polygon rings require closure and correct orientation."
+ )
+
+ coordinates = geometry.get("coordinates", [])
+ match geometry["type"]:
+ case "Point":
+ if coordinates:
+ position(coordinates)
+ case "MultiPoint":
+ line(coordinates, minimum=1)
+ case "LineString":
+ line(coordinates)
+ case "MultiLineString":
+ for values in coordinates:
+ line(values)
+ case "Polygon":
+ polygon(coordinates)
+ case "MultiPolygon":
+ for rings in coordinates:
+ polygon(rings)
+ case "GeometryCollection":
+ for child in geometry["geometries"]:
+ _validate_geojson_geometry(child)
+ case _:
+ raise ValueError("Unsupported GeoJSON geometry type.")
+
+
def serialize_geoparquet(
manager: TableManager[Any], geometry_column: str | None
) -> bytes | None:
diff --git a/marimo/_plugins/ui/_impl/utils/dataframe.py b/marimo/_plugins/ui/_impl/utils/dataframe.py
index c644dfd7b3..579ea975f1 100644
--- a/marimo/_plugins/ui/_impl/utils/dataframe.py
+++ b/marimo/_plugins/ui/_impl/utils/dataframe.py
@@ -13,6 +13,7 @@ from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._impl.tables.geometry_export import (
GeometryExportError,
prepare_geometry_text_export,
+ serialize_geojson,
serialize_geoparquet,
)
from marimo._plugins.ui._impl.tables.selection import INDEX_COLUMN_NAME
@@ -123,7 +124,7 @@ class DownloadOptions:
@dataclass(frozen=True)
class _ExportFormat:
extension: str
- serialize: Callable[[TableManager[Any], DownloadOptions], bytes]
+ serialize: Callable[[TableManager[Any], DownloadOptions], bytes] | None
def _serialize_delimited(
@@ -165,6 +166,7 @@ _EXPORT_FORMATS: dict[str, _ExportFormat] = {
"tsv": _ExportFormat("tsv", _serialize_delimited("\t")),
"json": _ExportFormat("json", _serialize_json),
"parquet": _ExportFormat("parquet", _serialize_parquet),
+ "geojson": _ExportFormat("geojson", None),
}
@@ -181,7 +183,7 @@ def download_as(
Args:
manager (TableManager[Any]): The table manager to download.
ext (str): The format to download the table data in. One of
- `csv`, `tsv`, `json`, or `parquet`.
+ `csv`, `tsv`, `json`, `parquet`, or `geojson`.
drop_marimo_index (bool, optional): Whether to drop the marimo
selection column. Defaults to False.
options (DownloadOptions | None, optional): Per-format output
@@ -212,19 +214,21 @@ def download_as(
if geometry_column is not None:
raise GeometryExportError(
"invalid_geometry",
- "A primary geometry can only be chosen for GeoParquet export.",
+ "A primary geometry can only be chosen for geographic export.",
column=geometry_column,
)
manager = prepare_geometry_text_export(manager)
- artifact = (
- serialize_geoparquet(manager, geometry_column)
- if ext == "parquet"
- else None
- )
- vfile = mo_data.any_data(
- artifact if artifact is not None else fmt.serialize(manager, options),
- ext=fmt.extension,
- )
+ artifact = None
+ if ext == "parquet":
+ artifact = serialize_geoparquet(manager, geometry_column)
+ elif ext == "geojson":
+ artifact = serialize_geojson(
+ manager, geometry_column, options.json.ensure_ascii
+ )
+ if artifact is None:
+ assert fmt.serialize is not None
+ artifact = fmt.serialize(manager, options)
+ vfile = mo_data.any_data(artifact, ext=fmt.extension)
base_name = filename if filename is not None else "download"
return (vfile.url, f"{base_name}.{fmt.extension}")
diff --git a/tests/_plugins/ui/_impl/test_export_metadata.py b/tests/_plugins/ui/_impl/test_export_metadata.py
index 086dd8d833..3a502ddbed 100644
--- a/tests/_plugins/ui/_impl/test_export_metadata.py
+++ b/tests/_plugins/ui/_impl/test_export_metadata.py
@@ -2,14 +2,14 @@
from __future__ import annotations
from dataclasses import asdict
-from typing import Any
+from typing import Any, Literal
from unittest.mock import patch
import pytest
from marimo._dependencies.dependencies import DependencyManager
from marimo._plugins import ui
-from marimo._plugins.ui._impl.table import DownloadAsArgs
+from marimo._plugins.ui._impl.table import DownloadAsArgs, DownloadAsResponse
from marimo._plugins.ui._impl.tables.narwhals_table import NarwhalsTableManager
from marimo._runtime.functions import EmptyArgs
from marimo._utils.parse_dataclass import parse_raw
@@ -47,6 +47,11 @@ def test_multigeometry_metadata_does_not_read_rows(widget: Any) -> None:
"primary_geometry_column": "geom_a",
"default_geometry_column": "geom_a",
"formats": {
+ "geojson": {
+ "available": True,
+ "reason": None,
+ "missing_packages": [],
+ },
"parquet": {
"available": True,
"reason": None,
@@ -92,10 +97,11 @@ def test_ambiguous_geometry_has_no_default(widget: Any) -> None:
]
assert result.primary_geometry_column is None
assert result.default_geometry_column is None
+ assert result.formats["geojson"].available
@pytest.mark.requires("geopandas")
-def test_old_geopandas_is_not_eligible(widget: Any) -> None:
+def test_old_geopandas_blocks_only_geoparquet(widget: Any) -> None:
with patch.object(
DependencyManager.geopandas, "get_version", return_value="0.14.0"
):
@@ -108,6 +114,7 @@ def test_old_geopandas_is_not_eligible(widget: Any) -> None:
"reason": "Update geopandas to 0.14.1 or newer to export GeoParquet.",
"missing_packages": [],
}
+ assert result.formats["geojson"].available
@pytest.mark.requires("geopandas")
@@ -117,6 +124,7 @@ def test_empty_name_can_be_the_source_primary(widget: Any) -> None:
result = widget(source)._get_export_metadata(EmptyArgs())
assert result.primary_geometry_column == ""
assert result.default_geometry_column == ""
+ assert result.formats["geojson"].available
@pytest.mark.requires("geopandas")
@@ -138,6 +146,11 @@ def test_missing_pyarrow_is_reported(widget: Any) -> None:
"reason": "GeoParquet export requires pyarrow.",
"missing_packages": ["pyarrow"],
}
+ assert asdict(result.formats["geojson"]) == {
+ "available": True,
+ "reason": None,
+ "missing_packages": [],
+ }
@pytest.mark.requires("geopandas")
@@ -150,6 +163,26 @@ def test_missing_geopandas_is_reported(widget: Any) -> None:
"reason": "This pandas table needs geopandas to export GeoParquet.",
"missing_packages": ["geopandas"],
}
+ assert asdict(result.formats["geojson"]) == {
+ "available": False,
+ "reason": "This pandas table needs geopandas to export GeoJSON.",
+ "missing_packages": ["geopandas"],
+ }
+
+
[email protected]("geopandas", "pyarrow")
+def test_old_shapely_disables_only_geojson(widget: Any) -> None:
+ subject = widget(fixtures.gdf_multi_geometry())
+ with patch.object(
+ DependencyManager.shapely, "has_at_version", return_value=False
+ ):
+ result = subject._get_export_metadata(EmptyArgs())
+ assert asdict(result.formats["geojson"]) == {
+ "available": False,
+ "reason": "Update shapely to 2.0 or newer to export GeoJSON.",
+ "missing_packages": [],
+ }
+ assert result.formats["parquet"].available
@pytest.mark.requires("pyarrow")
@@ -164,6 +197,43 @@ def test_arrow_crs_comes_from_field_metadata(widget: Any) -> None:
"reason": "GeoParquet export from Arrow tables is not supported yet.",
"missing_packages": [],
}
+ assert asdict(result.formats["geojson"]) == {
+ "available": False,
+ "reason": "GeoJSON export from Arrow tables is not supported yet.",
+ "missing_packages": [],
+ }
+
+
[email protected]("geopandas")
[email protected]("empty", [False, True])
+def test_geojson_support_does_not_depend_on_default_crs(
+ widget: Any, empty: bool
+) -> None:
+ import geopandas as gpd # type: ignore[import-untyped]
+
+ source = fixtures.gdf_multi_geometry()
+ source = gpd.GeoDataFrame(
+ {
+ "geom_a": gpd.GeoSeries(list(source["geom_a"])),
+ "geom_b": source["geom_b"],
+ },
+ geometry="geom_a",
+ )
+ if empty:
+ source = source.head(0)
+ subject = widget(source)
+ with patch.object(
+ gpd.GeoSeries,
+ "to_crs",
+ side_effect=AssertionError("Metadata must not reproject geometry"),
+ ):
+ result = subject._get_export_metadata(EmptyArgs())
+ assert result.default_geometry_column == "geom_a"
+ assert [column.crs for column in result.geometry_columns] == [
+ None,
+ "EPSG:3857",
+ ]
+ assert result.formats["geojson"].available
@pytest.mark.requires("pandas")
@@ -221,8 +291,36 @@ def test_download_request_accepts_optional_geometry(
assert parsed.format == payload["format"]
[email protected]("geopandas", "pyarrow")
-def test_widget_passes_geometry_request_to_export(widget: Any) -> None:
[email protected]("geometry_column", [None, "geom_b", ""])
+def test_geojson_request_uses_separate_contract(
+ geometry_column: str | None,
+) -> None:
+ from marimo._plugins.ui._impl.table import DownloadGeoJSONArgs
+
+ payload = {"format": "geojson", "geometry_column": geometry_column}
+ parsed = parse_raw(payload, DownloadGeoJSONArgs)
+ assert parsed.geometry_column == geometry_column
+ assert parsed.format == "geojson"
+ with pytest.raises(
+ ValueError, match="does not fit any type of the literal"
+ ):
+ parse_raw(payload, DownloadAsArgs)
+
+
+def test_download_response_accepts_missing_crs() -> None:
+ parsed = parse_raw(
+ {"code": "missing_crs", "column": "", "error": "Declare a CRS."},
+ DownloadAsResponse,
+ )
+ assert parsed.code == "missing_crs"
+ assert parsed.column == ""
+
+
[email protected]("geopandas")
[email protected]("request_format", ["parquet", "geojson"])
+def test_widget_passes_geometry_request_to_export(
+ widget: Any, request_format: Literal["parquet", "geojson"]
+) -> None:
subject = widget(fixtures.gdf_multi_geometry())
module = (
"marimo._plugins.ui._impl.table"
@@ -230,10 +328,11 @@ def test_widget_passes_geometry_request_to_export(widget: Any) -> None:
else "marimo._plugins.ui._impl.dataframes.dataframe"
)
with patch(
- f"{module}.download_as", return_value=("data:test", "test.parquet")
+ f"{module}.download_as",
+ return_value=("data:test", f"test.{request_format}"),
) as export:
response = subject._download_as(
- DownloadAsArgs(format="parquet", geometry_column="geom_b")
+ DownloadAsArgs(format=request_format, geometry_column="geom_b")
)
assert response.url == "data:test"
assert export.call_args.kwargs["geometry_column"] == "geom_b"
diff --git a/tests/_plugins/ui/_impl/test_geojson_export.py b/tests/_plugins/ui/_impl/test_geojson_export.py
new file mode 100644
index 0000000000..0ff08d06b3
--- /dev/null
+++ b/tests/_plugins/ui/_impl/test_geojson_export.py
@@ -0,0 +1,755 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+import json
+from typing import Any
+from unittest.mock import patch
+
+import pytest
+
+from marimo._dependencies.dependencies import DependencyManager
+from marimo._plugins import ui
+from marimo._plugins.ui._impl.table import DownloadAsArgs, DownloadGeoJSONArgs
+from marimo._utils.data_uri import from_data_uri
+from tests._plugins.ui._impl.tables import geometry_fixtures as fixtures
+
+pytestmark = pytest.mark.requires("geopandas")
+
+
[email protected]("wrapped", [False, True], ids=["native", "narwhals"])
[email protected]("geometry_only", [False, True])
[email protected]("index_kind", ["range", "named", "unnamed", "multi"])
+def test_properties_follow_manager_index_policy(
+ widget: Any, wrapped: bool, geometry_only: bool, index_kind: str
+) -> None:
+ import narwhals.stable.v2 as nw
+ import pandas as pd
+
+ source = _source().drop(columns=["alternate"])
+ if geometry_only:
+ source = source[["location"]]
+ if index_kind == "named":
+ source.index = pd.Index([7, 7], name="source_row")
+ elif index_kind == "unnamed":
+ source.index = pd.Index([7, 7])
+ elif index_kind == "multi":
+ source.index = pd.MultiIndex.from_tuples(
+ [("a", 7), ("a", 7)], names=["group", "row"]
+ )
+ subject = widget(
+ nw.from_native(source) if wrapped else source,
+ **({"selection": None} if widget is ui.table else {}),
+ )
+ ordinary = subject._download_as(DownloadAsArgs(format="json"))
+ expected = json.loads(from_data_uri(ordinary.url)[1])
+ for row in expected:
+ del row["location"]
+ assert [
+ feature["properties"] for feature in _artifact(subject)["features"]
+ ] == expected
+
+
+def test_old_shapely_rejects_direct_geojson_before_publication(
+ widget: Any,
+) -> None:
+ import geopandas as gpd
+
+ subject = widget(_source())
+ export_function = next(
+ function
+ for function in subject._args.functions
+ if function.name == "download_geojson"
+ )
+ with (
+ patch.object(
+ DependencyManager.shapely, "has_at_version", return_value=False
+ ),
+ patch.object(gpd.GeoSeries, "to_crs") as reproject,
+ patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish,
+ ):
+ response = export_function({"format": "geojson"})
+ assert response.code == "unsupported_version"
+ assert "shapely" in response.error
+ assert "2.0" in response.error
+ assert (response.url, response.filename, response.missing_packages) == (
+ "",
+ "",
+ None,
+ )
+ reproject.assert_not_called()
+ publish.assert_not_called()
+
+
[email protected]("ensure_ascii", [False, True])
[email protected]("choice", [None, "alternate"])
+def test_registered_geojson_keeps_geometry_and_ascii_options(
+ widget: Any, ensure_ascii: bool, choice: str | None
+) -> None:
+ source = _source()
+ source["name"] = ["café", "null"]
+ subject = widget(source)
+ export_function = next(
+ function
+ for function in subject._args.functions
+ if function.name == "download_geojson"
+ )
+ response = export_function(
+ {
+ "format": "geojson",
+ "geometry_column": choice,
+ "options": {"ensure_ascii": ensure_ascii},
+ }
+ )
+ assert response.error is None
+ assert response.filename.endswith(".geojson")
+ text = from_data_uri(response.url)[1].decode("utf-8")
+ assert (r"\u00e9" in text) is ensure_ascii
+ feature = json.loads(text)["features"][0]
+ assert feature["properties"]["name"] == "café"
+ assert feature["geometry"]["coordinates"] == pytest.approx(
+ [20, 5] if choice == "alternate" else [10, 0]
+ )
+
+
[email protected](params=[ui.table, ui.dataframe], ids=["table", "dataframe"])
+def widget(request: pytest.FixtureRequest) -> Any:
+ return request.param
+
+
+def _reject_constant(value: str) -> Any:
+ raise ValueError(value)
+
+
+def _artifact(subject: Any, choice: str | None = None) -> dict[str, Any]:
+ export_function = next(
+ function
+ for function in subject._args.functions
+ if function.name == "download_geojson"
+ )
+ response = export_function(
+ {"format": "geojson", "geometry_column": choice}
+ )
+ assert response.error is None, response.error
+ assert response.filename.endswith(".geojson")
+ document = json.loads(
+ from_data_uri(response.url)[1], parse_constant=_reject_constant
+ )
+ assert isinstance(document, dict)
+ return document
+
+
+def _source() -> Any:
+ import geopandas as gpd
+ from shapely.geometry import Point
+
+ return gpd.GeoDataFrame(
+ {
+ "name": ["projected", "null"],
+ "location": gpd.GeoSeries(
+ [Point(1113194.9079327357, 0), None], crs="EPSG:3857"
+ ),
+ "alternate": gpd.GeoSeries([Point(20, 5), None], crs="EPSG:4326"),
+ },
+ geometry="location",
+ )
+
+
[email protected]("choice", [None, "alternate"])
+def test_reprojection_and_secondary_wkt_preserve_source(
+ widget: Any, choice: str | None
+) -> None:
+ source = _source()
+ original = source.copy(deep=True)
+ subject = widget(source)
+ with patch.object(DependencyManager.pyarrow, "has", return_value=False):
+ document = _artifact(subject, choice)
+ assert document == {
+ "type": "FeatureCollection",
+ "features": [
+ {
+ "type": "Feature",
+ "geometry": {
+ "type": "Point",
+ "coordinates": pytest.approx(
+ [20, 5] if choice else [10, 0]
+ ),
+ },
+ "properties": {
+ "name": "projected",
+ ("location" if choice else "alternate"): (
+ "POINT (1113194.9079327357 0)"
+ if choice
+ else "POINT (20 5)"
+ ),
+ },
+ },
+ {
+ "type": "Feature",
+ "geometry": None,
+ "properties": {
+ "name": "null",
+ ("location" if choice else "alternate"): None,
+ },
+ },
+ ],
+ }
+ assert source.equals(original)
+ assert source.geometry.name == "location"
+ assert source.crs == original.crs
+ assert source["alternate"].crs == original["alternate"].crs
+
+
[email protected]("empty", [False, True])
+def test_null_and_empty_tables_require_crs(widget: Any, empty: bool) -> None:
+ source = fixtures.gdf_all_null()
+ if empty:
+ source = source.head(0)
+ subject = widget(source)
+ with patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish:
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson")
+ )
+ assert (
+ response.url,
+ response.filename,
+ response.code,
+ response.column,
+ ) == ("", "", "missing_crs", "geometry")
+ publish.assert_not_called()
+
+
[email protected]("empty", [False, True])
+def test_null_and_empty_tables_with_crs(widget: Any, empty: bool) -> None:
+ source = fixtures.gdf_all_null().set_crs("EPSG:4326")
+ if empty:
+ source = source.head(0)
+ assert _artifact(widget(source)) == {
+ "type": "FeatureCollection",
+ "features": []
+ if empty
+ else [
+ {"type": "Feature", "geometry": None, "properties": {"name": name}}
+ for name in ["a", "b"]
+ ],
+ }
+
+
+def test_geometry_only_table_keeps_rows(widget: Any) -> None:
+ source = _source()[["location"]]
+ assert [
+ feature["properties"]
+ for feature in _artifact(widget(source))["features"]
+ ] == [{}, {}]
+
+
+def test_geometry_only_table_keeps_named_index_properties(widget: Any) -> None:
+ import pandas as pd
+
+ source = _source()[["location"]]
+ source.index = pd.Index([7, 7], name="source_row")
+ assert [
+ feature["properties"]
+ for feature in _artifact(widget(source))["features"]
+ ] == [{"source_row": 7}, {"source_row": 7}]
+
+
+def test_projected_z_coordinate_is_preserved(widget: Any) -> None:
+ import geopandas as gpd
+ from shapely.geometry import Point
+
+ source = gpd.GeoDataFrame(
+ geometry=[Point(1113194.9079327357, 0, 123)], crs="EPSG:3857"
+ )
+ assert _artifact(widget(source))["features"][0]["geometry"][
+ "coordinates"
+ ] == pytest.approx([10, 0, 123])
+
+
+def test_duplicate_indices_and_reserved_property_names(widget: Any) -> None:
+ source = _source().rename(columns={"alternate": "geometry"})
+ source["id"] = ["first", "second"]
+ source["properties"] = [{"a": 1}, None]
+ source.index = [7, 7]
+ features = _artifact(widget(source))["features"]
+ assert [feature["properties"] for feature in features] == [
+ {
+ "Index0": 7,
+ "name": "projected",
+ "geometry": "POINT (20 5)",
+ "id": "first",
+ "properties": {"a": 1},
+ },
+ {
+ "Index0": 7,
+ "name": "null",
+ "geometry": None,
+ "id": "second",
+ "properties": None,
+ },
+ ]
+ assert features[0]["geometry"]["coordinates"] == pytest.approx([10, 0])
+ assert features[1]["geometry"] is None
+ assert all("id" not in feature for feature in features)
+
+
+def test_unnamed_geometry_can_be_chosen(widget: Any) -> None:
+ source = _source().rename(columns={"alternate": ""})
+ assert _artifact(widget(source), "")["features"][0]["geometry"] == {
+ "type": "Point",
+ "coordinates": [20, 5],
+ }
+
+
+ "factory", [fixtures.gdf_stale_pointer, fixtures.gdf_no_active_geometry]
+)
+def test_sole_geometry_resolves_without_active_primary(
+ widget: Any, factory: Any
+) -> None:
+ source = factory()
+ column = "geom" if factory is fixtures.gdf_stale_pointer else "g"
+ source[column] = source[column].set_crs("EPSG:4326", allow_override=True)
+ assert len(_artifact(widget(source))["features"]) == len(source)
+
+
+def test_ambiguous_geometry_requires_choice(widget: Any) -> None:
+ import pandas as pd
+
+ subject = widget(pd.DataFrame(_source()))
+ with patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish:
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson")
+ )
+ assert (response.url, response.code) == ("", "geometry_required")
+ publish.assert_not_called()
+ assert _artifact(subject, "alternate")["features"][0]["geometry"][
+ "coordinates"
+ ] == [20, 5]
+
+
+def test_known_alternate_crs_can_override_missing_primary_crs(
+ widget: Any,
+) -> None:
+ import geopandas as gpd
+
+ known = _source()
+ source = gpd.GeoDataFrame(
+ {
+ "location": gpd.GeoSeries(list(known["location"])),
+ "alternate": known["alternate"],
+ },
+ geometry="location",
+ )
+ subject = widget(source)
+ assert (
+ subject._download_geojson(DownloadGeoJSONArgs(format="geojson")).code
+ == "missing_crs"
+ )
+ assert _artifact(subject, "alternate")["features"][0]["geometry"][
+ "coordinates"
+ ] == [20, 5]
+ assert source["location"].crs is None
+
+
+def test_properties_match_ordinary_json_policy(widget: Any) -> None:
+ import datetime
+
+ import pandas as pd
+
+ class CustomValue:
+ def __str__(self) -> str:
+ return "custom-value"
+
+ source = _source()
+ source["date"] = [datetime.date(2026, 10, 5), None]
+ source["timestamp"] = [pd.Timestamp("2026-10-05T13:00:00Z"), None]
+ source["duration"] = [pd.Timedelta(days=1), None]
+ source["custom"] = [CustomValue(), None]
+ source["bytes"] = [b"abc", None]
+ source["complex"] = [1 + 2j, None]
+ source["number"] = [float("inf"), float("nan")]
+ source["nested"] = [{"n": float("nan")}, None]
+ source["large"] = [2**60, 2**60 + 1]
+ subject = widget(source)
+ response = subject._download_as(DownloadAsArgs(format="json"))
+ ordinary = json.loads(
+ from_data_uri(response.url)[1], parse_constant=_reject_constant
+ )
+ expected = [
+ {key: value for key, value in row.items() if key != "location"}
+ for row in ordinary
+ ]
+ assert [
+ feature["properties"] for feature in _artifact(subject)["features"]
+ ] == expected
+
+
+def test_secondary_wkt_is_complete_and_can_retain_m(widget: Any) -> None:
+ import geopandas as gpd
+ import numpy as np
+ from shapely import from_wkt
+ from shapely.geometry import LineString
+
+ source = _source()
+ long_geometry = LineString([(i, i / 7) for i in range(4000)])
+ source["long"] = gpd.GeoSeries([long_geometry, None], crs="EPSG:3857")
+ measured = from_wkt("POINT M (1 2 3)")
+ if getattr(measured, "has_m", False):
+ source["measured"] = gpd.GeoSeries([measured, None], crs="EPSG:4326")
+ properties = _artifact(widget(source))["features"][0]["properties"]
+ assert len(properties["long"]) > 40_000
+ assert np.asarray(from_wkt(properties["long"]).coords) == pytest.approx(
+ np.asarray(long_geometry.coords), rel=1e-15, abs=0
+ )
+ if "measured" in properties:
+ assert from_wkt(properties["measured"]).wkb == measured.wkb
+
+
+ "geometry_wkt",
+ [
+ "POINT Z (10 20 30)",
+ "LINESTRING Z (0 0 1, 1 1 2)",
+ "POLYGON ((0 0, 0 4, 4 4, 4 0, 0 0), (1 1, 3 1, 3 3, 1 3, 1 1))",
+ "MULTIPOLYGON (((0 0, 0 4, 4 4, 4 0, 0 0)))",
+ "GEOMETRYCOLLECTION (POINT Z (1 2 3), MULTIPOLYGON (((0 0, 0 4, 4 4, 4 0, 0 0))))",
+ "MULTIPOINT ((1 2), (3 4))",
+ "MULTILINESTRING ((1 2, 3 4), (5 6, 7 8))",
+ ],
+)
+def test_supported_geometries_and_ring_orientation(
+ widget: Any, geometry_wkt: str
+) -> None:
+ import geopandas as gpd
+ from shapely import from_wkt
+ from shapely.geometry import shape
+
+ geometry = from_wkt(geometry_wkt)
+ source = gpd.GeoDataFrame(geometry=[geometry], crs="EPSG:4326")
+ result = _artifact(widget(source))["features"][0]["geometry"]
+ restored = shape(result)
+ assert restored.equals(geometry)
+ assert restored.has_z == geometry.has_z
+ assert source.geometry.iloc[0].wkb == geometry.wkb
+
+ def check_rings(value: Any) -> None:
+ if value.geom_type == "Polygon":
+ assert value.exterior.is_ccw
+ assert all(not ring.is_ccw for ring in value.interiors)
+ elif hasattr(value, "geoms"):
+ for child in value.geoms:
+ check_rings(child)
+
+ check_rings(restored)
+ if geometry.geom_type == "Point":
+ assert result["coordinates"] == [10, 20, 30]
+
+
+ "geometry_type",
+ [
+ "POINT",
+ "LINESTRING",
+ "POLYGON",
+ "MULTIPOINT",
+ "MULTILINESTRING",
+ "MULTIPOLYGON",
+ "GEOMETRYCOLLECTION",
+ ],
+)
+def test_empty_geometry_preserves_its_type(
+ widget: Any, geometry_type: str
+) -> None:
+ import geopandas as gpd
+ from shapely import from_wkt
+
+ source = gpd.GeoDataFrame(
+ geometry=[from_wkt(f"{geometry_type} EMPTY")], crs="EPSG:4326"
+ )
+ result = _artifact(widget(source))["features"][0]["geometry"]
+ assert result == {
+ "type": source.geometry.iloc[0].geom_type,
+ "geometries"
+ if geometry_type == "GEOMETRYCOLLECTION"
+ else "coordinates": [],
+ }
+
+
+ "geometry_wkt",
+ [
+ "POINT M (1 2 3)",
+ "POINT ZM (1 2 3 4)",
+ "GEOMETRYCOLLECTION (POINT M (1 2 3))",
+ ],
+)
+def test_selected_m_geometry_is_rejected_atomically(
+ widget: Any, geometry_wkt: str
+) -> None:
+ import geopandas as gpd
+ from shapely import from_wkt
+
+ geometry = from_wkt(geometry_wkt)
+ if not getattr(geometry, "has_m", False):
+ pytest.skip("Installed Shapely cannot represent M coordinates")
+ subject = widget(gpd.GeoDataFrame(geometry=[geometry], crs="EPSG:4326"))
+ with patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish:
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson")
+ )
+ assert (response.url, response.code, response.column) == (
+ "",
+ "unsupported_representation",
+ "geometry",
+ )
+ publish.assert_not_called()
+
+
+ ("geometry_wkt", "crs"),
+ [
+ ("POINT (Infinity 2)", "EPSG:4326"),
+ ("LINESTRING (0 0, NaN 2)", "EPSG:4326"),
+ ("POINT Z (1 2 Infinity)", "EPSG:4326"),
+ ("POINT Z (1 2 NaN)", "EPSG:4326"),
+ ("POINT (190 20)", "EPSG:4326"),
+ ("POINT (1 95)", "EPSG:4326"),
+ ("POINT (30000000 0)", "EPSG:3857"),
+ ("POINT (1 1e300)", "EPSG:3857"),
+ ],
+)
+def test_invalid_or_lossy_coordinates_publish_no_artifact(
+ widget: Any, geometry_wkt: str, crs: str
+) -> None:
+ import geopandas as gpd
+ from shapely import from_wkt
+
+ subject = widget(
+ gpd.GeoDataFrame(geometry=[from_wkt(geometry_wkt)], crs=crs)
+ )
+ with patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish:
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson")
+ )
+ assert (response.url, response.filename, response.code) == (
+ "",
+ "",
+ "conversion_failed",
+ )
+ publish.assert_not_called()
+
+
+ "invalid_json",
+ [
+ '[{"name":NaN,"alternate":"POINT (20 5)"},{"name":"null","alternate":null}]',
+ '[{"name":Infinity,"alternate":"POINT (20 5)"},{"name":"null","alternate":null}]',
+ '[{"name":1e400,"alternate":"POINT (20 5)"},{"name":"null","alternate":null}]',
+ '[{"name":"projected"},{"name":"null"}]',
+ "[]",
+ "{}",
+ ],
+)
+def test_invalid_property_conversion_publishes_no_artifact(
+ widget: Any, invalid_json: str
+) -> None:
+ subject = widget(_source())
+ import pandas as pd
+
+ from marimo._plugins.ui._impl.tables.utils import get_table_manager
+
+ manager_type = type(get_table_manager(pd.DataFrame({"value": [1]})))
+ with (
+ patch.object(manager_type, "to_json_str", return_value=invalid_json),
+ patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish,
+ ):
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson")
+ )
+ assert (response.url, response.filename, response.code) == (
+ "",
+ "",
+ "conversion_failed",
+ )
+ publish.assert_not_called()
+
+
+def test_truncated_secondary_wkt_publishes_no_artifact(widget: Any) -> None:
+ import geopandas as gpd
+ import pandas as pd
+
+ subject = widget(_source())
+ with (
+ patch.object(
+ gpd.GeoSeries,
+ "to_wkt",
+ return_value=pd.Series(["POINT (21 5)", None]),
+ ),
+ patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish,
+ ):
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson")
+ )
+ assert (response.url, response.code) == ("", "conversion_failed")
+ publish.assert_not_called()
+
+
+ "failure", ["exception", "id", "crs", "geometry", "missing_row"]
+)
+def test_invalid_feature_writer_publishes_no_artifact(
+ widget: Any, failure: str
+) -> None:
+ import geopandas as gpd
+
+ subject = widget(_source())
+ original = gpd.GeoDataFrame.iterfeatures
+
+ def broken_writer(frame: Any, **kwargs: Any) -> Any:
+ if failure == "exception":
+ raise ValueError("writer failed")
+ for index, feature in enumerate(original(frame, **kwargs)):
+ if failure == "missing_row" and index == 0:
+ continue
+ if failure in ("id", "crs"):
+ feature[failure] = "unexpected"
+ elif failure == "geometry":
+ feature["geometry"] = None
+ yield feature
+
+ with (
+ patch.object(gpd.GeoDataFrame, "iterfeatures", broken_writer),
+ patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish,
+ ):
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson")
+ )
+ assert (response.url, response.filename, response.code) == (
+ "",
+ "",
+ "conversion_failed",
+ )
+ publish.assert_not_called()
+
+
+def test_missing_geopandas_is_rechecked(widget: Any) -> None:
+ subject = widget(_source())
+ with (
+ patch.object(DependencyManager.geopandas, "has", return_value=False),
+ patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish,
+ ):
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson")
+ )
+ assert (response.url, response.code, response.missing_packages) == (
+ "",
+ "missing_packages",
+ ["geopandas"],
+ )
+ publish.assert_not_called()
+
+
[email protected]("choice", ["absent", "name"])
+def test_invalid_choice_is_rejected_atomically(
+ widget: Any, choice: str
+) -> None:
+ subject = widget(_source())
+ with patch(
+ "marimo._plugins.ui._impl.utils.dataframe.mo_data.any_data"
+ ) as publish:
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson", geometry_column=choice)
+ )
+ assert (response.url, response.code, response.column) == (
+ "",
+ "invalid_geometry",
+ choice,
+ )
+ publish.assert_not_called()
+
+
+def test_arrow_geometry_is_not_exported_as_geojson(widget: Any) -> None:
+ subject = widget(fixtures.arrow_wkb_known_crs())
+ response = subject._download_geojson(DownloadGeoJSONArgs(format="geojson"))
+ assert (response.url, response.code) == ("", "unsupported_representation")
+
+
+def test_table_selection_search_and_cell_scope() -> None:
+ from marimo._plugins.ui._impl.table import SearchTableArgs
+
+ source = _source()
+ subject = ui.table(source, selection="multi")
+ subject._convert_value(["1"])
+ assert [
+ feature["properties"]["name"]
+ for feature in _artifact(subject)["features"]
+ ] == ["null"]
+ searched = ui.table(source, selection="multi")
+ searched._search(
+ SearchTableArgs(query="projected", page_size=10, page_number=0)
+ )
+ assert [
+ feature["properties"]["name"]
+ for feature in _artifact(searched)["features"]
+ ] == ["projected"]
+ searched._convert_value(["1"])
+ assert [
+ feature["properties"]["name"]
+ for feature in _artifact(searched)["features"]
+ ] == ["null"]
+ cells = ui.table(source, selection="multi-cell")
+ cells._search(
+ SearchTableArgs(query="projected", page_size=10, page_number=0)
+ )
+ cells._convert_value([{"rowId": "1", "columnName": "name"}])
+ assert [
+ feature["properties"]["name"]
+ for feature in _artifact(cells)["features"]
+ ] == ["projected"]
+
+
+def test_dataframe_transformed_value_and_obsolete_choice() -> None:
+ subject = ui.dataframe(_source())
+ subject._update(
+ {
+ "transforms": [
+ {"type": "select_columns", "column_ids": ["alternate"]}
+ ]
+ }
+ )
+ assert _artifact(subject)["features"][0]["geometry"]["coordinates"] == [
+ 20,
+ 5,
+ ]
+ response = subject._download_geojson(
+ DownloadGeoJSONArgs(format="geojson", geometry_column="location")
+ )
+ assert (response.url, response.code, response.column) == (
+ "",
+ "invalid_geometry",
+ "location",
+ )
+ subject._value = _source().iloc[[1]].copy()
+ assert [
+ feature["properties"]["name"]
+ for feature in _artifact(subject)["features"]
+ ] == ["null"]