Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat(kepler-jupyter): restore save_to_html() using kepler.gl UMD bundle from CDN (#3382)
Xun Li2938e27f9843
diff --git a/.github/workflows/build-publish-pypi.yml b/.github/workflows/build-publish-pypi.ymlindex 4f19b36a6..71931ad18 100644--- a/.github/workflows/build-publish-pypi.yml+++ b/.github/workflows/build-publish-pypi.yml@@ -19,6 +19,17 @@ jobs:steps:- uses: actions/checkout@v4+ - name: Verify CDN version matches package.json+ run: |+ MAJOR=$(node -p "require('./package.json').version.split('.')[0]")+ CDN=$(grep -Po '(?<=DEFAULT_KEPLER_GL_CDN_VERSION = ")[^"]+' bindings/python/keplergl/_html_export.py)+ echo "package.json major: $MAJOR"+ echo "Python CDN version: $CDN"+ if [ "$MAJOR" != "$CDN" ]; then+ echo "::error::DEFAULT_KEPLER_GL_CDN_VERSION ($CDN) in _html_export.py does not match major version ($MAJOR) from package.json. Please update it."+ exit 1+ fi+- name: Install uvuses: astral-sh/setup-uv@v4diff --git a/bindings/python/DEVELOPMENT.md b/bindings/python/DEVELOPMENT.mdindex c3c15006f..14d11bc6f 100644--- a/bindings/python/DEVELOPMENT.md+++ b/bindings/python/DEVELOPMENT.md@@ -102,6 +102,7 @@ The version in `pyproject.toml` determines what type of release you can publish:1. **Update the version** in both files:- `pyproject.toml` (line: `version = "x.x.x"`)- `keplergl/_version.py` (line: `__version__ = "x.x.x"`)+ - On a kepler.gl **major** release, also update `DEFAULT_KEPLER_GL_CDN_VERSION` in `keplergl/_html_export.py` to match the new major version.2. **Go to GitHub Actions** → "Build and Publish KeplerGL Python Package" workflowdiff --git a/bindings/python/keplergl/_html_export.py b/bindings/python/keplergl/_html_export.pynew file mode 100644index 000000000..2c0cae9a0--- /dev/null+++ b/bindings/python/keplergl/_html_export.py@@ -0,0 +1,235 @@+# SPDX-License-Identifier: MIT+# Copyright contributors to the kepler.gl project++"""Generate standalone HTML export using the kepler.gl UMD bundle from CDN."""++from __future__ import annotations++import json+from typing import Optional++import pandas as pd+import geopandas as gpd++DEFAULT_KEPLER_GL_CDN_VERSION = "3"+++def _dataset_to_csv(data) -> Optional[str]:+ """Convert a dataset value to CSV string for kepler.gl processCsvData."""+ if isinstance(data, gpd.GeoDataFrame):+ import shapely.wkt++ if data.crs and data.crs.to_epsg() != 4326:+ data = data.to_crs(4326)+ df = pd.DataFrame(data)+ geom_col = data.geometry.name+ df[geom_col] = data.geometry.apply(shapely.wkt.dumps)+ return df.to_csv(index=False)+ elif isinstance(data, pd.DataFrame):+ return data.to_csv(index=False)+ elif isinstance(data, str):+ return data+ else:+ return None+++def _dataset_to_geojson(data) -> Optional[dict]:+ """Try to convert dataset to GeoJSON dict."""+ if isinstance(data, gpd.GeoDataFrame):+ if data.crs and data.crs.to_epsg() != 4326:+ data = data.to_crs(4326)+ return json.loads(data.to_json())+ elif isinstance(data, dict):+ geojson_types = {+ "FeatureCollection", "Feature", "Point", "MultiPoint",+ "LineString", "MultiLineString", "Polygon", "MultiPolygon",+ "GeometryCollection",+ }+ if data.get("type") in geojson_types:+ return data+ elif isinstance(data, str):+ try:+ parsed = json.loads(data)+ if isinstance(parsed, dict) and parsed.get("type") in {+ "FeatureCollection", "Feature",+ }:+ return parsed+ except (json.JSONDecodeError, TypeError):+ pass+ return None+++def _serialize_datasets_for_html(data: dict) -> str:+ """Serialize datasets dict into JS code that calls addDataToMap.++ Generates a JS snippet that processes each dataset using kepler.gl's+ processCsvData or processGeojson, then dispatches addDataToMap.+ """+ snippets = []+ for name, dataset in data.items():+ geojson = _dataset_to_geojson(dataset)+ if geojson is not None:+ snippets.append(+ f" datasets.push({{info: {{id: {json.dumps(name, ensure_ascii=False)}, label: {json.dumps(name, ensure_ascii=False)}}}, "+ f"data: keplerGl.processGeojson({json.dumps(geojson, ensure_ascii=False)})}});"+ )+ else:+ csv_str = _dataset_to_csv(dataset)+ if csv_str is not None:+ snippets.append(+ f" datasets.push({{info: {{id: {json.dumps(name, ensure_ascii=False)}, label: {json.dumps(name, ensure_ascii=False)}}}, "+ f"data: keplerGl.processCsvData({json.dumps(csv_str, ensure_ascii=False)})}});"+ )+ return "\n".join(snippets)+++def export_map_html(+ data: dict,+ config: dict,+ read_only: bool = False,+ center_map: bool = False,+ mapbox_token: str = "",+ kepler_gl_version: str = DEFAULT_KEPLER_GL_CDN_VERSION,+) -> str:+ """Generate a standalone HTML string that renders a kepler.gl map.++ Loads all dependencies from CDN (unpkg). No local JS build required.+ """+ dataset_js = _serialize_datasets_for_html(data)+ config_json = json.dumps(config, ensure_ascii=False) if config else "{}"+ mapbox_token_json = json.dumps(mapbox_token)+ read_only_js = "true" if read_only else "false"+ center_map_js = "true" if center_map else "false"++ return f"""\+<!DOCTYPE html>+<html>+ <head>+ <meta charset="UTF-8"/>+ <title>Kepler.gl embedded map</title>++ <!--Uber Font-->+ <link rel="stylesheet" href="https://d1a3f4spazzrp4.cloudfront.net/kepler.gl/uber-fonts/4.0.0/superfine.css">++ <!--Kepler css-->+ <link href="https://unpkg.com/kepler.gl@{kepler_gl_version}/umd/keplergl.min.css" rel="stylesheet">++ <!--MapBox css-->+ <link href="https://api.tiles.mapbox.com/mapbox-gl-js/v1.1.1/mapbox-gl.css" rel="stylesheet">+ <link href="https://unpkg.com/maplibre-gl@^3/dist/maplibre-gl.css" rel="stylesheet">++ <!-- Load React/Redux -->+ <script src="https://unpkg.com/[email protected]/umd/react.production.min.js" crossorigin></script>+ <script src="https://unpkg.com/[email protected]/umd/react-dom.production.min.js" crossorigin></script>+ <script src="https://unpkg.com/[email protected]/dist/redux.js" crossorigin></script>+ <script src="https://unpkg.com/[email protected]/dist/react-redux.min.js" crossorigin></script>+ <script src="https://unpkg.com/[email protected]/dist/styled-components.min.js" crossorigin></script>++ <!-- Load Kepler.gl -->+ <script src="https://unpkg.com/kepler.gl@{kepler_gl_version}/umd/keplergl.min.js" crossorigin></script>++ <style type="text/css">+ body {{margin: 0; padding: 0; overflow: hidden;}}+ </style>++ <script>+ const MAPBOX_TOKEN = {mapbox_token_json};+ </script>+ </head>+ <body>+ <div id="app"></div>++ <script>+ /** STORE **/+ const reducers = (function createReducers(redux, keplerGl) {{+ return redux.combineReducers({{+ keplerGl: keplerGl.keplerGlReducer.initialState({{+ uiState: {{+ readOnly: {read_only_js},+ currentModal: null+ }}+ }})+ }});+ }}(Redux, KeplerGl));++ const middleWares = (function createMiddlewares(keplerGl) {{+ return keplerGl.enhanceReduxMiddleware([]);+ }}(KeplerGl));++ const enhancers = (function createEnhancers(redux, middles) {{+ return redux.applyMiddleware(...middles);+ }}(Redux, middleWares));++ const store = (function createStore(redux, enhancers) {{+ return redux.createStore(reducers, {{}}, redux.compose(enhancers));+ }}(Redux, enhancers));+ /** END STORE **/++ /** COMPONENTS **/+ var KeplerElement = (function makeKeplerElement(react, keplerGl, mapboxToken) {{+ return function App() {{+ var rootElm = react.useRef(null);+ var _useState = react.useState({{+ width: window.innerWidth,+ height: window.innerHeight+ }});+ var windowDimension = _useState[0];+ var setDimension = _useState[1];+ react.useEffect(function sideEffect() {{+ function handleResize() {{+ setDimension({{width: window.innerWidth, height: window.innerHeight}});+ }}+ window.addEventListener('resize', handleResize);+ return function() {{ window.removeEventListener('resize', handleResize); }};+ }}, []);+ return react.createElement(+ 'div',+ {{style: {{position: 'absolute', left: 0, width: '100vw', height: '100vh'}}}},+ react.createElement(keplerGl.KeplerGl, {{+ mapboxApiAccessToken: mapboxToken,+ id: "map",+ width: windowDimension.width,+ height: windowDimension.height+ }})+ );+ }};+ }}(React, KeplerGl, MAPBOX_TOKEN));++ const app = (function createReactReduxProvider(react, reactRedux, KeplerElement) {{+ return react.createElement(+ reactRedux.Provider,+ {{store}},+ react.createElement(KeplerElement, null)+ );+ }}(React, ReactRedux, KeplerElement));+ /** END COMPONENTS **/++ /** Render **/+ (function render(react, reactDOM, app) {{+ const container = document.getElementById('app');+ const root = reactDOM.createRoot(container);+ root.render(app);+ }}(React, ReactDOM, app));+ </script>++ <script>+ (function customize(keplerGl, store) {{+ var datasets = [];+{dataset_js}++ var config = {config_json};++ window.setTimeout(function() {{+ store.dispatch(keplerGl.addDataToMap({{+ datasets: datasets,+ config: config,+ options: {{+ centerMap: {center_map_js}+ }}+ }}));+ }}, 500);+ }}(KeplerGl, store));+ </script>+ </body>+</html>+"""diff --git a/bindings/python/keplergl/_version.py b/bindings/python/keplergl/_version.pyindex 8b056997f..6b3cf1d5a 100644--- a/bindings/python/keplergl/_version.py+++ b/bindings/python/keplergl/_version.py@@ -3,4 +3,4 @@"""Version information."""-__version__ = "0.4.0rc1"+__version__ = "0.4.0rc2"diff --git a/bindings/python/keplergl/serializers.py b/bindings/python/keplergl/serializers.pyindex dc410a608..a131f93ce 100644--- a/bindings/python/keplergl/serializers.py+++ b/bindings/python/keplergl/serializers.py@@ -17,6 +17,14 @@ def _debug(msg):print(f"[keplergl-serializer] {msg}")+def _arrow_table_to_base64(table: pa.Table) -> str:+ """Serialize an Arrow table to a base64-encoded IPC stream."""+ sink = pa.BufferOutputStream()+ with pa.ipc.new_stream(sink, table.schema) as writer:+ writer.write_table(table)+ return base64.b64encode(sink.getvalue().to_pybytes()).decode("utf-8")++def _try_parse_geojson(data: str) -> Optional[dict]:"""Try to parse a string as GeoJSON. Returns parsed dict if valid GeoJSON, None otherwise."""import json@@ -37,10 +45,11 @@ def _try_parse_geojson(data: str) -> Optional[dict]:def data_to_json(data: dict, widget) -> dict:"""Serialize Python data for JavaScript consumption."""_debug(f"data_to_json called with {len(data)} datasets")+ use_arrow = getattr(widget, '_use_arrow', False) if widget else Falseresult = {}for name, dataset in data.items():_debug(f" Serializing dataset '{name}' of type {type(dataset).__name__}")- result[name] = serialize_dataset(dataset, name)+ result[name] = serialize_dataset(dataset, name, use_arrow=use_arrow)_debug(f" Result format: {result[name].get('format')}")_debug(f"data_to_json result: {list(result.keys())}")return result@@ -51,19 +60,17 @@ def data_from_json(data: dict, widget) -> dict:return data-def serialize_dataset(data: Any, name: str) -> dict:+def serialize_dataset(data: Any, name: str, use_arrow: bool = False) -> dict:"""Serialize a single dataset."""if isinstance(data, gpd.GeoDataFrame):return serialize_geodataframe(data, name)elif isinstance(data, pd.DataFrame):- return serialize_dataframe(data, name)+ return serialize_dataframe(data, name, use_arrow=use_arrow)elif isinstance(data, str):- # Try to detect if the string is GeoJSONgeojson_data = _try_parse_geojson(data)if geojson_data is not None:_debug(f" Detected GeoJSON string for '{name}'")return {"id": name, "data": geojson_data, "format": "geojson"}- # Otherwise treat as CSVreturn {"id": name, "data": data, "format": "csv"}elif isinstance(data, dict):return {"id": name, "data": data, "format": "geojson"}@@ -71,12 +78,16 @@ def serialize_dataset(data: Any, name: str) -> dict:raise ValueError(f"Unsupported data type: {type(data)}")-def serialize_dataframe(df: pd.DataFrame, name: str) -> dict:- """Serialize DataFrame to JSON format for kepler.gl.-- We use JSON format instead of Arrow to avoid version mismatch issues- between the apache-arrow package used here and the one bundled with kepler.gl.+def serialize_dataframe(df: pd.DataFrame, name: str, use_arrow: bool = False) -> dict:+ """Serialize DataFrame for kepler.gl.++ When use_arrow=True, serializes as Arrow IPC (base64-encoded) which is more+ compact and preserves types better for large numeric datasets.+ When use_arrow=False (default), serializes as JSON columns+rows."""+ if use_arrow:+ return _serialize_dataframe_arrow(df, name)+columns = df.columns.tolist()rows = df.values.tolist()_debug(f"serialize_dataframe: {len(columns)} columns, {len(rows)} rows")@@ -92,6 +103,17 @@ def serialize_dataframe(df: pd.DataFrame, name: str) -> dict:}+def _serialize_dataframe_arrow(df: pd.DataFrame, name: str) -> dict:+ """Serialize DataFrame to Arrow IPC format (base64-encoded)."""+ table = pa.Table.from_pandas(df)+ _debug(f"_serialize_dataframe_arrow: {table.num_columns} columns, {table.num_rows} rows")+ return {+ "id": name,+ "data": _arrow_table_to_base64(table),+ "format": "arrow",+ }++def serialize_geodataframe(gdf: gpd.GeoDataFrame, name: str) -> dict:"""Serialize GeoDataFrame to GeoArrow format."""import geoarrow.pyarrow as ga@@ -107,12 +129,8 @@ def serialize_geodataframe(gdf: gpd.GeoDataFrame, name: str) -> dict:col_names = non_geom_cols + [geom_col]table = pa.table(dict(zip(col_names, arrays)))- sink = pa.BufferOutputStream()- with pa.ipc.new_stream(sink, table.schema) as writer:- writer.write_table(table)- arrow_bytes = sink.getvalue().to_pybytes()return {"id": name,- "data": base64.b64encode(arrow_bytes).decode("utf-8"),+ "data": _arrow_table_to_base64(table),"format": "geoarrow",}diff --git a/bindings/python/keplergl/widget.py b/bindings/python/keplergl/widget.pyindex 0977328e9..3e72d9ab8 100644--- a/bindings/python/keplergl/widget.py+++ b/bindings/python/keplergl/widget.py@@ -9,10 +9,10 @@ import anywidgetimport traitletsfrom .serializers import data_to_json, data_from_json+from ._html_export import export_map_html, DEFAULT_KEPLER_GL_CDN_VERSION_STATIC_DIR = pathlib.Path(__file__).parent / "static"-class KeplerGl(anywidget.AnyWidget):"""Kepler.gl Jupyter Widget using anywidget."""@@ -22,8 +22,9 @@ class KeplerGl(anywidget.AnyWidget):data = traitlets.Dict({}).tag(sync=True, to_json=data_to_json, from_json=data_from_json)config = traitlets.Dict({}).tag(sync=True)height = traitlets.Int(400).tag(sync=True)+ mapbox_token = traitlets.Unicode("").tag(sync=True)- def __init__(self, data=None, config=None, height=400, show_docs=False, **kwargs):+ def __init__(self, data=None, config=None, height=400, mapbox_token="", use_arrow=False, show_docs=False, **kwargs):"""Initialize KeplerGl widget.@@ -31,10 +32,14 @@ class KeplerGl(anywidget.AnyWidget):data: Dict of dataset name to data (DataFrame, GeoDataFrame, CSV, GeoJSON)config: Kepler.gl config dictheight: Widget height in pixels+ mapbox_token: Mapbox API access token for Mapbox basemap styles+ use_arrow: If True, serialize DataFrames as Arrow IPC (more compact, preserves types)show_docs: Deprecated, kept for compatibility"""super().__init__(**kwargs)+ self._use_arrow = use_arrowself.height = height+ self.mapbox_token = mapbox_tokenif config:self.config = config@@ -42,10 +47,19 @@ class KeplerGl(anywidget.AnyWidget):if data:self._add_data_dict(data)- def add_data(self, data, name="data"):- """Add data to the map."""+ def add_data(self, data, name="data", use_arrow=None):+ """Add data to the map.++ Args:+ data: DataFrame, GeoDataFrame, CSV string, or GeoJSON dict/string+ name: Dataset name/identifier+ use_arrow: If True, serialize DataFrame as Arrow IPC. If None (default),+ falls back to the widget-level use_arrow setting.+ """updated = copy.deepcopy(self.data)updated[name] = data+ if use_arrow is not None:+ self._use_arrow = use_arrowself.data = updateddef _add_data_dict(self, data_dict):@@ -61,14 +75,37 @@ class KeplerGl(anywidget.AnyWidget):data=None,config=None,read_only=False,- center_map=False,+ center_map=True,+ mapbox_token="",):"""Export the map to a standalone HTML file.- Note: This method is no longer supported in the new anywidget-based implementation.- Please use the "Share" button in the map config panel to export your map.+ The exported HTML loads kepler.gl from the unpkg CDN (no local build needed)+ and embeds the current data and configuration.++ Args:+ file_name: Output HTML file path (default: 'keplergl_map.html')+ data: Dict of dataset name to data. If None, uses current widget data.+ config: Map config dict. If None, uses current widget config.+ read_only: If True, hide side panel to disable map customization.+ center_map: If True, fit map bounds to the data (default: True).+ mapbox_token: Mapbox access token. Required for Mapbox basemap styles+ (e.g. "Dark", "Muted Light"). Leave empty for free MapLibre styles."""- print(- "save_to_html() is no longer supported in this version.\n"- "Please use the 'Share' button in the map config panel to export your map to HTML."+ data_to_save = data if data is not None else self.data+ config_to_save = config if config is not None else self.config+ token = mapbox_token if mapbox_token else self.mapbox_token++ html = export_map_html(+ data=data_to_save,+ config=config_to_save,+ read_only=read_only,+ center_map=center_map,+ mapbox_token=token,+ kepler_gl_version=DEFAULT_KEPLER_GL_CDN_VERSION,)++ with open(file_name, "w", encoding="utf-8") as f:+ f.write(html)++ print(f"Map saved to {file_name}!")diff --git a/bindings/python/notebooks/DataFrame.ipynb b/bindings/python/notebooks/DataFrame.ipynbindex 822748f8a..0b1c9c437 100644--- a/bindings/python/notebooks/DataFrame.ipynb+++ b/bindings/python/notebooks/DataFrame.ipynb@@ -2,7 +2,7 @@"cells": [{"cell_type": "code",- "execution_count": 1,+ "execution_count": 5,"metadata": {},"outputs": [],"source": [@@ -11,7 +11,7 @@},{"cell_type": "code",- "execution_count": 2,+ "execution_count": 6,"metadata": {},"outputs": [],"source": [@@ -26,21 +26,21 @@},{"cell_type": "code",- "execution_count": 3,+ "execution_count": 7,"metadata": {},"outputs": [{"data": {"application/vnd.jupyter.widget-view+json": {- "model_id": "37198f4ae24b463db826f3e81de6d4b3",+ "model_id": "791c9920051c48ecb9bb7422aff286bd","version_major": 2,"version_minor": 1},"text/plain": [- "<keplergl.widget.KeplerGl object at 0x13470de50>"+ "<keplergl.widget.KeplerGl object at 0x125b9b3e0>"]},- "execution_count": 3,+ "execution_count": 7,"metadata": {},"output_type": "execute_result"}@@ -53,15 +53,14 @@},{"cell_type": "code",- "execution_count": 4,+ "execution_count": 8,"metadata": {},"outputs": [{"name": "stdout","output_type": "stream","text": [- "save_to_html() is no longer supported in this version.\n",- "Please use the 'Share' button in the map config panel to export your map to HTML.\n"+ "Map saved to keplergl_map.html!\n"]}],diff --git a/bindings/python/package.json b/bindings/python/package.jsonindex 0df2a2698..f12581b55 100644--- a/bindings/python/package.json+++ b/bindings/python/package.json@@ -12,12 +12,12 @@"@anywidget/types": "^0.2.0","@types/react": "^18.2.0","@types/react-dom": "^18.2.0",- "esbuild": "^0.20.0",- "typescript": "^5.4.0",- "eslint": "^8.57.0","@typescript-eslint/eslint-plugin": "^7.0.0","@typescript-eslint/parser": "^7.0.0",- "prettier": "^3.2.0"+ "esbuild": "^0.20.0",+ "eslint": "^8.57.0",+ "prettier": "^3.2.0",+ "typescript": "^5.4.0"},"dependencies": {"@kepler.gl/actions": "^3.2.0",@@ -26,13 +26,13 @@"@kepler.gl/reducers": "^3.2.0","@kepler.gl/schemas": "^3.2.0","@kepler.gl/styles": "^3.2.0",+ "apache-arrow": "^21.0.0",+ "assert": "^2.1.0",+ "events": "^3.3.0","react": "^18.2.0","react-dom": "^18.2.0",- "redux": "^4.2.1","react-redux": "^8.0.5",- "styled-components": "^6.1.8",- "apache-arrow": "^21.0.0",- "assert": "^2.1.0",- "events": "^3.3.0"+ "redux": "^4.2.1",+ "styled-components": "^6.1.8"}}diff --git a/bindings/python/pyproject.toml b/bindings/python/pyproject.tomlindex dcc62b34c..5194af007 100644--- a/bindings/python/pyproject.toml+++ b/bindings/python/pyproject.toml@@ -1,6 +1,6 @@[project]name = "keplergl"-version = "0.4.0rc1"+version = "0.4.0rc2"description = "Kepler.gl Jupyter Widget"readme = "README.md"requires-python = ">=3.9"diff --git a/bindings/python/src/components/App.tsx b/bindings/python/src/components/App.tsxindex 2bf7dc0ae..3b1b1341c 100644--- a/bindings/python/src/components/App.tsx+++ b/bindings/python/src/components/App.tsx@@ -16,6 +16,7 @@ interface AppProps {export function App({model}: AppProps) {const [height, setHeight] = useState(model.get('height'));const [width, setWidth] = useState(800);+ const [mapboxToken, setMapboxToken] = useState(model.get('mapbox_token') || '');const containerRef = useRef<HTMLDivElement>(null);useEffect(() => {@@ -24,6 +25,12 @@ export function App({model}: AppProps) {return () => model.off('change:height', handleHeightChange);}, [model]);+ useEffect(() => {+ const handleTokenChange = () => setMapboxToken(model.get('mapbox_token') || '');+ model.on('change:mapbox_token', handleTokenChange);+ return () => model.off('change:mapbox_token', handleTokenChange);+ }, [model]);+// Observe container width changesuseEffect(() => {if (!containerRef.current) return;@@ -42,7 +49,7 @@ export function App({model}: AppProps) {return (<div ref={containerRef} style={{width: '100%', height}}>- <KeplerGl id={KEPLER_ID} width={width} height={height} mapboxApiAccessToken="" />+ <KeplerGl id={KEPLER_ID} width={width} height={height} mapboxApiAccessToken={mapboxToken} /></div>);}diff --git a/bindings/python/src/types.ts b/bindings/python/src/types.tsindex 644c6b62f..478a7be9c 100644--- a/bindings/python/src/types.ts+++ b/bindings/python/src/types.ts@@ -7,6 +7,7 @@ export interface KeplerGlWidgetModel {data: Record<string, DatasetPayload>;config: KeplerGlConfig;height: number;+ mapbox_token: string;}export interface DatasetPayload {diff --git a/bindings/python/src/widget.ts b/bindings/python/src/widget.tsindex ab41f359a..67175af5d 100644--- a/bindings/python/src/widget.ts+++ b/bindings/python/src/widget.ts@@ -10,6 +10,7 @@ import {processDataset} from './utils/data';import type {WidgetModel, DatasetPayload} from './types';import type {ParsedConfig} from '@kepler.gl/types';import {addDataToMap, receiveMapConfig, wrapTo} from '@kepler.gl/actions';+import KeplerGlSchema from '@kepler.gl/schemas';const DEBUG = false;function debug(...args: unknown[]) {@@ -23,6 +24,9 @@ export class KeplerGlWidget {private el: HTMLElement;private root: Root | null = null;private store: ReturnType<typeof createStore>;+ private previousConfigHash: string = '';+ private mapUpdateCounter: number = 0;+ private isSyncingConfig: boolean = false;constructor(model: WidgetModel, el: HTMLElement) {debug('KeplerGlWidget constructor');@@ -60,6 +64,13 @@ export class KeplerGlWidget {onConfigChange() {debug('onConfigChange() called');+ const config = this.model.get('config');+ const hash = JSON.stringify(config);+ // Avoid re-applying config that was just synced from the store+ if (hash === this.previousConfigHash) {+ debug('onConfigChange: config matches store, skipping');+ return;+ }this.loadConfig();}@@ -143,11 +154,38 @@ export class KeplerGlWidget {const config = this.model.get('config');debug('loadConfig() called, config:', config);if (config && Object.keys(config).length > 0) {+ this.isSyncingConfig = true;this.store.dispatch(wrapTo(KEPLER_ID, receiveMapConfig(config as ParsedConfig, {})));+ this.previousConfigHash = JSON.stringify(config);+ this.isSyncingConfig = false;}}private syncConfigToPython() {- // TODO: Extract config from store and sync back+ if (this.isSyncingConfig) {+ return;+ }++ const state = this.store.getState() as {keplerGl?: Record<string, unknown>};+ const instanceState = state.keplerGl?.[KEPLER_ID];+ if (!instanceState) {+ return;+ }++ this.mapUpdateCounter++;+ // Skip early store updates during component initialization+ if (this.mapUpdateCounter <= 2) {+ return;+ }++ const configToSave = KeplerGlSchema.getConfigToSave(instanceState);+ const hash = JSON.stringify(configToSave);++ if (hash !== this.previousConfigHash) {+ debug('Config changed, syncing to Python');+ this.previousConfigHash = hash;+ this.model.set('config', configToSave);+ this.model.save_changes();+ }}}diff --git a/bindings/python/tests/test_html_export.py b/bindings/python/tests/test_html_export.pynew file mode 100644index 000000000..8024765ac--- /dev/null+++ b/bindings/python/tests/test_html_export.py@@ -0,0 +1,351 @@+# SPDX-License-Identifier: MIT+# Copyright contributors to the kepler.gl project++"""Tests for save_to_html and HTML export functionality."""++import json+import os+import pandas as pd+import geopandas as gpd+import pytest+from shapely.geometry import Point++from keplergl import KeplerGl+from keplergl._html_export import (+ _dataset_to_csv,+ _dataset_to_geojson,+ _serialize_datasets_for_html,+ export_map_html,+)+++class TestDatasetToCsv:+ """Tests for _dataset_to_csv conversion."""++ def test_dataframe(self, sample_df):+ result = _dataset_to_csv(sample_df)+ assert "lat" in result+ assert "lng" in result+ assert "37.7749" in result++ def test_geodataframe_converts_geometry_to_wkt(self, sample_gdf):+ result = _dataset_to_csv(sample_gdf)+ assert "name" in result+ assert "POINT" in result++ def test_geodataframe_reprojects_to_4326(self):+ gdf = gpd.GeoDataFrame(+ {"name": ["A"]},+ geometry=[Point(500000, 4649776)],+ crs="EPSG:32610",+ )+ result = _dataset_to_csv(gdf)+ assert "POINT" in result+ assert "name" in result++ def test_geodataframe_already_4326_no_reproject(self, sample_gdf):+ """Ensure CRS EPSG:4326 data is not needlessly reprojected."""+ result = _dataset_to_csv(sample_gdf)+ assert "POINT" in result+ assert "-122.41" in result+ assert "37.77" in result++ def test_geodataframe_no_crs_skips_reproject(self):+ """GeoDataFrame with no CRS should not trigger reprojection."""+ gdf = gpd.GeoDataFrame(+ {"name": ["A"]},+ geometry=[Point(-122.4, 37.8)],+ )+ assert gdf.crs is None+ result = _dataset_to_csv(gdf)+ assert "POINT" in result++ def test_csv_string_passthrough(self):+ csv = "lat,lng\n37.7749,-122.4194"+ assert _dataset_to_csv(csv) == csv++ def test_unsupported_type_returns_none(self):+ assert _dataset_to_csv(12345) is None++ def test_empty_dataframe(self):+ df = pd.DataFrame({"a": [], "b": []})+ result = _dataset_to_csv(df)+ assert "a" in result+ assert "b" in result+++class TestDatasetToGeojson:+ """Tests for _dataset_to_geojson conversion."""++ def test_geodataframe(self, sample_gdf):+ result = _dataset_to_geojson(sample_gdf)+ assert result is not None+ assert result["type"] == "FeatureCollection"+ assert len(result["features"]) == 2++ def test_geodataframe_reprojects_non_4326(self):+ """GeoDataFrame in non-4326 CRS should be reprojected."""+ gdf = gpd.GeoDataFrame(+ {"name": ["A"]},+ geometry=[Point(500000, 4649776)],+ crs="EPSG:32610",+ )+ result = _dataset_to_geojson(gdf)+ assert result is not None+ coords = result["features"][0]["geometry"]["coordinates"]+ assert -125 < coords[0] < -119+ assert 37 < coords[1] < 43++ def test_geodataframe_already_4326_no_reproject(self, sample_gdf):+ """Ensure CRS EPSG:4326 data is not needlessly reprojected."""+ result = _dataset_to_geojson(sample_gdf)+ coords = result["features"][0]["geometry"]["coordinates"]+ assert abs(coords[0] - (-122.4194)) < 1e-4+ assert abs(coords[1] - 37.7749) < 1e-4++ def test_geodataframe_no_crs_skips_reproject(self):+ """GeoDataFrame with no CRS should not trigger reprojection."""+ gdf = gpd.GeoDataFrame(+ {"name": ["A"]},+ geometry=[Point(-122.4, 37.8)],+ )+ assert gdf.crs is None+ result = _dataset_to_geojson(gdf)+ assert result is not None+ coords = result["features"][0]["geometry"]["coordinates"]+ assert abs(coords[0] - (-122.4)) < 1e-4++ def test_geojson_dict(self):+ geojson = {"type": "FeatureCollection", "features": []}+ assert _dataset_to_geojson(geojson) is geojson++ def test_geojson_feature_dict(self):+ feature = {+ "type": "Feature",+ "geometry": {"type": "Point", "coordinates": [0, 0]},+ "properties": {},+ }+ assert _dataset_to_geojson(feature) is feature++ def test_geojson_string(self):+ geojson_str = json.dumps({"type": "FeatureCollection", "features": []})+ result = _dataset_to_geojson(geojson_str)+ assert result is not None+ assert result["type"] == "FeatureCollection"++ def test_non_geojson_dict_returns_none(self):+ assert _dataset_to_geojson({"key": "value"}) is None++ def test_non_geojson_string_returns_none(self):+ assert _dataset_to_geojson("just a csv string\n1,2,3") is None++ def test_dataframe_returns_none(self):+ df = pd.DataFrame({"x": [1]})+ assert _dataset_to_geojson(df) is None++ def test_int_returns_none(self):+ assert _dataset_to_geojson(42) is None+++class TestSerializeDatasetsForHtml:+ """Tests for _serialize_datasets_for_html JS snippet generation."""++ def test_dataframe_produces_processCsvData_call(self, sample_df):+ js = _serialize_datasets_for_html({"cities": sample_df})+ assert "processCsvData" in js+ assert '"cities"' in js++ def test_geojson_dict_produces_processGeojson_call(self):+ geojson = {"type": "FeatureCollection", "features": []}+ js = _serialize_datasets_for_html({"geo": geojson})+ assert "processGeojson" in js+ assert '"geo"' in js++ def test_geodataframe_produces_processGeojson_call(self, sample_gdf):+ js = _serialize_datasets_for_html({"points": sample_gdf})+ assert "processGeojson" in js+ assert '"points"' in js++ def test_csv_string_produces_processCsvData_call(self):+ js = _serialize_datasets_for_html({"csv": "a,b\n1,2"})+ assert "processCsvData" in js++ def test_multiple_datasets(self, sample_df, sample_gdf):+ js = _serialize_datasets_for_html({+ "tabular": sample_df,+ "spatial": sample_gdf,+ })+ assert "processCsvData" in js+ assert "processGeojson" in js+ assert '"tabular"' in js+ assert '"spatial"' in js++ def test_empty_data(self):+ js = _serialize_datasets_for_html({})+ assert js == ""+++class TestExportMapHtml:+ """Tests for the full export_map_html function."""++ def test_returns_valid_html(self, sample_df):+ html = export_map_html(data={"test": sample_df}, config={})+ assert html.startswith("<!DOCTYPE html>")+ assert "</html>" in html++ def test_contains_kepler_gl_cdn_script(self, sample_df):+ html = export_map_html(+ data={"test": sample_df},+ config={},+ kepler_gl_version="3.2.6",+ )+ assert "unpkg.com/[email protected]/umd/keplergl.min.js" in html+ assert "unpkg.com/[email protected]/umd/keplergl.min.css" in html++ def test_default_uses_latest_stable_cdn_tag(self, sample_df):+ html = export_map_html(data={"test": sample_df}, config={})+ assert "unpkg.com/kepler.gl@3/umd/keplergl.min.js" in html+ assert "unpkg.com/kepler.gl@3/umd/keplergl.min.css" in html++ def test_contains_react_redux_deps(self, sample_df):+ html = export_map_html(data={"test": sample_df}, config={})+ assert "react.production.min.js" in html+ assert "react-dom.production.min.js" in html+ assert "redux.js" in html+ assert "react-redux.min.js" in html+ assert "styled-components.min.js" in html++ def test_contains_dataset(self, sample_df):+ html = export_map_html(data={"my_data": sample_df}, config={})+ assert "my_data" in html+ assert "processCsvData" in html++ def test_read_only_mode(self, sample_df):+ html = export_map_html(data={"d": sample_df}, config={}, read_only=True)+ assert "readOnly: true" in html++ def test_edit_mode(self, sample_df):+ html = export_map_html(data={"d": sample_df}, config={}, read_only=False)+ assert "readOnly: false" in html++ def test_center_map(self, sample_df):+ html = export_map_html(data={"d": sample_df}, config={}, center_map=True)+ assert "centerMap: true" in html++ def test_mapbox_token_embedded(self, sample_df):+ html = export_map_html(+ data={"d": sample_df},+ config={},+ mapbox_token="pk.test_token_123",+ )+ assert "pk.test_token_123" in html++ def test_config_embedded(self, sample_df):+ config = {"version": "v1", "config": {"mapState": {"zoom": 12}}}+ html = export_map_html(data={"d": sample_df}, config=config)+ assert '"zoom": 12' in html+ assert '"version": "v1"' in html++ def test_empty_config(self, sample_df):+ html = export_map_html(data={"d": sample_df}, config={})+ assert "var config = {};" in html++ def test_none_config(self, sample_df):+ html = export_map_html(data={"d": sample_df}, config=None)+ assert "var config = {};" in html++ def test_addDataToMap_dispatch(self, sample_df):+ html = export_map_html(data={"d": sample_df}, config={})+ assert "addDataToMap" in html+ assert "store.dispatch" in html++ def test_geojson_dataset(self):+ geojson = {+ "type": "FeatureCollection",+ "features": [{+ "type": "Feature",+ "geometry": {"type": "Point", "coordinates": [-122.4, 37.8]},+ "properties": {"name": "SF"},+ }],+ }+ html = export_map_html(data={"geo": geojson}, config={})+ assert "processGeojson" in html+ assert "FeatureCollection" in html+++class TestSaveToHtml:+ """Tests for the KeplerGl.save_to_html widget method."""++ def test_saves_file(self, sample_df, tmp_path):+ widget = KeplerGl(data={"cities": sample_df})+ out = str(tmp_path / "map.html")+ widget.save_to_html(file_name=out)+ assert os.path.exists(out)+ with open(out) as f:+ content = f.read()+ assert "<!DOCTYPE html>" in content+ assert "cities" in content+ assert "unpkg.com/kepler.gl@3/umd/keplergl.min.js" in content++ def test_saves_with_config(self, sample_df, tmp_path):+ config = {"version": "v1", "config": {"mapState": {"zoom": 5}}}+ widget = KeplerGl(data={"d": sample_df}, config=config)+ out = str(tmp_path / "map.html")+ widget.save_to_html(file_name=out)+ with open(out) as f:+ content = f.read()+ assert '"zoom": 5' in content++ def test_saves_with_override_data(self, sample_df, tmp_path):+ widget = KeplerGl(data={"original": sample_df})+ override = pd.DataFrame({"x": [1, 2], "y": [3, 4]})+ out = str(tmp_path / "map.html")+ widget.save_to_html(file_name=out, data={"override": override})+ with open(out) as f:+ content = f.read()+ assert "override" in content+ assert "original" not in content++ def test_saves_with_geodataframe(self, sample_gdf, tmp_path):+ widget = KeplerGl(data={"geo": sample_gdf})+ out = str(tmp_path / "map.html")+ widget.save_to_html(file_name=out)+ with open(out) as f:+ content = f.read()+ assert "processGeojson" in content++ def test_saves_read_only(self, sample_df, tmp_path):+ widget = KeplerGl(data={"d": sample_df})+ out = str(tmp_path / "map.html")+ widget.save_to_html(file_name=out, read_only=True)+ with open(out) as f:+ content = f.read()+ assert "readOnly: true" in content++ def test_default_filename(self, sample_df, tmp_path):+ original_cwd = os.getcwd()+ try:+ os.chdir(tmp_path)+ widget = KeplerGl(data={"d": sample_df})+ widget.save_to_html()+ assert os.path.exists("keplergl_map.html")+ finally:+ os.chdir(original_cwd)++ def test_print_message(self, sample_df, tmp_path, capsys):+ widget = KeplerGl(data={"d": sample_df})+ out = str(tmp_path / "test.html")+ widget.save_to_html(file_name=out)+ captured = capsys.readouterr()+ assert "Map saved to" in captured.out+ assert out in captured.out++ def test_html_is_utf8(self, tmp_path):+ df = pd.DataFrame({"city": ["São Paulo", "Zürich"], "lat": [-23.5, 47.4], "lng": [-46.6, 8.5]})+ widget = KeplerGl(data={"intl": df})+ out = str(tmp_path / "map.html")+ widget.save_to_html(file_name=out)+ with open(out, encoding="utf-8") as f:+ content = f.read()+ assert "São Paulo" in content+ assert "Zürich" in contentdiff --git a/bindings/python/tests/test_serializers.py b/bindings/python/tests/test_serializers.pyindex 4ae746070..4c91daac4 100644--- a/bindings/python/tests/test_serializers.py+++ b/bindings/python/tests/test_serializers.py@@ -226,6 +226,98 @@ class TestCSVSerialization:assert result["data"] == csv_data+class TestArrowSerialization:+ """Tests for Arrow IPC serialization of DataFrames."""++ def test_serialize_dataframe_arrow(self, sample_df):+ """Test basic DataFrame Arrow serialization."""+ result = serialize_dataset(sample_df, "test", use_arrow=True)+ assert result["id"] == "test"+ assert result["format"] == "arrow"+ assert isinstance(result["data"], str)++ def test_serialize_dataframe_arrow_roundtrip(self, sample_df):+ """Test that Arrow-serialized data can be deserialized back."""+ import base64+ import pyarrow as pa++ result = serialize_dataset(sample_df, "test", use_arrow=True)+ arrow_bytes = base64.b64decode(result["data"])+ reader = pa.ipc.open_stream(arrow_bytes)+ table = reader.read_all()+ assert table.num_rows == len(sample_df)+ assert table.num_columns == len(sample_df.columns)+ assert set(table.column_names) == set(sample_df.columns)++ def test_serialize_dataframe_arrow_preserves_types(self):+ """Test that Arrow serialization preserves numeric types accurately."""+ import base64+ import pyarrow as pa++ df = pd.DataFrame({+ 'int_col': [1, 2, 3],+ 'float_col': [1.1, 2.2, 3.3],+ 'str_col': ['a', 'b', 'c'],+ 'bool_col': [True, False, True],+ })+ result = serialize_dataset(df, "typed", use_arrow=True)+ assert result["format"] == "arrow"++ arrow_bytes = base64.b64decode(result["data"])+ table = pa.ipc.open_stream(arrow_bytes).read_all()+ assert table.column('int_col').to_pylist() == [1, 2, 3]+ assert table.column('float_col').to_pylist() == pytest.approx([1.1, 2.2, 3.3])+ assert table.column('str_col').to_pylist() == ['a', 'b', 'c']+ assert table.column('bool_col').to_pylist() == [True, False, True]++ def test_serialize_dataframe_arrow_with_cities(self):+ """Test Arrow serialization with city data (parallel to JSON test)."""+ import base64+ import pyarrow as pa++ df = pd.DataFrame({+ 'City': ['Buenos Aires', 'Brasilia', 'Santiago', 'Bogota', 'Caracas'],+ 'Country': ['Argentina', 'Brazil', 'Chile', 'Colombia', 'Venezuela'],+ 'Latitude': [-34.58, -15.78, -33.45, 4.60, 10.48],+ 'Longitude': [-58.66, -47.91, -70.66, -74.08, -66.86],+ })+ result = serialize_dataset(df, "cities", use_arrow=True)+ assert result["format"] == "arrow"++ arrow_bytes = base64.b64decode(result["data"])+ table = pa.ipc.open_stream(arrow_bytes).read_all()+ assert table.num_rows == 5+ assert 'City' in table.column_names+ assert 'Latitude' in table.column_names+ assert table.column('City').to_pylist()[0] == 'Buenos Aires'++ def test_serialize_dataframe_arrow_empty(self):+ """Test Arrow serialization of empty DataFrame."""+ import base64+ import pyarrow as pa++ df = pd.DataFrame({'col1': pd.Series([], dtype='float64'), 'col2': pd.Series([], dtype='str')})+ result = serialize_dataset(df, "empty", use_arrow=True)+ assert result["format"] == "arrow"++ arrow_bytes = base64.b64decode(result["data"])+ table = pa.ipc.open_stream(arrow_bytes).read_all()+ assert table.num_rows == 0+ assert set(table.column_names) == {'col1', 'col2'}++ def test_serialize_dataframe_arrow_default_off(self, sample_df):+ """Test that use_arrow=False (default) still produces JSON format."""+ result = serialize_dataset(sample_df, "test", use_arrow=False)+ assert result["format"] == "df"+ assert "columns" in result["data"]+ assert "data" in result["data"]++ def test_serialize_geodataframe_ignores_use_arrow(self, sample_gdf):+ """Test that GeoDataFrame always uses geoarrow regardless of use_arrow flag."""+ result = serialize_dataset(sample_gdf, "test", use_arrow=True)+ assert result["format"] == "geoarrow"++class TestEdgeCases:"""Tests for edge cases and error handling."""diff --git a/bindings/python/tests/test_widget.py b/bindings/python/tests/test_widget.pyindex d1ecd0cb9..00f7c5166 100644--- a/bindings/python/tests/test_widget.py+++ b/bindings/python/tests/test_widget.py@@ -39,3 +39,33 @@ def test_widget_with_config():config = {"version": "v1", "config": {"mapState": {"zoom": 10}}}widget = KeplerGl(config=config)assert widget.config == config+++def test_widget_use_arrow_default():+ widget = KeplerGl()+ assert widget._use_arrow is False+++def test_widget_use_arrow_enabled():+ widget = KeplerGl(use_arrow=True)+ assert widget._use_arrow is True+++def test_widget_use_arrow_with_dataframe(sample_df):+ widget = KeplerGl(data={"test": sample_df}, use_arrow=True)+ assert "test" in widget.data+ assert widget._use_arrow is True+++def test_add_data_use_arrow(sample_df):+ widget = KeplerGl()+ assert widget._use_arrow is False+ widget.add_data(sample_df, name="test", use_arrow=True)+ assert "test" in widget.data+ assert widget._use_arrow is True+++def test_add_data_use_arrow_none_preserves_widget_setting(sample_df):+ widget = KeplerGl(use_arrow=True)+ widget.add_data(sample_df, name="test")+ assert widget._use_arrow is Truediff --git a/bindings/python/uv.lock b/bindings/python/uv.lockindex f898cbc2f..3b694f4d2 100644--- a/bindings/python/uv.lock+++ b/bindings/python/uv.lock@@ -1582,7 +1582,7 @@ wheels = [[[package]]name = "keplergl"-version = "0.4.0rc1"+version = "0.4.0rc2"source = { editable = "." }dependencies = [{ name = "anywidget" },