Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat: reload and poll remotely hosted datasets (#3667)
Igor Dykhtac45373a45b1f
diff --git a/examples/README.md b/examples/README.mdindex d4eb91689..f6c4cee83 100644--- a/examples/README.md+++ b/examples/README.md@@ -1,6 +1,9 @@# Examples-A list of examples demonstrating how to add `kepler.gl` to your app. Each example is a standalone project that can be run locally.+A list of examples demonstrating how to add `kepler.gl` to your app. Most+examples are standalone projects that can be run locally. The [Live Data][live-data]+harness is started from the repo root (`yarn start:live-data`) so it can bundle+local `src/`.## Getting started@@ -48,6 +51,9 @@ yarn start- ### [Clicked Feature][clicked-feature]Read `visState.clicked` from Redux and show a GeoJSON feature's `shapeName` in a host-app sidebar outside the map.+- ### [Live Data][live-data]+ Remotely hosted CSV of points orbiting San Francisco on a 2-minute loop. Kepler.gl hydrates the URL on load and polls it every 300 ms so points move on the map.+- ### [Custom Layer][custom-layer]Add a custom deck.gl layer (`ContourLayer`) to kepler.gl's layer type selector, so it can be picked from the dropdown, configured with dataset columns, and rendered on the map.@@ -69,6 +75,7 @@ yarn start[replace-component]: replace-component/README.md[custom-theme]: custom-theme/README.md[clicked-feature]: clicked-feature/README.md+[live-data]: live-data/README.md[custom-layer]: custom-layer/README.md[custom-map-style]: custom-map-style/README.md[node-app]: node-app/README.mddiff --git a/examples/live-data/README.md b/examples/live-data/README.mdnew file mode 100644index 000000000..0223a174e--- /dev/null+++ b/examples/live-data/README.md@@ -0,0 +1,57 @@+# Live remotely hosted data++Loads a CORS CSV of points orbiting San Francisco as a remotely hosted dataset+and **polls it every 1 second**. Positions are computed from wall-clock time:+each point completes one full loop in **2 minutes**. A fetch returns the+positions at that moment (there is no server-side snapshot timer).++This is a manual test harness for snapshot refresh (`refreshDataset` /+`metadata.refreshIntervalMs`) on `DatasetType.EXTERNALLY_HOSTED`. It bundles+local monorepo `src/` (not a published npm package).++## Pre-requirements++- [Node.js ^20.x](http://nodejs.org)+- Repo root already installed (`yarn` in kepler.gl)++## Start++From the **repo root**:++```sh+yarn start:live-data+```++The app opens at [http://localhost:8083](http://localhost:8083) (8083 so it can+run next to `yarn start` on 8080). The CSV server listens at+[http://localhost:4010/vehicles.csv](http://localhost:4010/vehicles.csv).++## What to look for++- Three points on three rings around San Francisco. Adjacent rings move in+ opposite directions. One full orbit takes 2 minutes.+- The right sidebar **orbit** percent advances with each poll (`progress` /+ `orbit_s` in the table).+- Layers panel → one **Point** layer (trip is not auto-created). Refresh is+ set on the dataset row; the reload icon samples the current time immediately.+- Field names stay the same, so the point layer is kept (not rebuilt from+ scratch).++## CSV server only (Add Data URL)++From this folder, or the repo root:++```sh+node examples/live-data/server.mjs+```++Then in any Kepler.gl that already has remotely hosted datasets: **Add Data →+URL**++```+http://localhost:4010/vehicles.csv+```++Fetch, then set **Refresh** to 1s (or Custom) on the dataset in the Layers panel.++[yarn-install]: https://yarnpkg.com/getting-started/installdiff --git a/examples/live-data/esbuild.config.mjs b/examples/live-data/esbuild.config.mjsnew file mode 100644index 000000000..6ae09f094--- /dev/null+++ b/examples/live-data/esbuild.config.mjs@@ -0,0 +1,171 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import esbuild from 'esbuild';+import {replace} from 'esbuild-plugin-replace';+import fs from 'node:fs';+import path from 'node:path';+import process from 'node:process';+import {fileURLToPath} from 'node:url';+import {spawn} from 'node:child_process';++import KeplerPackage from '../../package.json' assert {type: 'json'};+import {startLiveDataServer} from './server.mjs';++const args = process.argv;+const __dirname = path.dirname(fileURLToPath(import.meta.url));+const LIB_DIR = path.join(__dirname, '../..');+const SRC_DIR = path.join(LIB_DIR, 'src');+const NODE_MODULES_DIR = path.join(LIB_DIR, 'node_modules');+const DIST_DIR = path.join(__dirname, 'dist');+const port = Number(process.env.LIVE_DATA_APP_PORT || 8083);+const dataPort = Number(process.env.LIVE_DATA_PORT || 4010);+const liveDataUrl = process.env.LIVE_DATA_URL || `http://localhost:${dataPort}/vehicles.csv`;++function localKeplerAliases() {+ const aliases = {+ react: `${NODE_MODULES_DIR}/react`,+ 'react-dom': `${NODE_MODULES_DIR}/react-dom`,+ 'react-dom/client': `${NODE_MODULES_DIR}/react-dom/client`,+ 'react-redux': `${NODE_MODULES_DIR}/react-redux`,+ 'styled-components': `${NODE_MODULES_DIR}/styled-components`,+ 'react-intl': `${NODE_MODULES_DIR}/react-intl`,+ 'react-palm': `${NODE_MODULES_DIR}/react-palm`,+ 'apache-arrow': `${NODE_MODULES_DIR}/apache-arrow`,+ 'tiny-warning': path.join(SRC_DIR, 'utils/src/noop.ts')+ };+ for (const workspace of KeplerPackage.workspaces) {+ const moduleName = workspace.split('/').pop();+ const srcPath = path.join(SRC_DIR, moduleName, 'src');+ aliases[`@kepler.gl/${moduleName}`] = fs.existsSync(srcPath)+ ? srcPath+ : path.join(SRC_DIR, moduleName);+ }+ return aliases;+}++function copyIndexHtml() {+ fs.mkdirSync(DIST_DIR, {recursive: true});+ fs.copyFileSync(path.join(__dirname, 'src/index.html'), path.join(DIST_DIR, 'index.html'));+}++const config = {+ platform: 'browser',+ format: 'iife',+ logLevel: 'info',+ logOverride: {+ 'unsupported-jsx-comment': 'silent'+ },+ absWorkingDir: __dirname,+ loader: {'.js': 'jsx', '.css': 'css'},+ entryPoints: [path.join(__dirname, 'src/app.tsx')],+ outfile: path.join(DIST_DIR, 'bundle.js'),+ bundle: true,+ alias: localKeplerAliases(),+ define: {+ NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development'),+ 'process.env.LIVE_DATA_URL': JSON.stringify(liveDataUrl),+ 'process.env.MapboxAccessToken': JSON.stringify(process.env.MapboxAccessToken || ''),+ 'process.env.DropboxClientId': JSON.stringify(process.env.DropboxClientId || ''),+ 'process.env.MapboxExportToken': JSON.stringify(process.env.MapboxExportToken || ''),+ 'process.env.CartoClientId': JSON.stringify(process.env.CartoClientId || ''),+ 'process.env.FoursquareClientId': JSON.stringify(process.env.FoursquareClientId || ''),+ 'process.env.FoursquareDomain': JSON.stringify(process.env.FoursquareDomain || ''),+ 'process.env.FoursquareAPIURL': JSON.stringify(process.env.FoursquareAPIURL || ''),+ 'process.env.FoursquareUserMapsURL': JSON.stringify(process.env.FoursquareUserMapsURL || ''),+ 'process.env.OpenAIToken': JSON.stringify(process.env.OpenAIToken || ''),+ 'process.env.NODE_DEBUG': JSON.stringify(false)+ },+ plugins: [+ replace({+ __PACKAGE_VERSION__: KeplerPackage.version,+ include: /constants\/src\/default-settings\.ts/+ }),+ {+ name: 'dedupe-singletons',+ setup(build) {+ build.onResolve(+ {filter: /^(styled-components|react-palm(\/|$)|react$|react-dom$)/},+ async resolveArgs => {+ if (resolveArgs.pluginData?.deduped) return;+ const result = await build.resolve(resolveArgs.path, {+ resolveDir: NODE_MODULES_DIR,+ kind: resolveArgs.kind,+ pluginData: {deduped: true}+ });+ return result;+ }+ );+ }+ },+ {+ name: 'copy-index-html',+ setup(build) {+ build.onStart(() => {+ copyIndexHtml();+ });+ }+ }+ ]+};++function openURL(url) {+ const cmd = {+ darwin: ['open'],+ linux: ['xdg-open'],+ win32: ['cmd', '/c', 'start']+ };+ const command = cmd[process.platform];+ if (command) {+ spawn(command[0], [...command.slice(1), url]);+ }+}++(async () => {+ if (args.includes('--build')) {+ const result = await esbuild+ .build({+ ...config,+ minify: true,+ sourcemap: false,+ metafile: true+ })+ .catch(e => {+ console.error(e);+ process.exit(1);+ });+ fs.writeFileSync(path.join(DIST_DIR, 'esbuild-metadata.json'), JSON.stringify(result.metafile));+ }++ if (args.includes('--start')) {+ startLiveDataServer(dataPort);+ await esbuild+ .context({+ ...config,+ minify: false,+ sourcemap: true,+ banner: {+ js: `new EventSource('/esbuild').addEventListener('change', () => location.reload());`+ }+ })+ .then(async ctx => {+ await ctx.watch();+ await ctx.serve({+ servedir: DIST_DIR,+ port,+ fallback: path.join(DIST_DIR, 'index.html'),+ onRequest: ({remoteAddress, method, path: reqPath, status, timeInMS}) => {+ console.info(remoteAddress, status, `"${method} ${reqPath}" [${timeInMS}ms]`);+ }+ });+ console.info(+ `kepler.gl live-data example running at http://localhost:${port}, press Ctrl+C to stop`+ );+ openURL(`http://localhost:${port}`);+ })+ .catch(e => {+ console.error(e);+ process.exit(1);+ });+ }+})();diff --git a/examples/live-data/package.json b/examples/live-data/package.jsonnew file mode 100644index 000000000..cf4bf9f39--- /dev/null+++ b/examples/live-data/package.json@@ -0,0 +1,11 @@+{+ "name": "kepler-live-data",+ "version": "0.0.1",+ "private": true,+ "license": "MIT",+ "scripts": {+ "start": "node esbuild.config.mjs --start",+ "start:data": "node server.mjs",+ "build": "node esbuild.config.mjs --build"+ }+}diff --git a/examples/live-data/server.mjs b/examples/live-data/server.mjsnew file mode 100644index 000000000..c34b8b02b--- /dev/null+++ b/examples/live-data/server.mjs@@ -0,0 +1,169 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++/**+ * Serves a CORS CSV of points orbiting San Francisco.+ *+ * Positions are a function of wall-clock time: each point completes one full+ * loop every 120 seconds. GET /vehicles.csv returns the current positions at+ * request time (no server-side snapshot timer).+ *+ * Kepler.gl polls this URL as DatasetType.EXTERNALLY_HOSTED.+ */+import http from 'node:http';+import path from 'node:path';+import {fileURLToPath} from 'node:url';++const DEFAULT_PORT = Number(process.env.LIVE_DATA_PORT || 4010);+const PERIOD_MS = Number(process.env.LIVE_DATA_PERIOD_MS || 120_000);+const POINT_COUNT = Number(process.env.LIVE_DATA_POINTS || 3);+const SF = {lat: 37.7749, lng: -122.4194};+const COS_LAT = Math.cos((SF.lat * Math.PI) / 180);+const KM_PER_DEG_LAT = 111.32;+const RINGS = 3;+const POINTS_PER_RING = Math.max(1, Math.round(POINT_COUNT / RINGS));++function corsHeaders(extra = {}) {+ return {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',+ 'Access-Control-Allow-Headers': 'If-None-Match, If-Modified-Since, Content-Type',+ 'Access-Control-Expose-Headers': 'ETag, Last-Modified',+ 'Cache-Control': 'no-store',+ ...extra+ };+}++function orbitProgress(nowMs) {+ const elapsed = ((nowMs % PERIOD_MS) + PERIOD_MS) % PERIOD_MS;+ return elapsed / PERIOD_MS;+}++function pointAt(nowMs, index) {+ const ring = Math.floor(index / POINTS_PER_RING);+ const onRing = index % POINTS_PER_RING;+ const radiusKm = 1.8 + ring * 1.2;+ const radiusLat = radiusKm / KM_PER_DEG_LAT;+ const radiusLng = radiusKm / (KM_PER_DEG_LAT * COS_LAT);+ const direction = ring % 2 === 0 ? 1 : -1;+ const start = (onRing / POINTS_PER_RING) * 2 * Math.PI + ring * 0.35;+ const tau = orbitProgress(nowMs);+ const theta = start + direction * tau * 2 * Math.PI;+ const lat = SF.lat + radiusLat * Math.sin(theta);+ const lng = SF.lng + radiusLng * Math.cos(theta);+ const dLat = direction * radiusLat * Math.cos(theta);+ const dLng = direction * -radiusLng * Math.sin(theta);+ const heading = (Math.atan2(dLng, dLat) * 180) / Math.PI;+ const speedKmh = ((2 * Math.PI * radiusKm) / (PERIOD_MS / 1000)) * 3600;+ return {+ id: `veh-${String(index + 1).padStart(2, '0')}`,+ lat,+ lng,+ heading: (heading + 360) % 360,+ speed: speedKmh,+ ring: ring + 1,+ progress: tau+ };+}++function buildCsv(now = new Date()) {+ const nowMs = now.getTime();+ const tau = orbitProgress(nowMs);+ const updatedAt = now.toISOString();+ const header = 'id,lat,lng,heading,speed,ring,progress,orbit_s,updated_at';+ const rows = Array.from({length: POINT_COUNT}, (_, index) => {+ const point = pointAt(nowMs, index);+ return [+ point.id,+ point.lat.toFixed(6),+ point.lng.toFixed(6),+ point.heading.toFixed(1),+ point.speed.toFixed(1),+ point.ring,+ point.progress.toFixed(4),+ (tau * (PERIOD_MS / 1000)).toFixed(2),+ updatedAt+ ].join(',');+ });+ return `${header}\n${rows.join('\n')}\n`;+}++function serveCsv(req, res) {+ const now = new Date();+ const csv = buildCsv(now);+ const lastModifiedHttp = now.toUTCString();+ // Unique per request so If-None-Match never 304s: each fetch is a new time sample.+ const etag = `"t-${now.getTime()}"`;+ res.writeHead(+ 200,+ corsHeaders({+ 'Content-Type': 'text/csv; charset=utf-8',+ 'Content-Length': Buffer.byteLength(csv),+ ETag: etag,+ 'Last-Modified': lastModifiedHttp+ })+ );+ if (req.method !== 'HEAD') {+ res.end(csv);+ return;+ }+ res.end();+}++function serveIndex(res) {+ const tau = orbitProgress(Date.now());+ const body = `<!DOCTYPE html>+<html>+ <head><title>kepler.gl live-data</title></head>+ <body style="font-family: sans-serif; max-width: 42em; padding: 24px">+ <h1>Live orbit CSV</h1>+ <p>${POINT_COUNT} points circle San Francisco. One full loop every ${+ PERIOD_MS / 1000+ }s (currently ${(tau * 100).toFixed(1)}% through the orbit).</p>+ <ul>+ <li><a href="/vehicles.csv">/vehicles.csv</a> — positions at request time</li>+ </ul>+ <p>Paste that URL into Kepler.gl Add Data → URL, then set Refresh to 1s (or Custom) on the dataset.</p>+ </body>+</html>`;+ res.writeHead(200, corsHeaders({'Content-Type': 'text/html; charset=utf-8'}));+ res.end(body);+}++export function startLiveDataServer(port = DEFAULT_PORT) {+ const server = http.createServer((req, res) => {+ const url = new URL(req.url || '/', `http://127.0.0.1:${port}`);+ if (req.method === 'OPTIONS') {+ res.writeHead(204, corsHeaders());+ res.end();+ return;+ }+ if (url.pathname === '/vehicles.csv') {+ serveCsv(req, res);+ return;+ }+ if (url.pathname === '/' || url.pathname === '/index.html') {+ serveIndex(res);+ return;+ }+ res.writeHead(404, corsHeaders({'Content-Type': 'text/plain'}));+ res.end('Not found\n');+ });++ server.listen(port, () => {+ console.info(+ `Live CSV at http://localhost:${port}/vehicles.csv (${POINT_COUNT} points, ${+ PERIOD_MS / 1000+ }s orbit)`+ );+ });++ return server;+}++const isDirectRun =+ Boolean(process.argv[1]) && fileURLToPath(import.meta.url) === path.resolve(process.argv[1]);++if (isDirectRun) {+ startLiveDataServer();+}diff --git a/examples/live-data/src/app.tsx b/examples/live-data/src/app.tsxnew file mode 100644index 000000000..80d23e2b7--- /dev/null+++ b/examples/live-data/src/app.tsx@@ -0,0 +1,247 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import * as React from 'react';+import {useState, useEffect} from 'react';+import ReactDOM from 'react-dom/client';+import {Provider, useDispatch, useSelector} from 'react-redux';+import {applyMiddleware, combineReducers, compose, createStore} from 'redux';++import keplerGlReducer, {enhanceReduxMiddleware} from '@kepler.gl/reducers';+import KeplerGl from '@kepler.gl/components';+import {addDataToMap, wrapTo} from '@kepler.gl/actions';+import {DatasetType} from '@kepler.gl/constants';+import {initApplicationConfig} from '@kepler.gl/utils';++initApplicationConfig({enableAnnotations: false});++const MAP_ID = 'map';+const SIDEBAR_WIDTH = 280;+const DATASET_ID = 'live-vehicles';+const LIVE_DATA_URL = process.env.LIVE_DATA_URL || 'http://localhost:4010/vehicles.csv';+const REFRESH_INTERVAL_MS = 300;++type KeplerRootState = {+ keplerGl: {+ [id: string]: {+ visState: {+ datasets: Record<+ string,+ {+ fields?: {name: string}[];+ dataContainer?: {+ numRows: () => number;+ valueAt: (row: number, col: number) => unknown;+ };+ metadata?: {+ refreshStatus?: string;+ refreshError?: string;+ refreshProgress?: number;+ lastFetchedAt?: number;+ refreshIntervalMs?: number;+ };+ }+ >;+ };+ };+ };+};++const reducers = combineReducers({+ keplerGl: keplerGlReducer.initialState({+ mapStyle: {+ styleType: 'dark-matter'+ },+ uiState: {+ readOnly: false,+ currentModal: null+ }+ })+});++const middlewares = enhanceReduxMiddleware([]);+const enhancers = applyMiddleware(...middlewares);+const composeEnhancers = (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;+const store = createStore(reducers, {}, composeEnhancers(enhancers));++function fieldValue(+ dataset: KeplerRootState['keplerGl'][string]['visState']['datasets'][string] | undefined,+ name: string+) {+ const col = dataset?.fields?.findIndex(field => field.name === name) ?? -1;+ if (col < 0 || !dataset?.dataContainer?.numRows()) {+ return undefined;+ }+ return dataset.dataContainer.valueAt(0, col);+}++function useWindowSize() {+ const [size, setSize] = useState({width: window.innerWidth, height: window.innerHeight});+ useEffect(() => {+ const onResize = () => setSize({width: window.innerWidth, height: window.innerHeight});+ window.addEventListener('resize', onResize);+ return () => window.removeEventListener('resize', onResize);+ }, []);+ return size;+}++const sidebarStyle: React.CSSProperties = {+ width: SIDEBAR_WIDTH,+ height: '100%',+ padding: 16,+ overflow: 'auto',+ background: '#242730',+ color: '#f7f7f7',+ fontFamily: 'Helvetica, Arial, sans-serif',+ fontSize: 13,+ lineHeight: 1.45,+ flexShrink: 0+};++function LiveDataSidebar() {+ const dataset = useSelector(+ (state: KeplerRootState) => state.keplerGl[MAP_ID]?.visState?.datasets?.[DATASET_ID]+ );+ const progressAlongOrbit = fieldValue(dataset, 'progress');+ const orbitS = fieldValue(dataset, 'orbit_s');+ const updatedAt = fieldValue(dataset, 'updated_at');+ const lastFetchedAt = dataset?.metadata?.lastFetchedAt;+ const status = dataset?.metadata?.refreshStatus || (dataset ? 'idle' : 'loading');+ const progress = dataset?.metadata?.refreshProgress;++ return (+ <aside style={sidebarStyle}>+ <h2 style={{margin: '0 0 8px', fontSize: 16}}>Live orbit</h2>+ <p style={{margin: '0 0 12px', color: '#c3c9d5'}}>+ CSV at <code>{LIVE_DATA_URL}</code> returns the current positions of 3 points circling San+ Francisco (one full loop every 2 min). Kepler polls that URL once a second and replaces the+ table without tearing down the point layer.+ </p>+ <div style={{display: 'grid', gap: 8}}>+ <div style={{display: 'flex', justifyContent: 'space-between', gap: 12}}>+ <span style={{color: '#c3c9d5'}}>status</span>+ <span>+ {status}+ {status === 'loading' && typeof progress === 'number' ? ` ${progress}%` : ''}+ </span>+ </div>+ <div style={{display: 'flex', justifyContent: 'space-between', gap: 12}}>+ <span style={{color: '#c3c9d5'}}>orbit</span>+ <span style={{fontSize: 20, fontWeight: 600}}>+ {progressAlongOrbit == null+ ? '—'+ : `${Math.round(Number(progressAlongOrbit) * 100)}% (${+ orbitS == null ? '—' : `${Number(orbitS).toFixed(1)}s`+ } / 120s)`}+ </span>+ </div>+ <div style={{display: 'flex', justifyContent: 'space-between', gap: 12}}>+ <span style={{color: '#c3c9d5'}}>updated_at</span>+ <span>{updatedAt == null ? '—' : String(updatedAt)}</span>+ </div>+ <div style={{display: 'flex', justifyContent: 'space-between', gap: 12}}>+ <span style={{color: '#c3c9d5'}}>last fetch</span>+ <span>{lastFetchedAt ? new Date(lastFetchedAt).toLocaleTimeString() : '—'}</span>+ </div>+ <div style={{display: 'flex', justifyContent: 'space-between', gap: 12}}>+ <span style={{color: '#c3c9d5'}}>rows</span>+ <span>{dataset?.dataContainer?.numRows?.() ?? 0}</span>+ </div>+ </div>+ {dataset?.metadata?.refreshError ? (+ <p style={{margin: '12px 0 0', color: '#f19c99'}}>{dataset.metadata.refreshError}</p>+ ) : null}+ <p style={{margin: '16px 0 0', color: '#c3c9d5'}}>+ In the Layers panel, dataset refresh is set to 1s. Click the reload icon to sample the orbit+ immediately.+ </p>+ </aside>+ );+}++const App = () => {+ const dispatch = useDispatch();+ const {width, height} = useWindowSize();++ useEffect(() => {+ dispatch(+ wrapTo(+ MAP_ID,+ addDataToMap({+ datasets: {+ info: {+ id: DATASET_ID,+ label: 'Live orbit',+ type: DatasetType.EXTERNALLY_HOSTED+ },+ data: {fields: [], rows: []},+ metadata: {+ source: LIVE_DATA_URL,+ sourceFormat: 'csv',+ refreshIntervalMs: REFRESH_INTERVAL_MS+ }+ },+ options: {+ centerMap: true,+ autoCreateLayers: false,+ layerVisConfig: {radius: 24, filled: true, opacity: 0.85}+ },+ config: {+ version: 'v1',+ config: {+ visState: {+ layers: [+ {+ id: 'live-orbit-point',+ type: 'point',+ config: {+ dataId: DATASET_ID,+ label: 'Live orbit',+ columns: {lat: 'lat', lng: 'lng', altitude: null},+ isVisible: true,+ visConfig: {radius: 24, filled: true, opacity: 0.85}+ }+ }+ ]+ },+ mapState: {+ latitude: 37.7749,+ longitude: -122.4194,+ zoom: 12.2,+ pitch: 0,+ bearing: 0+ },+ mapStyle: {+ styleType: 'dark-matter'+ }+ }+ }+ })+ )+ );+ }, [dispatch]);++ return (+ <div style={{display: 'flex', width: '100%', height: '100%'}}>+ <div style={{position: 'relative', flex: 1, minWidth: 0}}>+ <KeplerGl+ mapboxApiAccessToken="pk.xxx.yyy"+ id={MAP_ID}+ width={Math.max(width - SIDEBAR_WIDTH, 0)}+ height={height}+ />+ </div>+ <LiveDataSidebar />+ </div>+ );+};++const Root = () => (+ <Provider store={store}>+ <App />+ </Provider>+);++const container = document.getElementById('root');+const root = ReactDOM.createRoot(container!);+root.render(<Root />);diff --git a/examples/live-data/src/index.html b/examples/live-data/src/index.htmlnew file mode 100644index 000000000..e8138c189--- /dev/null+++ b/examples/live-data/src/index.html@@ -0,0 +1,15 @@+<!DOCTYPE html>+<html>+ <head>+ <title>kepler.gl Live Data</title>+ <style>+ * { box-sizing: border-box; }+ html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; }+ #root { width: 100%; height: 100%; }+ </style>+ </head>+ <body>+ <div id="root" />+ <script src="./bundle.js"></script>+ </body>+</html>diff --git a/examples/live-data/tsconfig.json b/examples/live-data/tsconfig.jsonnew file mode 100644index 000000000..1035fe6da--- /dev/null+++ b/examples/live-data/tsconfig.json@@ -0,0 +1,11 @@+{+ "compilerOptions": {+ "sourceMap": true,+ "module": "commonjs",+ "target": "es5",+ "jsx": "react",+ "esModuleInterop": true+ },+ "include": ["src"],+ "compileOnSave": false+}diff --git a/package.json b/package.jsonindex 059e8d9de..d1e0e775a 100644--- a/package.json+++ b/package.json@@ -70,6 +70,7 @@"start:replace-component": "yarn install-and-start examples/replace-component start:local","start:custom-theme": "yarn install-and-start examples/custom-theme start-local","start:custom-map-style": "yarn install-and-start examples/custom-map-style start-local",+ "start:live-data": "node examples/live-data/esbuild.config.mjs --start","start:node-app": "yarn install-and-start examples/node-app start-local","start:web": "yarn install-and-start website start","start:https": "yarn install-and-start examples/demo-app start-local-https",diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.tsindex 9d1005e53..59048b6df 100644--- a/src/actions/src/action-types.ts+++ b/src/actions/src/action-types.ts@@ -115,6 +115,10 @@ export const ActionTypes = {NEXT_FILE_BATCH: `${ACTION_PREFIX}NEXT_FILE_BATCH`,PROCESS_FILE_CONTENT: `${ACTION_PREFIX}PROCESS_FILE_CONTENT`,UPDATE_TABLE_COLOR: `${ACTION_PREFIX}UPDATE_TABLE_COLOR`,+ REFRESH_DATASET: `${ACTION_PREFIX}REFRESH_DATASET`,+ REFRESH_DATASET_SUCCESS: `${ACTION_PREFIX}REFRESH_DATASET_SUCCESS`,+ REFRESH_DATASET_ERROR: `${ACTION_PREFIX}REFRESH_DATASET_ERROR`,+ REFRESH_DATASET_PROGRESS: `${ACTION_PREFIX}REFRESH_DATASET_PROGRESS`,ADD_EFFECT: `${ACTION_PREFIX}ADD_EFFECT`,REORDER_EFFECT: `${ACTION_PREFIX}REORDER_EFFECT`,REMOVE_EFFECT: `${ACTION_PREFIX}REMOVE_EFFECT`,diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.tsindex 0e94004f4..2deaa503f 100644--- a/src/actions/src/vis-state-actions.ts+++ b/src/actions/src/vis-state-actions.ts@@ -28,7 +28,8 @@ import {AnimationConfig,FilterAnimationConfig,LayerOrder,- LayerOrderGroup+ LayerOrderGroup,+ ProtoDataset} from '@kepler.gl/types';import {createAction} from '@reduxjs/toolkit';@@ -945,6 +946,91 @@ export function updateTableColor(};}+export type RefreshDatasetUpdaterAction = {+ dataId: string;+};+/**+ * Re-fetch an externally hosted dataset from its source URL.+ * @memberof visStateActions+ * @param dataId dataset id+ * @returns action+ * @public+ */+export function refreshDataset(+ dataId: string+): Merge<RefreshDatasetUpdaterAction, {type: typeof ActionTypes.REFRESH_DATASET}> {+ return {+ type: ActionTypes.REFRESH_DATASET,+ dataId+ };+}++export type RefreshDatasetSuccessUpdaterAction = {+ dataId: string;+ result: {+ data: ProtoDataset['data'] | null;+ notModified: boolean;+ etag?: string;+ lastModified?: string;+ size?: number;+ };+};+/**+ * Apply a successful remote dataset refresh.+ * @memberof visStateActions+ * @returns action+ */+export function refreshDatasetSuccess(+ dataId: string,+ result: RefreshDatasetSuccessUpdaterAction['result']+): Merge<RefreshDatasetSuccessUpdaterAction, {type: typeof ActionTypes.REFRESH_DATASET_SUCCESS}> {+ return {+ type: ActionTypes.REFRESH_DATASET_SUCCESS,+ dataId,+ result+ };+}++export type RefreshDatasetErrorUpdaterAction = {+ dataId: string;+ error: Error;+};+/**+ * Record a failed remote dataset refresh.+ * @memberof visStateActions+ * @returns action+ */+export function refreshDatasetError(+ dataId: string,+ error: Error+): Merge<RefreshDatasetErrorUpdaterAction, {type: typeof ActionTypes.REFRESH_DATASET_ERROR}> {+ return {+ type: ActionTypes.REFRESH_DATASET_ERROR,+ dataId,+ error+ };+}++export type RefreshDatasetProgressUpdaterAction = {+ dataId: string;+ percent: number;+};+/**+ * Update download progress for an in-flight remote dataset refresh (0–100).+ * @memberof visStateActions+ * @returns action+ */+export function refreshDatasetProgress(+ dataId: string,+ percent: number+): Merge<RefreshDatasetProgressUpdaterAction, {type: typeof ActionTypes.REFRESH_DATASET_PROGRESS}> {+ return {+ type: ActionTypes.REFRESH_DATASET_PROGRESS,+ dataId,+ percent+ };+}+export type SortTableColumnUpdaterAction = {dataId: string;column: string;diff --git a/src/components/src/common/file-uploader/file-upload.tsx b/src/components/src/common/file-uploader/file-upload.tsxindex 7da590359..f74a5f072 100644--- a/src/components/src/common/file-uploader/file-upload.tsx+++ b/src/components/src/common/file-uploader/file-upload.tsx@@ -51,7 +51,8 @@ const StyledFileDrop = styled.div<StyledFileDropProps>`border-radius: 4px;border-style: ${props => (props.$dragOver ? 'solid' : 'dashed')};border-width: 1px;- border-color: ${props => (props.$dragOver ? props.theme.textColorLT : props.theme.subtextColorLT)};+ border-color: ${props =>+ props.$dragOver ? props.theme.textColorLT : props.theme.subtextColorLT};text-align: center;width: 100%;min-height: 360px;@@ -333,8 +334,7 @@ function FileUploadFactory() {const {remoteUrl, remoteFormat, remoteError} = this.state;const {intl} = this.props;const showFormatSelector = getApplicationConfig().enableRemoteFileFormatSelector;- const format =- showFormatSelector && remoteFormat !== 'auto' ? remoteFormat : undefined;+ const format = showFormatSelector && remoteFormat !== 'auto' ? remoteFormat : undefined;if (!remoteUrl || remoteError || this.state.remoteLoading) {if (!remoteUrl) {this.setState({remoteError: {message: 'Incorrect URL'}});@@ -403,8 +403,16 @@ function FileUploadFactory() {};render() {- const {dragOver, files, errorFiles, remoteUrl, remoteFormat, remoteError, remoteLoading, remoteProgress} =- this.state;+ const {+ dragOver,+ files,+ errorFiles,+ remoteUrl,+ remoteFormat,+ remoteError,+ remoteLoading,+ remoteProgress+ } = this.state;const {fileLoading, fileLoadingProgress, theme, intl} = this.props;const {fileExtensions = [], fileFormatNames = []} = this.props;const showFormatSelector = getApplicationConfig().enableRemoteFileFormatSelector;@@ -505,6 +513,7 @@ function FileUploadFactory() {/>{showFormatSelector ? (<StyledRemoteFormatSelect+ className="file-uploader__remote-format"aria-label={intl.formatMessage({id: 'fileUploader.format'})}value={remoteFormat}onChange={this._onRemoteFormatChange}diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsxindex a822d5377..9aded605e 100644--- a/src/components/src/kepler-gl.tsx+++ b/src/components/src/kepler-gl.tsx@@ -60,6 +60,7 @@ import GeoCoderPanelFactory from './geocoder-panel';import EffectManagerFactory from './effects/effect-manager';import DndContextFactory from './dnd-context';import {CloudListProvider} from './hooks/use-cloud-list-provider';+import RemoteDatasetRefreshController from './remote-dataset-refresh-controller';import {filterObjectByPredicate,@@ -553,9 +554,7 @@ function KeplerGlFactory(this.uiThemeSelector,(theme, uiTheme) => {// When theme toggle is enabled, uiState.theme drives light/dark switching.- const themeInput = getApplicationConfig().enableThemeToggle- ? uiTheme || THEME.dark- : theme;+ const themeInput = getApplicationConfig().enableThemeToggle ? uiTheme || THEME.dark : theme;if (typeof themeInput === 'object' && themeInput !== null) {return {@@ -701,12 +700,18 @@ function KeplerGlFactory(ref={this.root}><NotificationPanel {...notificationPanelFields} />+ <RemoteDatasetRefreshController+ datasets={visState.datasets}+ refreshDataset={this.props.visStateActions.refreshDataset}+ /><DndContext visState={visState}>{!uiState.readOnly && !readOnly && <SidePanel {...sideFields} />}<MapsLayoutclassName="maps"mapState={this.props.mapState}- onSetSwipeComparePercentage={this.props.mapStateActions.setSwipeComparePercentage}+ onSetSwipeComparePercentage={+ this.props.mapStateActions.setSwipeComparePercentage+ }>{mapContainers}</MapsLayout>diff --git a/src/components/src/remote-dataset-refresh-controller.tsx b/src/components/src/remote-dataset-refresh-controller.tsxnew file mode 100644index 000000000..29d1c8a6c--- /dev/null+++ b/src/components/src/remote-dataset-refresh-controller.tsx@@ -0,0 +1,54 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {useEffect, useMemo} from 'react';+import {DatasetType, getDatasetRefreshIntervalMs} from '@kepler.gl/constants';+import {Datasets} from '@kepler.gl/table';++type RemoteDatasetRefreshControllerProps = {+ datasets: Datasets;+ refreshDataset?: (dataId: string) => void;+};++/**+ * Polls remotely hosted datasets that have metadata.refreshIntervalMs set.+ * Lives on KeplerGl so polling continues when the side panel is closed.+ */+export default function RemoteDatasetRefreshController({+ datasets,+ refreshDataset+}: RemoteDatasetRefreshControllerProps) {+ const pollTargets = useMemo(+ () =>+ Object.values(datasets)+ .filter(+ dataset =>+ dataset.type === DatasetType.EXTERNALLY_HOSTED &&+ getDatasetRefreshIntervalMs(dataset.metadata) > 0+ )+ .map(dataset => ({+ id: dataset.id,+ intervalMs: getDatasetRefreshIntervalMs(dataset.metadata)+ })),+ [datasets]+ );++ const pollKey = JSON.stringify(+ pollTargets.slice().sort((a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))+ );++ useEffect(() => {+ const targets: {id: string; intervalMs: number}[] = JSON.parse(pollKey);+ if (!refreshDataset || !targets.length) {+ return undefined;+ }+ const timers = targets.map(target =>+ window.setInterval(() => refreshDataset(target.id), target.intervalMs)+ );+ return () => {+ timers.forEach(timer => window.clearInterval(timer));+ };+ }, [pollKey, refreshDataset]);++ return null;+}diff --git a/src/components/src/side-panel/common/dataset-info.tsx b/src/components/src/side-panel/common/dataset-info.tsxindex 495b79a2b..8833ca44e 100644--- a/src/components/src/side-panel/common/dataset-info.tsx+++ b/src/components/src/side-panel/common/dataset-info.tsx@@ -1,54 +1,323 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React from 'react';+import React, {useCallback, useEffect, useState} from 'react';import styled from 'styled-components';import {format} from 'd3-format';+import {useIntl} from 'react-intl';-import {DatasetType} from '@kepler.gl/constants';+import {+ DatasetType,+ DATASET_REFRESH_CUSTOM_VALUE,+ DATASET_REFRESH_DEFAULT_CUSTOM_MS,+ DATASET_REFRESH_INTERVAL_OPTIONS,+ DATASET_REFRESH_MIN_INTERVAL_MS,+ formatCustomRefreshSeconds,+ getDatasetRefreshIntervalMs,+ isPresetDatasetRefreshInterval,+ parseCustomRefreshIntervalMs+} from '@kepler.gl/constants';import {FormattedMessage} from '@kepler.gl/localization';import {DataContainerInterface} from '@kepler.gl/utils';+import {VisStateActions, ActionHandler} from '@kepler.gl/actions';+import {Reset} from '../../common/icons';+import {Tooltip} from '../../common/styled-components';+import DatasetRefreshProgressIcon from './dataset-refresh-progress';const numFormat = format(',');type MiniDataset = {+ id: string;dataContainer: DataContainerInterface;type?: string;+ metadata?: {+ refreshIntervalMs?: number;+ refreshStatus?: string;+ refreshProgress?: number;+ };};export type DatasetInfoProps = {dataset: MiniDataset;+ showRefreshSettings?: boolean;+ refreshDataset?: ActionHandler<typeof VisStateActions.refreshDataset>;+ updateDatasetProps?: ActionHandler<typeof VisStateActions.updateDatasetProps>;};const StyledDataRowCount = styled.div`font-size: 11px;color: ${props => props.theme.subtextColor};padding-left: 19px;+ display: flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+`;++const StyledRefreshing = styled.span`+ display: inline-flex;+ align-items: center;+ gap: 4px;+ color: ${props => props.theme.inputColor};+`;++const StyledRefreshSettings = styled.div`+ display: inline-flex;+ align-items: center;+ gap: 8px;+ flex-wrap: wrap;+`;++const StyledRefreshLabel = styled.label`+ display: inline-flex;+ align-items: center;+ gap: 4px;+ margin: 0;+`;++const StyledRefreshSelect = styled.select`+ ${props => props.theme.input};+ height: 18px;+ font-size: 11px;+ padding: 0 4px;+ width: auto;+ max-width: 96px;+ cursor: pointer;+ background-color: transparent;+`;++const StyledCustomSeconds = styled.input`+ ${props => props.theme.input};+ height: 18px;+ font-size: 11px;+ padding: 0 4px;+ width: 52px;+ background-color: transparent;+`;++const StyledCustomUnit = styled.span`+ font-size: 11px;+`;++const StyledRefreshNow = styled.button`+ display: inline-flex;+ align-items: center;+ justify-content: center;+ margin: 0;+ padding: 0;+ border: 0;+ background: transparent;+ color: ${props => props.theme.subtextColor};+ cursor: pointer;+ width: 14px;+ height: 14px;++ &:disabled {+ cursor: default;+ opacity: 0.5;+ }++ &:hover:not(:disabled) {+ color: ${props => props.theme.textColorHl};+ }`;export default function DatasetInfoFactory() {- const DatasetInfo: React.FC<DatasetInfoProps> = ({dataset}: DatasetInfoProps) => (- <StyledDataRowCount className="source-data-rows">- <FormattedMessage- id={- dataset.type === DatasetType.VECTOR_TILE- ? 'datasetInfo.vectorTile'- : dataset.type === DatasetType.RASTER_TILE- ? 'datasetInfo.rasterTile'- : dataset.type === DatasetType.WMS_TILE- ? 'datasetInfo.wmsTile'- : dataset.type === DatasetType.TILE_3D- ? 'datasetInfo.tile3d'- : dataset.type === DatasetType.BITMAP- ? 'datasetInfo.bitmap'- : dataset.type === DatasetType.EXTERNALLY_HOSTED- ? 'datasetInfo.remoteFile'- : 'datasetInfo.rowCount'+ const DatasetInfo: React.FC<DatasetInfoProps> = ({+ dataset,+ showRefreshSettings,+ refreshDataset,+ updateDatasetProps+ }) => {+ const intl = useIntl();+ const isRemote = dataset.type === DatasetType.EXTERNALLY_HOSTED;+ const intervalMs = getDatasetRefreshIntervalMs(dataset.metadata);+ const matchingOption = DATASET_REFRESH_INTERVAL_OPTIONS.find(+ option => option.value === intervalMs+ );+ const isCustomInterval = intervalMs > 0 && !isPresetDatasetRefreshInterval(intervalMs);+ const [customMode, setCustomMode] = useState(isCustomInterval);+ const [customSeconds, setCustomSeconds] = useState(() =>+ formatCustomRefreshSeconds(intervalMs || DATASET_REFRESH_DEFAULT_CUSTOM_MS)+ );+ const showCustomInput = customMode || isCustomInterval;+ const selectValue = showCustomInput+ ? DATASET_REFRESH_CUSTOM_VALUE+ : String(matchingOption ? matchingOption.value : 0);++ useEffect(() => {+ const ms = getDatasetRefreshIntervalMs(dataset.metadata);+ const custom = ms > 0 && !isPresetDatasetRefreshInterval(ms);+ setCustomMode(custom);+ setCustomSeconds(formatCustomRefreshSeconds(ms || DATASET_REFRESH_DEFAULT_CUSTOM_MS));+ }, [dataset.id, dataset.metadata?.refreshIntervalMs]);++ const spinning = dataset.metadata?.refreshStatus === 'loading';+ const progress =+ typeof dataset.metadata?.refreshProgress === 'number'+ ? dataset.metadata.refreshProgress+ : undefined;+ const showPercent = spinning && typeof progress === 'number' && progress > 0 && progress < 100;+ const showRefreshControls = Boolean(+ showRefreshSettings && isRemote && (refreshDataset || updateDatasetProps)+ );++ const onRefreshNow = useCallback(+ (event: React.MouseEvent) => {+ event.stopPropagation();+ if (!spinning) {+ refreshDataset?.(dataset.id);+ }+ },+ [dataset.id, refreshDataset, spinning]+ );++ const commitCustomInterval = useCallback(+ (secondsText: string) => {+ const nextMs = parseCustomRefreshIntervalMs(secondsText);+ if (nextMs == null) {+ setCustomSeconds(+ formatCustomRefreshSeconds(intervalMs || DATASET_REFRESH_DEFAULT_CUSTOM_MS)+ );+ return;+ }+ setCustomSeconds(formatCustomRefreshSeconds(nextMs));+ if (nextMs !== intervalMs) {+ updateDatasetProps?.(dataset.id, {metadata: {refreshIntervalMs: nextMs}});}- values={{rowCount: numFormat(dataset.dataContainer.numRows())}}- />- </StyledDataRowCount>- );+ },+ [dataset.id, intervalMs, updateDatasetProps]+ );++ const onRefreshIntervalChange = useCallback(+ (event: React.ChangeEvent<HTMLSelectElement>) => {+ event.stopPropagation();+ const value = event.target.value;+ if (value === DATASET_REFRESH_CUSTOM_VALUE) {+ const secondsText = formatCustomRefreshSeconds(+ intervalMs || DATASET_REFRESH_DEFAULT_CUSTOM_MS+ );+ const nextMs = parseCustomRefreshIntervalMs(secondsText);+ setCustomMode(true);+ setCustomSeconds(secondsText);+ if (!intervalMs && nextMs != null) {+ updateDatasetProps?.(dataset.id, {+ metadata: {refreshIntervalMs: nextMs}+ });+ }+ return;+ }+ setCustomMode(false);+ updateDatasetProps?.(dataset.id, {+ metadata: {refreshIntervalMs: Number(value) || 0}+ });+ },+ [dataset.id, intervalMs, updateDatasetProps]+ );++ return (+ <StyledDataRowCount className="source-data-rows" aria-busy={spinning}>+ <FormattedMessage+ id={+ dataset.type === DatasetType.VECTOR_TILE+ ? 'datasetInfo.vectorTile'+ : dataset.type === DatasetType.RASTER_TILE+ ? 'datasetInfo.rasterTile'+ : dataset.type === DatasetType.WMS_TILE+ ? 'datasetInfo.wmsTile'+ : dataset.type === DatasetType.TILE_3D+ ? 'datasetInfo.tile3d'+ : dataset.type === DatasetType.BITMAP+ ? 'datasetInfo.bitmap'+ : isRemote+ ? 'datasetInfo.remoteFile'+ : 'datasetInfo.rowCount'+ }+ values={{rowCount: numFormat(dataset.dataContainer.numRows())}}+ />+ {spinning ? (+ <StyledRefreshing className="dataset-refresh-status">+ <DatasetRefreshProgressIcon percent={progress} size={12} />+ <FormattedMessage+ id={showPercent ? 'datasetInfo.refreshingPercent' : 'datasetInfo.refreshing'}+ values={{percent: Math.round(progress ?? 0)}}+ />+ </StyledRefreshing>+ ) : null}+ {showRefreshControls ? (+ <StyledRefreshSettings+ className="dataset-refresh-settings"+ onClick={event => event.stopPropagation()}+ >+ {updateDatasetProps ? (+ <StyledRefreshLabel>+ <FormattedMessage id="datasetInfo.refreshInterval" />+ <StyledRefreshSelect+ aria-label={intl.formatMessage({id: 'datasetInfo.refreshInterval'})}+ value={selectValue}+ onChange={onRefreshIntervalChange}+ >+ {DATASET_REFRESH_INTERVAL_OPTIONS.map(option => (+ <option key={option.value} value={String(option.value)}>+ {intl.formatMessage({id: option.labelId})}+ </option>+ ))}+ <option value={DATASET_REFRESH_CUSTOM_VALUE}>+ {intl.formatMessage({id: 'datasetTitle.refreshCustom'})}+ </option>+ </StyledRefreshSelect>+ {showCustomInput ? (+ <>+ <StyledCustomSeconds+ type="number"+ min={DATASET_REFRESH_MIN_INTERVAL_MS / 1000}+ step={0.1}+ inputMode="decimal"+ className="dataset-refresh-custom-seconds"+ aria-label={intl.formatMessage({id: 'datasetInfo.refreshCustomSeconds'})}+ value={customSeconds}+ onChange={event => {+ event.stopPropagation();+ setCustomSeconds(event.target.value);+ }}+ onBlur={event => commitCustomInterval(event.target.value)}+ onKeyDown={event => {+ event.stopPropagation();+ if (event.key === 'Enter') {+ event.preventDefault();+ commitCustomInterval(customSeconds);+ (event.target as HTMLInputElement).blur();+ }+ }}+ />+ <StyledCustomUnit>s</StyledCustomUnit>+ </>+ ) : null}+ </StyledRefreshLabel>+ ) : null}+ {refreshDataset ? (+ <StyledRefreshNow+ type="button"+ className="dataset-refresh-now"+ aria-label={intl.formatMessage({id: 'datasetTitle.refreshDataset'})}+ data-tip+ data-for={`refresh-now-${dataset.id}`}+ disabled={spinning}+ onClick={onRefreshNow}+ >+ <Reset height="14px" />+ <Tooltip id={`refresh-now-${dataset.id}`} effect="solid">+ <span>+ <FormattedMessage id={'datasetTitle.refreshDataset'} />+ </span>+ </Tooltip>+ </StyledRefreshNow>+ ) : null}+ </StyledRefreshSettings>+ ) : null}+ </StyledDataRowCount>+ );+ };return DatasetInfo;}diff --git a/src/components/src/side-panel/common/dataset-refresh-progress.tsx b/src/components/src/side-panel/common/dataset-refresh-progress.tsxnew file mode 100644index 000000000..13f18d7b1--- /dev/null+++ b/src/components/src/side-panel/common/dataset-refresh-progress.tsx@@ -0,0 +1,78 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import styled, {css, keyframes} from 'styled-components';++const spin = keyframes`+ to {+ transform: rotate(360deg);+ }+`;++const StyledProgress = styled.svg<{$indeterminate?: boolean}>`+ display: block;+ flex-shrink: 0;+ ${props =>+ props.$indeterminate &&+ css`+ animation: ${spin} 0.8s linear infinite;+ `}+`;++export type DatasetRefreshProgressIconProps = {+ /** Download progress from 0–100. Omit or 0 for an indeterminate spinner. */+ percent?: number;+ size?: number;+};++/**+ * Circular refresh indicator: spinning arc while size is unknown, filling ring+ * when Content-Length is available.+ */+export default function DatasetRefreshProgressIcon({+ percent,+ size = 14+}: DatasetRefreshProgressIconProps) {+ const strokeWidth = 2;+ const radius = (size - strokeWidth) / 2;+ const circumference = 2 * Math.PI * radius;+ const determinate = typeof percent === 'number' && percent > 0;+ const clamped = determinate ? Math.max(0, Math.min(100, percent)) : 0;+ const dashOffset = determinate ? circumference * (1 - clamped / 100) : circumference * 0.75;++ return (+ <StyledProgress+ $indeterminate={!determinate}+ width={size}+ height={size}+ viewBox={`0 0 ${size} ${size}`}+ role="progressbar"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={determinate ? Math.round(clamped) : undefined}+ >+ <circle+ cx={size / 2}+ cy={size / 2}+ r={radius}+ fill="none"+ stroke="currentColor"+ strokeWidth={strokeWidth}+ opacity={0.25}+ />+ <circle+ cx={size / 2}+ cy={size / 2}+ r={radius}+ fill="none"+ stroke="currentColor"+ strokeWidth={strokeWidth}+ strokeLinecap="round"+ strokeDasharray={circumference}+ strokeDashoffset={dashOffset}+ transform={`rotate(-90 ${size / 2} ${size / 2})`}+ />+ </StyledProgress>+ );+}diff --git a/src/components/src/side-panel/common/dataset-title.tsx b/src/components/src/side-panel/common/dataset-title.tsxindex f38464363..f5c15ba30 100644--- a/src/components/src/side-panel/common/dataset-title.tsx+++ b/src/components/src/side-panel/common/dataset-title.tsx@@ -3,11 +3,13 @@import React, {useCallback, useRef, useState} from 'react';import styled from 'styled-components';+import {useIntl} from 'react-intl';import {FormattedMessage} from '@kepler.gl/localization';import {Table} from '@kepler.gl/layers';import {CenterFlexbox, Tooltip} from '../../common/styled-components';-import {ArrowRight, Trash} from '../../common/icons';+import {ArrowRight, Clock, Trash, WarningSign} from '../../common/icons';+import {DatasetType} from '@kepler.gl/constants';import DatasetTagFactory from './dataset-tag';import CustomPicker from '../layer-panel/custom-picker';import {Portaled} from '../..';@@ -48,11 +50,44 @@ const DataTagAction = styled.div`opacity: 0;`;+const DataTagActionButton = styled.button`+ display: inline-flex;+ align-items: center;+ justify-content: center;+ margin-left: 12px;+ width: 16px;+ height: 16px;+ padding: 0;+ border: 0;+ background: transparent;+ color: inherit;+ cursor: pointer;+ opacity: 0;++ &:focus-visible {+ opacity: 1;+ outline: 1px solid ${props => props.theme.textColorHl};+ outline-offset: 1px;+ }+`;++const StyledRefreshError = styled.div`+ display: inline-flex;+ align-items: center;+ margin-left: 8px;+ height: 16px;+ flex-shrink: 0;+`;+type MiniDataset = {id: string;color: RGBColor;label?: string;disableDataOperation?: boolean;+ type?: string;+ metadata?: {+ refreshError?: string;+ };};export type DatasetTitleProps = {@@ -62,6 +97,7 @@ export type DatasetTitleProps = {showDatasetTable?: ActionHandler<typeof VisStateActions.showDatasetTable>;updateTableColor: ActionHandler<typeof VisStateActions.updateTableColor>;removeDataset?: ActionHandler<typeof openDeleteModal>;+ onToggleRefreshSettings?: () => void;};const ShowDataTable = ({id, showDatasetTable}: ShowDataTableProps) => (@@ -81,6 +117,30 @@ const ShowDataTable = ({id, showDatasetTable}: ShowDataTableProps) => (</DataTagAction>);+const RefreshDatasetSettings = ({id, onToggle}: {id: string; onToggle?: () => void}) => {+ const intl = useIntl();+ return (+ <DataTagActionButton+ type="button"+ className="dataset-action refresh-dataset-settings"+ data-tip+ data-for={`refresh-settings-${id}`}+ aria-label={intl.formatMessage({id: 'datasetTitle.refreshSettings'})}+ onClick={e => {+ e.stopPropagation();+ onToggle?.();+ }}+ >+ <Clock height="16px" />+ <Tooltip id={`refresh-settings-${id}`} effect="solid">+ <span>+ <FormattedMessage id={'datasetTitle.refreshSettings'} />+ </span>+ </Tooltip>+ </DataTagActionButton>+ );+};+const RemoveDataset = ({datasetKey, removeDataset}: RemoveDatasetProps) => (<DataTagActionclassName="dataset-action remove-dataset"@@ -102,6 +162,26 @@ const RemoveDataset = ({datasetKey, removeDataset}: RemoveDatasetProps) => (</DataTagAction>);+const RefreshErrorIcon = ({id, message}: {id: string; message: string}) => (+ <StyledRefreshError+ className="dataset-refresh-error"+ data-tip+ data-for={`refresh-error-${id}`}+ onClick={e => e.stopPropagation()}+ role="img"+ aria-label={message}+ >+ <WarningSign height="14px" />+ <Tooltip id={`refresh-error-${id}`} type="error" effect="solid">+ <span>+ <FormattedMessage id="datasetTitle.refreshFailed" />+ {': '}+ {message}+ </span>+ </Tooltip>+ </StyledRefreshError>+);+DatasetTitleFactory.deps = [DatasetTagFactory];export default function DatasetTitleFactory(@@ -113,7 +193,8 @@ export default function DatasetTitleFactory(onTitleClick,removeDataset,dataset,- updateTableColor+ updateTableColor,+ onToggleRefreshSettings}) => {const [displayColorPicker, setDisplayColorPicker] = useState(false);const root = useRef(null);@@ -145,6 +226,9 @@ export default function DatasetTitleFactory([onTitleClick, showDatasetTable, datasetId, dataset.disableDataOperation]);+ const isRemote = dataset.type === DatasetType.EXTERNALLY_HOSTED;+ const refreshError = dataset.metadata?.refreshError;+return (<div className="custom-palette-panel" ref={root}><StyledDatasetTitle@@ -170,9 +254,13 @@ export default function DatasetTitleFactory(<ArrowRight height="12px" /></CenterFlexbox>) : null}+ {refreshError ? <RefreshErrorIcon id={datasetId} message={refreshError} /> : null}{showDatasetTable && !dataset.disableDataOperation ? (<ShowDataTable id={datasetId} showDatasetTable={showDatasetTable} />) : null}+ {onToggleRefreshSettings && isRemote ? (+ <RefreshDatasetSettings id={datasetId} onToggle={onToggleRefreshSettings} />+ ) : null}{showDeleteDataset ? (<RemoveDataset datasetKey={datasetId} removeDataset={removeDataset} />) : null}diff --git a/src/components/src/side-panel/common/source-data-catalog.tsx b/src/components/src/side-panel/common/source-data-catalog.tsxindex 2a278ad09..c5f42ac23 100644--- a/src/components/src/side-panel/common/source-data-catalog.tsx+++ b/src/components/src/side-panel/common/source-data-catalog.tsx@@ -1,10 +1,11 @@// SPDX-License-Identifier: MIT// Copyright contributors to the kepler.gl project-import React from 'react';+import React, {useCallback, useState} from 'react';import styled from 'styled-components';import {openDeleteModal, VisStateActions, ActionHandler} from '@kepler.gl/actions';+import {DatasetType} from '@kepler.gl/constants';import {DataContainerInterface} from '@kepler.gl/utils';import {RGBColor} from '@kepler.gl/types';@@ -22,6 +23,7 @@ type MiniDataset = {label?: string;dataContainer: DataContainerInterface;type?: string;+ metadata?: Record<string, any>;};type MiniDatasets = {@@ -35,6 +37,8 @@ export type SourceDataCatalogProps = {showDatasetTable?: ActionHandler<typeof VisStateActions.showDatasetTable>;updateTableColor: ActionHandler<typeof VisStateActions.updateTableColor>;removeDataset?: ActionHandler<typeof openDeleteModal>;+ refreshDataset?: ActionHandler<typeof VisStateActions.refreshDataset>;+ updateDatasetProps?: ActionHandler<typeof VisStateActions.updateDatasetProps>;};SourceDataCatalogFactory.deps = [DatasetTitleFactory, DatasetInfoFactory];@@ -49,24 +53,53 @@ function SourceDataCatalogFactory(removeDataset,onTitleClick,updateTableColor,- showDeleteDataset = false- }: SourceDataCatalogProps) => (- <SourceDataCatalogWrapper className="source-data-catalog">- {Object.values(datasets).map(dataset => (- <SidePanelSection key={dataset.id}>- <DatasetTitle- showDatasetTable={showDatasetTable}- showDeleteDataset={showDeleteDataset}- removeDataset={removeDataset}- dataset={dataset}- onTitleClick={onTitleClick}- updateTableColor={updateTableColor}- />- {showDatasetTable ? <DatasetInfo dataset={dataset} /> : null}- </SidePanelSection>- ))}- </SourceDataCatalogWrapper>- );+ showDeleteDataset = false,+ refreshDataset,+ updateDatasetProps+ }: SourceDataCatalogProps) => {+ const [openRefreshSettingsId, setOpenRefreshSettingsId] = useState<string | null>(null);++ const onToggleRefreshSettings = useCallback((datasetId: string) => {+ setOpenRefreshSettingsId(current => (current === datasetId ? null : datasetId));+ }, []);++ return (+ <SourceDataCatalogWrapper className="source-data-catalog">+ {Object.values(datasets).map(dataset => {+ const showRefreshSettings = openRefreshSettingsId === dataset.id;+ const isRefreshing = dataset.metadata?.refreshStatus === 'loading';+ const showInfo = Boolean(showDatasetTable) || showRefreshSettings || isRefreshing;++ return (+ <SidePanelSection key={dataset.id}>+ <DatasetTitle+ showDatasetTable={showDatasetTable}+ showDeleteDataset={showDeleteDataset}+ removeDataset={removeDataset}+ dataset={dataset}+ onTitleClick={onTitleClick}+ updateTableColor={updateTableColor}+ onToggleRefreshSettings={+ (refreshDataset || updateDatasetProps) &&+ dataset.type === DatasetType.EXTERNALLY_HOSTED+ ? () => onToggleRefreshSettings(dataset.id)+ : undefined+ }+ />+ {showInfo ? (+ <DatasetInfo+ dataset={dataset}+ showRefreshSettings={showRefreshSettings}+ refreshDataset={refreshDataset}+ updateDatasetProps={updateDatasetProps}+ />+ ) : null}+ </SidePanelSection>+ );+ })}+ </SourceDataCatalogWrapper>+ );+ };return SourceDataCatalog;}diff --git a/src/components/src/side-panel/filter-manager.tsx b/src/components/src/side-panel/filter-manager.tsxindex a4c1ab7b1..143fabfa9 100644--- a/src/components/src/side-panel/filter-manager.tsx+++ b/src/components/src/side-panel/filter-manager.tsx@@ -152,6 +152,8 @@ function FilterManagerFactory(updateTableColor={updateTableColor}removeDataset={removeDataset}showDeleteDataset={showDeleteDataset}+ refreshDataset={visStateActions.refreshDataset}+ updateDatasetProps={visStateActions.updateDatasetProps}/><FilterListfiltersByIndex={filtersByIndex}@@ -225,7 +227,9 @@ function FilterManagerFactory(showDatasetTable,updateTableColor,removeDataset,- showDeleteDataset: true+ showDeleteDataset: true,+ refreshDataset: visStateActions.refreshDataset,+ updateDatasetProps: visStateActions.updateDatasetProps};return (diff --git a/src/components/src/side-panel/layer-manager.tsx b/src/components/src/side-panel/layer-manager.tsxindex 8122626c1..38fedc9b4 100644--- a/src/components/src/side-panel/layer-manager.tsx+++ b/src/components/src/side-panel/layer-manager.tsx@@ -255,6 +255,8 @@ function LayerManagerFactory(showDeleteDataset={showDeleteDataset}showDatasetList={!isSortByDatasetMode}showAddDataModal={showAddDataModal}+ refreshDataset={visStateActions.refreshDataset}+ updateDatasetProps={visStateActions.updateDatasetProps}/><SidePanelDivider /><SidePanelSection>diff --git a/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx b/src/components/src/side-panel/layer-panel/dataset-layer-section.tsxindex 8c49b1e49..a0754c56e 100644--- a/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx+++ b/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx@@ -114,6 +114,8 @@ function DatasetLayerSectionFactory(updateTableColor={updateTableColor}removeDataset={removeDataset}showDeleteDataset={showDeleteDataset}+ refreshDataset={visStateActions.refreshDataset}+ updateDatasetProps={visStateActions.updateDatasetProps}/><LayerListdatasets={datasets}diff --git a/src/components/src/side-panel/layer-panel/dataset-section.tsx b/src/components/src/side-panel/layer-panel/dataset-section.tsxindex 173417e87..da80175b8 100644--- a/src/components/src/side-panel/layer-panel/dataset-section.tsx+++ b/src/components/src/side-panel/layer-panel/dataset-section.tsx@@ -24,6 +24,8 @@ type DatasetSectionProps = {updateTableColor: ActionHandler<typeof VisStateActions.updateTableColor>;removeDataset: ActionHandler<typeof UIStateActions.openDeleteModal>;showAddDataModal: () => void;+ refreshDataset?: ActionHandler<typeof VisStateActions.refreshDataset>;+ updateDatasetProps?: ActionHandler<typeof VisStateActions.updateDatasetProps>;};const StyledDatasetTitle = styled.div<{$showDatasetList?: boolean}>`@@ -73,7 +75,9 @@ function DatasetSectionFactory(showDeleteDataset,removeDataset,showDatasetList,- showAddDataModal+ showAddDataModal,+ refreshDataset,+ updateDatasetProps} = props;const datasetCount = Object.keys(datasets).length;@@ -90,6 +94,8 @@ function DatasetSectionFactory(updateTableColor={updateTableColor}removeDataset={removeDataset}showDeleteDataset={showDeleteDataset}+ refreshDataset={refreshDataset}+ updateDatasetProps={updateDatasetProps}/>)}</StyledDatasetSection>diff --git a/src/constants/src/dataset.ts b/src/constants/src/dataset.tsindex e18509a1b..7692ce548 100644--- a/src/constants/src/dataset.ts+++ b/src/constants/src/dataset.ts@@ -42,6 +42,27 @@ export const MIME_TO_REMOTE_FILE_EXTENSION: Record<string, string> = {'application/x-parquet': 'parquet'};+export const DATASET_REFRESH_INTERVAL_OPTIONS: {value: number; labelId: string}[] = [+ {value: 0, labelId: 'datasetTitle.refreshOff'},+ {value: 10_000, labelId: 'datasetTitle.refresh10s'},+ {value: 15_000, labelId: 'datasetTitle.refresh15s'},+ {value: 60_000, labelId: 'datasetTitle.refresh1m'},+ {value: 300_000, labelId: 'datasetTitle.refresh5m'},+ {value: 900_000, labelId: 'datasetTitle.refresh15m'}+];++/** Select value for a user-entered interval that is not one of the presets. */+export const DATASET_REFRESH_CUSTOM_VALUE = 'custom';+/** Default custom poll interval when switching from Off to Custom. */+export const DATASET_REFRESH_DEFAULT_CUSTOM_MS = 30_000;+export const DATASET_REFRESH_MIN_INTERVAL_MS = 100;++export function isPresetDatasetRefreshInterval(ms: number): boolean {+ return DATASET_REFRESH_INTERVAL_OPTIONS.some(option => option.value === ms);+}++export type ExternalDatasetRefreshStatus = 'idle' | 'loading' | 'error';+export type ExternalDatasetMetadata = {/** Remote URL of the dataset file. */source: string;@@ -49,6 +70,8 @@ export type ExternalDatasetMetadata = {format?: Exclude<RemoteFileFormat, 'auto'> | string;/** Last known size of the hosted resource, in bytes. */size?: number;+ /** Poll interval in ms. Omitted or 0 means manual refresh only. */+ refreshIntervalMs?: number;};/** Runtime copy of {@link ExternalDatasetMetadata} with `format` renamed to avoid colliding with DATASET_FORMATS. */@@ -56,8 +79,39 @@ export type ExternalDatasetRuntimeMetadata = {source: string;sourceFormat?: Exclude<RemoteFileFormat, 'auto'> | string;size?: number;+ refreshIntervalMs?: number;+ etag?: string;+ lastModified?: string;+ lastFetchedAt?: number;+ refreshStatus?: ExternalDatasetRefreshStatus;+ refreshError?: string;+ /** Download progress 0–100 while `refreshStatus` is `loading`. */+ refreshProgress?: number;};+export function getDatasetRefreshIntervalMs(metadata?: {refreshIntervalMs?: unknown}): number {+ const value = metadata?.refreshIntervalMs;+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0;+}++/** Parse a seconds field into ms, or null if the input is not a positive number. */+export function parseCustomRefreshIntervalMs(secondsText: string): number | null {+ const seconds = Number.parseFloat(secondsText);+ if (!Number.isFinite(seconds) || seconds <= 0) {+ return null;+ }+ return Math.max(DATASET_REFRESH_MIN_INTERVAL_MS, Math.round(seconds * 1000));+}++/** Display string for the custom seconds input (keeps tenths for sub-second values). */+export function formatCustomRefreshSeconds(ms: number): string {+ const seconds = Math.max(DATASET_REFRESH_MIN_INTERVAL_MS, ms) / 1000;+ if (Number.isInteger(seconds)) {+ return String(seconds);+ }+ return String(Number(seconds.toFixed(3)));+}+export function getRemoteSourceFormat(metadata?: {sourceFormat?: unknown;format?: unknown;diff --git a/src/layers/src/base-layer.ts b/src/layers/src/base-layer.tsindex 37eb3ad91..e334f153a 100644--- a/src/layers/src/base-layer.ts+++ b/src/layers/src/base-layer.ts@@ -1299,13 +1299,25 @@ class Layer implements KeplerLayer {this.meta = {...this.meta, ...meta};}- getDataUpdateTriggers({filteredIndex, filteredIndexByLayer, id, dataContainer}: KeplerTable): any {+ getDataUpdateTriggers({+ filteredIndex,+ filteredIndexByLayer,+ id,+ dataContainer,+ dataRevision+ }: KeplerTable): any {const {columns} = this.config;const layerFilteredIndex = filteredIndexByLayer?.[this.id] ?? filteredIndex;return {- getData: {datasetId: id, dataContainer, columns, filteredIndex: layerFilteredIndex},- getMeta: {datasetId: id, dataContainer, columns},+ getData: {+ datasetId: id,+ dataContainer,+ columns,+ filteredIndex: layerFilteredIndex,+ dataRevision+ },+ getMeta: {datasetId: id, dataContainer, columns, dataRevision},...(this.config.textLabel || []).reduce((accu, tl, i) => ({...accu,@@ -1586,7 +1598,11 @@ class Layer implements KeplerLayer {getPosition?: ((d: any) => number[]) | arrow.Vector;getFiltered?: (data: {index: number}, objectInfo: {index: number}) => number;getPixelOffset: (textLabel: any) => number[] | ((d: any) => number[]);- backgroundProps?: {background: boolean; backgroundPadding?: number[]; getBackgroundColor?: any};+ backgroundProps?: {+ background: boolean;+ backgroundPadding?: number[];+ getBackgroundColor?: any;+ };updateTriggers: {[key: string]: any;};@@ -1603,9 +1619,7 @@ class Layer implements KeplerLayer {return data.textLabels.reduce((accu, d, i) => {if (d.getText) {const background = textLabel[i].background || backgroundProps?.background;- const getText = animationConfig- ? f => d.getText(f, animationConfig)- : d.getText;+ const getText = animationConfig ? f => d.getText(f, animationConfig) : d.getText;accu.push(// @ts-expect-error@@ -1631,8 +1645,7 @@ class Layer implements KeplerLayer {...(backgroundProps?.backgroundPadding? {backgroundPadding: backgroundProps.backgroundPadding}: null),- getBackgroundColor:- backgroundProps?.getBackgroundColor ?? textLabel[i].backgroundColor,+ getBackgroundColor: backgroundProps?.getBackgroundColor ?? textLabel[i].backgroundColor,fontSettings: {sdf: textLabel[i].outlineWidth > 0},diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.tsindex cd252916a..5b7ae0fe1 100644--- a/src/localization/src/translations/ca.ts+++ b/src/localization/src/translations/ca.ts@@ -291,7 +291,17 @@ export default {},datasetTitle: {showDataTable: 'Mostra taula de dades',- removeDataset: 'Elimina conjunt de dades'+ removeDataset: 'Elimina conjunt de dades',+ refreshDataset: 'Actualitza el conjunt de dades',+ refreshFailed: 'Error d’actualització',+ refreshSettings: 'Configuració d’actualització',+ refreshOff: 'Off',+ refresh10s: '10s',+ refresh15s: '15s',+ refresh1m: '1 min',+ refresh5m: '5 min',+ refresh15m: '15 min',+ refreshCustom: 'Personalitzat'},datasetInfo: {rowCount: '{rowCount} files',@@ -299,7 +309,11 @@ export default {rasterTile: 'Mosaic ràster',wmsTile: 'Mosaic WMS',tile3d: 'Mosaic 3D',- remoteFile: '{rowCount} files (remot)'+ remoteFile: '{rowCount} files (remot)',+ refreshInterval: 'Actualitza',+ refreshCustomSeconds: 'Segons',+ refreshing: 'S’està actualitzant…',+ refreshingPercent: 'S’està actualitzant {percent}%'},tooltip: {hideLayer: 'oculta la capa',diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.tsindex 2020179cc..c0e5583c0 100644--- a/src/localization/src/translations/cn.ts+++ b/src/localization/src/translations/cn.ts@@ -278,7 +278,17 @@ export default {},datasetTitle: {showDataTable: '显示数据表',- removeDataset: '删除数据集'+ removeDataset: '删除数据集',+ refreshDataset: '刷新数据集',+ refreshFailed: '刷新失败',+ refreshSettings: '刷新设置',+ refreshOff: '关闭',+ refresh10s: '10秒',+ refresh15s: '15秒',+ refresh1m: '1分钟',+ refresh5m: '5分钟',+ refresh15m: '15分钟',+ refreshCustom: '自定义'},datasetInfo: {rowCount: '{rowCount}行',@@ -286,7 +296,11 @@ export default {rasterTile: '栅格瓦片',wmsTile: 'WMS瓦片',tile3d: '3D瓦片',- remoteFile: '{rowCount}行(远程)'+ remoteFile: '{rowCount}行(远程)',+ refreshInterval: '刷新',+ refreshCustomSeconds: '秒',+ refreshing: '正在刷新…',+ refreshingPercent: '正在刷新 {percent}%'},tooltip: {hideLayer: '隐藏图层',diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex 0a544fe9d..45869490a 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -335,7 +335,17 @@ export default {},datasetTitle: {showDataTable: 'Show data table',- removeDataset: 'Remove dataset'+ removeDataset: 'Remove dataset',+ refreshDataset: 'Refresh dataset',+ refreshFailed: 'Refresh failed',+ refreshSettings: 'Refresh settings',+ refreshOff: 'Off',+ refresh10s: '10s',+ refresh15s: '15s',+ refresh1m: '1 min',+ refresh5m: '5 min',+ refresh15m: '15 min',+ refreshCustom: 'Custom'},datasetInfo: {rowCount: '{rowCount} rows',@@ -344,7 +354,11 @@ export default {wmsTile: 'WMS tile',tile3d: '3D tile',bitmap: 'Bitmap image',- remoteFile: '{rowCount} rows (remote)'+ remoteFile: '{rowCount} rows (remote)',+ refreshInterval: 'Refresh',+ refreshCustomSeconds: 'Seconds',+ refreshing: 'Refreshing…',+ refreshingPercent: 'Refreshing {percent}%'},tooltip: {hideLayer: 'Hide layer',diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.tsindex f12ca3979..cb7c364fa 100644--- a/src/localization/src/translations/es.ts+++ b/src/localization/src/translations/es.ts@@ -292,7 +292,17 @@ export default {},datasetTitle: {showDataTable: 'Mostar la tabla de datos',- removeDataset: 'Eliminar conjunto de datos'+ removeDataset: 'Eliminar conjunto de datos',+ refreshDataset: 'Actualizar conjunto de datos',+ refreshFailed: 'Error al actualizar',+ refreshSettings: 'Ajustes de actualización',+ refreshOff: 'Off',+ refresh10s: '10s',+ refresh15s: '15s',+ refresh1m: '1 min',+ refresh5m: '5 min',+ refresh15m: '15 min',+ refreshCustom: 'Personalizado'},datasetInfo: {rowCount: '{rowCount} filas',@@ -300,7 +310,11 @@ export default {rasterTile: 'Mosaico ráster',wmsTile: 'Mosaico WMS',tile3d: 'Mosaico 3D',- remoteFile: '{rowCount} filas (remoto)'+ remoteFile: '{rowCount} filas (remoto)',+ refreshInterval: 'Actualizar',+ refreshCustomSeconds: 'Segundos',+ refreshing: 'Actualizando…',+ refreshingPercent: 'Actualizando {percent}%'},tooltip: {hideLayer: 'Ocultar la capa',diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.tsindex e221a1778..090004bad 100644--- a/src/localization/src/translations/fi.ts+++ b/src/localization/src/translations/fi.ts@@ -290,7 +290,17 @@ export default {},datasetTitle: {showDataTable: 'Näytä attribuuttitaulu',- removeDataset: 'Poista aineisto'+ removeDataset: 'Poista aineisto',+ refreshDataset: 'Päivitä aineisto',+ refreshFailed: 'Päivitys epäonnistui',+ refreshSettings: 'Päivitysasetukset',+ refreshOff: 'Pois',+ refresh10s: '10 s',+ refresh15s: '15 s',+ refresh1m: '1 min',+ refresh5m: '5 min',+ refresh15m: '15 min',+ refreshCustom: 'Mukautettu'},datasetInfo: {rowCount: '{rowCount} riviä',@@ -298,7 +308,11 @@ export default {rasterTile: 'Rasteritiili',wmsTile: 'WMS-tiili',tile3d: '3D-tiili',- remoteFile: '{rowCount} riviä (etä)'+ remoteFile: '{rowCount} riviä (etä)',+ refreshInterval: 'Päivitys',+ refreshCustomSeconds: 'Sekuntia',+ refreshing: 'Päivitetään…',+ refreshingPercent: 'Päivitetään {percent}%'},tooltip: {hideLayer: 'Piilota taso',diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.tsindex ba7face12..e6e581629 100644--- a/src/localization/src/translations/ja.ts+++ b/src/localization/src/translations/ja.ts@@ -289,7 +289,17 @@ export default {},datasetTitle: {showDataTable: 'データ表を表示',- removeDataset: 'データセットを削除'+ removeDataset: 'データセットを削除',+ refreshDataset: 'データセットを更新',+ refreshFailed: '更新に失敗しました',+ refreshSettings: '更新設定',+ refreshOff: 'オフ',+ refresh10s: '10秒',+ refresh15s: '15秒',+ refresh1m: '1分',+ refresh5m: '5分',+ refresh15m: '15分',+ refreshCustom: 'カスタム'},datasetInfo: {rowCount: '{rowCount}行',@@ -297,7 +307,11 @@ export default {rasterTile: 'ラスタータイル',wmsTile: 'WMSタイル',tile3d: '3Dタイル',- remoteFile: '{rowCount}行(リモート)'+ remoteFile: '{rowCount}行(リモート)',+ refreshInterval: '更新',+ refreshCustomSeconds: '秒',+ refreshing: '更新中…',+ refreshingPercent: '更新中 {percent}%'},tooltip: {hideLayer: 'レイヤを非表示',diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.tsindex 47dab1806..49fe5b434 100644--- a/src/localization/src/translations/pt.ts+++ b/src/localization/src/translations/pt.ts@@ -292,7 +292,17 @@ export default {},datasetTitle: {showDataTable: 'Mostrar tabela de dados',- removeDataset: 'Remover tabela de dados'+ removeDataset: 'Remover tabela de dados',+ refreshDataset: 'Atualizar conjunto de dados',+ refreshFailed: 'Falha ao atualizar',+ refreshSettings: 'Configurações de atualização',+ refreshOff: 'Off',+ refresh10s: '10s',+ refresh15s: '15s',+ refresh1m: '1 min',+ refresh5m: '5 min',+ refresh15m: '15 min',+ refreshCustom: 'Personalizado'},datasetInfo: {rowCount: '{rowCount} linhas',@@ -300,7 +310,11 @@ export default {rasterTile: 'Mosaico raster',wmsTile: 'Mosaico WMS',tile3d: 'Mosaico 3D',- remoteFile: '{rowCount} linhas (remoto)'+ remoteFile: '{rowCount} linhas (remoto)',+ refreshInterval: 'Atualizar',+ refreshCustomSeconds: 'Segundos',+ refreshing: 'Atualizando…',+ refreshingPercent: 'Atualizando {percent}%'},tooltip: {hideLayer: 'esconder camada',diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.tsindex e23d3c980..3de4d3db6 100644--- a/src/localization/src/translations/ru.ts+++ b/src/localization/src/translations/ru.ts@@ -291,7 +291,17 @@ export default {},datasetTitle: {showDataTable: 'Показать таблицу данных ',- removeDataset: 'Удалить набор данных'+ removeDataset: 'Удалить набор данных',+ refreshDataset: 'Обновить набор данных',+ refreshFailed: 'Не удалось обновить',+ refreshSettings: 'Настройки обновления',+ refreshOff: 'Выкл.',+ refresh10s: '10 с',+ refresh15s: '15 с',+ refresh1m: '1 мин',+ refresh5m: '5 мин',+ refresh15m: '15 мин',+ refreshCustom: 'Свой'},datasetInfo: {rowCount: '{rowCount} строк',@@ -299,7 +309,11 @@ export default {rasterTile: 'Растровый тайл',wmsTile: 'WMS тайл',tile3d: '3D тайл',- remoteFile: '{rowCount} строк (удалённый)'+ remoteFile: '{rowCount} строк (удалённый)',+ refreshInterval: 'Обновление',+ refreshCustomSeconds: 'Секунды',+ refreshing: 'Обновление…',+ refreshingPercent: 'Обновление {percent}%'},tooltip: {hideLayer: 'скрыть слой',diff --git a/src/processors/src/file-handler.ts b/src/processors/src/file-handler.tsindex 8d090cb26..9c48a148c 100644--- a/src/processors/src/file-handler.ts+++ b/src/processors/src/file-handler.ts@@ -70,6 +70,12 @@ export type ProcessFileDataContent = {sourceUrl?: string;/** User-selected or inferred remote file format (csv, geojson, parquet, …). */keplerFormat?: string;+ /** Poll interval in ms, copied from a remote URL load. */+ refreshIntervalMs?: number;+ /** HTTP ETag from the remote fetch, used for the next conditional refresh. */+ etag?: string;+ /** HTTP Last-Modified from the remote fetch, used for the next conditional refresh. */+ lastModified?: string;/*** When true, skip Arrow record-batch compaction. Set on intermediate* progressive Arrow loads so each batch does not copy the growing table.@@ -141,10 +147,7 @@ export async function* makeProgressIterator(}// eslint-disable-next-line complexity-function getPersistedRemoteFormat(- keplerFormat?: string,- fileName?: string-): string | undefined {+function getPersistedRemoteFormat(keplerFormat?: string, fileName?: string): string | undefined {if (keplerFormat &&keplerFormat !== 'auto' &&@@ -163,7 +166,10 @@ export async function* readBatch(asyncIterator: AsyncIterable<any>,fileName: string,sourceUrl?: string,- keplerFormat?: string+ keplerFormat?: string,+ refreshIntervalMs?: number,+ etag?: string,+ lastModified?: string): AsyncGenerator {let result = null;const batches = <any>[];@@ -205,7 +211,12 @@ export async function* readBatch(// if dataset is CSV, data is set to the raw batchesdata: result ? result : batches,...(sourceUrl ? {sourceUrl} : {}),- ...(keplerFormat ? {keplerFormat} : {})+ ...(keplerFormat ? {keplerFormat} : {}),+ ...(typeof refreshIntervalMs === 'number' && refreshIntervalMs > 0+ ? {refreshIntervalMs}+ : {}),+ ...(etag ? {etag} : {}),+ ...(lastModified ? {lastModified} : {})};}}@@ -237,8 +248,20 @@ export async function readFileInBatches({const progressIterator = makeProgressIterator(batchIterator, {size: file.size});const sourceUrl = (file as File & {keplerSourceUrl?: string}).keplerSourceUrl;const keplerFormat = (file as File & {keplerFormat?: string}).keplerFormat;+ const refreshIntervalMs = (file as File & {keplerRefreshIntervalMs?: number})+ .keplerRefreshIntervalMs;+ const etag = (file as File & {keplerEtag?: string}).keplerEtag;+ const lastModified = (file as File & {keplerLastModified?: string}).keplerLastModified;- return readBatch(progressIterator, file.name, sourceUrl, keplerFormat);+ return readBatch(+ progressIterator,+ file.name,+ sourceUrl,+ keplerFormat,+ refreshIntervalMs,+ etag,+ lastModified+ );}export async function processFileData({@@ -308,7 +331,15 @@ export async function processFileData({? {metadata: {source: sourceUrl,- ...(remoteFormat ? {sourceFormat: remoteFormat} : {})+ ...(remoteFormat ? {sourceFormat: remoteFormat} : {}),+ ...(typeof content.refreshIntervalMs === 'number' && content.refreshIntervalMs > 0+ ? {refreshIntervalMs: content.refreshIntervalMs}+ : {}),+ ...(typeof content.etag === 'string' && content.etag ? {etag: content.etag} : {}),+ ...(typeof content.lastModified === 'string' && content.lastModified+ ? {lastModified: content.lastModified}+ : {}),+ lastFetchedAt: Date.now()}}: {})diff --git a/src/processors/src/remote-file.ts b/src/processors/src/remote-file.tsindex 1520e240e..aa0a678c3 100644--- a/src/processors/src/remote-file.ts+++ b/src/processors/src/remote-file.ts@@ -15,6 +15,34 @@ import {processFileData, ProcessFileDataContent, readFileInBatches} from './fileexport type KeplerRemoteFile = File & {keplerSourceUrl?: string;keplerFormat?: string;+ keplerRefreshIntervalMs?: number;+ keplerEtag?: string;+ keplerLastModified?: string;+};++export type FetchRemoteFileOptions = {+ format?: string | null;+ onProgress?: (progress: {loaded: number; total?: number; percent: number}) => void;+ etag?: string;+ lastModified?: string;+ /** Bypass the HTTP cache. Used for poll/reload, not the first remote URL load. */+ bypassCache?: boolean;+};++export type FetchRemoteFileResult = {+ file: KeplerRemoteFile | null;+ notModified: boolean;+ etag?: string;+ lastModified?: string;+ size?: number;+};++export type LoadExternallyHostedDatasetResult = {+ data: NonNullable<ProcessorResult> | null;+ notModified: boolean;+ etag?: string;+ lastModified?: string;+ size?: number;};function getPathFileName(url: string): string {@@ -60,7 +88,7 @@ export function getFileNameForRemoteUrl(format?: string | null,mimeType?: string | null): string {- let base = getPathFileName(url) || 'dataset';+ const base = getPathFileName(url) || 'dataset';const formatExt =format && format !== 'auto'@@ -87,19 +115,36 @@ export function getFileNameForRemoteUrl(}/**- * Fetch a remote dataset URL and wrap it as a File the existing loadFiles pipeline can parse.- * Sets File.type from an explicit format or the response Content-Type so extensionless- * URLs (SAS keys) still select the right loader.+ * Fetch a remote dataset URL. Honors If-None-Match / If-Modified-Since when etag+ * or lastModified are provided so unchanged files can skip a re-parse.*/-export async function fetchRemoteFileAsKeplerFile(+export async function fetchRemoteFile(url: string,- format?: string | null,- onProgress?: (progress: {loaded: number; total?: number; percent: number}) => void-): Promise<KeplerRemoteFile> {+ options: FetchRemoteFileOptions = {}+): Promise<FetchRemoteFileResult> {+ const {format, onProgress, etag, lastModified, bypassCache} = options;if (!isRemoteDatasetUrl(url)) {throw new Error('Remote dataset URL must use http or https');}- const response = await fetch(url);+ const headers: Record<string, string> = {};+ if (etag) {+ headers['If-None-Match'] = etag;+ }+ if (lastModified) {+ headers['If-Modified-Since'] = lastModified;+ }+ const response = await fetch(url, {+ ...(bypassCache ? {cache: 'no-store' as RequestCache} : {}),+ ...(Object.keys(headers).length ? {headers} : {})+ });+ if (response.status === 304) {+ return {+ file: null,+ notModified: true,+ etag: response.headers.get('etag') || etag || undefined,+ lastModified: response.headers.get('last-modified') || lastModified || undefined+ };+ }if (!response.ok) {// Don't put the response body in the error: 404 HTML pages would dump into the UI.response.body?.cancel?.().catch(() => undefined);@@ -113,12 +158,47 @@ export async function fetchRemoteFileAsKeplerFile(const headerType = response.headers.get('content-type') || blob.type || '';const mimeType = getMimeTypeForFormat(format) || headerType.split(';')[0].trim();const fileName = getFileNameForRemoteUrl(url, format, mimeType);- const file = new File([blob], fileName, mimeType ? {type: mimeType} : undefined) as KeplerRemoteFile;+ const file = new File(+ [blob],+ fileName,+ mimeType ? {type: mimeType} : undefined+ ) as KeplerRemoteFile;file.keplerSourceUrl = url;if (format && format !== 'auto') {file.keplerFormat = format;}- return file;+ const responseEtag = response.headers.get('etag') || undefined;+ const responseLastModified = response.headers.get('last-modified') || undefined;+ if (responseEtag) {+ file.keplerEtag = responseEtag;+ }+ if (responseLastModified) {+ file.keplerLastModified = responseLastModified;+ }+ return {+ file,+ notModified: false,+ etag: responseEtag,+ lastModified: responseLastModified,+ size: file.size+ };+}++/**+ * Fetch a remote dataset URL and wrap it as a File the existing loadFiles pipeline can parse.+ * Sets File.type from an explicit format or the response Content-Type so extensionless+ * URLs (SAS keys) still select the right loader.+ */+export async function fetchRemoteFileAsKeplerFile(+ url: string,+ format?: string | null,+ onProgress?: (progress: {loaded: number; total?: number; percent: number}) => void+): Promise<KeplerRemoteFile> {+ const result = await fetchRemoteFile(url, {format, onProgress});+ if (!result.file) {+ throw new Error(`Failed to fetch ${url} (304 Not Modified)`);+ }+ return result.file;}async function readResponseBlob(@@ -128,11 +208,27 @@ async function readResponseBlob(const contentLength = Number(response.headers.get('content-length'));const total = Number.isFinite(contentLength) && contentLength > 0 ? contentLength : undefined;+ const PROGRESS_INTERVAL_MS = 80;+ let lastEmitAt = 0;+ let lastEmittedPercent = -1;const emit = (loaded: number, complete = false) => {+ const percent = complete ? 1 : total ? Math.min(1, loaded / total) : 0;+ const rounded = Math.round(percent * 100);+ const now = typeof performance !== 'undefined' ? performance.now() : Date.now();+ if (+ !complete &&+ loaded !== 0 &&+ rounded === lastEmittedPercent &&+ now - lastEmitAt < PROGRESS_INTERVAL_MS+ ) {+ return;+ }+ lastEmitAt = now;+ lastEmittedPercent = rounded;onProgress?.({loaded,total,- percent: complete ? 1 : total ? Math.min(1, loaded / total) : 0+ percent});};@@ -161,9 +257,7 @@ async function readResponseBlob(return new Blob(chunks);}-function isTabularProcessorResult(- data: unknown-): data is NonNullable<ProcessorResult> {+function isTabularProcessorResult(data: unknown): data is NonNullable<ProcessorResult> {return Boolean(data &&typeof data === 'object' &&@@ -174,17 +268,38 @@ function isTabularProcessorResult(/*** Fetch, parse, and process a remote file into Kepler dataset data.- * Used when reloading an `externally-hosted` dataset from a saved map config.+ * Used when reloading an `externally-hosted` dataset from a saved map config+ * and when refreshing a live remote dataset.*/export async function loadExternallyHostedDataset(metadata: {source: string;format?: string;size?: number;-}): Promise<NonNullable<ProcessorResult>> {- const {source, format} = metadata;- const file = await fetchRemoteFileAsKeplerFile(source, format);+ etag?: string;+ lastModified?: string;+ bypassCache?: boolean;+ onProgress?: (progress: {loaded: number; total?: number; percent: number}) => void;+}): Promise<LoadExternallyHostedDatasetResult> {+ const {source, format, etag, lastModified, size, bypassCache, onProgress} = metadata;+ const fetched = await fetchRemoteFile(source, {+ format,+ etag,+ lastModified,+ bypassCache,+ onProgress+ });+ if (fetched.notModified || !fetched.file) {+ return {+ data: null,+ notModified: true,+ etag: fetched.etag,+ lastModified: fetched.lastModified,+ size+ };+ }+const batches = await readFileInBatches({- file,+ file: fetched.file,fileCache: [],loaders: [],loadOptions: {}@@ -210,7 +325,13 @@ export async function loadExternallyHostedDataset(metadata: {if (!isTabularProcessorResult(data)) {throw new Error(`Remote file is not a dataset: ${source}`);}- return data;+ return {+ data,+ notModified: false,+ etag: fetched.etag,+ lastModified: fetched.lastModified,+ size: fetched.size+ };}export function isExternallyHostedFile(file: File): file is KeplerRemoteFile {diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex cfa4e5ca6..409f26d8e 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -47,7 +47,10 @@ import {applyFilterConfig,SetLoadingIndicatorPayload,loadColumnStatsSuccess,- loadColumnStatsError+ loadColumnStatsError,+ refreshDatasetSuccess,+ refreshDatasetError,+ refreshDatasetProgress} from '@kepler.gl/actions';// Utils@@ -81,7 +84,8 @@ import {removeFilterPlot,isLayerAnimatable,isSideFilter,- getApplicationConfig+ getApplicationConfig,+ validateFiltersUpdateDatasets} from '@kepler.gl/utils';import {generateHashId, toArray, arrayMove} from '@kepler.gl/common-utils';// Mergers@@ -113,6 +117,7 @@ import {INITIAL_ANNOTATION_LINE_COLOR,AnnotationKind,DatasetType,+ getDatasetRefreshIntervalMs,getRemoteSourceFormat} from '@kepler.gl/constants';import {LAYER_ID_LENGTH, Layer, LayerClasses} from '@kepler.gl/layers';@@ -1147,10 +1152,7 @@ export function layerVisConfigChangeUpdater(// Exclusive bitmap editing: when editBounds is turned on for one bitmap layer,// turn it off for all other bitmap layers- if (- newLayer.type === 'bitmap' &&- action.newVisConfig.editBounds === true- ) {+ if (newLayer.type === 'bitmap' && action.newVisConfig.editBounds === true) {nextState = {...nextState,layers: nextState.layers.map((l, i) => {@@ -2010,10 +2012,7 @@ export const updateLayerGroupUpdater = (if (options.layerOrder) {newState.layerOrder = [...layerGroup.layerOrder, ...newState.layerOrder];options.layerOrder.forEach(layerId => {- newState.layerOrder = removeElementFromLayerOrder(- newState.layerOrder,- layerId as string- );+ newState.layerOrder = removeElementFromLayerOrder(newState.layerOrder, layerId as string);});}@@ -2244,10 +2243,7 @@ export const duplicateLayerUpdater = (const idxInGroup = parentGroup.layerOrder.findIndex(e => e === original.id);const newGroupLayerOrder = arrayInsert(parentGroup.layerOrder, idxInGroup, newLayer.id);const updatedGroup = {...parentGroup, layerOrder: newGroupLayerOrder};- const newLayerOrder = updateLayerGroupInLayerOrder(- layerOrderWithoutPrepended,- updatedGroup- );+ const newLayerOrder = updateLayerGroupInLayerOrder(layerOrderWithoutPrepended, updatedGroup);nextState = reorderLayerUpdater(nextState, {order: newLayerOrder});} else {// Layer is at root level - use original index-based insertion@@ -2891,7 +2887,9 @@ export const toggleLayerForMapUpdater = (};function hasTabularDatasetData(data?: ProtoDataset['data'] | null): boolean {- return Boolean(data?.rows?.length || data?.cols?.length || (data as {arrowTable?: unknown})?.arrowTable);+ return Boolean(+ data?.rows?.length || data?.cols?.length || (data as {arrowTable?: unknown})?.arrowTable+ );}function needsExternallyHostedHydrate(dataset: ProtoDataset): boolean {@@ -2906,12 +2904,27 @@ async function hydrateExternallyHostedProtoDataset(dataset: ProtoDataset): Promiif (!needsExternallyHostedHydrate(dataset)) {return dataset;}- const data = await loadExternallyHostedDataset({+ const loaded = await loadExternallyHostedDataset({source: dataset.metadata?.source as string,format: getRemoteSourceFormat(dataset.metadata),- size: typeof dataset.metadata?.size === 'number' ? dataset.metadata.size : undefined+ size: typeof dataset.metadata?.size === 'number' ? dataset.metadata.size : undefined,+ bypassCache: getDatasetRefreshIntervalMs(dataset.metadata) > 0});- return {...dataset, data};+ if (!loaded.data) {+ throw new Error(`No data loaded from ${dataset.metadata?.source}`);+ }+ return {+ ...dataset,+ data: loaded.data,+ metadata: {+ ...dataset.metadata,+ etag: loaded.etag,+ lastModified: loaded.lastModified,+ ...(typeof loaded.size === 'number' ? {size: loaded.size} : {}),+ lastFetchedAt: Date.now(),+ refreshStatus: 'idle'+ }+ };}const HYDRATE_EXTERNALLY_HOSTED_DATASET_TASK = Task.fromPromise(@@ -2936,6 +2949,292 @@ function createNewDataEntryTask(dataset: ProtoDataset, datasets: Datasets) {});}+function patchDatasetMetadata(dataset: Datasets[string], patch: Record<string, unknown>) {+ return copyTableAndUpdate(dataset, {+ metadata: {+ ...dataset.metadata,+ ...patch+ }+ });+}++async function refreshExternallyHostedTable({+ arg: metadata,+ onProgress+}: {+ arg: {+ source: string;+ format?: string;+ size?: number;+ etag?: string;+ lastModified?: string;+ };+ onProgress: (progress: {loaded: number; total?: number; percent: number}) => void;+}) {+ // Fetch only. Do not mutate the Redux table here: progress events copy it, and+ // the success updater applies the snapshot to whatever instance is in the store.+ return loadExternallyHostedDataset({...metadata, onProgress, bypassCache: true});+}++const REFRESH_EXTERNALLY_HOSTED_DATASET_TASK = Task.fromPromiseWithProgress(+ refreshExternallyHostedTable,+ 'REFRESH_EXTERNALLY_HOSTED_DATASET_TASK'+);++/**+ * Re-fetch an externally hosted dataset and replace its table contents in place.+ * Layers and filters are kept when field names match.+ * @memberof visStateUpdaters+ * @public+ */+export function refreshDatasetUpdater(+ state: VisState,+ {dataId}: VisStateActions.RefreshDatasetUpdaterAction+): VisState {+ const dataset = state.datasets[dataId];+ if (+ !dataset ||+ dataset.type !== DatasetType.EXTERNALLY_HOSTED ||+ typeof dataset.metadata?.source !== 'string'+ ) {+ return state;+ }+ if (dataset.metadata?.refreshStatus === 'loading') {+ return state;+ }++ const nextDataset = patchDatasetMetadata(dataset, {+ refreshStatus: 'loading',+ refreshError: undefined,+ refreshProgress: undefined+ });++ return withTask(+ {+ ...state,+ datasets: {+ ...state.datasets,+ [dataId]: nextDataset+ }+ },+ REFRESH_EXTERNALLY_HOSTED_DATASET_TASK({+ arg: {+ source: nextDataset.metadata.source as string,+ format: getRemoteSourceFormat(nextDataset.metadata),+ size: typeof nextDataset.metadata.size === 'number' ? nextDataset.metadata.size : undefined,+ etag: typeof nextDataset.metadata.etag === 'string' ? nextDataset.metadata.etag : undefined,+ lastModified:+ typeof nextDataset.metadata.lastModified === 'string'+ ? nextDataset.metadata.lastModified+ : undefined+ },+ onProgress: progress =>+ refreshDatasetProgress(dataId, Math.round((progress?.percent ?? 0) * 100))+ }).bimap(+ result => refreshDatasetSuccess(dataId, result),+ (error: Error) => refreshDatasetError(dataId, error)+ )+ );+}++/**+ * Record download progress for an in-flight remote dataset refresh.+ * @memberof visStateUpdaters+ * @public+ */+export function refreshDatasetProgressUpdater(+ state: VisState,+ {dataId, percent}: VisStateActions.RefreshDatasetProgressUpdaterAction+): VisState {+ const dataset = state.datasets[dataId];+ if (!dataset || dataset.metadata?.refreshStatus !== 'loading') {+ return state;+ }+ const nextPercent = Number.isFinite(percent)+ ? Math.max(0, Math.min(100, Math.round(percent)))+ : 0;+ if (dataset.metadata?.refreshProgress === nextPercent) {+ return state;+ }+ return {+ ...state,+ datasets: {+ ...state.datasets,+ [dataId]: patchDatasetMetadata(dataset, {refreshProgress: nextPercent})+ }+ };+}++function fieldNamesEqual(current: {name: string}[], incoming?: {name: string}[] | null): boolean {+ if (!incoming?.length) {+ return true;+ }+ if (current.length !== incoming.length) {+ return false;+ }+ return current.every((field, i) => field.name === incoming[i].name);+}++/**+ * When a remote snapshot changes column names, old layer fieldIdx / filter names+ * can point at the wrong column. Re-bind by name and drop configs that no longer fit.+ */+function rebindLayersAndFiltersAfterSchemaChange(+ state: VisState,+ dataId: string,+ datasets: VisState['datasets']+): VisState {+ const dataset = datasets[dataId];+ const nextLayers: Layer[] = [];+ const droppedLayers: Layer[] = [];++ state.layers.forEach(layer => {+ if (layer.config.dataId !== dataId) {+ nextLayers.push(layer);+ return;+ }+ const rebound = validateExistingLayerWithData(dataset, state.layerClasses, layer, state.schema);+ if (rebound?.isValidToSave()) {+ nextLayers.push(rebound);+ } else {+ droppedLayers.push(layer);+ }+ });++ let nextLayerOrder = state.layerOrder;+ let nextSplitMaps = state.splitMaps;+ droppedLayers.forEach(layer => {+ nextLayerOrder = removeElementFromLayerOrder(nextLayerOrder, layer.id);+ nextSplitMaps = removeLayerFromSplitMaps(nextSplitMaps, layer);+ });++ const nextLayerData = nextLayers.map(layer => {+ const oldIdx = state.layers.findIndex(oldLayer => oldLayer.id === layer.id);+ return oldIdx >= 0 ? state.layerData[oldIdx] : {};+ });++ const filtersForDataset = state.filters.filter(filter => toArray(filter.dataId).includes(dataId));+ const otherFilters = state.filters.filter(filter => !toArray(filter.dataId).includes(dataId));++ const {validated, updatedDatasets} = validateFiltersUpdateDatasets(+ {...state, datasets, layers: nextLayers},+ filtersForDataset+ );++ const nextFilters = [...otherFilters, ...validated];+ const filteredDatasets = applyFiltersToDatasets(+ [dataId],+ updatedDatasets,+ nextFilters,+ nextLayers+ );++ let nextState: VisState = {+ ...state,+ datasets: filteredDatasets,+ layers: nextLayers,+ layerData: nextLayerData,+ layerOrder: nextLayerOrder,+ splitMaps: nextSplitMaps,+ filters: nextFilters+ };+ nextState = updateAllLayerDomainData(nextState, [dataId], undefined);+ return updateAnimationDomain(nextState);+}++/**+ * Apply a finished remote refresh: keep layers, re-run filters and layer data.+ * @memberof visStateUpdaters+ * @public+ */+export function refreshDatasetSuccessUpdater(+ state: VisState,+ {dataId, result}: VisStateActions.RefreshDatasetSuccessUpdaterAction+): VisState {+ const dataset = state.datasets[dataId];+ if (!dataset) {+ return state;+ }++ const metadataPatch = {+ refreshStatus: 'idle',+ refreshError: undefined,+ refreshProgress: undefined,+ lastFetchedAt: Date.now(),+ // Always write validators. A 200 that omits them must not keep the previous+ // ETag or a later 304 can skip a body we no longer have.+ etag: result.etag,+ lastModified: result.lastModified,+ ...(typeof result.size === 'number' ? {size: result.size} : {})+ };++ const schemaUnchanged = fieldNamesEqual(dataset.fields, result.data?.fields);++ // Apply the snapshot to the table currently in the store. Progress may have+ // copied it off the object that started the fetch; the task never mutates it.+ if (!result.notModified && result.data) {+ // KeplerTable.update is async so DuckDB can await Arrow conversion. The+ // CSV/GeoJSON path (and KeplerTable.importData) run synchronously before+ // the first await, so the store table is updated before we copy it below.+ void dataset.update(result.data);+ }++ const refreshed = patchDatasetMetadata(dataset, metadataPatch);+ const datasets = {+ ...state.datasets,+ [dataId]: refreshed+ };++ if (result.notModified || !result.data) {+ return {+ ...state,+ datasets+ };+ }++ if (!schemaUnchanged) {+ return rebindLayersAndFiltersAfterSchemaChange(state, dataId, datasets);+ }++ const filteredDatasets = applyFiltersToDatasets([dataId], datasets, state.filters, state.layers);++ let nextState: VisState = {+ ...state,+ datasets: filteredDatasets+ };+ nextState = updateAllLayerDomainData(nextState, [dataId], undefined);+ return updateAnimationDomain(nextState);+}++/**+ * Record a failed remote dataset refresh without dropping existing rows.+ * @memberof visStateUpdaters+ * @public+ */+export function refreshDatasetErrorUpdater(+ state: VisState,+ {dataId, error}: VisStateActions.RefreshDatasetErrorUpdaterAction+): VisState {+ const dataset = state.datasets[dataId];+ if (!dataset) {+ return state;+ }++ const nextState = {+ ...state,+ datasets: {+ ...state.datasets,+ [dataId]: patchDatasetMetadata(dataset, {+ refreshStatus: 'error',+ refreshError: error?.message || String(error),+ refreshProgress: undefined+ })+ }+ };++ return nextState;+}+/*** Add new dataset to `visState`, with option to load a map config along with the datasets* @memberof visStateUpdaters@@ -3105,10 +3404,7 @@ function layerVisConfigFromAddDataOptions(* from columns on the first pass and must not be recalculated here.*/function polygonFilterDependsOnLayerMeta(layer: Layer): boolean {- return (- layer.type === LAYER_TYPES.geojson ||- layer.config?.columnMode === 'geojson'- );+ return layer.type === LAYER_TYPES.geojson || layer.config?.columnMode === 'geojson';}/**diff --git a/src/reducers/src/vis-state.ts b/src/reducers/src/vis-state.tsindex 88816d2f6..cccff49b7 100644--- a/src/reducers/src/vis-state.ts+++ b/src/reducers/src/vis-state.ts@@ -103,6 +103,14 @@ const actionHandler = {[ActionTypes.UPDATE_TABLE_COLOR]: visStateUpdaters.updateTableColorUpdater,+ [ActionTypes.REFRESH_DATASET]: visStateUpdaters.refreshDatasetUpdater,++ [ActionTypes.REFRESH_DATASET_SUCCESS]: visStateUpdaters.refreshDatasetSuccessUpdater,++ [ActionTypes.REFRESH_DATASET_ERROR]: visStateUpdaters.refreshDatasetErrorUpdater,++ [ActionTypes.REFRESH_DATASET_PROGRESS]: visStateUpdaters.refreshDatasetProgressUpdater,+[ActionTypes.TOGGLE_FILTER_ANIMATION]: visStateUpdaters.toggleFilterAnimationUpdater,[ActionTypes.UPDATE_FILTER_ANIMATION_SPEED]: visStateUpdaters.updateFilterAnimationSpeedUpdater,diff --git a/src/schemas/src/dataset-schema.ts b/src/schemas/src/dataset-schema.tsindex 2bbf85d32..595c09f44 100644--- a/src/schemas/src/dataset-schema.ts+++ b/src/schemas/src/dataset-schema.ts@@ -5,7 +5,12 @@ import pick from 'es-toolkit/compat/pick';import {console as globalConsole} from 'global/window';import * as arrow from 'apache-arrow';-import {ALL_FIELD_TYPES, DATASET_FORMATS, DatasetType, getRemoteSourceFormat} from '@kepler.gl/constants';+import {+ ALL_FIELD_TYPES,+ DATASET_FORMATS,+ DatasetType,+ getRemoteSourceFormat+} from '@kepler.gl/constants';import {ProtoDataset, RGBColor, JsonObject} from '@kepler.gl/types';import {KeplerTable} from '@kepler.gl/table';import {VERSIONS} from './versions';@@ -176,7 +181,11 @@ export class DatasetSchema extends Schema {fields: getFieldsForSaving(dataset.fields || []),metadata: {source: dataset.metadata.source,- ...(sourceFormat ? {format: sourceFormat} : {})+ ...(sourceFormat ? {format: sourceFormat} : {}),+ ...(typeof dataset.metadata.refreshIntervalMs === 'number' &&+ dataset.metadata.refreshIntervalMs > 0+ ? {refreshIntervalMs: dataset.metadata.refreshIntervalMs}+ : {})}})[this.key];}@@ -243,7 +252,11 @@ export class DatasetSchema extends Schema {metadata = {source: dataset.metadata.source,...(sourceFormat ? {sourceFormat} : {}),- ...(typeof dataset.metadata.size === 'number' ? {size: dataset.metadata.size} : {})+ ...(typeof dataset.metadata.size === 'number' ? {size: dataset.metadata.size} : {}),+ ...(typeof dataset.metadata.refreshIntervalMs === 'number' &&+ dataset.metadata.refreshIntervalMs > 0+ ? {refreshIntervalMs: dataset.metadata.refreshIntervalMs}+ : {})};}diff --git a/src/table/src/kepler-table.ts b/src/table/src/kepler-table.tsindex d5235a803..bf51ca82e 100644--- a/src/table/src/kepler-table.ts+++ b/src/table/src/kepler-table.ts@@ -157,9 +157,7 @@ function computePolygonFilteredIndexByLayer(for (const layer of layersOnDataset) {// For each polygon filter, check if this layer is targeted- const applicableFilters = polygonFilters.filter(- f => f.layerId && f.layerId.includes(layer.id)- );+ const applicableFilters = polygonFilters.filter(f => f.layerId && f.layerId.includes(layer.id));if (!applicableFilters.length) {// This layer is not targeted by any polygon filter - use base index@@ -199,6 +197,11 @@ class KeplerTable<F extends Field = Field> {fields: F[] = [];dataContainer: DataContainerInterface;+ /**+ * Bumped in {@link update} so layer `dataUpdateTriggers` notice in-place row+ * snapshots (the dataContainer instance stays the same).+ */+ dataRevision = 0;allIndexes: number[] = [];filteredIndex: number[] = [];@@ -310,15 +313,51 @@ class KeplerTable<F extends Field = Field> {/*** update table with new data- * @param data - new data e.g. the arrow data with new batches loaded+ * @param data - new data e.g. the arrow data with new batches loaded, or a full row snapshot*/async update(data: ProtoDataset['data']) {- const dataContainerData = data.arrowTable ?? data.cols ?? data.rows;- this.dataContainer.update?.(dataContainerData);+ // Arrow/DuckDB incremental loads pass `cols` (and empty `rows`). Row snapshots+ // for remote refresh pass `rows` only. Keep the column path close to the+ // pre-refresh update() so filters/gpuFilter are not wiped on a normal load.+ const isRowSnapshot = !data.cols && Array.isArray(data.rows);++ if (data.fields?.length && !fieldNamesMatch(this.fields, data.fields)) {+ await this.importData({data});+ this.dataRevision += 1;+ return this;+ }++ // Row snapshots must not pass leftover arrowTable into RowDataContainer.+ const dataContainerData = isRowSnapshot ? data.rows : data.arrowTable ?? data.cols ?? data.rows;++ if (typeof this.dataContainer.update === 'function') {+ this.dataContainer.update(dataContainerData);+ } else if (isRowSnapshot) {+ this.dataContainer = createDataContainer(dataContainerData, {+ fields: data.fields || this.fields,+ inputDataFormat: DataForm.ROWS_ARRAY+ });+ }++ if (isRowSnapshot) {+ this.fields = this.fields.map((f, i) => {+ const {filterProps: _filterProps, ...rest} = f;+ return {+ ...rest,+ valueAccessor: getFieldValueAccessor(f, i, this.dataContainer)+ };+ }) as F[];+ this.filterRecord = undefined;+ this.filterRecordCPU = undefined;+ this.changedFilters = undefined;+ this.gpuFilter = getGpuFilterProps([], this.id, this.fields, undefined);+ }+this.allIndexes = this.dataContainer.getPlainIndex();this.filteredIndex = this.allIndexes;this.filteredIndexForDomain = this.allIndexes;this.filteredIndexByLayer = {};+ this.dataRevision += 1;return this;}@@ -783,13 +822,19 @@ export function copyTableAndUpdate(}, copyTable(original));}+function fieldNamesMatch(current: {name: string}[], incoming: {name: string}[]): boolean {+ if (current.length !== incoming.length) {+ return false;+ }+ return current.every((field, i) => field.name === incoming[i].name);+}+/*** Arrow Int64/Uint64 columns yield JS BigInt. Detect from the column type once* at bind time so other columns keep the existing accessor with no extra checks.*/function isInt64ArrowColumn(dc: DataContainerInterface, fieldIdx: number): boolean {- const type = (dc.getColumn?.(fieldIdx) as {type?: {bitWidth?: number; isSigned?: boolean}})- ?.type;+ const type = (dc.getColumn?.(fieldIdx) as {type?: {bitWidth?: number; isSigned?: boolean}})?.type;return type?.bitWidth === 64 && typeof type.isSigned === 'boolean';}diff --git a/src/utils/src/row-data-container.ts b/src/utils/src/row-data-container.tsindex 6083df9b1..5a2805404 100644--- a/src/utils/src/row-data-container.ts+++ b/src/utils/src/row-data-container.ts@@ -52,6 +52,17 @@ export class RowDataContainer implements DataContainerInterface {this._numColumns = data.rows[0]?.length || 0;}+ /**+ * Replace all rows. Callers pass the full snapshot (same contract as ArrowDataContainer).+ */+ update(updateData: any[]): void {+ if (!Array.isArray(updateData)) {+ throw Error("RowDataContainer.update: rows object isn't an array");+ }+ this._rows = updateData;+ this._numColumns = updateData[0]?.length || 0;+ }+numRows(): number {return this._rows.length;}diff --git a/test/browser/components/common/file-uploader-test.js b/test/browser/components/common/file-uploader-test.jsindex 948108d60..0a758b0c2 100644--- a/test/browser/components/common/file-uploader-test.js+++ b/test/browser/components/common/file-uploader-test.js@@ -244,7 +244,7 @@ test('Components -> FileUpload remote URL form', t => {t.equal(urlInput.length, 1, 'should render URL input');t.ok(urlInput.first().prop('aria-label'), 'should set aria-label on URL input');t.equal(- wrapper.find('.file-uploader__remote-url select').hostNodes().length,+ wrapper.find('.file-uploader__remote-format').hostNodes().length,0,'format selector is hidden by default');@@ -260,9 +260,8 @@ test('Components -> FileUpload remote URL format selector flag', t => {</IntlWrapper>);- t.equal(- wrapper.find('.file-uploader__remote-url select').hostNodes().length,- 1,+ t.ok(+ wrapper.find('.file-uploader__remote-format').hostNodes().length >= 1,'should render format select when the flag is enabled');diff --git a/test/helpers/comparison-utils.js b/test/helpers/comparison-utils.jsindex def7ac223..dbea3c243 100644--- a/test/helpers/comparison-utils.js+++ b/test/helpers/comparison-utils.js@@ -325,18 +325,15 @@ export function cmpColumns(t, expectedColumns, actualColumns, layerName) {export function cmpDataset(t, expectedDataset, actualDataset, opt = {}) {assertDatasetIsTable(t, actualDataset);- // filteredIndexByLayer is an internal optimization property, skip in key comparison if not in expected+ // Internal fields added after fixtures were written; compare only when expected sets them.+ const optionalDatasetKeys = new Set(['filteredIndexByLayer', 'dataRevision']);const actualKeysForComparison = Object.keys(actualDataset).filter(- key => key !== 'filteredIndexByLayer' || key in expectedDataset+ key => !optionalDatasetKeys.has(key) || key in expectedDataset);const expectedKeysForComparison = Object.keys(expectedDataset);t.deepEqual(- actualKeysForComparison- .filter(key => actualDataset[key] !== undefined)- .sort(),- expectedKeysForComparison- .filter(key => expectedDataset[key] !== undefined)- .sort(),+ actualKeysForComparison.filter(key => actualDataset[key] !== undefined).sort(),+ expectedKeysForComparison.filter(key => expectedDataset[key] !== undefined).sort(),`dataset:${expectedDataset.id} should have same keys`);@@ -379,6 +376,7 @@ export function cmpDataset(t, expectedDataset, actualDataset, opt = {}) {});break;case 'filteredIndexByLayer':+ case 'dataRevision':if (key in expectedDataset) {t.deepEqual(actualDataset[key],diff --git a/test/node/processors/file-handler-test.js b/test/node/processors/file-handler-test.jsindex b190b92fb..2360076ca 100644--- a/test/node/processors/file-handler-test.js+++ b/test/node/processors/file-handler-test.js@@ -2,7 +2,14 @@// Copyright contributors to the kepler.gl projectimport test from 'tape';-import {isKeplerGlMap, makeProgressIterator, filesToDataPayload, processFileData, processArrowBatches} from '@kepler.gl/processors';+import {+ isKeplerGlMap,+ makeProgressIterator,+ filesToDataPayload,+ processFileData,+ processArrowBatches+} from '@kepler.gl/processors';+import {getDatasetRefreshIntervalMs} from '@kepler.gl/constants';import * as arrow from 'apache-arrow';import {parsedFields, parsedRows} from 'test/fixtures/row-object';import {@@ -189,6 +196,38 @@ test('#file-handler -> filesToDataPayload remote metadata', t => {t.end();});+test('#file-handler -> processFileData one-shot load does not enable polling', async t => {+ const rows = [{lat: 1, lng: 2}];+ const local = await processFileData({+ content: {fileName: 'local.csv', data: rows},+ fileCache: []+ });+ t.equal(local[0].info.type, undefined, 'local files are not marked externally-hosted');+ t.equal(local[0].metadata, undefined, 'local files get no remote refresh metadata');++ const remote = await processFileData({+ content: {+ fileName: 'remote.csv',+ data: rows,+ sourceUrl: 'https://example.com/remote.csv'+ },+ fileCache: []+ });+ t.equal(remote[0].info.type, 'externally-hosted', 'URL loads are still externally-hosted');+ t.equal(+ remote[0].metadata.refreshIntervalMs,+ undefined,+ 'a one-shot URL load does not set a poll interval'+ );+ t.equal(+ getDatasetRefreshIntervalMs(remote[0].metadata),+ 0,+ 'polling helper treats omitted interval as off'+ );++ t.end();+});+test('#file-handler -> processFileData persists remote file format', async t => {const cache = await processFileData({content: {@@ -202,11 +241,41 @@ test('#file-handler -> processFileData persists remote file format', async t =>t.equal(cache[0].info.type, 'externally-hosted', 'should mark the dataset as externally-hosted');t.equal(cache[0].info.format, 'row', 'processor format stays row for CSV');- t.deepEqual(- cache[0].metadata,- {source: 'https://example.com/abc123?sv=1', sourceFormat: 'csv'},+ t.equal(cache[0].metadata.source, 'https://example.com/abc123?sv=1');+ t.equal(+ cache[0].metadata.sourceFormat,+ 'csv','should persist the file format, not the processor format');+ t.equal(+ typeof cache[0].metadata.lastFetchedAt,+ 'number',+ 'should record lastFetchedAt on remote load'+ );+ t.equal(cache[0].metadata.etag, undefined, 'should omit etag when the fetch did not provide one');+ t.equal(+ cache[0].metadata.lastModified,+ undefined,+ 'should omit lastModified when the fetch did not provide one'+ );++ const withValidators = await processFileData({+ content: {+ fileName: 'quakes.csv',+ data: [{lat: 1, lng: 2}],+ sourceUrl: 'https://example.com/quakes.csv',+ keplerFormat: 'csv',+ etag: '"abc"',+ lastModified: 'Wed, 21 Oct 2015 07:28:00 GMT'+ },+ fileCache: []+ });+ t.equal(withValidators[0].metadata.etag, '"abc"', 'should persist ETag for the next refresh');+ t.equal(+ withValidators[0].metadata.lastModified,+ 'Wed, 21 Oct 2015 07:28:00 GMT',+ 'should persist Last-Modified for the next refresh'+ );const parquetCache = await processFileData({content: {diff --git a/test/node/processors/remote-file-test.js b/test/node/processors/remote-file-test.jsindex 33b18a84a..39512a659 100644--- a/test/node/processors/remote-file-test.js+++ b/test/node/processors/remote-file-test.js@@ -3,6 +3,7 @@import test from 'tape';import {+ fetchRemoteFile,fetchRemoteFileAsKeplerFile,getExtensionFromUrl,getFileNameForRemoteUrl,@@ -90,7 +91,7 @@ test('#remote-file -> fetchRemoteFileAsKeplerFile rejects non-http URLs', asynctest('#remote-file -> fetchRemoteFileAsKeplerFile does not dump error bodies', async t => {const origFetch = global.fetch;global.fetch = async () =>- new Response('<!DOCTYPE html><html><body>Not Found '.repeat(500) + '</body></html>', {+ new Response(`${'<!DOCTYPE html><html><body>Not Found '.repeat(500)}</body></html>`, {status: 404,statusText: 'Not Found'});@@ -142,3 +143,83 @@ test('#remote-file -> fetchRemoteFileAsKeplerFile progress without Content-Lengt}t.end();});++test('#remote-file -> fetchRemoteFileAsKeplerFile progress with Content-Length', async t => {+ const origFetch = global.fetch;+ const chunks = [new Uint8Array([1, 2, 3, 4]), new Uint8Array([5, 6, 7, 8])];+ let i = 0;+ global.fetch = async () =>+ new Response(+ new ReadableStream({+ pull(controller) {+ if (i < chunks.length) {+ controller.enqueue(chunks[i++]);+ } else {+ controller.close();+ }+ }+ }),+ {status: 200, headers: {'content-length': '8'}}+ );++ try {+ const percents = [];+ await fetchRemoteFileAsKeplerFile('https://example.com/data.csv', 'csv', ({percent}) => {+ percents.push(percent);+ });+ t.ok(+ percents.some(p => p > 0 && p < 1),+ 'should emit intermediate percent when Content-Length is known'+ );+ t.equal(percents[percents.length - 1], 1, 'should emit 100% when complete');+ } finally {+ global.fetch = origFetch;+ }+ t.end();+});++test('#remote-file -> fetchRemoteFileAsKeplerFile uses the default HTTP cache', async t => {+ const origFetch = global.fetch;+ global.fetch = async (url, init) => {+ t.equal(init?.cache, undefined, 'first remote URL load should not set cache: no-store');+ return new Response('a,b\n1,2', {status: 200, headers: {'content-type': 'text/csv'}});+ };++ try {+ await fetchRemoteFileAsKeplerFile('https://example.com/data.csv', 'csv');+ } finally {+ global.fetch = origFetch;+ }+ t.end();+});++test('#remote-file -> fetchRemoteFile returns notModified on 304', async t => {+ const origFetch = global.fetch;+ global.fetch = async (url, init) => {+ t.equal(init.headers['If-None-Match'], '"abc"', 'should send If-None-Match');+ t.equal(init.cache, 'no-store', 'refresh fetches should bypass the HTTP cache');+ return new Response(null, {+ status: 304,+ headers: {etag: '"xyz"', 'last-modified': 'Wed, 21 Oct 2015 07:28:00 GMT'}+ });+ };++ try {+ const result = await fetchRemoteFile('https://example.com/data.csv', {+ etag: '"abc"',+ lastModified: 'Tue, 20 Oct 2015 07:28:00 GMT',+ bypassCache: true+ });+ t.ok(result.notModified, 'should report notModified');+ t.equal(result.file, null, 'should not return a file');+ t.equal(result.etag, '"xyz"', 'should prefer the 304 response ETag');+ t.equal(+ result.lastModified,+ 'Wed, 21 Oct 2015 07:28:00 GMT',+ 'should prefer the 304 response Last-Modified'+ );+ } finally {+ global.fetch = origFetch;+ }+ t.end();+});diff --git a/test/node/reducers/vis-state-test.js b/test/node/reducers/vis-state-test.jsindex 9569156ae..c4276f45e 100644--- a/test/node/reducers/vis-state-test.js+++ b/test/node/reducers/vis-state-test.js@@ -22,7 +22,8 @@ import {syncTimeFilterWithLayerTimelineUpdater,setTimeFilterTimelineModeUpdater,setFilterAnimationTimeUpdater,- setFilterAnimationWindowUpdater+ setFilterAnimationWindowUpdater,+ calculateLayerData} from '@kepler.gl/reducers';import {processCsvData, processGeojson} from '@kepler.gl/processors';@@ -39,6 +40,7 @@ import {} from '@kepler.gl/utils';import {ALL_FIELD_TYPES,+ DatasetType,EDITOR_MODES,LAYER_VIS_CONFIGS,DEFAULT_TEXT_LABEL,@@ -943,7 +945,11 @@ test('visStateReducer -> layerDataIdChangeUpdater -> not valid to save layer rem// Verify precondition: layer has colorField sett.ok(pointLayer.config.colorField, 'point layer should have colorField set');- t.equal(pointLayer.config.colorField.name, 'gps_data.types', 'colorField should be gps_data.types');+ t.equal(+ pointLayer.config.colorField.name,+ 'gps_data.types',+ 'colorField should be gps_data.types'+ );// Add a new dataset with fewer rows but containing the same colorField nameconst newFields = [@@ -961,7 +967,10 @@ test('visStateReducer -> layerDataIdChangeUpdater -> not valid to save layer remaction: VisStateActions.updateVisData,payload: [[- {info: {id: 'small-dataset', label: 'Small Data'}, data: {fields: newFields, rows: newRows}}+ {+ info: {id: 'small-dataset', label: 'Small Data'},+ data: {fields: newFields, rows: newRows}+ }]]}@@ -998,7 +1007,11 @@ test('visStateReducer -> layerDataIdChangeUpdater -> not valid to save layer remt.equal(updatedLayer.config.dataId, 'small-dataset', 'should update layer dataId');// colorField should be remapped to the new dataset's field (same name exists)t.ok(updatedLayer.config.colorField, 'colorField should be remapped');- t.equal(updatedLayer.config.colorField.name, 'gps_data.types', 'colorField should match by name in new dataset');+ t.equal(+ updatedLayer.config.colorField.name,+ 'gps_data.types',+ 'colorField should match by name in new dataset'+ );// Now test clearing: switch to a dataset without the colorField nameconst noMatchFields = [@@ -1012,7 +1025,10 @@ test('visStateReducer -> layerDataIdChangeUpdater -> not valid to save layer remaction: VisStateActions.updateVisData,payload: [[- {info: {id: 'no-match-dataset', label: 'No Match'}, data: {fields: noMatchFields, rows: noMatchRows}}+ {+ info: {id: 'no-match-dataset', label: 'No Match'},+ data: {fields: noMatchFields, rows: noMatchRows}+ }]]}@@ -1032,7 +1048,11 @@ test('visStateReducer -> layerDataIdChangeUpdater -> not valid to save layer remconst finalLayer = finalState.layers[0];t.equal(finalLayer.config.dataId, 'no-match-dataset', 'should update dataId to no-match-dataset');- t.equal(finalLayer.config.colorField, null, 'colorField should be null when no matching field in new dataset');+ t.equal(+ finalLayer.config.colorField,+ null,+ 'colorField should be null when no matching field in new dataset'+ );t.end();});@@ -5037,7 +5057,11 @@ test('#visStateReducer -> POLYGON: Create polygon filter', t => {t.equal(newReducer.layerData[0].data.length, 2, 'Layer Point 1 should only show 2 points');- t.equal(newReducer.layerData[1].data.length, 4, 'Layer Point 2 should show all 4 points (not targeted by filter)');+ t.equal(+ newReducer.layerData[1].data.length,+ 4,+ 'Layer Point 2 should show all 4 points (not targeted by filter)'+ );const filterFeature = newReducer.filters[0].value;@@ -5051,9 +5075,17 @@ test('#visStateReducer -> POLYGON: Create polygon filter', t => {t.equal(newReducer.filters[0].layerId.length, 2, 'Should have two values in filter.layerId');- t.equal(newReducer.layerData[0].data.length, 2, 'Layer Point 1 should show 2 points (filtered by its own position)');+ t.equal(+ newReducer.layerData[0].data.length,+ 2,+ 'Layer Point 1 should show 2 points (filtered by its own position)'+ );- t.equal(newReducer.layerData[1].data.length, 0, 'Layer Point 2 should show 0 points (end positions are outside polygon)');+ t.equal(+ newReducer.layerData[1].data.length,+ 0,+ 'Layer Point 2 should show 0 points (end positions are outside polygon)'+ );// Adding a new dataset - creates extra 4 layersnewReducer = applyActions(reducer, newReducer, [@@ -5119,10 +5151,7 @@ test('#visStateReducer -> POLYGON: unselecting all layers returns sketch', t =>t.equal(state.filters.length, 0, 'Should remove the filter when no layers remain');t.equal(state.editor.features.length, 1, 'Should return the polygon to sketches');- t.notOk(- state.editor.features[0].properties.filterId,- 'Returned sketch should not be a filter'- );+ t.notOk(state.editor.features[0].properties.filterId, 'Returned sketch should not be a filter');t.equal(state.editor.selectedFeature.id,mockPolygonFeature.id,@@ -5703,9 +5732,7 @@ function loadDualLonLatPolygonState() {}function pointLayerByLat(state, latField) {- return state.layers.find(- l => l.type === 'point' && l.config.columns?.lat?.value === latField- );+ return state.layers.find(l => l.type === 'point' && l.config.columns?.lat?.value === latField);}function layerDataIndexes(state, layer) {@@ -5722,10 +5749,7 @@ test('#visStateReducer -> POLYGON: independent polygons on two layers', t => {VisStateActions.setFeatures([mockStartRegionPolygon, mockEndRegionPolygon]));state = reducer(state, VisStateActions.setSelectedFeature(mockStartRegionPolygon));- state = reducer(- state,- VisStateActions.setPolygonFilterLayer(startLayer, mockStartRegionPolygon)- );+ state = reducer(state, VisStateActions.setPolygonFilterLayer(startLayer, mockStartRegionPolygon));state = reducer(state, VisStateActions.setSelectedFeature(mockEndRegionPolygon));state = reducer(state, VisStateActions.setPolygonFilterLayer(endLayer, mockEndRegionPolygon));@@ -5776,15 +5800,9 @@ test('#visStateReducer -> POLYGON: intersecting polygons AND on the same layer',VisStateActions.setFeatures([mockStartRegionPolygon, mockEastOverlapPolygon]));state = reducer(state, VisStateActions.setSelectedFeature(mockStartRegionPolygon));- state = reducer(- state,- VisStateActions.setPolygonFilterLayer(startLayer, mockStartRegionPolygon)- );+ state = reducer(state, VisStateActions.setPolygonFilterLayer(startLayer, mockStartRegionPolygon));state = reducer(state, VisStateActions.setSelectedFeature(mockEastOverlapPolygon));- state = reducer(- state,- VisStateActions.setPolygonFilterLayer(startLayer, mockEastOverlapPolygon)- );+ state = reducer(state, VisStateActions.setPolygonFilterLayer(startLayer, mockEastOverlapPolygon));t.equal(state.filters.length, 2, 'Should create two polygon filters on the same layer');t.deepEqual(@@ -6213,7 +6231,11 @@ test('#visStateReducer -> SET_EDITOR_FEATURE_PROPERTIES', t => {state = reducer(state, VisStateActions.setEditorFeatureProperties(pointFeature, {}));t.notOk(state.editor.features[0].properties.name, 'Should remove user properties when cleared');- t.equal(state.editor.features[0].properties.isClosed, false, 'Should keep editor-only properties');+ t.equal(+ state.editor.features[0].properties.isClosed,+ false,+ 'Should keep editor-only properties'+ );t.end();});@@ -6348,7 +6370,9 @@ test('#visStateReducer -> LOAD_COLUMN_STATS', t => {initialState,VisStateActions.loadColumnStats(testCsvDataId, 'gps_data.lat'));- const loadingField = nextState.datasets[testCsvDataId].fields.find(f => f.name === 'gps_data.lat');+ const loadingField = nextState.datasets[testCsvDataId].fields.find(+ f => f.name === 'gps_data.lat'+ );t.equal(loadingField.isLoadingStats, true, 'should set isLoadingStats while loading');const tasks = drainTasksForTesting();@@ -7904,3 +7928,270 @@ test('#visStateReducer -> LAYER_COLOR_UI_CHANGE. custom palette - select new stet.end();});++test('VisStateUpdater -> refreshDataset', async t => {+ drainTasksForTesting();+ const initialData = processCsvData('lat,lng\n1,2\n3,4');+ const datasets = await createNewDataEntryMock({+ info: {id: 'remote-1', type: DatasetType.EXTERNALLY_HOSTED, label: 'quakes.csv'},+ data: initialData,+ metadata: {source: 'https://example.com/quakes.csv', sourceFormat: 'csv'}+ });++ const state = {+ ...INITIAL_VIS_STATE,+ datasets+ };++ t.equal(state.datasets['remote-1'].dataContainer.numRows(), 2, 'starts with 2 rows');++ const loadingState = reducer(state, VisStateActions.refreshDataset('remote-1'));+ t.equal(+ loadingState.datasets['remote-1'].metadata.refreshStatus,+ 'loading',+ 'should mark the dataset as loading'+ );++ const skipped = reducer(loadingState, VisStateActions.refreshDataset('remote-1'));+ t.equal(skipped, loadingState, 'should ignore a second refresh while loading');++ const [task, ...more] = drainTasksForTesting();+ t.equal(more.length, 0, 'should create one refresh task');+ t.equal(task.type, 'REFRESH_EXTERNALLY_HOSTED_DATASET_TASK', 'should fetch the remote file');++ const refreshed = processCsvData('lat,lng\n10,20\n30,40\n50,60');++ const successState = reducer(+ loadingState,+ succeedTaskInTest(task, {+ data: refreshed,+ notModified: false,+ etag: '"v2"',+ lastModified: 'Wed, 21 Oct 2015 07:28:00 GMT',+ size: 32+ })+ );++ t.equal(successState.datasets['remote-1'].dataContainer.numRows(), 3, 'should replace rows');+ t.equal(successState.datasets['remote-1'].metadata.refreshStatus, 'idle', 'should clear loading');+ t.equal(successState.datasets['remote-1'].metadata.etag, '"v2"', 'should store etag');+ t.equal(+ successState.datasets['remote-1'].metadata.lastModified,+ 'Wed, 21 Oct 2015 07:28:00 GMT',+ 'should store Last-Modified'+ );+ t.ok(successState.datasets['remote-1'].metadata.lastFetchedAt, 'should record lastFetchedAt');+ t.equal(+ successState.datasets['remote-1'].metadata.refreshProgress,+ undefined,+ 'should clear refresh progress'+ );++ const loadingAgain = reducer(successState, VisStateActions.refreshDataset('remote-1'));+ const [taskAgain] = drainTasksForTesting();+ const clearedValidators = reducer(+ loadingAgain,+ succeedTaskInTest(taskAgain, {+ data: processCsvData('lat,lng\n7,8'),+ notModified: false+ })+ );+ t.equal(+ clearedValidators.datasets['remote-1'].metadata.etag,+ undefined,+ 'a 200 without ETag should drop the previous validator'+ );+ t.equal(+ clearedValidators.datasets['remote-1'].metadata.lastModified,+ undefined,+ 'a 200 without Last-Modified should drop the previous validator'+ );++ t.end();+});++test('VisStateUpdater -> refreshDataset rebuilds point layer positions', async t => {+ drainTasksForTesting();+ const initialData = processCsvData('lat,lng\n37.77,-122.42');+ const datasets = await createNewDataEntryMock({+ info: {id: 'remote-1', type: DatasetType.EXTERNALLY_HOSTED, label: 'live.csv'},+ data: initialData,+ metadata: {source: 'https://example.com/live.csv', sourceFormat: 'csv'}+ });+ const {props} = PointLayer.findDefaultLayerProps(datasets['remote-1']);+ const pointLayer = new PointLayer({+ id: 'p1',+ dataId: 'remote-1',+ isVisible: true,+ ...props[0]+ });+ const stateWithLayer = {+ ...INITIAL_VIS_STATE,+ datasets,+ layers: [pointLayer],+ layerData: [{}]+ };+ const {layerData: initialLayerData, layer} = calculateLayerData(+ pointLayer,+ stateWithLayer,+ undefined+ );+ const state = {+ ...stateWithLayer,+ layers: [layer],+ layerData: [initialLayerData]+ };++ t.ok(initialLayerData.data?.[0]?.position, 'should format an initial point');+ const firstPos = initialLayerData.data[0].position.slice();++ const loadingState = reducer(state, VisStateActions.refreshDataset('remote-1'));+ const progressed = reducer(loadingState, VisStateActions.refreshDatasetProgress('remote-1', 50));+ t.notEqual(+ progressed.datasets['remote-1'],+ loadingState.datasets['remote-1'],+ 'progress should copy the table'+ );++ const [task] = drainTasksForTesting();+ const refreshed = processCsvData('lat,lng\n10,20');+ t.equal(+ progressed.datasets['remote-1'].dataContainer.numRows(),+ 1,+ 'progress must not apply the snapshot'+ );++ const successState = reducer(+ progressed,+ succeedTaskInTest(task, {+ data: refreshed,+ notModified: false,+ etag: '"v2"'+ })+ );++ const nextPos = successState.layerData[0].data[0].position;+ t.notDeepEqual(nextPos, firstPos, 'should rebuild point positions after refresh');+ t.deepEqual(nextPos.slice(0, 2), [20, 10], 'should use the new lng/lat');++ t.end();+});++test('VisStateUpdater -> refreshDataset rebinds or drops layers when field names change', async t => {+ drainTasksForTesting();+ const initialData = processCsvData('lat,lng\n37.77,-122.42');+ const datasets = await createNewDataEntryMock({+ info: {id: 'remote-1', type: DatasetType.EXTERNALLY_HOSTED, label: 'live.csv'},+ data: initialData,+ metadata: {source: 'https://example.com/live.csv', sourceFormat: 'csv'}+ });+ const {props} = PointLayer.findDefaultLayerProps(datasets['remote-1']);+ const pointLayer = new PointLayer({+ id: 'p1',+ dataId: 'remote-1',+ isVisible: true,+ ...props[0]+ });+ const {layerData, layer} = calculateLayerData(+ pointLayer,+ {...INITIAL_VIS_STATE, datasets, layers: [pointLayer], layerData: [{}]},+ undefined+ );+ const state = {+ ...INITIAL_VIS_STATE,+ datasets,+ layers: [layer],+ layerData: [layerData],+ layerOrder: [layer.id]+ };++ const loadingCompatible = reducer(state, VisStateActions.refreshDataset('remote-1'));+ const [compatibleTask] = drainTasksForTesting();+ const withExtraColumn = processCsvData('lat,lng,value\n10,20,3');+ const kept = reducer(+ loadingCompatible,+ succeedTaskInTest(compatibleTask, {data: withExtraColumn, notModified: false})+ );+ t.equal(kept.layers.length, 1, 'should keep the point layer when lat/lng still exist');+ t.equal(kept.layers[0].id, 'p1', 'should keep the same layer id');+ t.equal(kept.datasets['remote-1'].fields.length, 3, 'should load the extra column');++ const loadingIncompatible = reducer(kept, VisStateActions.refreshDataset('remote-1'));+ const [incompatibleTask] = drainTasksForTesting();+ const renamed = processCsvData('foo,bar\n1,2');+ const dropped = reducer(+ loadingIncompatible,+ succeedTaskInTest(incompatibleTask, {data: renamed, notModified: false})+ );+ t.equal(dropped.layers.length, 0, 'should drop the point layer when lat/lng are gone');+ t.deepEqual(dropped.layerOrder, [], 'should remove the layer from layerOrder');+ t.equal(dropped.datasets['remote-1'].fields[0].name, 'foo', 'should still apply the snapshot');++ t.end();+});++test('VisStateUpdater -> refreshDatasetProgress', async t => {+ drainTasksForTesting();+ const initialData = processCsvData('lat,lng\n1,2');+ const datasets = await createNewDataEntryMock({+ info: {id: 'remote-1', type: DatasetType.EXTERNALLY_HOSTED, label: 'quakes.csv'},+ data: initialData,+ metadata: {source: 'https://example.com/quakes.csv', sourceFormat: 'csv'}+ });+ const state = {...INITIAL_VIS_STATE, datasets};+ const loadingState = reducer(state, VisStateActions.refreshDataset('remote-1'));+ drainTasksForTesting();++ const progressed = reducer(loadingState, VisStateActions.refreshDatasetProgress('remote-1', 42));+ t.equal(+ progressed.datasets['remote-1'].metadata.refreshProgress,+ 42,+ 'should store download percent'+ );++ const same = reducer(progressed, VisStateActions.refreshDatasetProgress('remote-1', 42));+ t.equal(same, progressed, 'should skip redundant progress updates');++ const idle = reducer(state, VisStateActions.refreshDatasetProgress('remote-1', 50));+ t.equal(idle, state, 'should ignore progress when not loading');++ t.end();+});++test('VisStateUpdater -> refreshDataset 304 and error', async t => {+ drainTasksForTesting();+ const initialData = processCsvData('lat,lng\n1,2');+ const datasets = await createNewDataEntryMock({+ info: {id: 'remote-1', type: DatasetType.EXTERNALLY_HOSTED, label: 'quakes.csv'},+ data: initialData,+ metadata: {source: 'https://example.com/quakes.csv'}+ });+ const state = {...INITIAL_VIS_STATE, datasets};++ const loadingState = reducer(state, VisStateActions.refreshDataset('remote-1'));+ const [task] = drainTasksForTesting();++ const notModified = reducer(+ loadingState,+ succeedTaskInTest(task, {data: null, notModified: true, etag: '"same"'})+ );+ t.equal(notModified.datasets['remote-1'].dataContainer.numRows(), 1, '304 keeps existing rows');+ t.equal(notModified.datasets['remote-1'].metadata.refreshStatus, 'idle');+ t.equal(notModified.datasets['remote-1'].metadata.etag, '"same"');++ const loadingAgain = reducer(notModified, VisStateActions.refreshDataset('remote-1'));+ const [errorTask] = drainTasksForTesting();+ const failed = reducer(loadingAgain, errorTaskInTest(errorTask, new Error('network down')));+ t.equal(failed.datasets['remote-1'].metadata.refreshStatus, 'error');+ t.ok(+ String(failed.datasets['remote-1'].metadata.refreshError).includes('network down'),+ 'should store the error message'+ );+ t.equal(failed.datasets['remote-1'].dataContainer.numRows(), 1, 'error keeps existing rows');+ drainTasksForTesting();++ const ignored = reducer(state, VisStateActions.refreshDataset('missing'));+ t.equal(ignored, state, 'unknown dataset is a no-op');++ t.end();+});diff --git a/test/node/schemas/dataset-schema-test.js b/test/node/schemas/dataset-schema-test.jsindex db084a420..a4cc93ff1 100644--- a/test/node/schemas/dataset-schema-test.js+++ b/test/node/schemas/dataset-schema-test.js@@ -154,3 +154,56 @@ test('#DatasetSchema -> save externally-hosted dataset without inlining rows', tt.end();});++test('#DatasetSchema -> save externally-hosted dataset refresh interval', t => {+ const dataset = {+ id: 'remote-1',+ label: 'quakes.csv',+ color: [1, 2, 3],+ type: DatasetType.EXTERNALLY_HOSTED,+ fields: [{name: 'lat', type: 'real', format: '', analyzerType: 'FLOAT'}],+ metadata: {+ source: 'https://example.com/quakes.csv',+ sourceFormat: 'csv',+ refreshIntervalMs: 60_000,+ etag: '"skip-me"',+ refreshStatus: 'loading'+ }+ };++ const saved = datasetSchema[VERSIONS.v1].save(dataset);+ t.deepEqual(+ saved.metadata,+ {source: 'https://example.com/quakes.csv', format: 'csv', refreshIntervalMs: 60_000},+ 'should persist refresh interval without runtime status'+ );++ const loaded = SchemaManager.parseSavedData([{version: 'v1', data: saved}]);+ t.equal(loaded[0].metadata.refreshIntervalMs, 60_000, 'should restore refresh interval');+ t.equal(loaded[0].metadata.etag, undefined, 'should not restore etag');++ t.end();+});++test('#DatasetSchema -> save externally-hosted dataset custom refresh interval', t => {+ const dataset = {+ id: 'remote-1',+ label: 'quakes.csv',+ color: [1, 2, 3],+ type: DatasetType.EXTERNALLY_HOSTED,+ fields: [{name: 'lat', type: 'real', format: '', analyzerType: 'FLOAT'}],+ metadata: {+ source: 'https://example.com/quakes.csv',+ sourceFormat: 'csv',+ refreshIntervalMs: 45_000+ }+ };++ const saved = datasetSchema[VERSIONS.v1].save(dataset);+ t.equal(saved.metadata.refreshIntervalMs, 45_000, 'should persist a custom interval');++ const loaded = SchemaManager.parseSavedData([{version: 'v1', data: saved}]);+ t.equal(loaded[0].metadata.refreshIntervalMs, 45_000, 'should restore a custom interval');++ t.end();+});diff --git a/test/node/utils/data-container-test.js b/test/node/utils/data-container-test.jsindex 7095ef48e..f50c8a454 100644--- a/test/node/utils/data-container-test.js+++ b/test/node/utils/data-container-test.js@@ -3,7 +3,12 @@import test from 'tape';-import {createDataContainer, createIndexedDataContainer, compactArrowTable, ArrowDataContainer} from '@kepler.gl/utils';+import {+ createDataContainer,+ createIndexedDataContainer,+ compactArrowTable,+ ArrowDataContainer+} from '@kepler.gl/utils';import {GEOARROW_EXTENSIONS, GEOARROW_METADATA_KEY} from '@kepler.gl/constants';import * as arrow from 'apache-arrow';@@ -68,6 +73,19 @@ test('RowDataContainer', t => {t.end();});+test('RowDataContainer.update replaces rows', t => {+ const dc = createDataContainer(data);+ dc.update([+ [1, 2],+ [3, 4]+ ]);+ t.equal(dc.numRows(), 2, 'should replace with the new row count');+ t.equal(dc.numColumns(), 2, 'should keep column count');+ t.equal(dc.valueAt(0, 0), 1, 'should read values from the new rows');+ t.deepEqual(dc.getPlainIndex(), [0, 1], 'should rebuild the index');+ t.end();+});+test('IndexedDataContainer', t => {const dc = createIndexedDataContainer(createDataContainer(data), indices);@@ -137,10 +155,7 @@ test('ArrowDataContainer -> compactArrowTable collapses record batches over the'compactArrowTable should leave tables at or under maxArrowBatches unchanged');- combined.schema.metadata.set(- 'geo',- JSON.stringify({columns: {lng: {encoding: 'WKB'}}})- );+ combined.schema.metadata.set('geo', JSON.stringify({columns: {lng: {encoding: 'WKB'}}}));combined.schema.fields[0].metadata.set('ARROW:extension:name', 'geoarrow.wkb');const compacted = compactArrowTable(combined, 1);@@ -177,7 +192,9 @@ test('ArrowDataContainer -> compactArrowTable collapses record batches over thetest('ArrowDataContainer -> update does not collapse record batches', t => {const batchA = arrow.tableFromJSON([{lng: -122.4, lat: 37.8}]);- const colsA = Array.from({length: batchA.numCols}, (_, i) => batchA.getChildAt(i)).filter(Boolean);+ const colsA = Array.from({length: batchA.numCols}, (_, i) => batchA.getChildAt(i)).filter(+ Boolean+ );const dc = new ArrowDataContainer({cols: colsA,fields: batchA.schema.fields.map((field, fieldIdx) => ({@@ -305,10 +322,7 @@ test('compactArrowTable -> dictionary, WKB, and nested GeoArrow keep values', t[wkbPoint(-122.5, 37.9)],geoMeta(GEOARROW_EXTENSIONS.WKB));- wkbTable.schema.metadata.set(- 'geo',- JSON.stringify({columns: {geometry: {encoding: 'WKB'}}})- );+ wkbTable.schema.metadata.set('geo', JSON.stringify({columns: {geometry: {encoding: 'WKB'}}}));const wkbCompacted = compactArrowTable(wkbTable, 1);t.equal(wkbCompacted.batches.length, 1, 'WKB binary column should collapse to one batch');t.deepEqual(@@ -343,8 +357,18 @@ test('compactArrowTable -> dictionary, WKB, and nested GeoArrow keep values', tconst lineTable = concatColumnTables('geom',lineType,- [[[-122.4, 37.8], [-122.5, 37.9]]],- [[[0, 0], [1, 1]]],+ [+ [+ [-122.4, 37.8],+ [-122.5, 37.9]+ ]+ ],+ [+ [+ [0, 0],+ [1, 1]+ ]+ ],geoMeta(GEOARROW_EXTENSIONS.LINESTRING));const lineCompacted = compactArrowTable(lineTable, 1);@@ -403,7 +427,11 @@ test('compactArrowTable -> duplicate field names keep both columns', t => {const compacted = compactArrowTable(combined, 1);t.equal(compacted.numCols, 2, 'compaction should not drop a duplicate-named column');t.equal(compacted.numRows, 2, 'compaction should keep all rows');- t.equal(compacted.batches.length, 1, 'duplicate-named columns should still collapse to one batch');+ t.equal(+ compacted.batches.length,+ 1,+ 'duplicate-named columns should still collapse to one batch'+ );t.deepEqual([compacted.getChildAt(0).get(0), compacted.getChildAt(0).get(1)],[1.5, 2.5],diff --git a/test/node/utils/kepler-table-test.js b/test/node/utils/kepler-table-test.jsindex 92b36ad84..22f9ddd75 100644--- a/test/node/utils/kepler-table-test.js+++ b/test/node/utils/kepler-table-test.js@@ -6,7 +6,7 @@ import moment from 'moment';import testData, {numericRangesCsv, testFields} from 'test/fixtures/test-csv-data';import {preciseRound, getFilterFunction} from '@kepler.gl/utils';-import {findPointFieldPairs, KeplerTable} from '@kepler.gl/table';+import {findPointFieldPairs, KeplerTable, createNewDataEntry} from '@kepler.gl/table';import {processCsvData} from '@kepler.gl/processors';import {ALL_FIELD_TYPES, FILTER_TYPES} from '@kepler.gl/constants';import * as arrow from 'apache-arrow';@@ -447,3 +447,234 @@ test('KeplerTable -> Int64 field accessor converts BigInt to number', async t =>t.end();});++test('KeplerTable -> update with arrow cols keeps gpu filter state', async t => {+ const first = arrow.tableFromArrays({+ lat: [1, 2],+ lng: [3, 4]+ });+ const table = new KeplerTable({info: {id: 'arrow-inc'}, color: [0, 0, 0]});+ await table.importData({+ data: {+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'lng', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'}+ ],+ rows: [],+ cols: [first.getChildAt(0), first.getChildAt(1)],+ arrowTable: first+ }+ });++ const gpuFilter = table.gpuFilter;+ table.filterRecord = {name: 'keep-me'};++ const next = arrow.tableFromArrays({+ lat: [1, 2, 3],+ lng: [3, 4, 5]+ });+ await table.update({+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'lng', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'}+ ],+ rows: [],+ cols: [next.getChildAt(0), next.getChildAt(1)],+ arrowTable: next+ });++ t.equal(table.length, 3, 'arrow incremental update should grow rows');+ t.equal(table.gpuFilter, gpuFilter, 'arrow incremental update should keep gpuFilter');+ t.equal(table.filterRecord?.name, 'keep-me', 'arrow incremental update should keep filterRecord');+ t.equal(table.dataRevision, 1, 'arrow incremental update should bump dataRevision');+ t.end();+});++test('KeplerTable -> update DuckDB cols payload keeps fields and gpuFilter', async t => {+ const first = arrow.tableFromArrays({+ lat: [1, 2],+ lng: [3, 4]+ });+ const table = new KeplerTable({info: {id: 'duckdb-shape'}, color: [0, 0, 0]});+ await table.importData({+ data: {+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'lng', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'}+ ],+ rows: [],+ cols: [first.getChildAt(0), first.getChildAt(1)],+ arrowTable: first+ }+ });+ const gpuFilter = table.gpuFilter;+ const names = table.fields.map(field => field.name);++ const next = arrow.tableFromArrays({+ lat: [1, 2, 3],+ lng: [3, 4, 5]+ });+ // DuckDBTable.update calls super.update({cols, rows: [], fields: []})+ await table.update({+ cols: [next.getChildAt(0), next.getChildAt(1)],+ rows: [],+ fields: []+ });++ t.equal(table.length, 3, 'DuckDB-shaped update should grow rows');+ t.deepEqual(+ table.fields.map(field => field.name),+ names,+ 'empty fields must not rebuild schema'+ );+ t.equal(table.gpuFilter, gpuFilter, 'DuckDB-shaped update should keep gpuFilter');+ t.end();+});++test('createNewDataEntry -> existing id updates Arrow table in place', async t => {+ const fields = [+ {name: 'lat', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'lng', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'}+ ];+ const batch1 = arrow.tableFromArrays({lat: [1], lng: [2]});+ const datasets = await createNewDataEntryMock({+ info: {id: 'arrow-1'},+ data: {+ fields,+ rows: [],+ cols: [batch1.getChildAt(0), batch1.getChildAt(1)]+ }+ });+ const table = datasets['arrow-1'];+ t.equal(table.length, 1, 'first batch should create the table');+ const gpuFilter = table.gpuFilter;+ const revision = table.dataRevision;++ const batch2 = arrow.tableFromArrays({+ lat: [1, 3],+ lng: [2, 4]+ });+ const task = createNewDataEntry(+ {+ info: {id: 'arrow-1'},+ data: {+ fields,+ rows: [],+ cols: [batch2.getChildAt(0), batch2.getChildAt(1)]+ }+ },+ datasets+ );+ t.equal(task.type, 'UPDATE_TABLE_TASK', 'same id should update instead of creating');++ await task.run(+ async (effectorPrime, success, error) => {+ await effectorPrime(success, error);+ },+ value => {+ t.equal(value, table, 'should return the same table instance');+ }+ );++ t.equal(table.length, 2, 'second batch should replace/grow rows');+ t.equal(table.gpuFilter, gpuFilter, 'incremental createNewDataEntry should keep gpuFilter');+ t.ok(table.dataRevision > revision, 'incremental createNewDataEntry should bump dataRevision');+ t.end();+});++test('KeplerTable -> update rebuilds fields when arrow column names change', async t => {+ const first = arrow.tableFromArrays({+ lat: [1],+ lng: [2]+ });+ const table = new KeplerTable({info: {id: 'arrow-schema'}, color: [0, 0, 0]});+ await table.importData({+ data: {+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'lng', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'}+ ],+ rows: [],+ cols: [first.getChildAt(0), first.getChildAt(1)],+ arrowTable: first+ }+ });++ const next = arrow.tableFromArrays({+ lat: [1],+ lng: [2],+ name: ['a']+ });+ await table.update({+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'lng', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'name', type: ALL_FIELD_TYPES.string, analyzerType: 'STRING'}+ ],+ rows: [],+ cols: [next.getChildAt(0), next.getChildAt(1), next.getChildAt(2)],+ arrowTable: next+ });++ t.equal(table.fields.length, 3, 'column schema change should rebuild fields');+ t.equal(table.fields[2].name, 'name');+ t.end();+});++test('KeplerTable -> update replaces row snapshots', async t => {+ const table = new KeplerTable({info: {id: 'rows'}, color: [0, 0, 0]});+ await table.importData({+ data: {+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'lng', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'}+ ],+ rows: [+ [1, 2],+ [3, 4]+ ]+ }+ });+ t.equal(table.length, 2, 'starts with 2 rows');+ table.filterRecord = {name: 'stale'};++ await table.update({+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'lng', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'}+ ],+ rows: [+ [10, 20],+ [30, 40],+ [50, 60]+ ]+ });+ t.equal(table.length, 3, 'should grow to the new snapshot');+ t.equal(table.fields[0].valueAccessor({index: 0}), 10, 'accessors should read new values');+ t.equal(table.filteredIndex.length, 3, 'filtered index should match new length');+ t.equal(table.filterRecord, undefined, 'row snapshot should drop stale filterRecord');++ const leftoverArrow = arrow.tableFromArrays({lat: [0], lng: [0]});+ await table.update({+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'lng', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'}+ ],+ rows: [[7, 8]],+ arrowTable: leftoverArrow+ });+ t.equal(table.length, 1, 'row snapshot should win over leftover arrowTable');+ t.equal(table.fields[0].valueAccessor({index: 0}), 7);++ await table.update({+ fields: [+ {name: 'lat', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'lng', type: ALL_FIELD_TYPES.real, analyzerType: 'FLOAT'},+ {name: 'name', type: ALL_FIELD_TYPES.string, analyzerType: 'STRING'}+ ],+ rows: [['a', 'b', 'c']]+ });+ t.equal(table.fields.length, 3, 'schema change should rebuild fields');+ t.equal(table.length, 1, 'schema change should import the new rows');+ t.end();+});