Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

feat: optional charts panel (#3745)

Igor Dykhtae3fecd1d8a48
diff --git a/examples/demo-app-sqlrooms/esbuild.config.mjs b/examples/demo-app-sqlrooms/esbuild.config.mjs
index 238b45df5..e4678254f 100644
--- a/examples/demo-app-sqlrooms/esbuild.config.mjs
+++ b/examples/demo-app-sqlrooms/esbuild.config.mjs
@@ -48,6 +48,7 @@ const KEPLER_SRC_ALIASES = Object.fromEntries(
'actions',
'cloud-providers',
'common-utils',
+ 'charts',
'components',
'constants',
'duckdb',
@@ -64,7 +65,11 @@ const KEPLER_SRC_ALIASES = Object.fromEntries(
const getKeplerAliases = () => ({
...KEPLER_SRC_ALIASES,
- '@kepler.gl/sqlrooms/shell': join(SRC_DIR, 'sqlrooms/src/components/KeplerAppShell.tsx')
+ '@kepler.gl/sqlrooms/shell': join(SRC_DIR, 'sqlrooms/src/components/KeplerAppShell.tsx'),
+ // Chart factories live on a package subpath so the main components barrel
+ // does not load `@kepler.gl/charts`. The `@kepler.gl/components` alias is a
+ // file (index.ts), so this longer key is required.
+ '@kepler.gl/components/charts': join(SRC_DIR, 'components', 'src', 'charts.ts')
});
/**
diff --git a/examples/demo-app-sqlrooms/src/factories/map-control.js b/examples/demo-app-sqlrooms/src/factories/map-control.js
index 858eabb6b..1ebb689b5 100644
--- a/examples/demo-app-sqlrooms/src/factories/map-control.js
+++ b/examples/demo-app-sqlrooms/src/factories/map-control.js
@@ -8,11 +8,21 @@ import {
withState,
MapControlFactory,
EffectControlFactory,
- EffectManagerFactory
+ EffectManagerFactory,
+ ChartControlFactory
} from '@kepler.gl/components';
-// AnnotationManagerFactory is available in the workspace source (src/components) but not yet
-// published in the @kepler.gl/components version this example currently depends on.
-const AnnotationManagerFactory = require('@kepler.gl/components').AnnotationManagerFactory;
+import {getApplicationConfig} from '@kepler.gl/utils';
+// AnnotationManagerFactory is available in the workspace source (src/components)
+// but may not yet be published in the @kepler.gl/components version this example
+// currently depends on. ChartManagerFactory lives on `@kepler.gl/components/charts`
+// so the main components barrel does not load `@kepler.gl/charts`.
+const {AnnotationManagerFactory} = require('@kepler.gl/components');
+let ChartManagerFactory;
+try {
+ ChartManagerFactory = require('@kepler.gl/components/charts').ChartManagerFactory;
+} catch {
+ ChartManagerFactory = undefined;
+}
import {AiAssistantControlFactory} from '@openassistant/kepler-assistant/integration';
import {SampleMapPanel} from '../components/map-control/map-control';
@@ -57,21 +67,24 @@ const StyledMapControlOverlay = styled.div`
}
`;
-// `AnnotationManagerFactory` may be missing when this example is built against a published
-// `@kepler.gl/components` that predates it (see the require shim above). The component
+// These manager factories may be missing when this example is built against a published
+// `@kepler.gl/components` that predates them (see the require shim above). The component
// injector calls `.deps` on every entry of this array and on their transitive deps, so an
// `undefined` here crashes injection at startup. Substitute a harmless no-op factory so the
// deps array stays positionally aligned with `CustomMapControlFactory`'s parameters while
-// remaining injectable. `CustomMapControlFactory` already renders the annotation manager
-// conditionally, so the stub is never actually mounted.
-const NoopAnnotationManagerFactory = () => () => null;
-NoopAnnotationManagerFactory.deps = [];
-const SafeAnnotationManagerFactory = AnnotationManagerFactory || NoopAnnotationManagerFactory;
+// remaining injectable. `CustomMapControlFactory` already renders the managers
+// conditionally, so the stubs are never actually mounted.
+const noopManagerFactory = () => () => null;
+noopManagerFactory.deps = [];
+const SafeAnnotationManagerFactory = AnnotationManagerFactory || noopManagerFactory;
+const SafeChartManagerFactory = ChartManagerFactory || noopManagerFactory;
CustomMapControlFactory.deps = [
EffectControlFactory,
EffectManagerFactory,
SafeAnnotationManagerFactory,
+ SafeChartManagerFactory,
+ ChartControlFactory,
AiAssistantControlFactory,
...MapControlFactory.deps
];
@@ -79,20 +92,29 @@ function CustomMapControlFactory(
EffectControl,
EffectManager,
AnnotationManager,
+ ChartManager,
+ ChartControl,
AiAssistantControl,
...deps
) {
const MapControl = MapControlFactory(...deps);
- const actionComponents = [
- ...(MapControl.defaultActionComponents ?? []),
- EffectControl,
- AiAssistantControl
- ];
const CustomMapControl = props => {
+ const isExport = Boolean(props.isExport);
+ const chartsEnabled = Boolean(getApplicationConfig().enableChartsPanel);
+ const actionComponents = [
+ ...(MapControl.defaultActionComponents ?? []),
+ ...(chartsEnabled ? [ChartControl] : []),
+ EffectControl,
+ AiAssistantControl
+ ];
const showEffects = Boolean(props.mapControls?.effect?.active);
const showAnnotations = Boolean(props.mapControls?.annotation?.active);
- const rightPanelVisible = showEffects || showAnnotations;
+ const showChartsPanel = chartsEnabled && Boolean(props.mapControls?.chart?.active);
+ const hasPinnedCharts =
+ !isExport && chartsEnabled && (props.charts || []).some(chart => chart.pinned !== false);
+ const showCharts = showChartsPanel || hasPinnedCharts;
+ const rightPanelVisible = showEffects || showAnnotations || showCharts;
return (
<StyledMapControlOverlay top={props.top} rightPanelVisible={rightPanelVisible}>
<StyledMapControlPanel>
@@ -100,8 +122,9 @@ function CustomMapControlFactory(
<MapControl {...props} top={0} actionComponents={actionComponents} />
</StyledMapControlPanel>
<StyledMapControlContextPanel>
- {showEffects ? <EffectManager /> : null}
{showAnnotations ? <AnnotationManager /> : null}
+ {showCharts ? <ChartManager panelActive={showChartsPanel} isExport={isExport} /> : null}
+ {showEffects ? <EffectManager /> : null}
</StyledMapControlContextPanel>
</StyledMapControlOverlay>
);
diff --git a/examples/demo-app/esbuild.config.mjs b/examples/demo-app/esbuild.config.mjs
index 7b7ef59b9..339125e9e 100644
--- a/examples/demo-app/esbuild.config.mjs
+++ b/examples/demo-app/esbuild.config.mjs
@@ -45,6 +45,7 @@ const KEPLER_SRC_ALIASES = Object.fromEntries(
'actions',
'cloud-providers',
'common-utils',
+ 'charts',
'components',
'constants',
'duckdb',
@@ -63,7 +64,11 @@ const getKeplerAliases = () => ({
...KEPLER_SRC_ALIASES,
// duckdb ships a components subpath (SqlPanel); esbuild picks the longest
// matching alias key, so this wins for `@kepler.gl/duckdb/components`.
- '@kepler.gl/duckdb/components': join(SRC_DIR, 'duckdb', 'src', 'components', 'index.tsx')
+ '@kepler.gl/duckdb/components': join(SRC_DIR, 'duckdb', 'src', 'components', 'index.tsx'),
+ // Chart factories live on a package subpath so the main components barrel
+ // does not load `@kepler.gl/charts`. The `@kepler.gl/components` alias is a
+ // file (index.ts), so this longer key is required.
+ '@kepler.gl/components/charts': join(SRC_DIR, 'components', 'src', 'charts.ts')
});
/**
diff --git a/examples/demo-app/src/factories/map-control.js b/examples/demo-app/src/factories/map-control.js
index 1024b3263..112edd34b 100644
--- a/examples/demo-app/src/factories/map-control.js
+++ b/examples/demo-app/src/factories/map-control.js
@@ -8,11 +8,21 @@ import {
withState,
MapControlFactory,
EffectControlFactory,
- EffectManagerFactory
+ EffectManagerFactory,
+ ChartControlFactory
} from '@kepler.gl/components';
-// AnnotationManagerFactory is available in the workspace source (src/components) but not yet
-// published in the @kepler.gl/components version this example currently depends on.
-const AnnotationManagerFactory = require('@kepler.gl/components').AnnotationManagerFactory;
+import {getApplicationConfig} from '@kepler.gl/utils';
+// AnnotationManagerFactory is available in the workspace source (src/components)
+// but may not yet be published in the @kepler.gl/components version this example
+// currently depends on. ChartManagerFactory lives on `@kepler.gl/components/charts`
+// so the main components barrel does not load `@kepler.gl/charts`.
+const {AnnotationManagerFactory} = require('@kepler.gl/components');
+let ChartManagerFactory;
+try {
+ ChartManagerFactory = require('@kepler.gl/components/charts').ChartManagerFactory;
+} catch {
+ ChartManagerFactory = undefined;
+}
import {AiAssistantControlFactory} from '@openassistant/kepler-assistant';
import {BannerMapPanel, SampleMapPanel} from '../components/map-control/map-control';
@@ -58,21 +68,24 @@ const StyledMapControlOverlay = styled.div`
}
`;
-// `AnnotationManagerFactory` may be missing when this example is built against a published
-// `@kepler.gl/components` that predates it (see the require shim above). The component
+// These manager factories may be missing when this example is built against a published
+// `@kepler.gl/components` that predates them (see the require shim above). The component
// injector calls `.deps` on every entry of this array and on their transitive deps, so an
// `undefined` here crashes injection at startup. Substitute a harmless no-op factory so the
// deps array stays positionally aligned with `CustomMapControlFactory`'s parameters while
-// remaining injectable. `CustomMapControlFactory` already renders the annotation manager
-// conditionally, so the stub is never actually mounted.
-const NoopAnnotationManagerFactory = () => () => null;
-NoopAnnotationManagerFactory.deps = [];
-const SafeAnnotationManagerFactory = AnnotationManagerFactory || NoopAnnotationManagerFactory;
+// remaining injectable. `CustomMapControlFactory` already renders the managers
+// conditionally, so the stubs are never actually mounted.
+const noopManagerFactory = () => () => null;
+noopManagerFactory.deps = [];
+const SafeAnnotationManagerFactory = AnnotationManagerFactory || noopManagerFactory;
+const SafeChartManagerFactory = ChartManagerFactory || noopManagerFactory;
CustomMapControlFactory.deps = [
EffectControlFactory,
EffectManagerFactory,
SafeAnnotationManagerFactory,
+ SafeChartManagerFactory,
+ ChartControlFactory,
SqlPanelControlFactory,
AiAssistantControlFactory,
...MapControlFactory.deps
@@ -81,22 +94,31 @@ function CustomMapControlFactory(
EffectControl,
EffectManager,
AnnotationManager,
+ ChartManager,
+ ChartControl,
SqlPanelControl,
AiAssistantControl,
...deps
) {
const MapControl = MapControlFactory(...deps);
- const actionComponents = [
- ...(MapControl.defaultActionComponents ?? []),
- EffectControl,
- SqlPanelControl,
- AiAssistantControl
- ];
const CustomMapControl = props => {
+ const isExport = Boolean(props.isExport);
+ const chartsEnabled = Boolean(getApplicationConfig().enableChartsPanel);
+ const actionComponents = [
+ ...(MapControl.defaultActionComponents ?? []),
+ ...(chartsEnabled ? [ChartControl] : []),
+ EffectControl,
+ SqlPanelControl,
+ AiAssistantControl
+ ];
const showEffects = Boolean(props.mapControls?.effect?.active);
const showAnnotations = Boolean(props.mapControls?.annotation?.active);
- const rightPanelVisible = showEffects || showAnnotations;
+ const showChartsPanel = chartsEnabled && Boolean(props.mapControls?.chart?.active);
+ const hasPinnedCharts =
+ !isExport && chartsEnabled && (props.charts || []).some(chart => chart.pinned !== false);
+ const showCharts = showChartsPanel || hasPinnedCharts;
+ const rightPanelVisible = showEffects || showAnnotations || showCharts;
return (
<StyledMapControlOverlay top={props.top} rightPanelVisible={rightPanelVisible}>
<StyledMapControlPanel>
@@ -105,8 +127,9 @@ function CustomMapControlFactory(
<MapControl {...props} top={0} actionComponents={actionComponents} />
</StyledMapControlPanel>
<StyledMapControlContextPanel>
- {showEffects ? <EffectManager /> : null}
{showAnnotations ? <AnnotationManager /> : null}
+ {showCharts ? <ChartManager panelActive={showChartsPanel} isExport={isExport} /> : null}
+ {showEffects ? <EffectManager /> : null}
</StyledMapControlContextPanel>
</StyledMapControlOverlay>
);
diff --git a/examples/duckdb-vite/vite.config.ts b/examples/duckdb-vite/vite.config.ts
index ac0853118..5b769b6c9 100644
--- a/examples/duckdb-vite/vite.config.ts
+++ b/examples/duckdb-vite/vite.config.ts
@@ -40,6 +40,7 @@ const keplerPackages = [
'@kepler.gl/deckgl-layers',
'@kepler.gl/duckdb',
'@kepler.gl/effects',
+ '@kepler.gl/charts',
'@kepler.gl/layers',
'@kepler.gl/localization',
'@kepler.gl/processors',
diff --git a/examples/get-started-vite/src/main.tsx b/examples/get-started-vite/src/main.tsx
index d00cd5a58..b22896917 100644
--- a/examples/get-started-vite/src/main.tsx
+++ b/examples/get-started-vite/src/main.tsx
@@ -11,7 +11,8 @@ import keplerGlReducer, {enhanceReduxMiddleware} from '@kepler.gl/reducers';
import {initApplicationConfig} from '@kepler.gl/utils';
// Annotations require a custom MapControl that mounts AnnotationManager.
-// Disable them here so the default get-started example stays minimal.
+// Charts are enabled by default but still need ChartControl + ChartManager injected
+// (see demo-app) so stock MapControl never shows a dead charts button.
initApplicationConfig({
enableAnnotations: false
});
diff --git a/examples/get-started-vite/vite.config.ts b/examples/get-started-vite/vite.config.ts
index c716b74e7..4ea89c173 100644
--- a/examples/get-started-vite/vite.config.ts
+++ b/examples/get-started-vite/vite.config.ts
@@ -46,6 +46,7 @@ const keplerPackages = [
'@kepler.gl/deckgl-arrow-layers',
'@kepler.gl/deckgl-layers',
'@kepler.gl/effects',
+ '@kepler.gl/charts',
'@kepler.gl/layers',
'@kepler.gl/localization',
'@kepler.gl/processors',
diff --git a/examples/get-started/src/app.tsx b/examples/get-started/src/app.tsx
index 431bf6b00..d15e95ffb 100644
--- a/examples/get-started/src/app.tsx
+++ b/examples/get-started/src/app.tsx
@@ -12,7 +12,8 @@ import KeplerGl from '@kepler.gl/components';
import {initApplicationConfig} from '@kepler.gl/utils';
// Annotations require a custom MapControl that mounts AnnotationManager.
-// Disable them here so the default get-started example stays minimal.
+// Charts are enabled by default but still need ChartControl + ChartManager injected
+// (see demo-app) so stock MapControl never shows a dead charts button.
initApplicationConfig({
enableAnnotations: false
});
diff --git a/package.json b/package.json
index 216ac5776..c440a210a 100644
--- a/package.json
+++ b/package.json
@@ -33,6 +33,7 @@
"./src/tasks",
"./src/actions",
"./src/effects",
+ "./src/charts",
"./src/reducers",
"./src/components",
"./src/duckdb",
diff --git a/src/actions/src/action-types.ts b/src/actions/src/action-types.ts
index e539cb671..91f50f093 100644
--- a/src/actions/src/action-types.ts
+++ b/src/actions/src/action-types.ts
@@ -127,6 +127,11 @@ export const ActionTypes = {
REMOVE_EFFECT: `${ACTION_PREFIX}REMOVE_EFFECT`,
UPDATE_EFFECT: `${ACTION_PREFIX}UPDATE_EFFECT`,
+ // charts
+ ADD_CHART: `${ACTION_PREFIX}ADD_CHART`,
+ UPDATE_CHART: `${ACTION_PREFIX}UPDATE_CHART`,
+ REMOVE_CHART: `${ACTION_PREFIX}REMOVE_CHART`,
+
// annotations
ADD_ANNOTATION: `${ACTION_PREFIX}ADD_ANNOTATION`,
REMOVE_ANNOTATION: `${ACTION_PREFIX}REMOVE_ANNOTATION`,
diff --git a/src/actions/src/ui-state-actions.ts b/src/actions/src/ui-state-actions.ts
index 5eebf6352..db44ec6f7 100644
--- a/src/actions/src/ui-state-actions.ts
+++ b/src/actions/src/ui-state-actions.ts
@@ -240,7 +240,7 @@ export type SetExportImageSettingUpdaterAction = {
payload: Partial<ExportImage>;
};
/**
- * Set `exportImage` settings: ratio, resolution, legend
+ * Set `exportImage` settings: ratio, resolution, legend, charts
* @memberof uiStateActions
* @param newSetting - {ratio: '1x'}
* @public
diff --git a/src/actions/src/vis-state-actions.ts b/src/actions/src/vis-state-actions.ts
index 95f8ab22b..e06ea6a34 100644
--- a/src/actions/src/vis-state-actions.ts
+++ b/src/actions/src/vis-state-actions.ts
@@ -29,7 +29,8 @@ import {
FilterAnimationConfig,
LayerOrder,
LayerOrderGroup,
- ProtoDataset
+ ProtoDataset,
+ ChartConfig
} from '@kepler.gl/types';
import {createAction} from '@reduxjs/toolkit';
@@ -775,6 +776,72 @@ export function updateEffect(
};
}
+// Chart Actions
+
+export type AddChartUpdaterAction = {
+ chart: ChartConfig;
+};
+
+/**
+ * Add a chart to the charts panel
+ * @memberof visStateActions
+ * @param chart - chart config
+ * @returns action
+ * @public
+ */
+export function addChart(
+ chart: ChartConfig
+): Merge<AddChartUpdaterAction, {type: typeof ActionTypes.ADD_CHART}> {
+ return {
+ type: ActionTypes.ADD_CHART,
+ chart
+ };
+}
+
+export type UpdateChartUpdaterAction = {
+ id: string;
+ props: Partial<ChartConfig>;
+};
+
+/**
+ * Update a chart
+ * @memberof visStateActions
+ * @param id - chart id
+ * @param props - partial chart config
+ * @returns action
+ * @public
+ */
+export function updateChart(
+ id: string,
+ props: Partial<ChartConfig>
+): Merge<UpdateChartUpdaterAction, {type: typeof ActionTypes.UPDATE_CHART}> {
+ return {
+ type: ActionTypes.UPDATE_CHART,
+ id,
+ props
+ };
+}
+
+export type RemoveChartUpdaterAction = {
+ id: string;
+};
+
+/**
+ * Remove a chart
+ * @memberof visStateActions
+ * @param id - chart id
+ * @returns action
+ * @public
+ */
+export function removeChart(
+ id: string
+): Merge<RemoveChartUpdaterAction, {type: typeof ActionTypes.REMOVE_CHART}> {
+ return {
+ type: ActionTypes.REMOVE_CHART,
+ id
+ };
+}
+
// Annotation Actions
export type AddAnnotationUpdaterAction = {
diff --git a/src/charts/babel.config.js b/src/charts/babel.config.js
new file mode 100644
index 000000000..da66d37be
--- /dev/null
+++ b/src/charts/babel.config.js
@@ -0,0 +1,51 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+const KeplerPackage = require('./package');
+
+const SHARED_PLUGINS = [
+ ['@babel/plugin-transform-typescript', {isTSX: true, allowDeclareFields: true}],
+ '@babel/plugin-transform-class-properties',
+ '@babel/plugin-transform-optional-chaining',
+ '@babel/plugin-transform-logical-assignment-operators',
+ '@babel/plugin-transform-nullish-coalescing-operator',
+ '@babel/plugin-transform-export-namespace-from',
+ [
+ 'search-and-replace',
+ {
+ rules: [
+ {
+ search: '__PACKAGE_VERSION__',
+ replace: KeplerPackage.version
+ }
+ ]
+ }
+ ]
+];
+
+module.exports = function babel(api) {
+ api.cache.using(() => process.env.BABEL_ENV || process.env.NODE_ENV || 'development');
+
+ const isEsm = api.env('esm');
+ const isTest = api.env('test');
+ const isDebug = api.env('debug');
+
+ const presets = [
+ ['@babel/preset-env', isEsm ? {modules: false} : {}],
+ '@babel/preset-react',
+ '@babel/preset-typescript'
+ ];
+
+ const plugins = [
+ ...SHARED_PLUGINS,
+ ...(isEsm ? [] : ['@babel/plugin-transform-modules-commonjs']),
+ ['@babel/transform-runtime', {regenerator: true, ...(isEsm ? {useESModules: true} : {})}],
+ ...(isTest ? ['istanbul'] : [])
+ ];
+
+ return {
+ presets,
+ plugins,
+ ...(isDebug ? {sourceMaps: 'inline', retainLines: true} : {})
+ };
+};
diff --git a/src/charts/package.json b/src/charts/package.json
new file mode 100644
index 000000000..d10a6d5ff
--- /dev/null
+++ b/src/charts/package.json
@@ -0,0 +1,69 @@
+{
+ "name": "@kepler.gl/charts",
+ "author": "Shan He <[email protected]>",
+ "version": "3.3.0-alpha.13",
+ "description": "kepler.gl chart panel types, builders and renderers",
+ "license": "MIT",
+ "main": "dist/cjs/index.js",
+ "types": "dist/index.d.ts",
+ "keywords": [
+ "babel",
+ "es6",
+ "react",
+ "visualization",
+ "charts"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/keplergl/kepler.gl.git"
+ },
+ "scripts": {
+ "build": "rm -fr dist && babel src --out-dir dist/cjs --source-maps inline --extensions '.ts,.tsx,.js,.jsx' --ignore '**/*.d.ts' && BABEL_ENV=esm babel src --out-dir dist/esm --source-maps inline --extensions '.ts,.tsx,.js,.jsx' --ignore '**/*.d.ts'",
+ "build:types": "tsc --project ./tsconfig.production.json",
+ "prepublishOnly": "babel-node ../../scripts/license-header/bin --license ../../FILE-HEADER && yarn build && yarn build:types",
+ "stab": "mkdir -p dist/cjs dist/esm && touch dist/cjs/index.js dist/esm/index.js"
+ },
+ "files": [
+ "dist"
+ ],
+ "dependencies": {
+ "@kepler.gl/types": "3.3.0-alpha.13",
+ "@types/d3-array": "^2.8.0",
+ "@types/d3-time": "^2",
+ "@types/react": "^19.0.0",
+ "@types/styled-components": "^5.1.32",
+ "d3-array": "^2.8.0",
+ "d3-time": "^2.1.1",
+ "styled-components": "6.4.3"
+ },
+ "peerDependencies": {
+ "react": ">=18"
+ },
+ "nyc": {
+ "sourceMap": false,
+ "instrument": false
+ },
+ "maintainers": [
+ "Shan He <[email protected]>",
+ "Giuseppe Macri <[email protected]>",
+ "Igor Dykhta <[email protected]>",
+ "Xun Li <[email protected]>"
+ ],
+ "engines": {
+ "node": ">=20"
+ },
+ "volta": {
+ "node": "20.19.3",
+ "yarn": "4.4.0"
+ },
+ "packageManager": "[email protected]",
+ "module": "dist/esm/index.js",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "import": "./dist/esm/index.js",
+ "require": "./dist/cjs/index.js",
+ "default": "./dist/cjs/index.js"
+ }
+ }
+}
diff --git a/src/charts/src/aggregation.ts b/src/charts/src/aggregation.ts
new file mode 100644
index 000000000..82ddfb50a
--- /dev/null
+++ b/src/charts/src/aggregation.ts
@@ -0,0 +1,941 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {
+ deviation,
+ histogram,
+ max as d3Max,
+ mean,
+ median,
+ min as d3Min,
+ quantile,
+ sum,
+ variance as d3Variance
+} from 'd3-array';
+import {utcDay, utcHour, utcMonth, utcWeek, utcYear} from 'd3-time';
+
+import {
+ CHART_COLORS,
+ DEFAULT_NUM_GROUPS,
+ MAX_CHART_POINTS,
+ OTHERS_KEY,
+ TIME_FIELD_TYPES
+} from './constants';
+import {BinType, SortType} from './constants';
+import {
+ ChartableDataset,
+ ChartAggregation,
+ ChartBin,
+ ChartAxis,
+ HeatmapCell,
+ PivotTableResult
+} from './types';
+
+const PERCENTILE_AGGREGATIONS: Partial<Record<ChartAggregation, number>> = {
+ p05: 0.05,
+ p25: 0.25,
+ p50: 0.5,
+ p75: 0.75,
+ p95: 0.95
+};
+
+/**
+ * Format chart values for display. Prefer compact SI suffixes for large
+ * magnitudes so Big Number (and other chart labels) never fall back to
+ * scientific notation like `7.67e+5`.
+ */
+export function formatNumber(n: number): string {
+ if (!Number.isFinite(n)) {
+ return '0';
+ }
+
+ const abs = Math.abs(n);
+ const sign = n < 0 ? '-' : '';
+
+ const compact = (value: number, suffix: string, digits: number): string => {
+ const scaled =
+ value / (suffix === 'k' ? 1e3 : suffix === 'M' ? 1e6 : suffix === 'G' ? 1e9 : 1e12);
+ const rounded = Number(scaled.toFixed(digits));
+ return `${sign}${rounded}${suffix}`;
+ };
+
+ if (abs >= 1e12) {
+ return compact(abs, 'T', 2);
+ }
+ if (abs >= 1e9) {
+ return compact(abs, 'G', 2);
+ }
+ if (abs >= 1e6) {
+ return compact(abs, 'M', 2);
+ }
+ if (abs >= 10000) {
+ return compact(abs, 'k', 1);
+ }
+ if (abs >= 1000) {
+ return `${sign}${Math.round(abs).toLocaleString('en-US')}`;
+ }
+ if (Number.isInteger(n)) {
+ return String(n);
+ }
+ return Number(n.toPrecision(4)).toString();
+}
+
+function modeValue(values: number[]): number {
+ const counts = new Map<number, number>();
+ let best = values[0];
+ let bestCount = 0;
+ for (const value of values) {
+ const next = (counts.get(value) || 0) + 1;
+ counts.set(value, next);
+ if (next > bestCount) {
+ best = value;
+ bestCount = next;
+ }
+ }
+ return best;
+}
+
+function aggregateValues(values: number[], technique: ChartAggregation | null | undefined): number {
+ if (!values.length) {
+ return 0;
+ }
+ switch (technique) {
+ case 'sum':
+ return sum(values) ?? 0;
+ case 'average':
+ return mean(values) ?? 0;
+ case 'maximum':
+ return d3Max(values) ?? 0;
+ case 'minimum':
+ return d3Min(values) ?? 0;
+ case 'median':
+ return median(values) ?? 0;
+ case 'stdev':
+ return deviation(values) ?? 0;
+ case 'variance':
+ return d3Variance(values) ?? 0;
+ case 'p05':
+ case 'p25':
+ case 'p50':
+ case 'p75':
+ case 'p95':
+ return quantile(values, PERCENTILE_AGGREGATIONS[technique] as number) ?? 0;
+ case 'mode':
+ return modeValue(values);
+ case 'countUnique':
+ return new Set(values).size;
+ case 'count':
+ default:
+ return values.length;
+ }
+}
+
+export function getChartIndexes(dataset: ChartableDataset, applyFilters: boolean): number[] {
+ return applyFilters ? dataset.filteredIndex : dataset.allIndexes;
+}
+
+export function colorAt(index: number): string {
+ return CHART_COLORS[index % CHART_COLORS.length];
+}
+
+export function rgbToCss(rgb?: [number, number, number]): string {
+ if (!rgb) {
+ return CHART_COLORS[0];
+ }
+ return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
+}
+
+function toNumber(value: unknown): number | null {
+ if (value === null || value === undefined || value === '') {
+ return null;
+ }
+ const n = typeof value === 'number' ? value : Number(value);
+ return Number.isFinite(n) ? n : null;
+}
+
+function toKey(value: unknown): string {
+ if (value === null || value === undefined) {
+ return '';
+ }
+ if (value instanceof Date) {
+ return value.toISOString();
+ }
+ return String(value);
+}
+
+function aggregateIndexes(
+ indexes: number[],
+ dataset: ChartableDataset,
+ valueField: string | undefined,
+ aggregation: ChartAggregation | null | undefined
+): number {
+ if (!indexes.length) {
+ return 0;
+ }
+ const technique = aggregation || 'count';
+ if (technique === 'count' || !valueField) {
+ return indexes.length;
+ }
+ // Count unique / mode should consider raw field values (incl. categorical),
+ // not only values that coerce to numbers.
+ if (technique === 'countUnique') {
+ const keys = new Set<string>();
+ for (const idx of indexes) {
+ const key = toKey(dataset.getValue(valueField, idx));
+ if (key) {
+ keys.add(key);
+ }
+ }
+ return keys.size;
+ }
+ const values = indexes
+ .map(idx => toNumber(dataset.getValue(valueField, idx)))
+ .filter((v): v is number => v !== null);
+ if (!values.length) {
+ return 0;
+ }
+ return aggregateValues(values, technique);
+}
+
+function sortBins(bins: ChartBin[], sort?: SortType): ChartBin[] {
+ const next = [...bins];
+ switch (sort) {
+ case SortType.ascending:
+ next.sort((a, b) => a.value - b.value);
+ break;
+ case SortType.descending:
+ next.sort((a, b) => b.value - a.value);
+ break;
+ case SortType.alphaAsc:
+ next.sort((a, b) => String(a.key).localeCompare(String(b.key)));
+ break;
+ case SortType.alphaDesc:
+ next.sort((a, b) => String(b.key).localeCompare(String(a.key)));
+ break;
+ default:
+ break;
+ }
+ return next;
+}
+
+function truncateBins(bins: ChartBin[], numGroups: number, groupOthers: boolean): ChartBin[] {
+ if (numGroups <= 0 || bins.length <= numGroups) {
+ return bins;
+ }
+ const head = bins.slice(0, numGroups);
+ if (!groupOthers) {
+ return head;
+ }
+ const rest = bins.slice(numGroups);
+ const other: ChartBin = {
+ key: OTHERS_KEY,
+ value: rest.reduce((sum, bin) => sum + bin.value, 0),
+ count: rest.reduce((sum, bin) => sum + bin.count, 0),
+ color: colorAt(numGroups)
+ };
+ return [...head, other];
+}
+
+function uniqueGroupMap(
+ indexes: number[],
+ dataset: ChartableDataset,
+ fieldName: string
+): Map<string, number[]> {
+ const groups = new Map<string, number[]>();
+ for (const idx of indexes) {
+ const key = toKey(dataset.getValue(fieldName, idx));
+ if (!key) {
+ continue;
+ }
+ const list = groups.get(key);
+ if (list) {
+ list.push(idx);
+ } else {
+ groups.set(key, [idx]);
+ }
+ }
+ return groups;
+}
+
+/**
+ * Build interior thresholds for exactly `numBins` equal-width bins over [min, max].
+ * d3.bin treats a numeric thresholds() argument as a *hint* (nice ticks), which can
+ * yield fewer/more bins than requested — pass an explicit array instead.
+ */
+function exactBinThresholds(min: number, max: number, numBins: number): number[] {
+ const n = Math.max(2, numBins);
+ if (!(Number.isFinite(min) && Number.isFinite(max)) || !(max > min)) {
+ return [];
+ }
+ const step = (max - min) / n;
+ const thresholds: number[] = [];
+ for (let i = 1; i < n; i++) {
+ thresholds.push(min + step * i);
+ }
+ return thresholds;
+}
+
+/** Separates lossless numeric-bin identity (`x0`, `x1`) from compact display labels. */
+const NUMERIC_BIN_KEY_SEP = '\u001f';
+
+function numericBinKey(x0: number, x1: number): string {
+ return `${x0}${NUMERIC_BIN_KEY_SEP}${x1}`;
+}
+
+/** Display label for a bin key; numeric histogram keys decode to compact ranges. */
+export function displayBinKey(key: string): string {
+ const text = String(key);
+ const sep = text.indexOf(NUMERIC_BIN_KEY_SEP);
+ if (sep < 0) {
+ return text;
+ }
+ const x0 = Number(text.slice(0, sep));
+ const x1 = Number(text.slice(sep + 1));
+ if (Number.isFinite(x0) && Number.isFinite(x1)) {
+ return `${formatNumber(x0)} – ${formatNumber(x1)}`;
+ }
+ return text;
+}
+
+function numericGroupMap(
+ indexes: number[],
+ dataset: ChartableDataset,
+ fieldName: string,
+ numBins: number
+): {groups: Map<string, number[]>; filterValues: Map<string, Array<string | number | boolean>>} {
+ const values = indexes
+ .map(idx => ({idx, value: toNumber(dataset.getValue(fieldName, idx))}))
+ .filter((d): d is {idx: number; value: number} => d.value !== null);
+ if (!values.length) {
+ return {groups: new Map(), filterValues: new Map()};
+ }
+ const min = d3Min(values, d => d.value);
+ const max = d3Max(values, d => d.value);
+ if (min === undefined || max === undefined) {
+ return {groups: new Map(), filterValues: new Map()};
+ }
+ const binCount = Math.max(2, numBins > 0 ? numBins : DEFAULT_NUM_GROUPS);
+ const hist = histogram<{idx: number; value: number}, number>()
+ .value(d => d.value)
+ .domain([min, max])
+ .thresholds(exactBinThresholds(min, max, binCount));
+ const bins = hist(values);
+ const groups = new Map<string, number[]>();
+ const filterValues = new Map<string, Array<string | number | boolean>>();
+ bins.forEach(bin => {
+ const x0 = bin.x0 ?? 0;
+ const x1 = bin.x1 ?? x0;
+ const key = numericBinKey(x0, x1);
+ groups.set(
+ key,
+ bin.map(d => d.idx)
+ );
+ filterValues.set(key, [x0, x1]);
+ });
+ return {groups, filterValues};
+}
+
+function getTimeFloor(interval?: string) {
+ switch (interval) {
+ case 'year':
+ return utcYear.floor;
+ case 'month':
+ return utcMonth.floor;
+ case 'week':
+ return utcWeek.floor;
+ case 'hour':
+ return utcHour.floor;
+ case 'day':
+ default:
+ return utcDay.floor;
+ }
+}
+
+function getTimeOffset(interval: string | undefined, startDate: Date): Date {
+ switch (interval) {
+ case 'year':
+ return utcYear.offset(startDate, 1);
+ case 'month':
+ return utcMonth.offset(startDate, 1);
+ case 'week':
+ return utcWeek.offset(startDate, 1);
+ case 'hour':
+ return utcHour.offset(startDate, 1);
+ case 'day':
+ default:
+ return utcDay.offset(startDate, 1);
+ }
+}
+
+const DAY_MS = 24 * 60 * 60 * 1000;
+const HOUR_MS = 60 * 60 * 1000;
+const WEEK_MS = 7 * DAY_MS;
+const MONTH_MS = 30 * DAY_MS;
+const YEAR_MS = 365 * DAY_MS;
+/** Soft target for auto period selection; hard cap is MAX_CHART_POINTS. */
+const TARGET_TIME_BUCKETS = 200;
+
+function pad2(n: number): string {
+ return String(n).padStart(2, '0');
+}
+
+function formatUtcDate(ms: number): string {
+ const date = new Date(ms);
+ return `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}-${pad2(date.getUTCDate())}`;
+}
+
+function formatUtcDateTime(ms: number): string {
+ const date = new Date(ms);
+ return `${formatUtcDate(ms)} ${pad2(date.getUTCHours())}:${pad2(date.getUTCMinutes())}`;
+}
+
+/** Label a time bin; omit clock time when the bin spans a day or more. */
+function formatTimeBinRange(x0: number, x1: number): string {
+ const span = Math.max(0, x1 - x0);
+ const crossesDay = formatUtcDate(x0) !== formatUtcDate(x1);
+ if (span >= DAY_MS || crossesDay) {
+ return `${formatUtcDate(x0)} – ${formatUtcDate(x1)}`;
+ }
+ return `${formatUtcDateTime(x0)} – ${formatUtcDateTime(x1)}`;
+}
+
+function formatTimePeriodLabel(ms: number, interval?: string): string {
+ const date = new Date(ms);
+ if (Number.isNaN(date.getTime())) {
+ return String(ms);
+ }
+ switch (interval) {
+ case 'year':
+ return String(date.getUTCFullYear());
+ case 'month':
+ return `${date.getUTCFullYear()}-${pad2(date.getUTCMonth() + 1)}`;
+ case 'week':
+ return `Week of ${formatUtcDate(ms)}`;
+ case 'day':
+ return formatUtcDate(ms);
+ case 'hour':
+ default:
+ return formatUtcDateTime(ms);
+ }
+}
+
+/**
+ * Pick a time period so the [min, max] span yields about `targetBuckets` buckets.
+ */
+function chooseTimeInterval(spanMs: number, targetBuckets = TARGET_TIME_BUCKETS): string {
+ if (!(spanMs > 0)) {
+ return 'day';
+ }
+ const candidates: Array<[string, number]> = [
+ ['hour', HOUR_MS],
+ ['day', DAY_MS],
+ ['week', WEEK_MS],
+ ['month', MONTH_MS],
+ ['year', YEAR_MS]
+ ];
+ for (const [name, size] of candidates) {
+ if (spanMs / size <= targetBuckets) {
+ return name;
+ }
+ }
+ return 'year';
+}
+
+function equalWidthTimeBins(
+ points: Array<{idx: number; t: number}>,
+ min: number,
+ max: number,
+ binCount: number
+): {groups: Map<string, number[]>; filterValues: Map<string, Array<string | number | boolean>>} {
+ const hist = histogram<{idx: number; t: number}, number>()
+ .value(d => d.t)
+ .domain([min, max])
+ .thresholds(exactBinThresholds(min, max, binCount));
+ const bins = hist(points);
+ const groups = new Map<string, number[]>();
+ const filterValues = new Map<string, Array<string | number | boolean>>();
+ bins.forEach(bin => {
+ const x0 = bin.x0 ?? min;
+ const x1 = bin.x1 ?? max;
+ const key = formatTimeBinRange(x0, x1);
+ groups.set(
+ key,
+ bin.map(d => d.idx)
+ );
+ filterValues.set(key, [x0, x1]);
+ });
+ return {groups, filterValues};
+}
+
+function timeGroupMap(
+ indexes: number[],
+ dataset: ChartableDataset,
+ fieldName: string,
+ interval?: string,
+ numBins = 0
+): {groups: Map<string, number[]>; filterValues: Map<string, Array<string | number | boolean>>} {
+ const points = indexes
+ .map(idx => {
+ const raw = dataset.getValue(fieldName, idx);
+ const date = raw instanceof Date ? raw : new Date(raw);
+ const t = date.getTime();
+ return Number.isNaN(t) ? null : {idx, t};
+ })
+ .filter((d): d is {idx: number; t: number} => d !== null);
+
+ if (!points.length) {
+ return {groups: new Map(), filterValues: new Map()};
+ }
+
+ const min = d3Min(points, d => d.t);
+ const max = d3Max(points, d => d.t);
+ if (min === undefined || max === undefined) {
+ return {groups: new Map(), filterValues: new Map()};
+ }
+
+ // Bar charts: split the full [min, max] domain into exactly numBins equal ranges.
+ if (numBins > 0) {
+ return equalWidthTimeBins(points, min, max, Math.max(2, numBins));
+ }
+
+ // Line / full series: period-group by interval (auto-chosen from span when unset).
+ // When Auto, coarsen hour → day → week → month → year until under the point cap.
+ const INTERVAL_ORDER = ['hour', 'day', 'week', 'month', 'year'];
+ const autoInterval = !interval;
+ let resolvedInterval = interval || chooseTimeInterval(max - min, TARGET_TIME_BUCKETS);
+ let groups = new Map<string, number[]>();
+ let keyStarts = new Map<string, number>();
+
+ const buildPeriodGroups = (period: string) => {
+ const floor = getTimeFloor(period);
+ const nextGroups = new Map<string, number[]>();
+ const nextStarts = new Map<string, number>();
+ for (const point of points) {
+ const start = floor(new Date(point.t)).getTime();
+ const key = formatTimePeriodLabel(start, period);
+ const list = nextGroups.get(key);
+ if (list) {
+ list.push(point.idx);
+ } else {
+ nextGroups.set(key, [point.idx]);
+ nextStarts.set(key, start);
+ }
+ }
+ return {nextGroups, nextStarts};
+ };
+
+ for (;;) {
+ const built = buildPeriodGroups(resolvedInterval);
+ groups = built.nextGroups;
+ keyStarts = built.nextStarts;
+ if (groups.size <= MAX_CHART_POINTS) {
+ break;
+ }
+ // Too dense for this period: coarsen when Auto, otherwise equal-width cap.
+ if (!autoInterval) {
+ return equalWidthTimeBins(points, min, max, MAX_CHART_POINTS);
+ }
+ const idx = INTERVAL_ORDER.indexOf(resolvedInterval);
+ if (idx < 0 || idx >= INTERVAL_ORDER.length - 1) {
+ return equalWidthTimeBins(points, min, max, MAX_CHART_POINTS);
+ }
+ resolvedInterval = INTERVAL_ORDER[idx + 1];
+ }
+
+ const filterValues = new Map<string, Array<string | number | boolean>>();
+ const ordered = new Map<string, number[]>();
+ Array.from(groups.keys())
+ .sort(
+ (a, b) =>
+ (keyStarts.get(a) || 0) - (keyStarts.get(b) || 0) || String(a).localeCompare(String(b))
+ )
+ .forEach(key => {
+ const floored = keyStarts.get(key) || 0;
+ ordered.set(key, groups.get(key) || []);
+ filterValues.set(key, [
+ floored,
+ getTimeOffset(resolvedInterval, new Date(floored)).getTime()
+ ]);
+ });
+ return {groups: ordered, filterValues};
+}
+
+function uniqueGroupFilterValues(
+ groups: Map<string, number[]>,
+ fieldType?: string
+): Map<string, Array<string | number | boolean>> {
+ const filterValues = new Map<string, Array<string | number | boolean>>();
+ const numeric = fieldType === 'real' || fieldType === 'integer';
+ groups.forEach((_, key) => {
+ if (numeric) {
+ const n = Number(key);
+ filterValues.set(key, Number.isFinite(n) ? [n, n] : [key]);
+ } else if (fieldType === 'boolean') {
+ // Kepler boolean filters are select filters with a scalar boolean value.
+ filterValues.set(key, [key === 'true']);
+ } else {
+ filterValues.set(key, [key]);
+ }
+ });
+ return filterValues;
+}
+
+function datasetHasField(dataset: ChartableDataset, fieldName?: string | null): boolean {
+ return Boolean(fieldName && dataset.fields.some(field => field.name === fieldName));
+}
+
+function presentFieldName(
+ dataset: ChartableDataset,
+ fieldName?: string | null
+): string | undefined {
+ return datasetHasField(dataset, fieldName) ? fieldName || undefined : undefined;
+}
+
+export function groupIndexes(
+ indexes: number[],
+ dataset: ChartableDataset,
+ axis: ChartAxis | undefined,
+ numBins = DEFAULT_NUM_GROUPS
+): {groups: Map<string, number[]>; filterValues: Map<string, Array<string | number | boolean>>} {
+ const fieldName = axis?.field?.name;
+ if (!fieldName) {
+ return {
+ groups: new Map([['All', indexes]]),
+ filterValues: new Map([['All', ['All']]])
+ };
+ }
+ if (!datasetHasField(dataset, fieldName)) {
+ return {groups: new Map(), filterValues: new Map()};
+ }
+ const fieldType = axis.field?.type;
+ const aggregation = axis.aggregation;
+
+ // Time fields → time bins (unless explicitly forced to unique categories)
+ if (
+ (aggregation === BinType.timeBin || TIME_FIELD_TYPES.includes(fieldType || '')) &&
+ aggregation !== BinType.uniqueBin &&
+ aggregation !== BinType.numericBin
+ ) {
+ return timeGroupMap(indexes, dataset, fieldName, axis.interval || undefined, numBins);
+ }
+
+ // Continuous reals (and explicit numericBin) → histogram across the full domain.
+ // uniqueBin on floats only shows a few clustered values after top-N truncation.
+ if (aggregation === BinType.numericBin || fieldType === 'real') {
+ return numericGroupMap(indexes, dataset, fieldName, numBins);
+ }
+
+ // Integers: prefer unique categories, but fall back to a histogram when cardinality
+ // exceeds the chart's group budget.
+ if (fieldType === 'integer') {
+ if (aggregation === BinType.numericBin) {
+ return numericGroupMap(indexes, dataset, fieldName, numBins);
+ }
+ const uniques = uniqueGroupMap(indexes, dataset, fieldName);
+ if (numBins > 0 && uniques.size > numBins) {
+ return numericGroupMap(indexes, dataset, fieldName, numBins);
+ }
+ return {groups: uniques, filterValues: uniqueGroupFilterValues(uniques, fieldType)};
+ }
+
+ const groups = uniqueGroupMap(indexes, dataset, fieldName);
+ return {groups, filterValues: uniqueGroupFilterValues(groups, fieldType)};
+}
+
+export function buildGroupedBins({
+ dataset,
+ applyFilters,
+ indexes: indexesOverride,
+ binAxis,
+ valueAxis,
+ groupByAxis,
+ numGroups = DEFAULT_NUM_GROUPS,
+ groupOthers = false,
+ sort,
+ color,
+ colors,
+ truncate = true
+}: {
+ dataset: ChartableDataset;
+ applyFilters: boolean;
+ indexes?: number[];
+ binAxis?: ChartAxis;
+ valueAxis?: ChartAxis;
+ groupByAxis?: ChartAxis;
+ numGroups?: number;
+ groupOthers?: boolean;
+ sort?: SortType;
+ /** Single color applied to every bin. */
+ color?: string;
+ /** Palette used to color bins by category when `color` is not set. */
+ colors?: string[];
+ /** When false, keep every bin (used for numeric/time domain bins). */
+ truncate?: boolean;
+}): ChartBin[] {
+ const indexes = indexesOverride || getChartIndexes(dataset, applyFilters);
+ const {groups, filterValues} = groupIndexes(indexes, dataset, binAxis, numGroups);
+ const valueField = datasetHasField(dataset, valueAxis?.field?.name)
+ ? valueAxis?.field?.name
+ : undefined;
+ const aggregation = (valueAxis?.aggregation as ChartAggregation) || 'count';
+ const groupByField = datasetHasField(dataset, groupByAxis?.field?.name)
+ ? groupByAxis?.field?.name
+ : undefined;
+
+ let bins: ChartBin[] = [];
+ let colorIndex = 0;
+ groups.forEach((groupIndexesList, key) => {
+ const series = groupByField
+ ? Array.from(uniqueGroupMap(groupIndexesList, dataset, groupByField).entries()).map(
+ ([seriesKey, seriesIndexes], seriesIdx) => ({
+ key: seriesKey,
+ value: aggregateIndexes(seriesIndexes, dataset, valueField, aggregation),
+ count: seriesIndexes.length,
+ color: colors?.length ? colors[seriesIdx % colors.length] : colorAt(seriesIdx)
+ })
+ )
+ : undefined;
+ bins.push({
+ key,
+ value: series
+ ? series.reduce((sum, item) => sum + item.value, 0)
+ : aggregateIndexes(groupIndexesList, dataset, valueField, aggregation),
+ count: groupIndexesList.length,
+ color:
+ color ||
+ (colors?.length ? colors[colorIndex % colors.length] : undefined) ||
+ colorAt(colorIndex),
+ filterValue: filterValues.get(key) || [key],
+ series
+ });
+ colorIndex += 1;
+ });
+
+ bins = sortBins(bins, sort);
+ if (!truncate || numGroups <= 0) {
+ // Line charts pass numGroups=0 (no categorical top-N); still hard-cap points.
+ return bins.length > MAX_CHART_POINTS ? bins.slice(0, MAX_CHART_POINTS) : bins;
+ }
+ return truncateBins(bins, numGroups, groupOthers);
+}
+
+export function buildBigNumber({
+ dataset,
+ applyFilters,
+ axis
+}: {
+ dataset: ChartableDataset;
+ applyFilters: boolean;
+ axis?: ChartAxis;
+}): {value: number; count: number} {
+ const indexes = getChartIndexes(dataset, applyFilters);
+ return {
+ count: indexes.length,
+ value: aggregateIndexes(
+ indexes,
+ dataset,
+ presentFieldName(dataset, axis?.field?.name),
+ (axis?.aggregation as ChartAggregation) || 'count'
+ )
+ };
+}
+
+/**
+ * Numeric/time: keep domain order from groupIndexes.
+ * Categories: take the top-N by frequency, then sort labels A→Z.
+ */
+function pickAxisEntries(
+ groups: Map<string, number[]>,
+ filterValues: Map<string, Array<string | number | boolean>>,
+ axis: ChartAxis | undefined,
+ limit: number
+): Array<[string, number[]]> {
+ const entries = Array.from(groups.entries());
+ if (isOrderedAxis(axis)) {
+ // Prefer sorting by numeric filter range start when available (histogram order).
+ return entries
+ .sort((a, b) => {
+ const a0 = filterValues.get(a[0])?.[0];
+ const b0 = filterValues.get(b[0])?.[0];
+ if (typeof a0 === 'number' && typeof b0 === 'number') {
+ return a0 - b0;
+ }
+ return String(a[0]).localeCompare(String(b[0]));
+ })
+ .slice(0, limit);
+ }
+ return entries
+ .sort((a, b) => b[1].length - a[1].length || String(a[0]).localeCompare(String(b[0])))
+ .slice(0, limit)
+ .sort((a, b) => String(a[0]).localeCompare(String(b[0])));
+}
+
+export function buildHeatmapCells({
+ dataset,
+ applyFilters,
+ xAxis,
+ yAxis,
+ valueAxis,
+ numGroups = DEFAULT_NUM_GROUPS
+}: {
+ dataset: ChartableDataset;
+ applyFilters: boolean;
+ xAxis?: ChartAxis;
+ yAxis?: ChartAxis;
+ valueAxis?: ChartAxis;
+ numGroups?: number;
+}): HeatmapCell[] {
+ const indexes = getChartIndexes(dataset, applyFilters);
+ if (!xAxis?.field?.name || !yAxis?.field?.name) {
+ return [];
+ }
+ // Cap both axes at 10×10 (Studio-style labeled table).
+ const limit = Math.min(
+ Math.max(1, numGroups > 0 ? numGroups : DEFAULT_NUM_GROUPS),
+ DEFAULT_NUM_GROUPS
+ );
+
+ const xResult = groupIndexes(indexes, dataset, xAxis, limit);
+ const yResult = groupIndexes(indexes, dataset, yAxis, limit);
+
+ const xEntries = pickAxisEntries(xResult.groups, xResult.filterValues, xAxis, limit);
+ const yEntries = pickAxisEntries(yResult.groups, yResult.filterValues, yAxis, limit);
+ const yKeys = yEntries.map(([key]) => key);
+
+ // Index → set for O(1) membership when intersecting X and Y buckets.
+ const ySets = new Map<string, Set<number>>();
+ yEntries.forEach(([key, idxs]) => {
+ ySets.set(key, new Set(idxs));
+ });
+
+ const valueField = presentFieldName(dataset, valueAxis?.field?.name);
+ const aggregation = (valueAxis?.aggregation as ChartAggregation) || 'count';
+ const cells: HeatmapCell[] = [];
+
+ // Full cartesian grid so the view always shows a table (zeros for empty cells).
+ xEntries.forEach(([x, xIdxs]) => {
+ yKeys.forEach(y => {
+ const ySet = ySets.get(y);
+ const intersected = ySet ? xIdxs.filter(idx => ySet.has(idx)) : [];
+ cells.push({
+ x,
+ y,
+ value: intersected.length
+ ? aggregateIndexes(intersected, dataset, valueField, aggregation)
+ : 0,
+ filterValueX: xResult.filterValues.get(x) || [x],
+ filterValueY: yResult.filterValues.get(y) || [y]
+ });
+ });
+ });
+ return cells;
+}
+
+/** True when axis bins are a continuous domain (should stay in min→max order). */
+function isOrderedAxis(axis?: ChartAxis): boolean {
+ if (!axis?.field) {
+ return false;
+ }
+ const fieldType = axis.field.type;
+ return (
+ axis.aggregation === BinType.numericBin ||
+ axis.aggregation === BinType.timeBin ||
+ fieldType === 'real' ||
+ fieldType === 'integer' ||
+ TIME_FIELD_TYPES.includes(fieldType || '')
+ );
+}
+
+export function buildPivotTable({
+ dataset,
+ applyFilters,
+ xAxis,
+ yAxis,
+ valueAxis,
+ numGroups = DEFAULT_NUM_GROUPS
+}: {
+ dataset: ChartableDataset;
+ applyFilters: boolean;
+ xAxis?: ChartAxis;
+ yAxis?: ChartAxis;
+ valueAxis?: ChartAxis;
+ numGroups?: number;
+}): PivotTableResult {
+ const empty: PivotTableResult = {rowKeys: [], columnKeys: [], values: {}};
+ if (!xAxis?.field?.name || !yAxis?.field?.name) {
+ return empty;
+ }
+ const indexes = getChartIndexes(dataset, applyFilters);
+ // Same 10×10 cap and binning as heatmap (numeric histogram, category top-N).
+ const limit = Math.min(
+ Math.max(1, numGroups > 0 ? numGroups : DEFAULT_NUM_GROUPS),
+ DEFAULT_NUM_GROUPS
+ );
+
+ const xResult = groupIndexes(indexes, dataset, xAxis, limit);
+ const yResult = groupIndexes(indexes, dataset, yAxis, limit);
+ const columnEntries = pickAxisEntries(xResult.groups, xResult.filterValues, xAxis, limit);
+ const rowEntries = pickAxisEntries(yResult.groups, yResult.filterValues, yAxis, limit);
+ const columnKeys = columnEntries.map(([key]) => key);
+ const rowKeys = rowEntries.map(([key]) => key);
+
+ const rowSets = new Map<string, Set<number>>();
+ rowEntries.forEach(([key, idxs]) => {
+ rowSets.set(key, new Set(idxs));
+ });
+
+ const valueField = presentFieldName(dataset, valueAxis?.field?.name);
+ const aggregation = (valueAxis?.aggregation as ChartAggregation) || 'count';
+ const values: Record<string, Record<string, number>> = {};
+
+ rowKeys.forEach(row => {
+ values[row] = {};
+ const rowSet = rowSets.get(row);
+ columnEntries.forEach(([col, colIdxs]) => {
+ const intersected = rowSet ? colIdxs.filter(idx => rowSet.has(idx)) : [];
+ values[row][col] = intersected.length
+ ? aggregateIndexes(intersected, dataset, valueField, aggregation)
+ : 0;
+ });
+ });
+
+ return {rowKeys, columnKeys, values};
+}
+
+export function buildTimeSeries({
+ dataset,
+ indexes,
+ xAxis,
+ yAxis,
+ interval
+}: {
+ dataset: ChartableDataset;
+ indexes: number[];
+ xAxis?: ChartAxis;
+ yAxis?: ChartAxis;
+ interval?: string;
+}): ChartBin[] {
+ if (!presentFieldName(dataset, xAxis?.field?.name) || !xAxis?.field?.name) {
+ return [];
+ }
+ const {groups, filterValues} = timeGroupMap(indexes, dataset, xAxis.field.name, interval);
+ const bins: ChartBin[] = [];
+ groups.forEach((groupIndexes, key) => {
+ bins.push({
+ key,
+ value: aggregateIndexes(
+ groupIndexes,
+ dataset,
+ presentFieldName(dataset, yAxis?.field?.name),
+ (yAxis?.aggregation as ChartAggregation) || 'count'
+ ),
+ count: groupIndexes.length,
+ color: CHART_COLORS[0],
+ filterValue: filterValues.get(key) || [key]
+ });
+ });
+ // Preserve chronological order from timeGroupMap (period labels are not ISO strings).
+ return bins;
+}
+
+export {toKey};
diff --git a/src/charts/src/builders.ts b/src/charts/src/builders.ts
new file mode 100644
index 000000000..88fc0c886
--- /dev/null
+++ b/src/charts/src/builders.ts
@@ -0,0 +1,337 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {
+ CHART_ID_LENGTH,
+ ChartType,
+ LayerChartType,
+ BinType,
+ ChartColorBy,
+ DEFAULT_NUM_GROUPS,
+ CATEGORICAL_FIELD_TYPES,
+ NUMERIC_FIELD_TYPES,
+ TIME_FIELD_TYPES,
+ getDefaultChartColorRange,
+ getDefaultHeatmapColorRange
+} from './constants';
+import {
+ ChartConfig,
+ ChartAxis,
+ DatasetChartConfig,
+ LayerChartConfig,
+ ChartableDataset,
+ isLayerChartConfig
+} from './types';
+
+function generateHashId(len: number): string {
+ return Math.random()
+ .toString(36)
+ .slice(2, 2 + len);
+}
+
+function makeAxis(
+ field: {name: string; type: string} | null = null,
+ aggregation: ChartAxis['aggregation'] = 'count'
+): ChartAxis {
+ return {
+ field,
+ aggregation,
+ title: field?.name ?? null
+ };
+}
+
+function baseChart(
+ props: Partial<ChartConfig> = {}
+): Pick<
+ DatasetChartConfig,
+ 'id' | 'title' | 'dataId' | 'applyFilters' | 'pinned' | 'display' | 'chartDisplay' | 'crossFilter'
+> {
+ return {
+ id: props.id || generateHashId(CHART_ID_LENGTH),
+ title: props.title || 'New Chart',
+ dataId: props.dataId ?? null,
+ applyFilters: props.applyFilters ?? true,
+ // New charts start unpinned; user can pin to keep them visible when the panel is off.
+ pinned: props.pinned ?? false,
+ display: {
+ isConfigActive: props.display?.isConfigActive ?? false
+ },
+ chartDisplay: props.chartDisplay || {},
+ ...(props.crossFilter ? {crossFilter: props.crossFilter} : {})
+ };
+}
+
+export function createBigNumberChart(props: Partial<DatasetChartConfig> = {}): DatasetChartConfig {
+ return {
+ ...baseChart({
+ ...props,
+ chartDisplay: {
+ format: 'DECIMAL_SHORT_COMMA',
+ showCaption: true,
+ ...props.chartDisplay
+ }
+ }),
+ type: ChartType.bigNumber,
+ axis: props.axis || makeAxis(null, 'count'),
+ title: props.title || 'Count of rows'
+ };
+}
+
+export function createBarChart(props: Partial<DatasetChartConfig> = {}): DatasetChartConfig {
+ const numGroups = props.numGroups ?? DEFAULT_NUM_GROUPS;
+ return {
+ ...baseChart({
+ ...props,
+ chartDisplay: {
+ colorRange: getDefaultChartColorRange(numGroups),
+ ...props.chartDisplay
+ }
+ }),
+ type: ChartType.barChart,
+ xAxis: props.xAxis || makeAxis(null, BinType.uniqueBin),
+ yAxis: props.yAxis || makeAxis(null, 'count'),
+ groupBy: props.groupBy || makeAxis(null, BinType.uniqueBin),
+ numGroups,
+ groupOthers: props.groupOthers ?? false,
+ colorBy: props.colorBy ?? ChartColorBy.category,
+ title: props.title || 'Bar chart'
+ };
+}
+
+export function createHorizontalBarChart(
+ props: Partial<DatasetChartConfig> = {}
+): DatasetChartConfig {
+ return {
+ ...createBarChart(props),
+ type: ChartType.horizontalBar,
+ title: props.title || 'Horizontal bar'
+ };
+}
+
+export function createLineChart(props: Partial<DatasetChartConfig> = {}): DatasetChartConfig {
+ return {
+ ...baseChart(props),
+ type: ChartType.lineChart,
+ xAxis: props.xAxis || makeAxis(null, BinType.uniqueBin),
+ yAxis: props.yAxis || makeAxis(null, 'count'),
+ groupBy: props.groupBy || makeAxis(null, BinType.uniqueBin),
+ // 0 = no top-N truncation (line charts show the full series)
+ numGroups: props.numGroups ?? 0,
+ title: props.title || 'Line chart'
+ };
+}
+
+export function createHeatmapChart(props: Partial<DatasetChartConfig> = {}): DatasetChartConfig {
+ return {
+ ...baseChart(props),
+ type: ChartType.heatmapChart,
+ xAxis: props.xAxis || makeAxis(null, BinType.uniqueBin),
+ yAxis: props.yAxis || makeAxis(null, BinType.uniqueBin),
+ value: props.value || makeAxis(null, 'count'),
+ numGroups: props.numGroups ?? DEFAULT_NUM_GROUPS,
+ title: props.title || 'Heatmap',
+ chartDisplay: {
+ colorRange: getDefaultHeatmapColorRange(),
+ ...props.chartDisplay
+ }
+ };
+}
+
+export function createPivotTableChart(props: Partial<DatasetChartConfig> = {}): DatasetChartConfig {
+ return {
+ ...baseChart(props),
+ type: ChartType.pivotTable,
+ xAxis: props.xAxis || makeAxis(null, BinType.uniqueBin),
+ yAxis: props.yAxis || makeAxis(null, BinType.uniqueBin),
+ value: props.value || makeAxis(null, 'count'),
+ numGroups: props.numGroups ?? DEFAULT_NUM_GROUPS,
+ title: props.title || 'Pivot table'
+ };
+}
+
+export function createLayerChart(
+ layerId: string,
+ layerChartType: LayerChartType,
+ props: Partial<LayerChartConfig> = {}
+): LayerChartConfig {
+ return {
+ ...baseChart(props),
+ type: ChartType.layerChart,
+ layerId,
+ layerChartType,
+ dataId: props.dataId ?? null,
+ axis: props.axis || makeAxis(null, BinType.uniqueBin),
+ xAxis: props.xAxis || makeAxis(null, BinType.timeBin),
+ yAxis: props.yAxis || makeAxis(null, 'count'),
+ title:
+ props.title ||
+ (layerChartType === LayerChartType.TIME_SERIES ? 'Time series' : 'Category breakdown'),
+ chartDisplay: {
+ idField: props.chartDisplay?.idField ?? null,
+ numEntries: props.chartDisplay?.numEntries ?? 5,
+ // Leave unset so aggregation auto-picks hour/day/week/month/year from the span.
+ interval: props.chartDisplay?.interval,
+ ...props.chartDisplay
+ }
+ };
+}
+
+function firstField(
+ dataset: ChartableDataset | undefined,
+ types: string[],
+ skipName?: string | null
+): {name: string; type: string} | null {
+ const field = dataset?.fields.find(
+ f => types.includes(f.type) && (!skipName || f.name !== skipName)
+ );
+ return field ? {name: field.name, type: field.type} : null;
+}
+
+export function createChart(args: {
+ type: ChartType | LayerChartType;
+ dataId?: string | null;
+ dataset?: ChartableDataset;
+ layerId?: string;
+ options?: {activateConfig?: boolean};
+}): ChartConfig | null {
+ const {type, dataId, dataset, layerId, options} = args;
+ const categorical = firstField(dataset, CATEGORICAL_FIELD_TYPES);
+ const numeric = firstField(dataset, NUMERIC_FIELD_TYPES);
+ const temporal = firstField(dataset, TIME_FIELD_TYPES);
+ const categoricalY =
+ firstField(dataset, CATEGORICAL_FIELD_TYPES, categorical?.name) || categorical;
+ const display = {isConfigActive: options?.activateConfig ?? false};
+
+ switch (type) {
+ case ChartType.bigNumber:
+ return createBigNumberChart({
+ dataId: dataId ?? dataset?.id ?? null,
+ title: dataset ? `Count of rows in ${dataset.label || dataset.id}` : 'Count of rows',
+ axis: makeAxis(null, 'count'),
+ display
+ });
+ case ChartType.barChart:
+ return createBarChart({
+ dataId: dataId ?? dataset?.id ?? null,
+ xAxis: makeAxis(categorical, BinType.uniqueBin),
+ yAxis: makeAxis(null, 'count'),
+ title: categorical ? `Count by ${categorical.name}` : 'Bar chart',
+ display
+ });
+ case ChartType.horizontalBar:
+ return createHorizontalBarChart({
+ dataId: dataId ?? dataset?.id ?? null,
+ xAxis: makeAxis(null, 'count'),
+ yAxis: makeAxis(categorical, BinType.uniqueBin),
+ title: categorical ? `Count by ${categorical.name}` : 'Horizontal bar',
+ display
+ });
+ case ChartType.lineChart:
+ return createLineChart({
+ dataId: dataId ?? dataset?.id ?? null,
+ xAxis: makeAxis(temporal || categorical, temporal ? BinType.timeBin : BinType.uniqueBin),
+ yAxis: makeAxis(numeric, numeric ? 'sum' : 'count'),
+ title: 'Line chart',
+ display
+ });
+ case ChartType.heatmapChart:
+ return createHeatmapChart({
+ dataId: dataId ?? dataset?.id ?? null,
+ xAxis: makeAxis(categorical, BinType.uniqueBin),
+ yAxis: makeAxis(categoricalY, BinType.uniqueBin),
+ value: makeAxis(numeric, numeric ? 'sum' : 'count'),
+ title: 'Heatmap',
+ display
+ });
+ case ChartType.pivotTable:
+ return createPivotTableChart({
+ dataId: dataId ?? dataset?.id ?? null,
+ xAxis: makeAxis(categorical, BinType.uniqueBin),
+ yAxis: makeAxis(categoricalY, BinType.uniqueBin),
+ value: makeAxis(numeric, numeric ? 'sum' : 'count'),
+ title: 'Pivot table',
+ display
+ });
+ case LayerChartType.BREAKDOWN_BY_CATEGORY:
+ case LayerChartType.TIME_SERIES:
+ if (!layerId) {
+ return null;
+ }
+ return createLayerChart(layerId, type, {
+ dataId: dataId ?? dataset?.id ?? null,
+ axis: makeAxis(categorical, BinType.uniqueBin),
+ xAxis: makeAxis(temporal, BinType.timeBin),
+ yAxis: makeAxis(numeric, numeric ? 'sum' : 'count'),
+ display
+ });
+ default:
+ return null;
+ }
+}
+
+export function serializeCharts(charts: ChartConfig[]): ChartConfig[] {
+ return charts.map(chart => ({
+ ...chart,
+ display: {
+ ...chart.display,
+ isConfigActive: false
+ }
+ }));
+}
+
+/**
+ * Rebuild field-bearing axes for a new dataset (or layer) so stale names like
+ * `Join_Count` are not looked up row-by-row on a table that does not have them.
+ */
+export function propsForChartDatasetChange(
+ chart: ChartConfig,
+ dataset: ChartableDataset | null | undefined,
+ next: {dataId?: string | null; layerId?: string}
+): Partial<ChartConfig> {
+ const dataId = next.dataId ?? chart.dataId ?? null;
+ const layerId = next.layerId ?? (isLayerChartConfig(chart) ? chart.layerId : undefined);
+ const type: ChartType | LayerChartType = isLayerChartConfig(chart)
+ ? (chart.layerChartType as LayerChartType)
+ : (chart.type as ChartType);
+ const rebuilt = createChart({
+ type,
+ dataId,
+ dataset: dataset || undefined,
+ layerId,
+ options: {activateConfig: chart.display?.isConfigActive}
+ });
+ const crossFilter = chart.crossFilter
+ ? {...chart.crossFilter, enabled: false, value: {}, fieldNames: {}}
+ : undefined;
+ if (!rebuilt) {
+ return {
+ dataId,
+ ...(layerId ? {layerId} : {}),
+ xAxis: makeAxis(null),
+ yAxis: makeAxis(null),
+ axis: makeAxis(null),
+ groupBy: makeAxis(null),
+ value: makeAxis(null),
+ crossFilter
+ };
+ }
+ const prevDisplay = (chart.chartDisplay || {}) as Record<string, unknown>;
+ return {
+ ...rebuilt,
+ id: chart.id,
+ pinned: chart.pinned,
+ applyFilters: chart.applyFilters,
+ display: chart.display,
+ title: chart.title,
+ dataId,
+ ...(layerId ? {layerId} : {}),
+ chartDisplay: {
+ ...rebuilt.chartDisplay,
+ format: prevDisplay.format,
+ color: prevDisplay.color,
+ colorRange: prevDisplay.colorRange,
+ showCaption: prevDisplay.showCaption
+ },
+ crossFilter
+ };
+}
diff --git a/src/charts/src/chart-views.tsx b/src/charts/src/chart-views.tsx
new file mode 100644
index 000000000..0291d8121
--- /dev/null
+++ b/src/charts/src/chart-views.tsx
@@ -0,0 +1,1212 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React from 'react';
+import styled from 'styled-components';
+
+import {displayBinKey, formatNumber} from './aggregation';
+
+import {ChartBin, HeatmapCell, PivotTableResult} from './types';
+import {ChartViewData} from './compute';
+import {HEATMAP_COLORS, HEATMAP_COLOR_STEPS} from './constants';
+
+const ChartWrap = styled.div`
+ width: 100%;
+ padding: 8px 12px 8px;
+ box-sizing: border-box;
+ overflow: visible;
+`;
+
+/** Heatmap: less left inset so side labels sit closer to the panel edge. */
+const HeatChartWrap = styled(ChartWrap)`
+ padding-left: 4px;
+`;
+
+const EmptyState = styled.div`
+ color: ${props => props.theme.subtextColor};
+ font-size: 11px;
+ padding: 3px 0;
+ line-height: 1.3;
+`;
+
+/** Compact padding when the chart only shows a placeholder message. */
+const EmptyChartWrap = styled(ChartWrap)`
+ padding-top: 4px;
+ padding-bottom: 4px;
+`;
+
+const BigNumberValue = styled.div`
+ font-size: 28px;
+ font-weight: 500;
+ color: ${props => props.theme.textColor};
+ line-height: 1.2;
+`;
+
+const BigNumberCaption = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ color: ${props => props.theme.subtextColor};
+ margin-top: 4px;
+`;
+
+const BigNumberCaptionText = styled.span`
+ min-width: 0;
+`;
+
+const BigNumberCaptionToggle = styled.button`
+ flex: 0 0 auto;
+ display: inline-flex;
+ align-items: center;
+ justify-content: center;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ background: transparent;
+ color: ${props => props.theme.subtextColor};
+ cursor: pointer;
+ line-height: 0;
+
+ &:hover {
+ color: ${props => props.theme.textColor};
+ }
+`;
+
+const BarRow = styled.div<{$clickable?: boolean; $selected?: boolean}>`
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 4px 0;
+ position: relative;
+ z-index: ${props => (props.$selected ? 1 : 0)};
+ cursor: ${props => (props.$clickable ? 'pointer' : 'default')};
+ &:focus-visible {
+ outline: 1px solid ${props => props.theme.activeColor};
+ outline-offset: 1px;
+ }
+`;
+
+const BarLabel = styled.div`
+ flex: 0 1 auto;
+ max-width: 40%;
+ min-width: 72px;
+ font-size: 11px;
+ color: ${props => props.theme.textColor};
+ white-space: normal;
+ overflow-wrap: anywhere;
+ line-height: 1.2;
+`;
+
+const selectedBinRing = (theme: {activeColor?: string; panelBackground?: string}) => `
+ box-shadow:
+ 0 0 0 1px ${theme.panelBackground || '#242730'},
+ 0 0 0 3px ${theme.activeColor || '#1FBAD6'};
+`;
+
+const BarTrack = styled.div<{$selected?: boolean}>`
+ flex: 1;
+ height: 10px;
+ background: ${props => props.theme.sliderBarBgd};
+ border-radius: 2px;
+ overflow: ${props => (props.$selected ? 'visible' : 'hidden')};
+`;
+
+const BarFill = styled.div<{
+ $color: string;
+ $width: number;
+ $active?: boolean;
+ $dimmed?: boolean;
+}>`
+ height: 100%;
+ width: ${props => props.$width}%;
+ background: ${props => props.$color};
+ border-radius: 2px;
+ box-sizing: border-box;
+ position: relative;
+ z-index: ${props => (props.$active ? 1 : 0)};
+ opacity: ${props => (props.$active ? 1 : props.$dimmed ? 0.4 : 0.85)};
+ ${props => (props.$active ? selectedBinRing(props.theme) : '')}
+`;
+
+const BarValue = styled.div`
+ flex: 0 0 auto;
+ min-width: 52px;
+ font-size: 11px;
+ text-align: right;
+ color: ${props => props.theme.subtextColor};
+ white-space: nowrap;
+`;
+
+const VerticalBarChart = styled.div<{$padRight?: number; $gap?: number}>`
+ display: flex;
+ flex-direction: column;
+ gap: ${props => props.$gap ?? 20}px;
+ overflow: visible;
+ padding-right: ${props => props.$padRight || 0}px;
+ box-sizing: border-box;
+`;
+
+const VerticalBarBars = styled.div`
+ display: flex;
+ align-items: stretch;
+ gap: 8px;
+ height: 140px;
+ min-height: 140px;
+ overflow: visible;
+`;
+
+const VerticalBarCol = styled.div<{$clickable?: boolean; $selected?: boolean}>`
+ flex: 1 1 0;
+ min-width: 0;
+ height: 100%;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 4px;
+ overflow: visible;
+ z-index: ${props => (props.$selected ? 1 : 0)};
+ cursor: ${props => (props.$clickable ? 'pointer' : 'default')};
+ &:focus-visible {
+ outline: 1px solid ${props => props.theme.activeColor};
+ outline-offset: 1px;
+ }
+`;
+
+const VerticalBarValue = styled.div`
+ flex: 0 0 auto;
+ font-size: 10px;
+ line-height: 1.1;
+ color: ${props => props.theme.subtextColor};
+ white-space: nowrap;
+ overflow: visible;
+ text-align: center;
+`;
+
+const VerticalBarTrack = styled.div<{$selected?: boolean}>`
+ flex: 1 1 auto;
+ width: 100%;
+ max-width: 32px;
+ min-height: 0;
+ display: flex;
+ align-items: flex-end;
+ background: ${props => props.theme.sliderBarBgd};
+ border-radius: 2px;
+ overflow: ${props => (props.$selected ? 'visible' : 'hidden')};
+`;
+
+const VerticalBarFill = styled.div<{
+ $color: string;
+ $height: number;
+ $active?: boolean;
+ $dimmed?: boolean;
+}>`
+ width: 100%;
+ height: ${props => props.$height}%;
+ background: ${props => props.$color};
+ border-radius: 2px 2px 0 0;
+ box-sizing: border-box;
+ position: relative;
+ z-index: ${props => (props.$active ? 1 : 0)};
+ opacity: ${props => (props.$active ? 1 : props.$dimmed ? 0.4 : 0.85)};
+ ${props => (props.$active ? selectedBinRing(props.theme) : '')}
+`;
+
+const VerticalBarLabels = styled.div<{$height: number; $rotated?: boolean}>`
+ display: flex;
+ /* Top-align rotated labels so they hang down into the band instead of into the bars. */
+ align-items: ${props => (props.$rotated ? 'flex-start' : 'center')};
+ gap: 8px;
+ height: ${props => props.$height}px;
+ overflow: visible;
+`;
+
+const VerticalBarLabelCell = styled.div<{$rotated?: boolean}>`
+ flex: 1 1 0;
+ min-width: 0;
+ height: 100%;
+ display: flex;
+ align-items: ${props => (props.$rotated ? 'flex-start' : 'center')};
+ justify-content: ${props => (props.$rotated ? 'flex-start' : 'center')};
+ overflow: visible;
+`;
+
+const VerticalBarLabel = styled.div<{$rotated?: boolean}>`
+ font-size: 10px;
+ color: ${props => props.theme.textColor};
+ white-space: nowrap;
+ overflow: visible;
+ /* Clockwise so text hangs down-right from top-left into the label band (not up into bars). */
+ transform: ${props => (props.$rotated ? `rotate(${LABEL_ROTATE_DEG}deg)` : 'none')};
+ transform-origin: top left;
+ line-height: 1.1;
+ pointer-events: none;
+`;
+
+/** ~px per character at 10px font; used to decide rotation + label band height. */
+const LABEL_CHAR_WIDTH = 6;
+const LABEL_ROTATE_DEG = 40;
+/** Approximate chart plot width inside the panel (for fit checks). */
+const VERTICAL_BAR_PLOT_WIDTH = 260;
+
+function getVerticalBarLabelLayout(bins: ChartBin[]): {
+ rotated: boolean;
+ labelBand: number;
+ padRight: number;
+ gap: number;
+} {
+ const maxLen = Math.max(1, ...bins.map(bin => displayBinKey(String(bin.key)).length));
+ const slotWidth = VERTICAL_BAR_PLOT_WIDTH / Math.max(1, bins.length);
+ const labelWidth = maxLen * LABEL_CHAR_WIDTH;
+ // Keep short labels horizontal (Studio-like); rotate when they won't fit in their slot.
+ const rotated = labelWidth > slotWidth * 0.9 || maxLen > 8;
+ if (!rotated) {
+ return {rotated: false, labelBand: 5, padRight: 0, gap: 6};
+ }
+ const sin = Math.sin((LABEL_ROTATE_DEG * Math.PI) / 180);
+ // Full downward projection of the angled label (origin is top-left, rotates clockwise).
+ const projectedHeight = labelWidth * sin + 10;
+ // Small fixed clearance under bars; length is absorbed by the label band below.
+ return {
+ rotated: true,
+ labelBand: Math.max(24, Math.ceil(projectedHeight)),
+ padRight: 2,
+ gap: 8
+ };
+}
+
+const HeatGrid = styled.div<{
+ $cols: number;
+ $rows: number;
+ $sideWidth: number;
+ $headerHeight: number;
+}>`
+ display: grid;
+ grid-template-columns: ${props => props.$sideWidth}px repeat(
+ ${props => props.$cols},
+ minmax(22px, 1fr)
+ );
+ grid-template-rows: ${props => props.$headerHeight}px repeat(
+ ${props => props.$rows},
+ minmax(22px, auto)
+ );
+ gap: 1px;
+ font-size: 8px;
+ align-items: stretch;
+ width: 100%;
+ min-width: 0;
+ overflow: visible;
+`;
+
+const HeatCorner = styled.div`
+ min-width: 0;
+`;
+
+const HeatAxisTitles = styled.div<{$sideWidth: number}>`
+ display: grid;
+ grid-template-columns: ${props => props.$sideWidth}px 1fr;
+ align-items: center;
+ margin-bottom: 4px;
+ min-height: 14px;
+ gap: 2px;
+`;
+
+const HeatAxisTitle = styled.div<{
+ $align?: 'left' | 'center' | 'right';
+}>`
+ padding: 0 2px;
+ text-align: ${props => props.$align || 'center'};
+ font-size: 9px;
+ line-height: 1.2;
+ color: ${props => props.theme.textColor};
+ opacity: 0.95;
+ white-space: nowrap;
+ overflow: visible;
+`;
+
+const HEAT_CELL_MIN_HEIGHT = 22;
+
+const HeatLabel = styled.div<{
+ $header?: boolean;
+ $active?: boolean;
+ $rotated?: boolean;
+}>`
+ position: relative;
+ display: flex;
+ align-items: ${props => (props.$rotated ? 'flex-start' : 'center')};
+ justify-content: ${props => {
+ if (props.$header) {
+ return props.$rotated ? 'flex-start' : 'center';
+ }
+ // Side labels: hug the grid (right edge of the side column).
+ return 'flex-end';
+ }};
+ min-width: 0;
+ overflow: visible;
+ color: ${props => (props.$active ? props.theme.textColor : props.theme.subtextColor)};
+ font-weight: ${props => (props.$active ? 600 : 400)};
+ padding: 0;
+ font-size: 8px;
+ line-height: 1.1;
+ transition: color 80ms ease;
+`;
+
+const HeatLabelText = styled.span<{$header?: boolean; $rotated?: boolean}>`
+ display: inline-block;
+ white-space: nowrap;
+ /* Same clockwise angle as vertical bar labels; hang into the label band.
+ Side labels also shift down by half a row so they sit on the row center. */
+ transform: ${props => {
+ if (!props.$rotated) {
+ return 'none';
+ }
+ if (props.$header) {
+ return `rotate(${LABEL_ROTATE_DEG}deg)`;
+ }
+ return `translateY(${HEAT_CELL_MIN_HEIGHT / 2}px) rotate(${LABEL_ROTATE_DEG}deg)`;
+ }};
+ transform-origin: ${props => (props.$header ? 'top left' : 'top right')};
+ max-width: none;
+`;
+
+const HeatCell = styled.div<{
+ $bg: string;
+ $fg: string;
+ $clickable?: boolean;
+ $dimmed?: boolean;
+ $selected?: boolean;
+}>`
+ min-height: ${HEAT_CELL_MIN_HEIGHT}px;
+ min-width: 0;
+ padding: 1px 2px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ text-align: center;
+ background: ${props => props.$bg};
+ color: ${props => props.$fg};
+ font-size: 8px;
+ font-variant-numeric: tabular-nums;
+ line-height: 1.1;
+ overflow: ${props => (props.$selected ? 'visible' : 'hidden')};
+ box-sizing: border-box;
+ border: 1px solid transparent;
+ opacity: ${props => (props.$dimmed && !props.$selected ? 0.45 : 1)};
+ cursor: ${props => (props.$clickable ? 'pointer' : 'default')};
+ transition: opacity 80ms ease, border-color 80ms ease, box-shadow 80ms ease;
+ position: relative;
+
+ ${props =>
+ props.$selected
+ ? `
+ border-color: ${props.theme.activeColor || '#1FBAD6'};
+ ${selectedBinRing(props.theme)}
+ opacity: 1;
+ z-index: 2;
+ `
+ : ''}
+
+ &:focus-visible {
+ outline: 1px solid ${props => props.theme.activeColor};
+ outline-offset: 1px;
+ }
+`;
+
+const PivotChartWrap = styled(ChartWrap)`
+ padding-bottom: 4px;
+ max-width: 100%;
+ min-width: 0;
+ overflow: hidden;
+`;
+
+const PivotTableScroll = styled.div`
+ display: block;
+ width: 100%;
+ max-width: 100%;
+ min-width: 0;
+ overflow-x: auto;
+ overflow-y: hidden;
+ overscroll-behavior-x: contain;
+`;
+
+const PivotTableEl = styled.table`
+ border-collapse: collapse;
+ font-size: 11px;
+ color: ${props => props.theme.textColor};
+ /* Content-sized; scroll parent clips to the panel. */
+ width: max-content;
+ max-width: none;
+ table-layout: auto;
+
+ th,
+ td {
+ border: 1px solid ${props => props.theme.panelBorderColor};
+ padding: 4px 6px;
+ text-align: right;
+ color: inherit;
+ white-space: nowrap;
+ }
+ th {
+ color: ${props => props.theme.titleTextColor};
+ font-weight: 500;
+ }
+ /* Row header column stays horizontal; match column header type. */
+ th:first-child,
+ td:first-child {
+ text-align: left;
+ position: sticky;
+ left: 0;
+ z-index: 1;
+ background: ${props => props.theme.panelBackground};
+ color: ${props => props.theme.titleTextColor};
+ font-size: 11px;
+ font-weight: 500;
+ }
+ /* Column headers: full label, vertical. Column width follows cell values. */
+ thead th:not(:first-child) {
+ writing-mode: vertical-rl;
+ transform: rotate(180deg);
+ text-align: left;
+ vertical-align: bottom;
+ padding: 8px 2px;
+ min-width: 26px;
+ box-sizing: border-box;
+ }
+ td:not(:first-child) {
+ min-width: 26px;
+ text-align: center;
+ padding: 4px 4px;
+ box-sizing: border-box;
+ overflow: visible;
+ }
+`;
+
+const LineSvg = styled.svg`
+ width: 100%;
+ height: 160px;
+ display: block;
+ overflow: visible;
+ color: ${props => props.theme.textColor};
+`;
+
+const LineSelectedRing = styled.circle`
+ fill: none;
+ stroke: ${props => props.theme.activeColor || '#1FBAD6'};
+ stroke-width: 1.2;
+`;
+
+const LinePointHit = styled.circle<{$clickable?: boolean}>`
+ fill: transparent;
+ cursor: ${props => (props.$clickable ? 'pointer' : 'default')};
+`;
+
+const LINE_CHART_WIDTH = 320;
+const LINE_CHART_HEIGHT = 160;
+const LINE_MARGIN = {top: 12, right: 12, bottom: 40, left: 56};
+const LINE_Y_AXIS_TITLE_X = 10;
+const LINE_POINT_R = 1;
+const LINE_POINT_SELECTED_R = 2.5;
+const LINE_POINT_RING_R = 5;
+const LINE_POINT_HIT_R = 8;
+
+type ClickHandler = (
+ key: string,
+ extra?: {
+ filterValue?: Array<string | number | boolean>;
+ filterValueY?: Array<string | number | boolean>;
+ x?: string;
+ y?: string;
+ }
+) => void;
+
+function onActivateKey(event: React.KeyboardEvent, activate?: () => void): void {
+ if (!activate) {
+ return;
+ }
+ if (event.key === 'Enter' || event.key === ' ') {
+ event.preventDefault();
+ activate();
+ }
+}
+
+function maxValue(bins: ChartBin[]): number {
+ return Math.max(1, ...bins.map(bin => bin.value));
+}
+
+export function BigNumberView({
+ value,
+ caption,
+ formattedValue,
+ showCaption = true,
+ onToggleCaption,
+ captionToggleIcon,
+ captionToggleLabel
+}: {
+ value: number;
+ caption?: string;
+ formattedValue?: string;
+ showCaption?: boolean;
+ onToggleCaption?: () => void;
+ captionToggleIcon?: React.ReactNode;
+ captionToggleLabel?: string;
+}): React.ReactElement {
+ const captionVisible = showCaption !== false && Boolean(caption);
+ const toggleLabel = captionToggleLabel || (captionVisible ? 'Hide caption' : 'Show caption');
+ return (
+ <ChartWrap>
+ <BigNumberValue>{formattedValue ?? formatNumber(value)}</BigNumberValue>
+ {captionVisible ? (
+ <BigNumberCaption>
+ <BigNumberCaptionText>{caption}</BigNumberCaptionText>
+ {onToggleCaption && captionToggleIcon ? (
+ <BigNumberCaptionToggle
+ type="button"
+ aria-label={toggleLabel}
+ title={toggleLabel}
+ onClick={event => {
+ event.stopPropagation();
+ onToggleCaption();
+ }}
+ >
+ {captionToggleIcon}
+ </BigNumberCaptionToggle>
+ ) : null}
+ </BigNumberCaption>
+ ) : onToggleCaption && captionToggleIcon ? (
+ <BigNumberCaption>
+ <BigNumberCaptionToggle
+ type="button"
+ aria-label={toggleLabel}
+ title={toggleLabel}
+ onClick={event => {
+ event.stopPropagation();
+ onToggleCaption();
+ }}
+ >
+ {captionToggleIcon}
+ </BigNumberCaptionToggle>
+ </BigNumberCaption>
+ ) : null}
+ </ChartWrap>
+ );
+}
+
+export function BarChartView({
+ bins,
+ horizontal = false,
+ selectedKey,
+ onSelect
+}: {
+ bins: ChartBin[];
+ horizontal?: boolean;
+ selectedKey?: string;
+ onSelect?: ClickHandler;
+}): React.ReactElement {
+ if (!bins.length) {
+ return (
+ <ChartWrap>
+ <EmptyState>Select a category field to plot this chart.</EmptyState>
+ </ChartWrap>
+ );
+ }
+ const max = maxValue(bins);
+
+ if (!horizontal) {
+ const {rotated, labelBand, padRight, gap} = getVerticalBarLabelLayout(bins);
+ return (
+ <ChartWrap className="bar-chart">
+ <VerticalBarChart $padRight={padRight} $gap={gap}>
+ <VerticalBarBars>
+ {bins.map(bin => {
+ const activate = onSelect
+ ? () => onSelect(String(bin.key), {filterValue: bin.filterValue})
+ : undefined;
+ const selected = selectedKey === String(bin.key);
+ return (
+ <VerticalBarCol
+ key={bin.key}
+ $clickable={Boolean(activate)}
+ $selected={selected}
+ role={activate ? 'button' : undefined}
+ tabIndex={activate ? 0 : undefined}
+ aria-pressed={activate ? selected : undefined}
+ aria-label={`${displayBinKey(String(bin.key))}: ${formatNumber(bin.value)}`}
+ onClick={activate}
+ onKeyDown={event => onActivateKey(event, activate)}
+ >
+ <VerticalBarValue>{formatNumber(bin.value)}</VerticalBarValue>
+ <VerticalBarTrack $selected={selected}>
+ <VerticalBarFill
+ $color={bin.color}
+ $height={(bin.value / max) * 100}
+ $active={selected}
+ $dimmed={Boolean(selectedKey) && !selected}
+ />
+ </VerticalBarTrack>
+ </VerticalBarCol>
+ );
+ })}
+ </VerticalBarBars>
+ <VerticalBarLabels $height={labelBand} $rotated={rotated}>
+ {bins.map(bin => (
+ <VerticalBarLabelCell key={`label-${bin.key}`} $rotated={rotated}>
+ <VerticalBarLabel $rotated={rotated}>
+ {displayBinKey(String(bin.key))}
+ </VerticalBarLabel>
+ </VerticalBarLabelCell>
+ ))}
+ </VerticalBarLabels>
+ </VerticalBarChart>
+ </ChartWrap>
+ );
+ }
+
+ return (
+ <ChartWrap className="horizontal-bar-chart">
+ {bins.map(bin => {
+ const activate = onSelect
+ ? () => onSelect(String(bin.key), {filterValue: bin.filterValue})
+ : undefined;
+ const selected = selectedKey === String(bin.key);
+ return (
+ <BarRow
+ key={bin.key}
+ $clickable={Boolean(activate)}
+ $selected={selected}
+ role={activate ? 'button' : undefined}
+ tabIndex={activate ? 0 : undefined}
+ aria-pressed={activate ? selected : undefined}
+ aria-label={`${displayBinKey(String(bin.key))}: ${formatNumber(bin.value)}`}
+ onClick={activate}
+ onKeyDown={event => onActivateKey(event, activate)}
+ >
+ <BarLabel>{displayBinKey(String(bin.key))}</BarLabel>
+ <BarTrack $selected={selected}>
+ <BarFill
+ $color={bin.color}
+ $width={(bin.value / max) * 100}
+ $active={selected}
+ $dimmed={Boolean(selectedKey) && !selected}
+ />
+ </BarTrack>
+ <BarValue>{formatNumber(bin.value)}</BarValue>
+ </BarRow>
+ );
+ })}
+ </ChartWrap>
+ );
+}
+
+function niceTicks(min: number, max: number, count = 4): number[] {
+ if (!(max > min)) {
+ return [min];
+ }
+ const span = max - min;
+ const step = span / Math.max(1, count - 1);
+ const ticks: number[] = [];
+ for (let i = 0; i < count; i++) {
+ ticks.push(min + step * i);
+ }
+ return ticks;
+}
+
+function sampleBinIndexes(length: number, count = 4): number[] {
+ if (length <= 0) {
+ return [];
+ }
+ if (length <= count) {
+ return Array.from({length}, (_, i) => i);
+ }
+ const indexes = new Set<number>();
+ for (let i = 0; i < count; i++) {
+ indexes.add(Math.round((i * (length - 1)) / (count - 1)));
+ }
+ return Array.from(indexes).sort((a, b) => a - b);
+}
+
+function shortenAxisLabel(label: string, maxLen = 12): string {
+ const text = String(label);
+ if (text.length <= maxLen) {
+ return text;
+ }
+ // Prefer date-looking prefixes when present.
+ const dateMatch = text.match(/^\d{4}-\d{2}-\d{2}/);
+ if (dateMatch) {
+ return dateMatch[0];
+ }
+ return `${text.slice(0, maxLen - 1)}…`;
+}
+
+export function LineChartView({
+ bins,
+ xLabel,
+ yLabel,
+ selectedKey,
+ onSelect
+}: {
+ bins: ChartBin[];
+ xLabel?: string;
+ yLabel?: string;
+ selectedKey?: string;
+ onSelect?: ClickHandler;
+}): React.ReactElement {
+ if (bins.length < 2) {
+ return (
+ <ChartWrap>
+ <EmptyState>Need at least two points for a line chart.</EmptyState>
+ </ChartWrap>
+ );
+ }
+ const values = bins.map(b => b.value);
+ const max = Math.max(...values);
+ const min = Math.min(...values);
+ const span = Math.max(1e-9, max - min);
+ const plotW = LINE_CHART_WIDTH - LINE_MARGIN.left - LINE_MARGIN.right;
+ const plotH = LINE_CHART_HEIGHT - LINE_MARGIN.top - LINE_MARGIN.bottom;
+ const points = bins.map((bin, i) => {
+ const x = LINE_MARGIN.left + (i / (bins.length - 1)) * plotW;
+ const y = LINE_MARGIN.top + (1 - (bin.value - min) / span) * plotH;
+ return `${x},${y}`;
+ });
+ const yTicks = niceTicks(min, max, 4);
+ const xIndexes = sampleBinIndexes(bins.length, Math.min(4, bins.length));
+ const stroke = bins[0].color || '#1F71C5';
+
+ return (
+ <ChartWrap>
+ <LineSvg
+ viewBox={`0 0 ${LINE_CHART_WIDTH} ${LINE_CHART_HEIGHT}`}
+ preserveAspectRatio="xMidYMid meet"
+ >
+ {/* Plot frame */}
+ <rect
+ x={LINE_MARGIN.left}
+ y={LINE_MARGIN.top}
+ width={plotW}
+ height={plotH}
+ fill="none"
+ stroke="currentColor"
+ strokeOpacity={0.15}
+ strokeWidth={1}
+ />
+ {/* Y grid + ticks */}
+ {yTicks.map(tick => {
+ const y = LINE_MARGIN.top + (1 - (tick - min) / span) * plotH;
+ return (
+ <g key={`y-${tick}`}>
+ <line
+ x1={LINE_MARGIN.left}
+ x2={LINE_MARGIN.left + plotW}
+ y1={y}
+ y2={y}
+ stroke="currentColor"
+ strokeOpacity={0.08}
+ strokeWidth={1}
+ />
+ <text
+ x={LINE_MARGIN.left - 4}
+ y={y}
+ textAnchor="end"
+ dominantBaseline="middle"
+ fill="currentColor"
+ opacity={0.9}
+ fontSize={9}
+ >
+ {formatNumber(tick)}
+ </text>
+ </g>
+ );
+ })}
+ {/* X ticks */}
+ {xIndexes.map(index => {
+ const x = LINE_MARGIN.left + (index / (bins.length - 1)) * plotW;
+ return (
+ <g key={`x-${index}`}>
+ <line
+ x1={x}
+ x2={x}
+ y1={LINE_MARGIN.top + plotH}
+ y2={LINE_MARGIN.top + plotH + 4}
+ stroke="currentColor"
+ strokeOpacity={0.35}
+ strokeWidth={1}
+ />
+ <text
+ x={x}
+ y={LINE_MARGIN.top + plotH + 14}
+ textAnchor="middle"
+ fill="currentColor"
+ opacity={0.9}
+ fontSize={9}
+ >
+ {shortenAxisLabel(displayBinKey(String(bins[index].key)))}
+ </text>
+ </g>
+ );
+ })}
+ <polyline
+ fill="none"
+ stroke={stroke}
+ strokeWidth={1.25}
+ strokeLinejoin="round"
+ strokeLinecap="round"
+ points={points.join(' ')}
+ />
+ {bins.map((bin, i) => {
+ const x = LINE_MARGIN.left + (i / (bins.length - 1)) * plotW;
+ const y = LINE_MARGIN.top + (1 - (bin.value - min) / span) * plotH;
+ const selected = selectedKey === String(bin.key);
+ const activate = onSelect
+ ? () => onSelect(String(bin.key), {filterValue: bin.filterValue})
+ : undefined;
+ return (
+ <g
+ key={`pt-${bin.key}`}
+ role={activate ? 'button' : undefined}
+ tabIndex={activate ? 0 : undefined}
+ aria-pressed={activate ? selected : undefined}
+ aria-label={`${displayBinKey(String(bin.key))}: ${formatNumber(bin.value)}`}
+ onClick={activate}
+ onKeyDown={event => onActivateKey(event, activate)}
+ >
+ {selected ? <LineSelectedRing cx={x} cy={y} r={LINE_POINT_RING_R} /> : null}
+ <circle
+ cx={x}
+ cy={y}
+ r={selected ? LINE_POINT_SELECTED_R : activate ? LINE_POINT_R : 0}
+ fill={stroke}
+ stroke={selected ? '#fff' : 'none'}
+ strokeWidth={selected ? 1 : 0}
+ pointerEvents="none"
+ />
+ {activate ? <LinePointHit cx={x} cy={y} r={LINE_POINT_HIT_R} $clickable /> : null}
+ </g>
+ );
+ })}
+ {/* Axis names */}
+ {yLabel ? (
+ <text
+ x={LINE_Y_AXIS_TITLE_X}
+ y={LINE_MARGIN.top + plotH / 2}
+ textAnchor="middle"
+ fill="currentColor"
+ opacity={1}
+ fontSize={10}
+ transform={`rotate(-90 ${LINE_Y_AXIS_TITLE_X} ${LINE_MARGIN.top + plotH / 2})`}
+ >
+ {shortenAxisLabel(yLabel, 18)}
+ </text>
+ ) : null}
+ {xLabel ? (
+ <text
+ x={LINE_MARGIN.left + plotW / 2}
+ y={LINE_CHART_HEIGHT - 4}
+ textAnchor="middle"
+ fill="currentColor"
+ opacity={1}
+ fontSize={10}
+ >
+ {shortenAxisLabel(xLabel, 24)}
+ </text>
+ ) : null}
+ </LineSvg>
+ </ChartWrap>
+ );
+}
+
+function heatColorIndex(value: number, max: number, steps: number): number {
+ if (!(max > 0) || !(value > 0) || steps <= 1) {
+ return 0;
+ }
+ const t = Math.min(1, Math.max(0, value / max));
+ return Math.min(steps - 1, Math.floor(t * steps));
+}
+
+function heatColor(value: number, max: number, colors: string[]): string {
+ if (!(value > 0)) {
+ return 'transparent';
+ }
+ const steps = Math.max(2, colors.length);
+ return colors[heatColorIndex(value, max, steps)] || colors[0];
+}
+
+/** Light text on dark/saturated cells; dark text on pale cells. */
+function heatLabelColor(value: number, max: number, colors: string[]): string {
+ if (!(value > 0)) {
+ return 'rgba(128, 128, 128, 0.55)';
+ }
+ const hex = heatColor(value, max, colors);
+ const match = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
+ if (!match) {
+ return 'rgba(0, 0, 0, 0.85)';
+ }
+ const r = parseInt(match[1], 16);
+ const g = parseInt(match[2], 16);
+ const b = parseInt(match[3], 16);
+ const luminance = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 255;
+ return luminance > 0.55 ? 'rgba(0, 0, 0, 0.85)' : 'rgba(255, 255, 255, 0.95)';
+}
+
+export function HeatmapView({
+ cells,
+ colors,
+ xLabel,
+ yLabel,
+ selectedKey,
+ onSelect
+}: {
+ cells: HeatmapCell[];
+ colors?: string[];
+ xLabel?: string;
+ yLabel?: string;
+ selectedKey?: string;
+ onSelect?: ClickHandler;
+}): React.ReactElement {
+ const [hovered, setHovered] = React.useState<{x: string; y: string} | null>(null);
+ const palette =
+ colors && colors.length >= 2 ? colors : HEATMAP_COLORS.slice(0, HEATMAP_COLOR_STEPS);
+
+ if (!cells.length) {
+ return (
+ <ChartWrap>
+ <EmptyState>Select X and Y fields to plot this heatmap.</EmptyState>
+ </ChartWrap>
+ );
+ }
+ const xs = Array.from(new Set(cells.map(c => c.x)));
+ const ys = Array.from(new Set(cells.map(c => c.y)));
+ const max = Math.max(1, ...cells.map(c => c.value));
+ const lookup = new Map(cells.map(c => [`${c.x}|${c.y}`, c]));
+ const hasHover = Boolean(hovered);
+ const maxHeaderLen = Math.max(1, ...xs.map(x => displayBinKey(String(x)).length));
+ const maxSideLen = Math.max(1, ...ys.map(y => displayBinKey(String(y)).length));
+ const sin = Math.sin((LABEL_ROTATE_DEG * Math.PI) / 180);
+ const cos = Math.cos((LABEL_ROTATE_DEG * Math.PI) / 180);
+ // Tighter band than bars: smaller char width + less padding; labels may clip slightly.
+ const heatCharW = 4.2;
+ const headerHeight = Math.max(16, Math.ceil(Math.min(maxHeaderLen, 12) * heatCharW * sin + 4));
+ const sideWidth = Math.max(
+ 14,
+ Math.ceil(Math.min(maxSideLen, 12) * heatCharW * cos + 2),
+ // Keep Y axis title on one line in the left title slot.
+ yLabel ? Math.ceil(String(yLabel).length * 5.2) : 0
+ );
+ return (
+ <HeatChartWrap>
+ {xLabel || yLabel ? (
+ <HeatAxisTitles $sideWidth={sideWidth}>
+ <HeatAxisTitle $align="right" title={yLabel}>
+ {yLabel || null}
+ </HeatAxisTitle>
+ <HeatAxisTitle $align="center" title={xLabel}>
+ {xLabel ? shortenAxisLabel(xLabel, 28) : null}
+ </HeatAxisTitle>
+ </HeatAxisTitles>
+ ) : null}
+ <HeatGrid
+ $cols={xs.length}
+ $rows={ys.length}
+ $sideWidth={sideWidth}
+ $headerHeight={headerHeight}
+ onMouseLeave={() => setHovered(null)}
+ >
+ <HeatCorner />
+ {xs.map(x => (
+ <HeatLabel
+ key={`h-${x}`}
+ $header
+ $rotated
+ $active={hovered?.x === x}
+ title={displayBinKey(String(x))}
+ >
+ <HeatLabelText $header $rotated>
+ {shortenAxisLabel(displayBinKey(String(x)), 12)}
+ </HeatLabelText>
+ </HeatLabel>
+ ))}
+ {ys.map(y => (
+ <React.Fragment key={`r-${y}`}>
+ <HeatLabel $rotated title={displayBinKey(String(y))} $active={hovered?.y === y}>
+ <HeatLabelText $rotated>
+ {shortenAxisLabel(displayBinKey(String(y)), 12)}
+ </HeatLabelText>
+ </HeatLabel>
+ {xs.map(x => {
+ const cellKey = `${x}|${y}`;
+ const cell = lookup.get(cellKey);
+ const value = cell?.value ?? 0;
+ const label = formatNumber(value);
+ const isSelected = selectedKey === cellKey;
+ const isHovered = hovered?.x === x && hovered?.y === y;
+ const activate = onSelect
+ ? () =>
+ onSelect(cellKey, {
+ x,
+ y,
+ filterValue: cell?.filterValueX,
+ filterValueY: cell?.filterValueY
+ })
+ : undefined;
+ return (
+ <HeatCell
+ key={cellKey}
+ $bg={heatColor(value, max, palette)}
+ $fg={heatLabelColor(value, max, palette)}
+ $clickable={Boolean(activate)}
+ $dimmed={hasHover && !isHovered && !isSelected}
+ $selected={isSelected}
+ role={activate ? 'button' : undefined}
+ tabIndex={activate ? 0 : undefined}
+ aria-label={`${x} / ${y}: ${label}`}
+ aria-pressed={isSelected || undefined}
+ title={`${x} / ${y}: ${label}`}
+ onMouseEnter={() => setHovered({x, y})}
+ onClick={activate}
+ onKeyDown={event => onActivateKey(event, activate)}
+ >
+ {label}
+ </HeatCell>
+ );
+ })}
+ </React.Fragment>
+ ))}
+ </HeatGrid>
+ </HeatChartWrap>
+ );
+}
+
+export function PivotTableView({
+ table,
+ xLabel,
+ yLabel
+}: {
+ table: PivotTableResult;
+ xLabel?: string;
+ yLabel?: string;
+}): React.ReactElement {
+ if (!table.rowKeys.length || !table.columnKeys.length) {
+ return (
+ <ChartWrap>
+ <EmptyState>Select row and column fields for the pivot table.</EmptyState>
+ </ChartWrap>
+ );
+ }
+ const maxRowLen = Math.max(1, ...table.rowKeys.map(r => displayBinKey(String(r)).length));
+ const sideWidth = Math.max(
+ 48,
+ Math.ceil(Math.min(maxRowLen, 18) * 6.2 + 8),
+ yLabel ? Math.ceil(String(yLabel).length * 5.2) : 0
+ );
+ return (
+ <PivotChartWrap>
+ {xLabel || yLabel ? (
+ <HeatAxisTitles $sideWidth={sideWidth}>
+ <HeatAxisTitle $align="right" title={yLabel}>
+ {yLabel || null}
+ </HeatAxisTitle>
+ <HeatAxisTitle $align="center" title={xLabel}>
+ {xLabel || null}
+ </HeatAxisTitle>
+ </HeatAxisTitles>
+ ) : null}
+ <PivotTableScroll>
+ <PivotTableEl>
+ <thead>
+ <tr>
+ <th />
+ {table.columnKeys.map(col => (
+ <th key={col} title={displayBinKey(String(col))}>
+ {displayBinKey(String(col))}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {table.rowKeys.map(row => (
+ <tr key={row}>
+ <td title={displayBinKey(String(row))}>{displayBinKey(String(row))}</td>
+ {table.columnKeys.map(col => (
+ <td key={col}>{formatNumber(table.values[row]?.[col] ?? 0)}</td>
+ ))}
+ </tr>
+ ))}
+ </tbody>
+ </PivotTableEl>
+ </PivotTableScroll>
+ </PivotChartWrap>
+ );
+}
+
+export function ChartRenderer({
+ data,
+ selectedKey,
+ onSelect,
+ showCaption,
+ onToggleCaption,
+ captionToggleIcon,
+ captionToggleLabel
+}: {
+ data: ChartViewData;
+ selectedKey?: string;
+ onSelect?: ClickHandler;
+ showCaption?: boolean;
+ onToggleCaption?: () => void;
+ captionToggleIcon?: React.ReactNode;
+ captionToggleLabel?: string;
+}): React.ReactElement {
+ switch (data.kind) {
+ case 'bigNumber':
+ return (
+ <BigNumberView
+ value={data.value}
+ caption={data.caption}
+ formattedValue={data.formattedValue}
+ showCaption={showCaption}
+ onToggleCaption={onToggleCaption}
+ captionToggleIcon={captionToggleIcon}
+ captionToggleLabel={captionToggleLabel}
+ />
+ );
+ case 'bars':
+ return (
+ <BarChartView
+ bins={data.bins}
+ horizontal={data.horizontal}
+ selectedKey={selectedKey}
+ onSelect={onSelect}
+ />
+ );
+ case 'line':
+ return (
+ <LineChartView
+ bins={data.bins}
+ xLabel={data.xLabel}
+ yLabel={data.yLabel}
+ selectedKey={selectedKey}
+ onSelect={onSelect}
+ />
+ );
+ case 'heatmap':
+ return (
+ <HeatmapView
+ cells={data.cells}
+ colors={data.colors}
+ xLabel={data.xLabel}
+ yLabel={data.yLabel}
+ selectedKey={selectedKey}
+ onSelect={onSelect}
+ />
+ );
+ case 'pivot':
+ return <PivotTableView table={data.table} xLabel={data.xLabel} yLabel={data.yLabel} />;
+ case 'empty':
+ default:
+ return (
+ <EmptyChartWrap>
+ <EmptyState>{data.kind === 'empty' ? data.message : undefined}</EmptyState>
+ </EmptyChartWrap>
+ );
+ }
+}
+
+export {EmptyState, ChartWrap};
diff --git a/src/charts/src/compute.ts b/src/charts/src/compute.ts
new file mode 100644
index 000000000..c8c9f2dc4
--- /dev/null
+++ b/src/charts/src/compute.ts
@@ -0,0 +1,353 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {
+ buildBigNumber,
+ buildGroupedBins,
+ buildHeatmapCells,
+ buildPivotTable,
+ buildTimeSeries
+} from './aggregation';
+import {
+ ChartType,
+ LayerChartType,
+ SortType,
+ BinType,
+ TIME_FIELD_TYPES,
+ ChartColorBy,
+ CHART_COLORS,
+ getDefaultHeatmapColorRange
+} from './constants';
+import {
+ ChartBin,
+ ChartConfig,
+ ChartableDataset,
+ ChartAxis,
+ DatasetChartConfig,
+ HeatmapCell,
+ LayerChartConfig,
+ PivotTableResult,
+ isLayerChartConfig
+} from './types';
+
+export type ChartViewData =
+ | {kind: 'empty'; message?: string}
+ | {
+ kind: 'bigNumber';
+ value: number;
+ caption?: string;
+ format?: string | null;
+ formattedValue?: string;
+ }
+ | {kind: 'bars'; bins: ChartBin[]; horizontal?: boolean}
+ | {kind: 'line'; bins: ChartBin[]; xLabel?: string; yLabel?: string}
+ | {kind: 'heatmap'; cells: HeatmapCell[]; colors?: string[]; xLabel?: string; yLabel?: string}
+ | {kind: 'pivot'; table: PivotTableResult; xLabel?: string; yLabel?: string};
+
+function axisTitle(axis?: ChartAxis, fallback = ''): string {
+ if (!axis) {
+ return fallback;
+ }
+ if (axis.title) {
+ return axis.title;
+ }
+ const fieldName = axis.field?.name;
+ if (!fieldName) {
+ return fallback;
+ }
+ const aggregation = axis.aggregation;
+ if (
+ !aggregation ||
+ aggregation === 'uniqueBin' ||
+ aggregation === 'numericBin' ||
+ aggregation === 'timeBin'
+ ) {
+ return fieldName;
+ }
+ return `${aggregation} of ${fieldName}`;
+}
+
+function isOrderedBinAxis(axis?: ChartAxis): boolean {
+ if (!axis?.field) {
+ return false;
+ }
+ const fieldType = axis.field.type;
+ return (
+ axis.aggregation === BinType.numericBin ||
+ axis.aggregation === BinType.timeBin ||
+ fieldType === 'real' ||
+ TIME_FIELD_TYPES.includes(fieldType || '')
+ );
+}
+
+function rgbCss(rgb?: number[]): string | undefined {
+ if (!rgb || rgb.length < 3) {
+ return undefined;
+ }
+ return `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;
+}
+
+function barColorOptions(
+ chart: DatasetChartConfig,
+ dataset: ChartableDataset
+): {color?: string; colors?: string[]} {
+ const colorBy = chart.colorBy ?? ChartColorBy.category;
+ if (colorBy === ChartColorBy.none) {
+ return {
+ color: rgbCss(chart.chartDisplay?.color) || rgbCss(dataset.color) || CHART_COLORS[0]
+ };
+ }
+ const palette = chart.chartDisplay?.colorRange?.colors;
+ return {
+ colors: Array.isArray(palette) && palette.length ? palette : CHART_COLORS
+ };
+}
+
+const hoverIdIndexCache = new WeakMap<number[], Map<string, Map<string, number[]>>>();
+
+function getIdRowIndex(dataset: ChartableDataset, idField: string): Map<string, number[]> {
+ const indexes = dataset.allIndexes;
+ let byField = hoverIdIndexCache.get(indexes);
+ if (!byField) {
+ byField = new Map();
+ hoverIdIndexCache.set(indexes, byField);
+ }
+ let index = byField.get(idField);
+ if (!index) {
+ index = new Map();
+ for (let i = 0; i < indexes.length; i++) {
+ const idx = indexes[i];
+ const value = dataset.getValue(idField, idx);
+ if (value === null || value === undefined || value === '') {
+ continue;
+ }
+ const key = String(value);
+ const rows = index.get(key);
+ if (rows) {
+ rows.push(idx);
+ } else {
+ index.set(key, [idx]);
+ }
+ }
+ byField.set(idField, index);
+ }
+ return index;
+}
+
+export function getHoverRowIndexes(
+ dataset: ChartableDataset,
+ chart: LayerChartConfig,
+ hoverRowIndex?: number | null
+): number[] {
+ if (hoverRowIndex === null || hoverRowIndex === undefined || hoverRowIndex < 0) {
+ return [];
+ }
+ const idField = chart.chartDisplay?.idField;
+ if (!idField) {
+ return [hoverRowIndex];
+ }
+ const id = dataset.getValue(idField, hoverRowIndex);
+ if (id === null || id === undefined || id === '') {
+ return [hoverRowIndex];
+ }
+ return getIdRowIndex(dataset, idField).get(String(id)) || [hoverRowIndex];
+}
+
+export function computeDatasetChart(
+ chart: DatasetChartConfig,
+ dataset: ChartableDataset | null
+): ChartViewData {
+ if (!dataset) {
+ return {kind: 'empty', message: 'Select a dataset to plot this chart.'};
+ }
+ switch (chart.type) {
+ case ChartType.bigNumber: {
+ const result = buildBigNumber({
+ dataset,
+ applyFilters: chart.applyFilters,
+ axis: chart.axis
+ });
+ return {
+ kind: 'bigNumber',
+ value: result.value,
+ format: chart.chartDisplay?.format ?? null,
+ caption: chart.axis?.field?.name
+ ? `${chart.axis.aggregation || 'count'} of ${chart.axis.field.name}`
+ : 'Count of rows'
+ };
+ }
+ case ChartType.barChart:
+ case ChartType.horizontalBar: {
+ const binAxis = chart.type === ChartType.horizontalBar ? chart.yAxis : chart.xAxis;
+ if (!binAxis?.field?.name) {
+ return {
+ kind: 'bars',
+ horizontal: chart.type === ChartType.horizontalBar,
+ bins: []
+ };
+ }
+ const ordered = isOrderedBinAxis(binAxis);
+ const {color, colors} = barColorOptions(chart, dataset);
+ return {
+ kind: 'bars',
+ horizontal: chart.type === ChartType.horizontalBar,
+ bins: buildGroupedBins({
+ dataset,
+ applyFilters: chart.applyFilters,
+ binAxis,
+ valueAxis: chart.type === ChartType.horizontalBar ? chart.xAxis : chart.yAxis,
+ groupByAxis: chart.groupBy,
+ numGroups: chart.numGroups,
+ groupOthers: ordered ? false : chart.groupOthers,
+ // Numeric/time bins stay in domain order; categories rank by value.
+ sort: ordered ? SortType.dataOrder : SortType.descending,
+ // Histogram/time bins already span the domain — do not top-N truncate.
+ truncate: !ordered,
+ color,
+ colors
+ })
+ };
+ }
+ case ChartType.lineChart: {
+ const xField = chart.xAxis?.field?.name;
+ if (xField && !dataset.fields.some(field => field.name === xField)) {
+ return {
+ kind: 'line',
+ bins: [],
+ xLabel: axisTitle(chart.xAxis, 'X'),
+ yLabel: axisTitle(chart.yAxis, 'Y')
+ };
+ }
+ const ordered = isOrderedBinAxis(chart.xAxis);
+ const interval = chart.xAxis?.interval ?? chart.chartDisplay?.interval ?? null;
+ const binAxis = chart.xAxis ? {...chart.xAxis, interval: interval || undefined} : chart.xAxis;
+ return {
+ kind: 'line',
+ // Line charts plot a full series; do not apply the categorical top-N
+ // truncation used by bar charts (DEFAULT_NUM_GROUPS = 10).
+ // Datetime X uses period grouping (auto hour/day/week/month/year).
+ bins: buildGroupedBins({
+ dataset,
+ applyFilters: chart.applyFilters,
+ binAxis,
+ valueAxis: chart.yAxis,
+ groupByAxis: chart.groupBy,
+ numGroups: 0,
+ sort: ordered ? SortType.dataOrder : SortType.alphaAsc
+ }),
+ xLabel: axisTitle(chart.xAxis, 'X'),
+ yLabel: axisTitle(chart.yAxis, 'Y')
+ };
+ }
+ case ChartType.heatmapChart: {
+ const palette = chart.chartDisplay?.colorRange?.colors;
+ const colors =
+ Array.isArray(palette) && palette.length >= 2
+ ? palette
+ : getDefaultHeatmapColorRange().colors;
+ return {
+ kind: 'heatmap',
+ cells: buildHeatmapCells({
+ dataset,
+ applyFilters: chart.applyFilters,
+ xAxis: chart.xAxis,
+ yAxis: chart.yAxis,
+ valueAxis: chart.value,
+ numGroups: chart.numGroups
+ }),
+ colors,
+ xLabel: axisTitle(chart.xAxis, 'X'),
+ yLabel: axisTitle(chart.yAxis, 'Y')
+ };
+ }
+ case ChartType.pivotTable:
+ return {
+ kind: 'pivot',
+ table: buildPivotTable({
+ dataset,
+ applyFilters: chart.applyFilters,
+ xAxis: chart.xAxis,
+ yAxis: chart.yAxis,
+ valueAxis: chart.value,
+ numGroups: chart.numGroups
+ }),
+ xLabel: axisTitle(chart.xAxis, 'X'),
+ yLabel: axisTitle(chart.yAxis, 'Y')
+ };
+ default:
+ return {kind: 'empty'};
+ }
+}
+
+export function computeLayerChart(
+ chart: LayerChartConfig,
+ dataset: ChartableDataset | null,
+ hoverIndexes: number[]
+): ChartViewData {
+ if (!dataset) {
+ return {kind: 'empty'};
+ }
+ if (!hoverIndexes.length) {
+ return {kind: 'empty', message: 'Hover a feature to see this chart.'};
+ }
+ if (chart.layerChartType === LayerChartType.TIME_SERIES) {
+ return {
+ kind: 'line',
+ bins: buildTimeSeries({
+ dataset,
+ indexes: hoverIndexes,
+ xAxis: chart.xAxis,
+ yAxis: chart.yAxis,
+ interval: chart.xAxis?.interval || chart.chartDisplay?.interval
+ })
+ };
+ }
+ return {
+ kind: 'bars',
+ bins: buildGroupedBins({
+ dataset,
+ applyFilters: false,
+ indexes: hoverIndexes,
+ binAxis: chart.axis,
+ valueAxis: chart.yAxis,
+ numGroups: chart.chartDisplay?.numEntries ?? 5,
+ sort: SortType.descending
+ })
+ };
+}
+
+export function computeChart(
+ chart: ChartConfig,
+ dataset: ChartableDataset | null,
+ hoverIndexes?: number[]
+): ChartViewData {
+ if (isLayerChartConfig(chart)) {
+ return computeLayerChart(chart, dataset, hoverIndexes || []);
+ }
+ return computeDatasetChart(chart, dataset);
+}
+
+export function getCrossFilterField(chart: ChartConfig): string | null {
+ return getCrossFilterFields(chart)[0] ?? null;
+}
+
+/** Fields that a chart click should drive as map filters (heatmap uses X and Y). */
+export function getCrossFilterFields(chart: ChartConfig): string[] {
+ if (isLayerChartConfig(chart)) {
+ return [];
+ }
+ if (chart.type === ChartType.horizontalBar) {
+ return chart.yAxis?.field?.name ? [chart.yAxis.field.name] : [];
+ }
+ if (chart.type === ChartType.heatmapChart) {
+ const fields: string[] = [];
+ if (chart.xAxis?.field?.name) {
+ fields.push(chart.xAxis.field.name);
+ }
+ if (chart.yAxis?.field?.name && chart.yAxis.field.name !== chart.xAxis?.field?.name) {
+ fields.push(chart.yAxis.field.name);
+ }
+ return fields;
+ }
+ return chart.xAxis?.field?.name ? [chart.xAxis.field.name] : [];
+}
diff --git a/src/charts/src/constants.ts b/src/charts/src/constants.ts
new file mode 100644
index 000000000..44b5bff1c
--- /dev/null
+++ b/src/charts/src/constants.ts
@@ -0,0 +1,207 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+export const CHART_ID_LENGTH = 6;
+
+export const CHART_AGGREGATIONS = [
+ 'count',
+ 'sum',
+ 'average',
+ 'maximum',
+ 'minimum',
+ 'median',
+ 'stdev',
+ 'variance',
+ 'p05',
+ 'p25',
+ 'p50',
+ 'p75',
+ 'p95',
+ 'mode',
+ 'countUnique'
+] as const;
+
+export const CHART_AGGREGATION_OPTIONS: {id: (typeof CHART_AGGREGATIONS)[number]; label: string}[] =
+ [
+ {id: 'count', label: 'Count'},
+ {id: 'sum', label: 'Sum'},
+ {id: 'average', label: 'Average'},
+ {id: 'maximum', label: 'Maximum'},
+ {id: 'minimum', label: 'Minimum'},
+ {id: 'median', label: 'Median'},
+ {id: 'stdev', label: 'Std Deviation'},
+ {id: 'variance', label: 'Variance'},
+ {id: 'p05', label: 'P05'},
+ {id: 'p25', label: 'P25'},
+ {id: 'p50', label: 'P50'},
+ {id: 'p75', label: 'P75'},
+ {id: 'p95', label: 'P95'},
+ {id: 'mode', label: 'Mode'},
+ {id: 'countUnique', label: 'Count Unique'}
+ ];
+
+/** Time-series period options. `auto` lets aggregation pick from the data span. */
+export const TIME_INTERVALS = ['auto', 'hour', 'day', 'week', 'month', 'year'] as const;
+export type TimeInterval = (typeof TIME_INTERVALS)[number];
+
+export const TIME_INTERVAL_OPTIONS: {id: TimeInterval; label: string}[] = [
+ {id: 'auto', label: 'Auto'},
+ {id: 'hour', label: 'Hour'},
+ {id: 'day', label: 'Day'},
+ {id: 'week', label: 'Week'},
+ {id: 'month', label: 'Month'},
+ {id: 'year', label: 'Year'}
+];
+
+export enum ChartType {
+ bigNumber = 'bigNumber',
+ barChart = 'barChart',
+ horizontalBar = 'horizontalBar',
+ lineChart = 'lineChart',
+ heatmapChart = 'heatmapChart',
+ pivotTable = 'pivotTable',
+ layerChart = 'layerChart'
+}
+
+export enum LayerChartType {
+ TIME_SERIES = 'TIME_SERIES',
+ BREAKDOWN_BY_CATEGORY = 'BREAKDOWN_BY_CATEGORY'
+}
+
+export enum BinType {
+ uniqueBin = 'uniqueBin',
+ numericBin = 'numericBin',
+ timeBin = 'timeBin'
+}
+
+export enum AxisType {
+ bin = 'bin',
+ aggregation = 'aggregation'
+}
+
+export enum SortType {
+ dataOrder = 'dataOrder',
+ ascending = 'ascending',
+ descending = 'descending',
+ alphaAsc = 'alphaAsc',
+ alphaDesc = 'alphaDesc'
+}
+
+export enum ChartColorBy {
+ none = 'none',
+ category = 'category'
+}
+
+export const DEFAULT_NUM_GROUPS = 10;
+/** Hard cap on line / time-series points after grouping. */
+export const MAX_CHART_POINTS = 1000;
+/** Discrete color steps for heatmap cell fills. */
+export const HEATMAP_COLOR_STEPS = 20;
+/** Third sequential palette in KEPLER_COLOR_PALETTES (Uber Viz Sequential, Global Warming, Sunrise, …). */
+export const DEFAULT_HEATMAP_COLOR_PALETTE = 'Sunrise';
+
+/** Control points from the Sunrise sequential palette (dark → light). */
+const HEATMAP_RGB_STOPS: Array<[number, number, number]> = [
+ [53, 92, 125], // #355C7D
+ [192, 108, 132], // #C06C84
+ [248, 177, 149] // #F8B195
+];
+
+function lerp(a: number, b: number, t: number): number {
+ return a + (b - a) * t;
+}
+
+function sampleHeatmapRgb(t: number): [number, number, number] {
+ const clamped = Math.min(1, Math.max(0, t));
+ const scaled = clamped * (HEATMAP_RGB_STOPS.length - 1);
+ const i = Math.min(HEATMAP_RGB_STOPS.length - 2, Math.floor(scaled));
+ const local = scaled - i;
+ const a = HEATMAP_RGB_STOPS[i];
+ const b = HEATMAP_RGB_STOPS[i + 1];
+ return [
+ Math.round(lerp(a[0], b[0], local)),
+ Math.round(lerp(a[1], b[1], local)),
+ Math.round(lerp(a[2], b[2], local))
+ ];
+}
+
+function rgbToHex(rgb: [number, number, number]): string {
+ return `#${rgb.map(c => c.toString(16).padStart(2, '0')).join('')}`;
+}
+
+/** Sunrise sequential palette sampled to HEATMAP_COLOR_STEPS. */
+export const HEATMAP_COLORS: string[] = Array.from({length: HEATMAP_COLOR_STEPS}, (_, i) =>
+ rgbToHex(sampleHeatmapRgb(i / Math.max(1, HEATMAP_COLOR_STEPS - 1)))
+);
+export const OTHERS_KEY = 'Other';
+
+export const CHART_COLORS = [
+ '#12939A',
+ '#DDB27C',
+ '#88572C',
+ '#FF991F',
+ '#F15C17',
+ '#223F9A',
+ '#DA70BF',
+ '#125C77',
+ '#4DC19C',
+ '#776E57',
+ '#17B8BE',
+ '#F6D18A',
+ '#B7885E',
+ '#FFCB99',
+ '#F89570'
+];
+
+export const CHART_COLOR_BY_OPTIONS: {id: ChartColorBy; label: string}[] = [
+ {id: ChartColorBy.none, label: 'Single color'},
+ {id: ChartColorBy.category, label: 'Category'}
+];
+
+export function getDefaultChartColorRange(steps = DEFAULT_NUM_GROUPS): {
+ name: string;
+ type: string;
+ category: string;
+ colors: string[];
+} {
+ const colors = Array.from(
+ {length: Math.max(2, steps)},
+ (_, i) => CHART_COLORS[i % CHART_COLORS.length]
+ );
+ return {
+ name: 'Chart Colors',
+ type: 'ordinal',
+ category: 'Uber',
+ colors
+ };
+}
+
+/** Default sequential palette for heatmap charts (Sunrise, 20 steps). */
+export function getDefaultHeatmapColorRange(): {
+ name: string;
+ type: string;
+ category: string;
+ colors: string[];
+} {
+ return {
+ name: DEFAULT_HEATMAP_COLOR_PALETTE,
+ type: 'sequential',
+ category: 'Uber',
+ colors: HEATMAP_COLORS.slice(0, HEATMAP_COLOR_STEPS)
+ };
+}
+
+export const NUMERIC_FIELD_TYPES = ['integer', 'real'];
+export const CATEGORICAL_FIELD_TYPES = ['string', 'boolean', 'integer'];
+export const TIME_FIELD_TYPES = ['timestamp', 'date'];
+
+export const DEFAULT_CHART_TYPE_OPTIONS: {id: ChartType | LayerChartType; label: string}[] = [
+ {id: ChartType.bigNumber, label: 'Big Number'},
+ {id: ChartType.barChart, label: 'Bar'},
+ {id: ChartType.horizontalBar, label: 'Horizontal Bar'},
+ {id: ChartType.lineChart, label: 'Line'},
+ {id: ChartType.heatmapChart, label: 'Heatmap'},
+ {id: ChartType.pivotTable, label: 'Pivot Table'},
+ {id: LayerChartType.BREAKDOWN_BY_CATEGORY, label: 'Tooltip: Category'},
+ {id: LayerChartType.TIME_SERIES, label: 'Tooltip: Time Series'}
+];
diff --git a/src/charts/src/dataset.ts b/src/charts/src/dataset.ts
new file mode 100644
index 000000000..98355f18a
--- /dev/null
+++ b/src/charts/src/dataset.ts
@@ -0,0 +1,31 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {ChartableDataset} from './types';
+
+/**
+ * Adapt a KeplerTable-like dataset to the chart aggregation interface.
+ * Pass `filteredIndex` to override the table's CPU-only filteredIndex (e.g. with
+ * GPU range/time filters applied the same way map layers do).
+ */
+export function toChartableDataset(
+ dataset: any,
+ options?: {filteredIndex?: number[]}
+): ChartableDataset | null {
+ if (!dataset?.id || typeof dataset.getValue !== 'function') {
+ return null;
+ }
+ const fields = dataset.fields || [];
+ const fieldNames = new Set(fields.map(field => field.name));
+ return {
+ id: dataset.id,
+ label: dataset.label,
+ color: dataset.color,
+ allIndexes: dataset.allIndexes || [],
+ filteredIndex: options?.filteredIndex ?? dataset.filteredIndex ?? dataset.allIndexes ?? [],
+ fields,
+ // KeplerTable.getValue logs (and can freeze the tab) when the field is missing.
+ getValue: (fieldName, rowIdx) =>
+ fieldNames.has(fieldName) ? dataset.getValue(fieldName, rowIdx) : null
+ };
+}
diff --git a/src/charts/src/index.ts b/src/charts/src/index.ts
new file mode 100644
index 000000000..d0c7bde98
--- /dev/null
+++ b/src/charts/src/index.ts
@@ -0,0 +1,10 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+export * from './constants';
+export * from './types';
+export * from './aggregation';
+export * from './builders';
+export * from './chart-views';
+export * from './dataset';
+export * from './compute';
diff --git a/src/charts/src/types.ts b/src/charts/src/types.ts
new file mode 100644
index 000000000..7fa753418
--- /dev/null
+++ b/src/charts/src/types.ts
@@ -0,0 +1,65 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {ChartConfig, LayerChartConfig} from '@kepler.gl/types';
+
+import {ChartType} from './constants';
+
+export type {
+ ChartAggregation,
+ ChartAxisField,
+ ChartAxis,
+ ChartCrossFilter,
+ BaseChartConfig,
+ DatasetChartConfig,
+ LayerChartConfig,
+ ChartConfig
+} from '@kepler.gl/types';
+
+export type ChartableDataset = {
+ id: string;
+ label?: string;
+ color?: [number, number, number];
+ allIndexes: number[];
+ filteredIndex: number[];
+ fields: Array<{name: string; displayName?: string; type: string; fieldIdx?: number}>;
+ getValue: (fieldName: string, rowIdx: number) => any;
+};
+
+export type ChartBin = {
+ key: string;
+ value: number;
+ count: number;
+ color: string;
+ /**
+ * Value to apply when cross-filtering from this bin. For numeric/time bins this
+ * is a `[min, max]` range; for categories it is `[key]`; for booleans `[true]`/`[false]`.
+ */
+ filterValue?: Array<string | number | boolean>;
+ series?: ChartBin[];
+};
+
+export type ChartSeriesPoint = {
+ x: string | number;
+ y: number;
+};
+
+export type HeatmapCell = {
+ x: string;
+ y: string;
+ value: number;
+ /** Numeric/time `[min, max]`, categorical `[key]`, or boolean `[true]`/`[false]` for the X bin. */
+ filterValueX?: Array<string | number | boolean>;
+ /** Numeric/time `[min, max]`, categorical `[key]`, or boolean `[true]`/`[false]` for the Y bin. */
+ filterValueY?: Array<string | number | boolean>;
+};
+
+export type PivotTableResult = {
+ rowKeys: string[];
+ columnKeys: string[];
+ values: Record<string, Record<string, number>>;
+};
+
+export function isLayerChartConfig(chart: ChartConfig): chart is LayerChartConfig {
+ return chart.type === ChartType.layerChart;
+}
diff --git a/src/charts/tsconfig.production.json b/src/charts/tsconfig.production.json
new file mode 100644
index 000000000..5f999e9a1
--- /dev/null
+++ b/src/charts/tsconfig.production.json
@@ -0,0 +1,29 @@
+{
+ "compilerOptions": {
+ "target": "es2020",
+ "allowJs": false,
+ "checkJs": false,
+ "jsx": "react",
+ "module": "esnext",
+ "moduleResolution": "node",
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "noImplicitAny": false,
+ "noImplicitReturns": true,
+ "noImplicitThis": true,
+ "noUnusedLocals": true,
+ "outDir": "dist",
+ "sourceMap": true,
+ "strictNullChecks": true,
+ "suppressImplicitAnyIndexErrors": false,
+ "esModuleInterop": true,
+ "allowSyntheticDefaultImports": true,
+ "skipLibCheck": true,
+ "strict": true,
+ "resolveJsonModule": true,
+ "isolatedModules": true,
+ "baseUrl": "./src"
+ },
+ "include": ["src", "../styles/src/styled.d.ts"],
+ "exclude": ["**/*.spec.*"]
+}
diff --git a/src/components/package.json b/src/components/package.json
index e1578a24a..e361dd631 100644
--- a/src/components/package.json
+++ b/src/components/package.json
@@ -41,6 +41,7 @@
"@hubble.gl/core": "2.0.0-alpha.4",
"@hubble.gl/react": "2.0.0-alpha.4",
"@kepler.gl/actions": "3.3.0-alpha.13",
+ "@kepler.gl/charts": "3.3.0-alpha.13",
"@kepler.gl/cloud-providers": "3.3.0-alpha.13",
"@kepler.gl/common-utils": "3.3.0-alpha.13",
"@kepler.gl/constants": "3.3.0-alpha.13",
@@ -148,6 +149,12 @@
"require": "./dist/cjs/index.js",
"default": "./dist/cjs/index.js"
},
+ "./charts": {
+ "types": "./dist/charts.d.ts",
+ "import": "./dist/esm/charts.js",
+ "require": "./dist/cjs/charts.js",
+ "default": "./dist/cjs/charts.js"
+ },
"./*": {
"types": "./dist/*.d.ts",
"import": "./dist/esm/*.js",
diff --git a/src/components/src/charts.ts b/src/components/src/charts.ts
new file mode 100644
index 000000000..afa92c0f6
--- /dev/null
+++ b/src/components/src/charts.ts
@@ -0,0 +1,11 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+/**
+ * Chart panel factories. Import these from `@kepler.gl/components/charts`
+ * (not the main `@kepler.gl/components` barrel) so apps that disable the charts
+ * panel never load `@kepler.gl/charts`.
+ */
+export {default as ChartManagerFactory} from './map/charts/chart-manager';
+export {default as ChartPanelContentFactory} from './map/charts/chart-panel';
+export {default as ChartTypeSelectorFactory} from './map/charts/chart-type-selector';
diff --git a/src/components/src/common/icons/pin.tsx b/src/components/src/common/icons/pin.tsx
index e4b94f860..85c540e58 100644
--- a/src/components/src/common/icons/pin.tsx
+++ b/src/components/src/common/icons/pin.tsx
@@ -4,23 +4,34 @@
import React, {Component} from 'react';
import Base, {BaseProps} from './base';
-export default class Pin extends Component<Partial<BaseProps>> {
+type PinProps = Partial<BaseProps> & {
+ /** When true, render a solid pin (active / pinned state). */
+ filled?: boolean;
+};
+
+export default class Pin extends Component<PinProps> {
static defaultProps = {
height: '16px',
viewBox: '0 0 24 24',
- predefinedClassName: 'data-ex-icons-pin'
+ predefinedClassName: 'data-ex-icons-pin',
+ filled: false
};
render() {
+ const {filled, ...rest} = this.props;
return (
<Base
- {...this.props}
- style={{fill: 'none', stroke: 'currentcolor'}}
+ {...rest}
+ style={
+ filled
+ ? {fill: 'currentColor', stroke: 'currentColor'}
+ : {fill: 'none', stroke: 'currentColor'}
+ }
strokeWidth="2"
strokeLinecap="round"
strokeLinejoin="round"
>
- <path d="M12 17v5" />
+ <path d="M12 17v5" fill="none" />
<path d="M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z" />
</Base>
);
diff --git a/src/components/src/index.ts b/src/components/src/index.ts
index 3568aa5dc..281ee1980 100644
--- a/src/components/src/index.ts
+++ b/src/components/src/index.ts
@@ -161,6 +161,7 @@ export {default as LayerHoverInfoFactory} from './map/layer-hover-info';
export {default as LazyTippy} from './map/lazy-tippy';
export {default as LocalePanelFactory} from './map/locale-panel';
export {default as ThemeToggleButtonFactory} from './map/theme-toggle-button';
+export {default as ChartControlFactory} from './map/charts/chart-control';
export {default as ViewportJsonEditorControlFactory} from './map/viewport-json-editor';
export {default as MapControlFactory} from './map/map-control';
export {default as MapNavigationControlFactory} from './map/map-navigation-control';
diff --git a/src/components/src/kepler-gl.tsx b/src/components/src/kepler-gl.tsx
index fcc27a393..50e151026 100644
--- a/src/components/src/kepler-gl.tsx
+++ b/src/components/src/kepler-gl.tsx
@@ -243,6 +243,7 @@ export const plotContainerSelector = (props: KeplerGLProps) => ({
ratio: props.uiState.exportImage.ratio,
resolution: props.uiState.exportImage.resolution,
legend: props.uiState.exportImage.legend,
+ charts: props.uiState.exportImage.charts,
center: props.uiState.exportImage.center,
imageSize: props.uiState.exportImage.imageSize,
escapeXhtmlForWebpack: props.uiState.exportImage.escapeXhtmlForWebpack,
diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsx
index 1207ff36a..81a484997 100644
--- a/src/components/src/map-container.tsx
+++ b/src/components/src/map-container.tsx
@@ -896,6 +896,8 @@ export default function MapContainerFactory(
setSelectedFeature={this.props.visStateActions.setSelectedFeature}
// @ts-ignore Argument of type 'Readonly<MapContainerProps>' is not assignable to parameter of type 'never'
featureCollection={this.featureCollectionSelector(this.props)}
+ charts={this.props.visState.charts}
+ datasets={datasets}
/>
)}
{layerHoverProp && (!layerPinnedProp || compareMode) && (
@@ -910,6 +912,8 @@ export default function MapContainerFactory(
setSelectedFeature={this.props.visStateActions.setSelectedFeature}
// @ts-ignore Argument of type 'Readonly<MapContainerProps>' is not assignable to parameter of type 'never'
featureCollection={this.featureCollectionSelector(this.props)}
+ charts={this.props.visState.charts}
+ datasets={datasets}
/>
)}
</ErrorBoundary>
@@ -1490,6 +1494,8 @@ export default function MapContainerFactory(
activeSidePanel={activeSidePanel}
splitMaps={this.props.visState.splitMaps}
onToggleLayerForMap={visStateActions.toggleLayerForMap}
+ charts={this.props.visState.charts}
+ visStateActions={visStateActions}
/>
)}
{isSplitSelector(this.props) && <Droppable containerId={containerId} />}
diff --git a/src/components/src/map/charts/chart-config-group.tsx b/src/components/src/map/charts/chart-config-group.tsx
new file mode 100644
index 000000000..81fe0e160
--- /dev/null
+++ b/src/components/src/map/charts/chart-config-group.tsx
@@ -0,0 +1,206 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useCallback, useEffect, useState} from 'react';
+import styled from 'styled-components';
+import classnames from 'classnames';
+import {FormattedMessage} from '@kepler.gl/localization';
+
+import {ArrowDownSmall, ArrowRight} from '../../common/icons';
+import {StyledConfigGroupHeader} from '../../side-panel/layer-panel/layer-config-group';
+
+export const ConfigUncollapsibleContent = styled.div.attrs({
+ className: 'chart-config-group__content__uncollapsible'
+})``;
+
+export const ChartConfigSection = styled.div`
+ margin-bottom: 6px;
+`;
+
+/**
+ * Compact label | control rows, matching Studio chart settings density.
+ */
+export const ChartConfigSectionWrapper = styled.div`
+ display: grid;
+ grid-template-columns: minmax(72px, 40%) 1fr;
+ align-items: center;
+ row-gap: 4px;
+ column-gap: 6px;
+ margin-bottom: 4px;
+
+ .item-selector {
+ height: 28px;
+ }
+ .item-selector__dropdown {
+ height: 26px;
+ }
+ .side-panel-panel__label {
+ line-height: 16px;
+ margin-bottom: 0;
+ }
+ .side-panel-section {
+ margin-bottom: 0;
+ }
+ input {
+ height: 28px;
+ }
+`;
+
+const StyledChartConfigGroup = styled.div`
+ padding-left: 14px;
+ margin-bottom: 10px;
+ cursor: auto;
+ position: relative;
+
+ .layer-config-group__header {
+ margin-bottom: 4px;
+ }
+
+ &.disabled {
+ opacity: 0.3;
+ pointer-events: none;
+ }
+
+ &.collapsed {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 8px;
+ margin-bottom: 0;
+ min-height: 28px;
+
+ .layer-config-group__header {
+ margin-bottom: 0;
+ /* Fixed label column so right-side controls share one start edge. */
+ flex: 0 0 80px;
+ width: 80px;
+ max-width: 80px;
+ }
+
+ .chart-config-group__label {
+ width: 100%;
+ }
+
+ .chart-config-group__label span {
+ width: 100%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ .chart-config-group__content {
+ flex: 1 1 auto;
+ min-width: 0;
+
+ & > *:not(.chart-config-group__content__uncollapsible) {
+ overflow: hidden;
+ max-height: 0;
+ margin: 0;
+ padding: 0;
+ border: 0;
+ }
+
+ .chart-config-group__content__uncollapsible {
+ width: 100%;
+ display: flex;
+ align-items: center;
+ min-width: 0;
+ }
+
+ .chart-config-group__content__uncollapsible > * {
+ margin-bottom: 0;
+ width: 100%;
+ min-width: 0;
+ }
+
+ /* Color swatch stays on the same row as the group label. */
+ .chart-config-group__content__uncollapsible .side-panel-section,
+ .chart-config-group__content__uncollapsible .color-selector {
+ margin-bottom: 0;
+ }
+ }
+ }
+`;
+
+const ConfigGroupContent = styled.div`
+ &.disabled {
+ opacity: 0.3;
+ pointer-events: none;
+ * {
+ pointer-events: none;
+ }
+ }
+`;
+
+const StyledChartConfigGroupLabel = styled.div`
+ line-height: 12px;
+ height: 28px;
+ display: flex;
+ align-items: center;
+ cursor: pointer;
+ position: relative;
+
+ .chart-config-group__label__prefix {
+ position: absolute;
+ display: flex;
+ align-items: center;
+ left: -16px;
+
+ svg {
+ color: ${props => props.theme.textColor};
+ }
+ }
+
+ span {
+ color: ${props => props.theme.textColor};
+ font-weight: 500;
+ letter-spacing: 0.2px;
+ text-transform: capitalize;
+ margin-left: 2px;
+ font-size: 11px;
+ width: 80px;
+ }
+`;
+
+type ChartConfigGroupProps = {
+ label: string;
+ defaultMessage?: string;
+ children?: React.ReactNode;
+ expanded?: boolean;
+ className?: string;
+};
+
+export const ChartConfigGroup: React.FC<ChartConfigGroupProps> = ({
+ label,
+ defaultMessage,
+ children,
+ className,
+ expanded = false
+}) => {
+ const [collapsed, setCollapsed] = useState(!expanded);
+ const onToggleCollapsed = useCallback(() => {
+ setCollapsed(prev => !prev);
+ }, []);
+
+ useEffect(() => {
+ setCollapsed(!expanded);
+ }, [expanded]);
+
+ return (
+ <StyledChartConfigGroup className={classnames(className ?? 'chart-config-group', {collapsed})}>
+ <StyledConfigGroupHeader onClick={onToggleCollapsed} collapsible>
+ <StyledChartConfigGroupLabel className="chart-config-group__label">
+ <div className="chart-config-group__label__prefix">
+ {collapsed ? <ArrowRight height="12px" /> : <ArrowDownSmall height="12px" />}
+ </div>
+ <span>
+ <FormattedMessage id={label} defaultMessage={defaultMessage || label} />
+ </span>
+ </StyledChartConfigGroupLabel>
+ </StyledConfigGroupHeader>
+ <ConfigGroupContent className="chart-config-group__content">{children}</ConfigGroupContent>
+ </StyledChartConfigGroup>
+ );
+};
+
+export default ChartConfigGroup;
diff --git a/src/components/src/map/charts/chart-control.tsx b/src/components/src/map/charts/chart-control.tsx
new file mode 100644
index 000000000..411fc7e6b
--- /dev/null
+++ b/src/components/src/map/charts/chart-control.tsx
@@ -0,0 +1,73 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {ComponentType, useCallback} from 'react';
+
+import {MapControls} from '@kepler.gl/types';
+import {getApplicationConfig} from '@kepler.gl/utils';
+
+import {LineChart} from '../../common/icons';
+import {MapControlButton} from '../../common/styled-components';
+import MapControlTooltipFactory from '../map-control-tooltip';
+
+interface ChartControlIcons {
+ chartIcon: ComponentType<any>;
+}
+
+export type ChartControlProps = {
+ mapControls: MapControls;
+ onToggleMapControl: (control: string) => void;
+ actionIcons?: ChartControlIcons;
+};
+
+ChartControlFactory.deps = [MapControlTooltipFactory];
+
+export default function ChartControlFactory(
+ MapControlTooltip: ReturnType<typeof MapControlTooltipFactory>
+): React.FC<ChartControlProps> {
+ const defaultActionIcons = {
+ chartIcon: LineChart
+ };
+
+ const ChartControl = ({
+ mapControls,
+ onToggleMapControl,
+ actionIcons = defaultActionIcons
+ }: ChartControlProps) => {
+ const onClick = useCallback(
+ event => {
+ event.preventDefault();
+ onToggleMapControl('chart');
+ },
+ [onToggleMapControl]
+ );
+
+ if (!getApplicationConfig().enableChartsPanel) {
+ return null;
+ }
+
+ const showControl = mapControls?.chart?.show;
+ if (!showControl) {
+ return null;
+ }
+
+ const active = mapControls?.chart?.active;
+ return (
+ <MapControlTooltip
+ id="show-chart-panel"
+ message={active ? 'tooltip.hideChartPanel' : 'tooltip.showChartPanel'}
+ >
+ <MapControlButton
+ className="map-control-button toggle-chart-panel"
+ onClick={onClick}
+ active={active}
+ >
+ <actionIcons.chartIcon height="22px" />
+ </MapControlButton>
+ </MapControlTooltip>
+ );
+ };
+
+ ChartControl.displayName = 'ChartControl';
+ return React.memo(ChartControl);
+}
diff --git a/src/components/src/map/charts/chart-manager.tsx b/src/components/src/map/charts/chart-manager.tsx
new file mode 100644
index 000000000..0833c191b
--- /dev/null
+++ b/src/components/src/map/charts/chart-manager.tsx
@@ -0,0 +1,206 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useCallback, useContext, useMemo, useState} from 'react';
+import {useDispatch, useSelector} from 'react-redux';
+import styled from 'styled-components';
+import {injectIntl, IntlShape} from 'react-intl';
+
+import {
+ addChart,
+ updateChart,
+ removeChart,
+ createOrUpdateFilter,
+ ActionHandler,
+ VisStateActions
+} from '@kepler.gl/actions';
+import {ChartType, LayerChartType, createChart, toChartableDataset} from '@kepler.gl/charts';
+import {VisState} from '@kepler.gl/schemas';
+import {Datasets} from '@kepler.gl/table';
+import {getApplicationConfig} from '@kepler.gl/utils';
+
+import KeplerGlContext from '../../context';
+import SidePanelTitleFactory from '../../effects/side-panel-title';
+import ChartPanelContentFactory from './chart-panel';
+import ChartTypeSelectorFactory from './chart-type-selector';
+
+export type ChartManagerState = {
+ visState: VisState;
+ visStateActions: {
+ addChart: ActionHandler<typeof addChart>;
+ updateChart: ActionHandler<typeof updateChart>;
+ removeChart: ActionHandler<typeof removeChart>;
+ createOrUpdateFilter: ActionHandler<typeof createOrUpdateFilter>;
+ };
+ /** When false, only pinned charts are shown (panel control is inactive). */
+ panelActive?: boolean;
+ /** Image export: show all charts without edit chrome. */
+ isExport?: boolean;
+ children?: React.ReactNode;
+};
+
+export type ChartManagerProps = {intl: IntlShape} & Partial<ChartManagerState>;
+
+const StyledChartPanelContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ pointer-events: none !important;
+ flex-grow: 1;
+ justify-content: space-between;
+ overflow: hidden;
+ width: ${({theme}) => theme.effectPanelWidth}px;
+ min-width: 0;
+
+ & > * {
+ pointer-events: all;
+ }
+`;
+
+const StyledChartPanel = styled.div`
+ top: 0;
+ background-color: ${props => props.theme.sidePanelBg};
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ overflow: hidden;
+ min-width: 0;
+`;
+
+const StyledChartPanelHeader = styled.div`
+ padding: ${({theme}) =>
+ `${theme.effectPanelPaddingTop || 8}px ${theme.effectPanelPaddingSide || 16}px 4px ${
+ theme.effectPanelPaddingSide || 16
+ }px`};
+ border-bottom: 1px solid ${props => props.theme.borderColor};
+ min-width: ${({theme}) => theme.effectPanelWidth}px;
+`;
+
+type StyledChartPanelContentProps = {
+ $extended?: boolean;
+};
+const StyledChartPanelContent = styled.div<StyledChartPanelContentProps>`
+ ${props => props.theme.sidePanelScrollBar};
+ padding: ${props => (props.$extended ? '32px' : '3px 0')};
+ overflow-x: hidden;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ flex-grow: 1;
+ min-width: 0;
+`;
+
+ChartManagerFactory.deps = [
+ ChartPanelContentFactory,
+ SidePanelTitleFactory,
+ ChartTypeSelectorFactory
+];
+
+export default function ChartManagerFactory(
+ ChartPanelContent: ReturnType<typeof ChartPanelContentFactory>,
+ SidePanelTitle: ReturnType<typeof SidePanelTitleFactory>,
+ ChartTypeSelector: ReturnType<typeof ChartTypeSelectorFactory>
+): React.FC<ChartManagerProps> {
+ const ChartManager = (props: ChartManagerProps) => {
+ const {intl, children, panelActive = true, isExport = false} = props;
+ const dispatch = useDispatch();
+ const {selector} = useContext(KeplerGlContext);
+ const visStateFromStore = useSelector(state => selector(state)?.visState);
+ const visState = props.visState ?? visStateFromStore;
+ const visStateActions = useMemo(
+ () =>
+ props.visStateActions ?? {
+ addChart: chart => dispatch(addChart(chart)),
+ updateChart: (id, next) => dispatch(updateChart(id, next)),
+ removeChart: id => dispatch(removeChart(id)),
+ createOrUpdateFilter: (id, dataId, field, value) =>
+ dispatch(createOrUpdateFilter(id, dataId, field, value))
+ },
+ [dispatch, props.visStateActions]
+ );
+
+ const charts = useMemo(() => {
+ const allCharts = visState?.charts ?? [];
+ return panelActive || isExport
+ ? allCharts
+ : allCharts.filter(chart => chart.pinned !== false);
+ }, [visState?.charts, panelActive, isExport]);
+ const datasets = useMemo<Datasets>(() => visState?.datasets ?? {}, [visState?.datasets]);
+ const layers = useMemo(() => visState?.layers ?? [], [visState?.layers]);
+ const [typeSelectorOpened, setTypeSelectorOpened] = useState(false);
+
+ const onAddChart = useCallback(
+ (type: ChartType | LayerChartType) => {
+ const firstDataset = Object.values(datasets)[0];
+ const isLayer =
+ type === LayerChartType.BREAKDOWN_BY_CATEGORY || type === LayerChartType.TIME_SERIES;
+ const layer = isLayer ? layers[0] : undefined;
+ const dataId = layer?.config.dataId || firstDataset?.id;
+ const dataset = dataId
+ ? toChartableDataset(datasets[dataId])
+ : toChartableDataset(firstDataset);
+ const chart = createChart({
+ type,
+ dataId,
+ dataset: dataset || undefined,
+ layerId: layer?.id,
+ options: {activateConfig: true}
+ });
+ if (chart) {
+ visStateActions.addChart(chart);
+ }
+ },
+ [datasets, layers, visStateActions]
+ );
+
+ const onTypeSelectOpen = useCallback(() => {
+ setTypeSelectorOpened(true);
+ }, []);
+
+ const onTypeSelectClose = useCallback(() => {
+ setTypeSelectorOpened(false);
+ }, []);
+
+ if (!getApplicationConfig().enableChartsPanel) {
+ return null;
+ }
+
+ if (!panelActive && !isExport && charts.length === 0) {
+ return null;
+ }
+
+ return (
+ <StyledChartPanelContainer className="chart-manager">
+ <StyledChartPanel>
+ {panelActive && !isExport ? (
+ <StyledChartPanelHeader className="chart-panel-header">
+ <SidePanelTitle
+ className="chart-manager-title"
+ title={intl.formatMessage({id: 'header.charts'})}
+ >
+ <ChartTypeSelector
+ onSelect={onAddChart}
+ onOpen={onTypeSelectOpen}
+ onBlur={onTypeSelectClose}
+ />
+ </SidePanelTitle>
+ </StyledChartPanelHeader>
+ ) : null}
+ <StyledChartPanelContent
+ $extended={panelActive && !isExport && typeSelectorOpened && charts.length === 0}
+ >
+ <ChartPanelContent
+ charts={charts}
+ datasets={datasets}
+ layers={layers}
+ visStateActions={visStateActions as typeof VisStateActions}
+ readOnly={!panelActive || isExport}
+ />
+ </StyledChartPanelContent>
+ </StyledChartPanel>
+ {children}
+ </StyledChartPanelContainer>
+ );
+ };
+
+ return injectIntl(ChartManager) as React.FC<ChartManagerProps>;
+}
diff --git a/src/components/src/map/charts/chart-panel.tsx b/src/components/src/map/charts/chart-panel.tsx
new file mode 100644
index 000000000..cd467145c
--- /dev/null
+++ b/src/components/src/map/charts/chart-panel.tsx
@@ -0,0 +1,1474 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useCallback, useState} from 'react';
+import styled from 'styled-components';
+
+import {VisStateActions} from '@kepler.gl/actions';
+import {
+ ChartConfig,
+ ChartType,
+ ChartRenderer,
+ LayerChartType,
+ computeChart,
+ getCrossFilterFields,
+ isLayerChartConfig,
+ toChartableDataset,
+ propsForChartDatasetChange,
+ ChartAxis,
+ CHART_AGGREGATION_OPTIONS,
+ CHART_COLOR_BY_OPTIONS,
+ ChartColorBy,
+ BinType,
+ TIME_FIELD_TYPES,
+ TIME_INTERVAL_OPTIONS,
+ getDefaultChartColorRange,
+ HEATMAP_COLOR_STEPS,
+ formatNumber
+} from '@kepler.gl/charts';
+import {
+ DEFAULT_COLOR_UI,
+ TOOLTIP_FORMATS,
+ TOOLTIP_FORMAT_TYPES,
+ KEPLER_COLOR_PALETTES,
+ colorPaletteToColorRange
+} from '@kepler.gl/constants';
+import {FormattedMessage} from '@kepler.gl/localization';
+import {Layer} from '@kepler.gl/layers';
+import {Datasets} from '@kepler.gl/table';
+import {ColorRange, ColorUI, Filter, NestedPartial, RGBColor} from '@kepler.gl/types';
+import {generateHashId} from '@kepler.gl/common-utils';
+import {
+ applyDefaultFormat,
+ getFilterFunction,
+ runGpuFilterForPlot,
+ updateColorRangeByMatchingPalette,
+ updateCustomColorRangeByColorUI
+} from '@kepler.gl/utils';
+
+import {Settings, Trash, Pin, EyeSeen, EyeUnseen} from '../../common/icons';
+import {Input, PanelLabel, Tooltip} from '../../common/styled-components';
+import Switch from '../../common/switch';
+import ItemSelector from '../../common/item-selector/item-selector';
+import FieldSelectorFactory from '../../common/field-selector';
+import SourceDataSelectorFactory from '../../side-panel/common/source-data-selector';
+import ColorSelectorFactory, {ColorSet} from '../../side-panel/layer-panel/color-selector';
+import {
+ ChartConfigGroup,
+ ChartConfigSection,
+ ChartConfigSectionWrapper,
+ ConfigUncollapsibleContent
+} from './chart-config-group';
+
+const DEFAULT_SINGLE_COLOR: RGBColor = [18, 147, 154];
+const DEFAULT_BIG_NUMBER_FORMAT = TOOLTIP_FORMATS.DECIMAL_SHORT_COMMA.id;
+const BIG_NUMBER_FORMAT_TYPES = [
+ TOOLTIP_FORMAT_TYPES.NONE,
+ TOOLTIP_FORMAT_TYPES.DECIMAL,
+ TOOLTIP_FORMAT_TYPES.PERCENTAGE
+];
+const BIG_NUMBER_FORMAT_OPTIONS = Object.values(TOOLTIP_FORMATS).filter(fm =>
+ BIG_NUMBER_FORMAT_TYPES.includes(fm.type)
+);
+
+/** Third sequential palette (Uber Viz Sequential, Global Warming, Sunrise, …) at 20 steps. */
+function defaultHeatmapColorRange(): ColorRange {
+ const sequential = KEPLER_COLOR_PALETTES.filter(palette => palette.type === 'sequential');
+ const palette = sequential[2] || sequential[0];
+ return colorPaletteToColorRange(palette, {
+ steps: HEATMAP_COLOR_STEPS,
+ reversed: false
+ }) as ColorRange;
+}
+
+function asRgbColor(value: unknown): RGBColor {
+ if (Array.isArray(value) && value.length >= 3) {
+ return [Number(value[0]), Number(value[1]), Number(value[2])];
+ }
+ return DEFAULT_SINGLE_COLOR;
+}
+
+function formatBigNumberTick(value: number, formatId?: string | null): string {
+ const id = formatId || DEFAULT_BIG_NUMBER_FORMAT;
+ const tooltipFormat = BIG_NUMBER_FORMAT_OPTIONS.find(fm => fm.id === id);
+ if (!tooltipFormat || tooltipFormat.id === TOOLTIP_FORMATS.NONE.id || !tooltipFormat.format) {
+ return formatNumber(value);
+ }
+ return applyDefaultFormat(tooltipFormat)(value);
+}
+
+const COLOR_RANGE_UI_KEYS = ['reversed', 'steps', 'colorBlindSafe', 'type'] as const;
+
+function shouldUpdateChartColorRange(next: NestedPartial<ColorUI>, current: ColorUI): boolean {
+ const config = next.colorRangeConfig;
+ if (!config) {
+ return false;
+ }
+ return COLOR_RANGE_UI_KEYS.some(
+ key =>
+ Object.prototype.hasOwnProperty.call(config, key) &&
+ config[key] !== current.colorRangeConfig?.[key]
+ );
+}
+
+function colorRangeFromColorUI(
+ currentRange: ColorRange,
+ colorRangeConfig: ColorUI['colorRangeConfig'],
+ next: NestedPartial<ColorUI>
+): ColorRange {
+ const isCustomReversed =
+ currentRange.category === 'Custom' &&
+ Boolean(next.colorRangeConfig) &&
+ Object.prototype.hasOwnProperty.call(next.colorRangeConfig, 'reversed');
+ if (isCustomReversed) {
+ return updateCustomColorRangeByColorUI(currentRange, colorRangeConfig);
+ }
+
+ const updated = updateColorRangeByMatchingPalette(currentRange, colorRangeConfig);
+ if (updated !== currentRange) {
+ return updated;
+ }
+
+ // Fallback for custom chart palettes that are not in KEPLER_COLOR_PALETTES.
+ const baseColors = currentRange.colors?.length
+ ? currentRange.colors
+ : getDefaultChartColorRange(colorRangeConfig.steps || 10).colors;
+ const steps = Math.max(2, colorRangeConfig.steps || baseColors.length);
+ const colors = Array.from({length: steps}, (_, i) => baseColors[i % baseColors.length]);
+ if (colorRangeConfig.reversed) {
+ colors.reverse();
+ }
+ return {
+ ...currentRange,
+ colors,
+ ...(colorRangeConfig.reversed ? {reversed: true} : {reversed: false})
+ };
+}
+
+/** Resize / rematch a chart color range to a target step count. */
+function colorRangeWithSteps(currentRange: ColorRange | undefined, steps: number): ColorRange {
+ const stepsClamped = Math.max(2, steps);
+ const range = (currentRange || getDefaultChartColorRange(stepsClamped)) as ColorRange;
+ if ((range.colors?.length || 0) === stepsClamped) {
+ return range;
+ }
+ const colorRangeConfig = {
+ type: (range.type as ColorUI['colorRangeConfig']['type']) || 'all',
+ steps: stepsClamped,
+ reversed: Boolean(range.reversed),
+ custom: false,
+ customBreaks: false,
+ colorBlindSafe: false
+ };
+ return colorRangeFromColorUI(range, colorRangeConfig, {colorRangeConfig: {steps: stepsClamped}});
+}
+
+/**
+ * After a bar chart bin-axis change, sync palette steps to the resulting bin count.
+ */
+function withColorRangeSyncedToBins(
+ chart: ChartConfig,
+ dataset: ReturnType<typeof toChartableDataset> | null,
+ axisUpdate: Partial<ChartConfig>
+): Partial<ChartConfig> {
+ if (chart.type !== ChartType.barChart && chart.type !== ChartType.horizontalBar) {
+ return axisUpdate;
+ }
+ const nextChart = {...chart, ...axisUpdate} as ChartConfig;
+ const view = computeChart(nextChart, dataset);
+ if (view.kind !== 'bars' || view.bins.length < 2) {
+ return axisUpdate;
+ }
+ return {
+ ...axisUpdate,
+ chartDisplay: {
+ ...chart.chartDisplay,
+ colorRange: colorRangeWithSteps(chart.chartDisplay?.colorRange, view.bins.length)
+ }
+ };
+}
+
+/** Kepler boolean filters are select filters with a scalar boolean, not `['true']`. */
+function toCrossFilterValue(
+ raw: Array<string | number | boolean> | undefined,
+ fallback: string
+): Array<string | number | boolean> | boolean {
+ if (raw?.length === 1 && typeof raw[0] === 'boolean') {
+ return raw[0];
+ }
+ if (raw?.length) {
+ return raw;
+ }
+ return [fallback];
+}
+
+function chartOwnedFilterIds(chart: ChartConfig): string[] {
+ const id = chart.crossFilter?.filterId;
+ if (!id) {
+ return [];
+ }
+ return [id, `${id}-x`, `${id}-y`];
+}
+
+function fieldNameForFilter(
+ filter: {dataId?: string | string[] | null; name?: string | string[] | null},
+ dataId: string
+): string | null {
+ const names = Array.isArray(filter.name) ? filter.name : [filter.name];
+ const dataIds = Array.isArray(filter.dataId) ? filter.dataId : [filter.dataId];
+ const idx = dataIds.indexOf(dataId);
+ const name = names[idx >= 0 ? idx : 0];
+ return typeof name === 'string' && name ? name : null;
+}
+
+/**
+ * Rebuild CPU filteredIndex without this chart's own select/multiSelect filters
+ * so category bins stay visible after a cross-filter click.
+ */
+function cpuIndexExcludingFilterIds(
+ dataset: Datasets[string],
+ dataId: string,
+ skipFilterIds: string[],
+ layers: Layer[]
+): number[] | undefined {
+ const cpuFilters = dataset.filterRecord?.cpu;
+ if (!cpuFilters?.length || !skipFilterIds.length || !dataset.dataContainer) {
+ return undefined;
+ }
+ const skip = new Set(skipFilterIds);
+ const remaining = cpuFilters.filter(filter => !skip.has(filter.id));
+ if (remaining.length === cpuFilters.length) {
+ return undefined;
+ }
+ if (!remaining.length) {
+ return dataset.allIndexes;
+ }
+ const {dataContainer, fields = []} = dataset;
+ const funcs = remaining.map(filter => {
+ const fieldName = fieldNameForFilter(filter, dataId);
+ const field = fieldName ? fields.find(item => item.name === fieldName) || null : null;
+ return getFilterFunction(field, dataId, filter as Filter, layers, dataContainer);
+ });
+ return dataset.allIndexes.filter(index => funcs.every(fn => fn({index})));
+}
+
+/**
+ * Charts should respect the same filters as the map. Kepler keeps range/time
+ * filters on the GPU, so `dataset.filteredIndex` alone is not enough — apply
+ * GPU filters on CPU the same way filter histograms do.
+ * When skip lists are set, this chart's own cross-filter is ignored so bins
+ * stay visible (map still filters).
+ */
+function toMapFilteredChartDataset(
+ dataset: Datasets[string] | undefined,
+ options?: {
+ dataId?: string | null;
+ skipFieldName?: string | null;
+ skipFieldNames?: string[] | null;
+ skipFilterIds?: string[] | null;
+ layers?: Layer[];
+ }
+) {
+ if (!dataset) {
+ return null;
+ }
+ const skipNames = (options?.skipFieldNames || []).filter(Boolean) as string[];
+ if (options?.skipFieldName) {
+ skipNames.push(options.skipFieldName);
+ }
+ const uniqueSkip = Array.from(new Set(skipNames));
+ const skipFilterIds = (options?.skipFilterIds || []).filter(Boolean);
+ const cpuIndex =
+ options?.dataId && skipFilterIds.length
+ ? cpuIndexExcludingFilterIds(dataset, options.dataId, skipFilterIds, options.layers || [])
+ : undefined;
+ const plotSource = cpuIndex ? ({...dataset, filteredIndex: cpuIndex} as typeof dataset) : dataset;
+ const filteredIndex =
+ plotSource.gpuFilter?.filterValueAccessor != null
+ ? runGpuFilterForPlot(plotSource, undefined, uniqueSkip.length ? uniqueSkip : undefined)
+ : cpuIndex;
+ return toChartableDataset(dataset, filteredIndex ? {filteredIndex} : undefined);
+}
+
+function binAggregationForField(field: {type: string} | null): ChartAxis['aggregation'] {
+ if (!field) {
+ return BinType.uniqueBin;
+ }
+ if (TIME_FIELD_TYPES.includes(field.type)) {
+ return BinType.timeBin;
+ }
+ if (field.type === 'real') {
+ return BinType.numericBin;
+ }
+ return BinType.uniqueBin;
+}
+
+function isTimeAxis(axis?: ChartAxis | null): boolean {
+ if (!axis) {
+ return false;
+ }
+ if (axis.aggregation === BinType.timeBin) {
+ return true;
+ }
+ return Boolean(axis.field?.type && TIME_FIELD_TYPES.includes(axis.field.type));
+}
+
+function resolveTimeInterval(chart: ChartConfig): string | null {
+ return chart.xAxis?.interval || chart.chartDisplay?.interval || null;
+}
+
+const ChartList = styled.div`
+ width: 100%;
+ max-width: 100%;
+ min-width: 0;
+ padding: 4px 8px;
+ box-sizing: border-box;
+`;
+
+const ChartCard = styled.div<{
+ $showPinOnHover?: boolean;
+}>`
+ border: 1px solid ${props => props.theme.panelBorderColor};
+ border-radius: 4px;
+ margin-bottom: 8px;
+ background-color: ${props => props.theme.panelBackground};
+ position: relative;
+ max-width: 100%;
+ min-width: 0;
+ overflow: hidden;
+ box-sizing: border-box;
+
+ &:last-child {
+ margin-bottom: 0;
+ }
+
+ ${props =>
+ props.$showPinOnHover
+ ? `
+ .chart-card__pin-action {
+ position: absolute;
+ top: 6px;
+ right: 6px;
+ z-index: 2;
+ margin-left: 0;
+ padding: 4px;
+ border-radius: 2px;
+ background-color: ${props.theme.panelBackground};
+ box-shadow: 0 0 0 1px ${props.theme.panelBorderColor};
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity 0.15s ease;
+ }
+ &:hover .chart-card__pin-action,
+ &:focus-within .chart-card__pin-action {
+ opacity: 1;
+ pointer-events: auto;
+ }
+ `
+ : ''}
+`;
+
+const ChartCardHeader = styled.div`
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ padding: 8px 8px 0;
+ min-width: 0;
+`;
+
+const ChartTitleInput = styled(Input)`
+ flex: 1 1 auto;
+ min-width: 0;
+ width: auto;
+`;
+
+const ChartTitleText = styled.div`
+ flex: 1 1 auto;
+ min-width: 0;
+ font-size: 12px;
+ font-weight: 500;
+ color: ${props => props.theme.textColor};
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ padding: 6px 0;
+`;
+
+const ChartHeaderActions = styled.div`
+ display: flex;
+ align-items: center;
+ flex: 0 0 auto;
+`;
+
+const ChartHeaderAction = styled.div<{
+ $active?: boolean;
+ $hoverColor?: string;
+}>`
+ margin-left: 8px;
+ display: flex;
+ align-items: center;
+ color: ${props =>
+ props.$active ? props.theme.panelHeaderIconActive : props.theme.panelHeaderIcon};
+ cursor: pointer;
+
+ &:hover {
+ color: ${props =>
+ props.$hoverColor ? props.theme[props.$hoverColor] : props.theme.panelHeaderIconHover};
+ }
+`;
+
+const ConfigBlock = styled.div`
+ padding: 6px 8px 8px;
+ border-top: 1px solid ${props => props.theme.panelBorderColor};
+ max-height: 70vh;
+ overflow-y: auto;
+`;
+
+const SourceDataSelectorWrapper = styled.div`
+ .side-panel-section {
+ margin-bottom: 0;
+ }
+ label {
+ display: none;
+ }
+`;
+
+const CompactFieldSelector = styled.div`
+ min-width: 0;
+
+ .field-selector {
+ margin-bottom: 0;
+ }
+`;
+
+/** Keep the palette panel compact inside the chart settings column. */
+const ChartColorSelectorWrapper = styled.div`
+ .color-selector__dropdown {
+ max-height: 220px;
+ overflow-y: auto;
+ }
+`;
+
+function axisFromField(
+ field: {name: string; type: string} | null,
+ aggregation: ChartAxis['aggregation']
+): ChartAxis {
+ return {
+ field: field ? {name: field.name, type: field.type} : null,
+ aggregation,
+ title: field?.name ?? null
+ };
+}
+
+export type ChartPanelProps = {
+ charts?: ChartConfig[];
+ datasets: Datasets;
+ layers: Layer[];
+ visStateActions?: typeof VisStateActions;
+ /** When true, hide edit chrome and only render chart views (pinned overlay). */
+ readOnly?: boolean;
+};
+
+ChartPanelContentFactory.deps = [
+ FieldSelectorFactory,
+ SourceDataSelectorFactory,
+ ColorSelectorFactory
+];
+
+export function ChartPanelContentFactory(
+ FieldSelector: ReturnType<typeof FieldSelectorFactory>,
+ SourceDataSelector: ReturnType<typeof SourceDataSelectorFactory>,
+ ColorSelector: ReturnType<typeof ColorSelectorFactory>
+): React.FC<ChartPanelProps> {
+ const ChartPanelContent: React.FC<ChartPanelProps> = ({
+ charts = [],
+ datasets,
+ layers,
+ visStateActions,
+ readOnly = false
+ }) => {
+ const [colorUIByChart, setColorUIByChart] = useState<Record<string, ColorUI>>({});
+
+ const onUpdate = useCallback(
+ (id: string, props: Partial<ChartConfig>) => {
+ visStateActions?.updateChart(id, props);
+ },
+ [visStateActions]
+ );
+
+ const syncColorUISteps = useCallback((chartId: string, colorRange?: ColorRange) => {
+ if (!colorRange?.colors?.length) {
+ return;
+ }
+ setColorUIByChart(prev => {
+ const current = prev[chartId] || DEFAULT_COLOR_UI;
+ return {
+ ...prev,
+ [chartId]: {
+ ...current,
+ colorRangeConfig: {
+ ...current.colorRangeConfig,
+ steps: colorRange.colors.length,
+ reversed: Boolean(colorRange.reversed)
+ }
+ }
+ };
+ });
+ }, []);
+
+ const updateBarBinAxis = useCallback(
+ (
+ chart: ChartConfig,
+ dataset: ReturnType<typeof toChartableDataset> | null,
+ axisUpdate: Partial<ChartConfig>
+ ) => {
+ const updates = withColorRangeSyncedToBins(chart, dataset, axisUpdate);
+ onUpdate(chart.id, updates);
+ const colorRange = (updates.chartDisplay as {colorRange?: ColorRange} | undefined)
+ ?.colorRange;
+ syncColorUISteps(chart.id, colorRange);
+ },
+ [onUpdate, syncColorUISteps]
+ );
+
+ const onRemove = useCallback(
+ (id: string) => {
+ visStateActions?.removeChart(id);
+ },
+ [visStateActions]
+ );
+
+ const onSelectBin = useCallback(
+ (
+ chart: ChartConfig,
+ key: string,
+ extra?: {
+ filterValue?: Array<string | number | boolean>;
+ filterValueY?: Array<string | number | boolean>;
+ x?: string;
+ y?: string;
+ }
+ ) => {
+ if (isLayerChartConfig(chart) || !chart.dataId) {
+ return;
+ }
+ const fields = getCrossFilterFields(chart);
+ if (!fields.length) {
+ return;
+ }
+ const filterId = chart.crossFilter?.filterId || `chart-${chart.id}-${generateHashId(4)}`;
+ const alreadySelected =
+ chart.crossFilter?.enabled && String(chart.crossFilter.value?.x) === key;
+ if (alreadySelected) {
+ // Disable and drop owned filters (heatmap uses filterId-x / filterId-y).
+ visStateActions?.updateChart(chart.id, {
+ crossFilter: {
+ enabled: false,
+ filterId,
+ fieldNames: Object.fromEntries(fields.map((name, i) => [i === 0 ? 'x' : 'y', name])),
+ value: {}
+ }
+ });
+ return;
+ }
+
+ const filterValueX = toCrossFilterValue(extra?.filterValue, key);
+ const xField = fields[0];
+ const yField = fields[1];
+
+ if (chart.type === ChartType.heatmapChart && yField && extra?.y != null) {
+ const filterValueY = toCrossFilterValue(extra.filterValueY, extra.y);
+ visStateActions?.createOrUpdateFilter(
+ `${filterId}-x`,
+ chart.dataId,
+ xField,
+ filterValueX
+ );
+ visStateActions?.createOrUpdateFilter(
+ `${filterId}-y`,
+ chart.dataId,
+ yField,
+ filterValueY
+ );
+ visStateActions?.updateChart(chart.id, {
+ crossFilter: {
+ enabled: true,
+ filterId,
+ fieldNames: {x: xField, y: yField},
+ value: {x: key, y: extra.y}
+ }
+ });
+ return;
+ }
+
+ // Numeric/time bins pass [min, max]; categories pass [key]. Never pass the
+ // display label alone when a numeric filterValue is available.
+ visStateActions?.createOrUpdateFilter(filterId, chart.dataId, xField, filterValueX);
+ visStateActions?.updateChart(chart.id, {
+ crossFilter: {
+ enabled: true,
+ filterId,
+ fieldNames: {x: xField},
+ value: {x: key}
+ }
+ });
+ },
+ [visStateActions]
+ );
+
+ return (
+ <ChartList className="chart-panel">
+ {charts.map(chart => {
+ const rawDataset = chart.dataId ? datasets[chart.dataId] : undefined;
+ const crossFilterFields = getCrossFilterFields(chart);
+ const dataset = chart.dataId
+ ? chart.applyFilters
+ ? toMapFilteredChartDataset(rawDataset, {
+ dataId: chart.dataId,
+ // Keep this chart's bins stable while its own cross-filter drives the map.
+ skipFieldNames: chart.crossFilter?.enabled ? crossFilterFields : null,
+ skipFilterIds: chart.crossFilter?.enabled ? chartOwnedFilterIds(chart) : null,
+ layers
+ })
+ : toChartableDataset(rawDataset)
+ : null;
+ const fields = dataset?.fields || [];
+ const rawView = computeChart(chart, dataset);
+ const view =
+ rawView.kind === 'bigNumber'
+ ? {
+ ...rawView,
+ formattedValue: formatBigNumberTick(rawView.value, rawView.format)
+ }
+ : rawView;
+ const selectedKey =
+ chart.crossFilter?.enabled && chart.crossFilter.value?.x != null
+ ? String(chart.crossFilter.value.x)
+ : undefined;
+ return (
+ <ChartCard key={chart.id} className="chart-card" $showPinOnHover={readOnly}>
+ {readOnly ? (
+ <>
+ <ChartHeaderAction
+ className="chart-card__pin-action"
+ $active
+ data-tip
+ data-for={`chart-pin_${chart.id}`}
+ aria-label="Unpin chart"
+ onClick={() => onUpdate(chart.id, {pinned: false})}
+ >
+ <Pin height="16px" filled />
+ </ChartHeaderAction>
+ <Tooltip id={`chart-pin_${chart.id}`} effect="solid" delayShow={500}>
+ <span>
+ <FormattedMessage id="tooltip.unpinChart" defaultMessage="Unpin chart" />
+ </span>
+ </Tooltip>
+ </>
+ ) : null}
+ <ChartCardHeader>
+ {readOnly ? (
+ <ChartTitleText>{chart.title}</ChartTitleText>
+ ) : (
+ <ChartTitleInput
+ type="text"
+ value={chart.title}
+ onChange={event => onUpdate(chart.id, {title: event.target.value})}
+ />
+ )}
+ {readOnly ? null : (
+ <ChartHeaderActions>
+ <ChartHeaderAction
+ className="chart-card__pin-action"
+ $active={chart.pinned !== false}
+ data-tip
+ data-for={`chart-pin_${chart.id}`}
+ aria-label={chart.pinned !== false ? 'Unpin chart' : 'Pin chart'}
+ onClick={() =>
+ onUpdate(chart.id, {
+ pinned: chart.pinned === false
+ })
+ }
+ >
+ <Pin height="16px" filled={chart.pinned !== false} />
+ </ChartHeaderAction>
+ <Tooltip id={`chart-pin_${chart.id}`} effect="solid" delayShow={500}>
+ <span>
+ <FormattedMessage
+ id={chart.pinned !== false ? 'tooltip.unpinChart' : 'tooltip.pinChart'}
+ defaultMessage={chart.pinned !== false ? 'Unpin chart' : 'Pin chart'}
+ />
+ </span>
+ </Tooltip>
+ <ChartHeaderAction
+ $active={Boolean(chart.display?.isConfigActive)}
+ data-tip
+ data-for={`chart-settings_${chart.id}`}
+ onClick={() =>
+ onUpdate(chart.id, {
+ display: {isConfigActive: !chart.display?.isConfigActive}
+ })
+ }
+ >
+ <Settings height="16px" />
+ </ChartHeaderAction>
+ <Tooltip id={`chart-settings_${chart.id}`} effect="solid" delayShow={500}>
+ <span>
+ <FormattedMessage
+ id="tooltip.chartSettings"
+ defaultMessage="Chart settings"
+ />
+ </span>
+ </Tooltip>
+ <ChartHeaderAction
+ aria-label="Remove chart"
+ data-tip
+ data-for={`chart-remove_${chart.id}`}
+ onClick={() => onRemove(chart.id)}
+ >
+ <Trash height="16px" />
+ </ChartHeaderAction>
+ <Tooltip id={`chart-remove_${chart.id}`} effect="solid" delayShow={500}>
+ <span>
+ <FormattedMessage id="tooltip.removeChart" defaultMessage="Remove chart" />
+ </span>
+ </Tooltip>
+ </ChartHeaderActions>
+ )}
+ </ChartCardHeader>
+ <ChartRenderer
+ data={view}
+ selectedKey={selectedKey}
+ onSelect={(key, extra) => onSelectBin(chart, key, extra)}
+ showCaption={
+ chart.type === ChartType.bigNumber
+ ? // While editing, always show the caption; hide only applies in pinned mode.
+ readOnly
+ ? chart.chartDisplay?.showCaption !== false
+ : true
+ : undefined
+ }
+ onToggleCaption={
+ !readOnly && chart.type === ChartType.bigNumber && !isLayerChartConfig(chart)
+ ? () =>
+ onUpdate(chart.id, {
+ chartDisplay: {
+ ...chart.chartDisplay,
+ showCaption: chart.chartDisplay?.showCaption === false
+ }
+ })
+ : undefined
+ }
+ captionToggleIcon={
+ !readOnly && chart.type === ChartType.bigNumber ? (
+ chart.chartDisplay?.showCaption === false ? (
+ <EyeUnseen height="12px" />
+ ) : (
+ <EyeSeen height="12px" />
+ )
+ ) : undefined
+ }
+ captionToggleLabel={
+ !readOnly && chart.type === ChartType.bigNumber
+ ? chart.chartDisplay?.showCaption === false
+ ? 'Show caption when pinned'
+ : 'Hide caption when pinned'
+ : undefined
+ }
+ />
+ {!readOnly && chart.display?.isConfigActive ? (
+ <ConfigBlock>
+ <ChartConfigGroup
+ label="chartPanel.dataset"
+ defaultMessage="Dataset"
+ expanded={!chart.dataId && !isLayerChartConfig(chart)}
+ >
+ <ConfigUncollapsibleContent>
+ {!isLayerChartConfig(chart) ? (
+ <SourceDataSelectorWrapper>
+ <SourceDataSelector
+ datasets={datasets}
+ dataId={chart.dataId}
+ onSelect={dataId => {
+ const nextDataId = String(dataId);
+ onUpdate(
+ chart.id,
+ propsForChartDatasetChange(
+ chart,
+ toChartableDataset(datasets[nextDataId]),
+ {dataId: nextDataId}
+ )
+ );
+ }}
+ />
+ </SourceDataSelectorWrapper>
+ ) : (
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage id="chartPanel.layer" defaultMessage="Layer" />
+ </PanelLabel>
+ <ItemSelector
+ selectedItems={layers.find(layer => layer.id === chart.layerId) || null}
+ options={layers}
+ displayOption={(layer: Layer) => layer.config.label || layer.id}
+ getOptionValue={(layer: Layer) => layer.id}
+ multiSelect={false}
+ searchable={false}
+ size="small"
+ onChange={layerId => {
+ const layer = layers.find(l => l.id === layerId);
+ const nextDataId = layer?.config.dataId ?? chart.dataId;
+ onUpdate(
+ chart.id,
+ propsForChartDatasetChange(
+ chart,
+ nextDataId ? toChartableDataset(datasets[nextDataId]) : null,
+ {dataId: nextDataId, layerId: String(layerId)}
+ )
+ );
+ }}
+ />
+ </ChartConfigSectionWrapper>
+ )}
+ </ConfigUncollapsibleContent>
+ {chart.type === ChartType.bigNumber && !isLayerChartConfig(chart) ? (
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage
+ id="chartPanel.applyFilters"
+ defaultMessage="Apply map filters"
+ />
+ </PanelLabel>
+ <Switch
+ id={`${chart.id}-apply-filters`}
+ checked={chart.applyFilters}
+ onChange={() => onUpdate(chart.id, {applyFilters: !chart.applyFilters})}
+ />
+ </ChartConfigSectionWrapper>
+ ) : null}
+ </ChartConfigGroup>
+
+ {chart.type === ChartType.bigNumber ||
+ (isLayerChartConfig(chart) &&
+ chart.layerChartType === LayerChartType.BREAKDOWN_BY_CATEGORY) ? (
+ <ChartConfigGroup label="chartPanel.field" defaultMessage="Field">
+ <ConfigUncollapsibleContent>
+ <ChartConfigSection>
+ <CompactFieldSelector>
+ <FieldSelector
+ fields={fields as any}
+ value={chart.axis?.field?.name}
+ erasable
+ onSelect={item =>
+ onUpdate(chart.id, {
+ axis: axisFromField(
+ (item as any) || null,
+ chart.type === ChartType.bigNumber
+ ? chart.axis?.aggregation || 'count'
+ : chart.axis?.aggregation ?? null
+ )
+ })
+ }
+ />
+ </CompactFieldSelector>
+ </ChartConfigSection>
+ </ConfigUncollapsibleContent>
+ {chart.type === ChartType.bigNumber ? (
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage
+ id="chartPanel.aggregation"
+ defaultMessage="Aggregation"
+ />
+ </PanelLabel>
+ <ItemSelector
+ selectedItems={
+ CHART_AGGREGATION_OPTIONS.find(
+ option => option.id === chart.axis?.aggregation
+ ) || CHART_AGGREGATION_OPTIONS[0]
+ }
+ options={CHART_AGGREGATION_OPTIONS}
+ displayOption={(d: {label: string}) => d.label}
+ getOptionValue={(d: {id: string}) => d.id}
+ multiSelect={false}
+ searchable={false}
+ size="small"
+ onChange={aggregation =>
+ onUpdate(chart.id, {
+ axis: {
+ ...(chart.axis as ChartAxis),
+ aggregation: aggregation as ChartAxis['aggregation']
+ }
+ })
+ }
+ />
+ </ChartConfigSectionWrapper>
+ ) : null}
+ </ChartConfigGroup>
+ ) : null}
+
+ {chart.type !== ChartType.bigNumber &&
+ !(
+ isLayerChartConfig(chart) &&
+ chart.layerChartType === LayerChartType.BREAKDOWN_BY_CATEGORY
+ ) ? (
+ <ChartConfigGroup label="chartPanel.xAxis" defaultMessage="X axis">
+ <ConfigUncollapsibleContent>
+ <ChartConfigSection>
+ <CompactFieldSelector>
+ <FieldSelector
+ fields={fields as any}
+ value={chart.xAxis?.field?.name}
+ erasable
+ onSelect={item => {
+ const field = (item as any) || null;
+ const xAxis = axisFromField(
+ field,
+ chart.type === ChartType.horizontalBar
+ ? chart.xAxis?.aggregation || 'count'
+ : binAggregationForField(field)
+ );
+ // Keep period when switching between time fields.
+ if (field && TIME_FIELD_TYPES.includes(field.type)) {
+ xAxis.interval = resolveTimeInterval(chart);
+ }
+ // Vertical bar: X is the bin axis — sync palette steps to bins.
+ if (chart.type === ChartType.barChart) {
+ updateBarBinAxis(chart, dataset, {xAxis});
+ return;
+ }
+ onUpdate(chart.id, {xAxis});
+ }}
+ />
+ </CompactFieldSelector>
+ </ChartConfigSection>
+ </ConfigUncollapsibleContent>
+ {chart.type === ChartType.horizontalBar ? (
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage
+ id="chartPanel.aggregation"
+ defaultMessage="Aggregation"
+ />
+ </PanelLabel>
+ <ItemSelector
+ selectedItems={
+ CHART_AGGREGATION_OPTIONS.find(
+ option => option.id === chart.xAxis?.aggregation
+ ) || CHART_AGGREGATION_OPTIONS[0]
+ }
+ options={CHART_AGGREGATION_OPTIONS}
+ displayOption={(d: {label: string}) => d.label}
+ getOptionValue={(d: {id: string}) => d.id}
+ multiSelect={false}
+ searchable={false}
+ size="small"
+ onChange={aggregation =>
+ onUpdate(chart.id, {
+ xAxis: {
+ ...(chart.xAxis as ChartAxis),
+ aggregation: aggregation as ChartAxis['aggregation']
+ }
+ })
+ }
+ />
+ </ChartConfigSectionWrapper>
+ ) : null}
+ {(chart.type === ChartType.lineChart ||
+ (isLayerChartConfig(chart) &&
+ chart.layerChartType === LayerChartType.TIME_SERIES)) &&
+ isTimeAxis(chart.xAxis) ? (
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage id="chartPanel.period" defaultMessage="Period" />
+ </PanelLabel>
+ <ItemSelector
+ selectedItems={
+ TIME_INTERVAL_OPTIONS.find(
+ option => option.id === (resolveTimeInterval(chart) || 'auto')
+ ) || TIME_INTERVAL_OPTIONS[0]
+ }
+ options={TIME_INTERVAL_OPTIONS}
+ displayOption={(d: {label: string}) => d.label}
+ getOptionValue={(d: {id: string}) => d.id}
+ multiSelect={false}
+ searchable={false}
+ size="small"
+ onChange={period => {
+ const interval = !period || period === 'auto' ? null : String(period);
+ onUpdate(chart.id, {
+ xAxis: {
+ ...(chart.xAxis as ChartAxis),
+ interval
+ },
+ chartDisplay: {
+ ...chart.chartDisplay,
+ // Keep in sync so compute / layer time series both see it.
+ interval: interval || undefined
+ }
+ });
+ }}
+ />
+ </ChartConfigSectionWrapper>
+ ) : null}
+ </ChartConfigGroup>
+ ) : null}
+
+ {chart.type === ChartType.barChart ||
+ chart.type === ChartType.horizontalBar ||
+ chart.type === ChartType.lineChart ||
+ (isLayerChartConfig(chart) &&
+ chart.layerChartType === LayerChartType.TIME_SERIES) ? (
+ <ChartConfigGroup label="chartPanel.yAxis" defaultMessage="Y axis">
+ <ConfigUncollapsibleContent>
+ <ChartConfigSection>
+ <CompactFieldSelector>
+ <FieldSelector
+ fields={fields as any}
+ value={chart.yAxis?.field?.name}
+ erasable
+ onSelect={item => {
+ const yAxis = axisFromField(
+ (item as any) || null,
+ chart.type === ChartType.horizontalBar
+ ? binAggregationForField((item as any) || null)
+ : chart.yAxis?.aggregation || 'count'
+ );
+ // Horizontal bar: Y is the bin axis — sync palette steps to bins.
+ if (chart.type === ChartType.horizontalBar) {
+ updateBarBinAxis(chart, dataset, {yAxis});
+ return;
+ }
+ onUpdate(chart.id, {yAxis});
+ }}
+ />
+ </CompactFieldSelector>
+ </ChartConfigSection>
+ </ConfigUncollapsibleContent>
+ {chart.type !== ChartType.horizontalBar ? (
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage
+ id="chartPanel.aggregation"
+ defaultMessage="Aggregation"
+ />
+ </PanelLabel>
+ <ItemSelector
+ selectedItems={
+ CHART_AGGREGATION_OPTIONS.find(
+ option => option.id === chart.yAxis?.aggregation
+ ) || CHART_AGGREGATION_OPTIONS[0]
+ }
+ options={CHART_AGGREGATION_OPTIONS}
+ displayOption={(d: {label: string}) => d.label}
+ getOptionValue={(d: {id: string}) => d.id}
+ multiSelect={false}
+ searchable={false}
+ size="small"
+ onChange={aggregation =>
+ onUpdate(chart.id, {
+ yAxis: {
+ ...(chart.yAxis as ChartAxis),
+ aggregation: aggregation as ChartAxis['aggregation']
+ }
+ })
+ }
+ />
+ </ChartConfigSectionWrapper>
+ ) : null}
+ </ChartConfigGroup>
+ ) : null}
+
+ {chart.type === ChartType.heatmapChart || chart.type === ChartType.pivotTable ? (
+ <>
+ <ChartConfigGroup label="chartPanel.yAxis" defaultMessage="Y axis">
+ <ConfigUncollapsibleContent>
+ <ChartConfigSection>
+ <CompactFieldSelector>
+ <FieldSelector
+ fields={fields as any}
+ value={chart.yAxis?.field?.name}
+ erasable
+ onSelect={item =>
+ onUpdate(chart.id, {
+ yAxis: axisFromField(
+ (item as any) || null,
+ chart.yAxis?.aggregation || null
+ )
+ })
+ }
+ />
+ </CompactFieldSelector>
+ </ChartConfigSection>
+ </ConfigUncollapsibleContent>
+ </ChartConfigGroup>
+ <ChartConfigGroup label="chartPanel.value" defaultMessage="Value">
+ <ConfigUncollapsibleContent>
+ <ChartConfigSection>
+ <CompactFieldSelector>
+ <FieldSelector
+ fields={fields as any}
+ value={chart.value?.field?.name}
+ erasable
+ onSelect={item =>
+ onUpdate(chart.id, {
+ value: axisFromField(
+ (item as any) || null,
+ chart.value?.aggregation || 'count'
+ )
+ })
+ }
+ />
+ </CompactFieldSelector>
+ </ChartConfigSection>
+ </ConfigUncollapsibleContent>
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage
+ id="chartPanel.aggregation"
+ defaultMessage="Aggregation"
+ />
+ </PanelLabel>
+ <ItemSelector
+ selectedItems={
+ CHART_AGGREGATION_OPTIONS.find(
+ option => option.id === chart.value?.aggregation
+ ) || CHART_AGGREGATION_OPTIONS[0]
+ }
+ options={CHART_AGGREGATION_OPTIONS}
+ displayOption={(d: {label: string}) => d.label}
+ getOptionValue={(d: {id: string}) => d.id}
+ multiSelect={false}
+ searchable={false}
+ size="small"
+ onChange={aggregation =>
+ onUpdate(chart.id, {
+ value: {
+ ...(chart.value as ChartAxis),
+ aggregation: aggregation as ChartAxis['aggregation']
+ }
+ })
+ }
+ />
+ </ChartConfigSectionWrapper>
+ </ChartConfigGroup>
+ </>
+ ) : null}
+
+ {isLayerChartConfig(chart) ? (
+ <ChartConfigGroup label="chartPanel.idField" defaultMessage="Feature id field">
+ <ConfigUncollapsibleContent>
+ <ChartConfigSection>
+ <CompactFieldSelector>
+ <FieldSelector
+ fields={fields as any}
+ value={chart.chartDisplay?.idField}
+ erasable
+ onSelect={item =>
+ onUpdate(chart.id, {
+ chartDisplay: {
+ ...chart.chartDisplay,
+ idField: (item as any)?.name ?? null
+ }
+ } as Partial<ChartConfig>)
+ }
+ />
+ </CompactFieldSelector>
+ </ChartConfigSection>
+ </ConfigUncollapsibleContent>
+ </ChartConfigGroup>
+ ) : null}
+
+ {chart.type === ChartType.barChart || chart.type === ChartType.horizontalBar ? (
+ <ChartConfigGroup label="chartPanel.color" defaultMessage="Color">
+ <ChartConfigSection>
+ <ChartColorSelectorWrapper>
+ <ColorSelector
+ colorSets={[
+ ((chart.colorBy ?? ChartColorBy.category) === ChartColorBy.none
+ ? {
+ selectedColor: asRgbColor(chart.chartDisplay?.color),
+ setColor: color =>
+ onUpdate(chart.id, {
+ chartDisplay: {
+ ...chart.chartDisplay,
+ color: color as RGBColor
+ }
+ })
+ }
+ : {
+ selectedColor: (chart.chartDisplay?.colorRange ||
+ getDefaultChartColorRange(
+ chart.numGroups || 10
+ )) as ColorRange,
+ isRange: true,
+ setColor: colorRange =>
+ onUpdate(chart.id, {
+ chartDisplay: {
+ ...chart.chartDisplay,
+ colorRange: colorRange as ColorRange
+ }
+ })
+ }) as ColorSet
+ ]}
+ colorUI={colorUIByChart[chart.id] || DEFAULT_COLOR_UI}
+ setColorUI={(next: NestedPartial<ColorUI>) => {
+ const current = colorUIByChart[chart.id] || DEFAULT_COLOR_UI;
+ const merged = {
+ ...current,
+ ...next,
+ colorRangeConfig: {
+ ...current.colorRangeConfig,
+ ...(next.colorRangeConfig || {})
+ }
+ } as ColorUI;
+ setColorUIByChart(prev => ({
+ ...prev,
+ [chart.id]: merged
+ }));
+
+ // Steps / reversed / type changes should refresh bar colors
+ // immediately (same as layer color UI), not only after picking
+ // another palette.
+ if (shouldUpdateChartColorRange(next, current)) {
+ const currentRange = (chart.chartDisplay?.colorRange ||
+ getDefaultChartColorRange(chart.numGroups || 10)) as ColorRange;
+ const colorRange = colorRangeFromColorUI(
+ currentRange,
+ merged.colorRangeConfig,
+ next
+ );
+ onUpdate(chart.id, {
+ chartDisplay: {
+ ...chart.chartDisplay,
+ colorRange
+ }
+ });
+ }
+ }}
+ />
+ </ChartColorSelectorWrapper>
+ </ChartConfigSection>
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage id="chartPanel.colorBy" defaultMessage="Color by" />
+ </PanelLabel>
+ <ItemSelector
+ selectedItems={
+ CHART_COLOR_BY_OPTIONS.find(
+ option => option.id === (chart.colorBy ?? ChartColorBy.category)
+ ) || CHART_COLOR_BY_OPTIONS[1]
+ }
+ options={CHART_COLOR_BY_OPTIONS}
+ displayOption={(d: {label: string}) => d.label}
+ getOptionValue={(d: {id: string}) => d.id}
+ multiSelect={false}
+ searchable={false}
+ size="small"
+ onChange={value =>
+ onUpdate(chart.id, {
+ colorBy: String(value) as ChartColorBy
+ })
+ }
+ />
+ </ChartConfigSectionWrapper>
+ </ChartConfigGroup>
+ ) : null}
+
+ {chart.type === ChartType.heatmapChart ? (
+ <ChartConfigGroup label="chartPanel.color" defaultMessage="Color">
+ <ChartConfigSection>
+ <ChartColorSelectorWrapper>
+ <ColorSelector
+ colorSets={[
+ {
+ selectedColor: (chart.chartDisplay?.colorRange ||
+ defaultHeatmapColorRange()) as ColorRange,
+ isRange: true,
+ setColor: colorRange => {
+ const nextRange = colorRange as ColorRange;
+ onUpdate(chart.id, {
+ chartDisplay: {
+ ...chart.chartDisplay,
+ colorRange: nextRange
+ }
+ });
+ syncColorUISteps(chart.id, nextRange);
+ }
+ } as ColorSet
+ ]}
+ colorUI={
+ colorUIByChart[chart.id] || {
+ ...DEFAULT_COLOR_UI,
+ colorRangeConfig: {
+ ...DEFAULT_COLOR_UI.colorRangeConfig,
+ type: 'sequential',
+ steps: HEATMAP_COLOR_STEPS
+ }
+ }
+ }
+ setColorUI={(next: NestedPartial<ColorUI>) => {
+ const current =
+ colorUIByChart[chart.id] ||
+ ({
+ ...DEFAULT_COLOR_UI,
+ colorRangeConfig: {
+ ...DEFAULT_COLOR_UI.colorRangeConfig,
+ type: 'sequential',
+ steps: HEATMAP_COLOR_STEPS
+ }
+ } as ColorUI);
+ const merged = {
+ ...current,
+ ...next,
+ colorRangeConfig: {
+ ...current.colorRangeConfig,
+ ...(next.colorRangeConfig || {})
+ }
+ } as ColorUI;
+ setColorUIByChart(prev => ({
+ ...prev,
+ [chart.id]: merged
+ }));
+
+ if (shouldUpdateChartColorRange(next, current)) {
+ const currentRange = (chart.chartDisplay?.colorRange ||
+ defaultHeatmapColorRange()) as ColorRange;
+ const colorRange = colorRangeFromColorUI(
+ currentRange,
+ merged.colorRangeConfig,
+ next
+ );
+ onUpdate(chart.id, {
+ chartDisplay: {
+ ...chart.chartDisplay,
+ colorRange
+ }
+ });
+ }
+ }}
+ />
+ </ChartColorSelectorWrapper>
+ </ChartConfigSection>
+ </ChartConfigGroup>
+ ) : null}
+
+ {!isLayerChartConfig(chart) ? (
+ chart.type === ChartType.bigNumber ? (
+ <ChartConfigGroup label="chartPanel.options" defaultMessage="Options">
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage id="chartPanel.pinned" defaultMessage="Pinned" />
+ </PanelLabel>
+ <Switch
+ id={`${chart.id}-pinned`}
+ checked={chart.pinned !== false}
+ onChange={() => onUpdate(chart.id, {pinned: chart.pinned === false})}
+ />
+ </ChartConfigSectionWrapper>
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage
+ id="chartPanel.formatTicks"
+ defaultMessage="Format Ticks"
+ />
+ </PanelLabel>
+ <ItemSelector
+ selectedItems={
+ BIG_NUMBER_FORMAT_OPTIONS.find(
+ option =>
+ option.id ===
+ (chart.chartDisplay?.format || DEFAULT_BIG_NUMBER_FORMAT)
+ ) || BIG_NUMBER_FORMAT_OPTIONS[0]
+ }
+ options={BIG_NUMBER_FORMAT_OPTIONS}
+ displayOption="label"
+ getOptionValue="id"
+ multiSelect={false}
+ searchable={false}
+ size="small"
+ onChange={format =>
+ onUpdate(chart.id, {
+ chartDisplay: {
+ ...chart.chartDisplay,
+ format: String(format)
+ }
+ })
+ }
+ />
+ </ChartConfigSectionWrapper>
+ </ChartConfigGroup>
+ ) : (
+ <ChartConfigGroup label="chartPanel.options" defaultMessage="Options">
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage id="chartPanel.pinned" defaultMessage="Pinned" />
+ </PanelLabel>
+ <Switch
+ id={`${chart.id}-pinned`}
+ checked={chart.pinned !== false}
+ onChange={() => onUpdate(chart.id, {pinned: chart.pinned === false})}
+ />
+ </ChartConfigSectionWrapper>
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage
+ id="chartPanel.applyFilters"
+ defaultMessage="Apply map filters"
+ />
+ </PanelLabel>
+ <Switch
+ id={`${chart.id}-apply-filters`}
+ checked={chart.applyFilters}
+ onChange={() => onUpdate(chart.id, {applyFilters: !chart.applyFilters})}
+ />
+ </ChartConfigSectionWrapper>
+ {chart.type === ChartType.barChart ||
+ chart.type === ChartType.horizontalBar ||
+ chart.type === ChartType.heatmapChart ? (
+ <ChartConfigSectionWrapper>
+ <PanelLabel>
+ <FormattedMessage
+ id="chartPanel.crossFilter"
+ defaultMessage="Cross-filter map"
+ />
+ </PanelLabel>
+ <Switch
+ id={`${chart.id}-cross-filter`}
+ checked={Boolean(chart.crossFilter?.enabled)}
+ onChange={() => {
+ const fieldNames = getCrossFilterFields(chart);
+ const filterId =
+ chart.crossFilter?.filterId ||
+ `chart-${chart.id}-${generateHashId(4)}`;
+ onUpdate(chart.id, {
+ crossFilter: {
+ enabled: !chart.crossFilter?.enabled,
+ filterId,
+ fieldNames: Object.fromEntries(
+ fieldNames.map((name, i) => [i === 0 ? 'x' : 'y', name])
+ ),
+ value: {}
+ }
+ });
+ }}
+ />
+ </ChartConfigSectionWrapper>
+ ) : null}
+ </ChartConfigGroup>
+ )
+ ) : null}
+ </ConfigBlock>
+ ) : null}
+ </ChartCard>
+ );
+ })}
+ </ChartList>
+ );
+ };
+
+ ChartPanelContent.displayName = 'ChartPanelContent';
+ return ChartPanelContent;
+}
+
+export default ChartPanelContentFactory;
diff --git a/src/components/src/map/charts/chart-type-selector.tsx b/src/components/src/map/charts/chart-type-selector.tsx
new file mode 100644
index 000000000..bd18d8c86
--- /dev/null
+++ b/src/components/src/map/charts/chart-type-selector.tsx
@@ -0,0 +1,199 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useMemo} from 'react';
+import styled, {withTheme} from 'styled-components';
+import classNames from 'classnames';
+
+import {DEFAULT_CHART_TYPE_OPTIONS, ChartType, LayerChartType} from '@kepler.gl/charts';
+import {FormattedMessage} from '@kepler.gl/localization';
+
+import {Add} from '../../common/icons';
+import ItemSelector from '../../common/item-selector/item-selector';
+import {classList} from '../../common/item-selector/dropdown-list';
+
+export const CHART_TYPE_DUMMY_ID = 'dummy';
+
+export type ChartTypeOption = {
+ id: ChartType | LayerChartType | typeof CHART_TYPE_DUMMY_ID;
+ label: string;
+};
+
+export type ChartTypeSelectorProps = {
+ onSelect: (type: ChartType | LayerChartType) => void;
+ theme?: any;
+ onBlur?: () => void;
+ onOpen?: () => void;
+};
+
+const DropdownWrapper = styled.div`
+ border: 0;
+ left: 0;
+ z-index: ${props => props.theme.dropdownWrapperZ};
+ width: 220px;
+ margin-left: -140px;
+ margin-top: 26px;
+
+ .typeahead__input {
+ border-color: ${props => props.theme.activeColor};
+ border-radius: 4px 4px 0px 0px !important;
+ }
+ .typeahead__input_box {
+ padding: 0px;
+ }
+ .typeahead__input_icon {
+ top: 34px;
+ right: 9px;
+ }
+`;
+
+const StyledChartTypeSelector = styled.div`
+ .item-selector .item-selector__dropdown {
+ padding: 4px 10px 4px 10px;
+ width: fit-content;
+ background-color: ${props => props.theme.secondaryBtnBgd};
+ border-radius: ${props => props.theme.primaryBtnRadius};
+ font-size: ${props => props.theme.primaryBtnFontSizeDefault};
+ border: none;
+
+ &:hover {
+ background-color: ${props => props.theme.secondaryBtnBgdHover};
+ }
+
+ .item-selector__dropdown__value {
+ color: ${props => props.theme.secondaryBtnActColor};
+ }
+ }
+`;
+
+const StyledAddButton = styled(Add)`
+ margin-right: 8px;
+ height: 16px;
+`;
+
+const StyledPlaceholderButton = styled.div`
+ align-items: center;
+ display: flex;
+ justify-content: space-between;
+ margin-left: 3px;
+ margin-right: 3px;
+ letter-spacing: 0.3px;
+ font-weight: 500;
+`;
+
+const DropdownListWrapper = styled.div`
+ ${props => props.theme.dropdownList};
+ background-color: ${props => props.theme.dropdownListBgd};
+ display: flex;
+ flex-direction: column;
+ padding: 8px 0;
+ max-height: 320px;
+ overflow-y: auto;
+`;
+
+const StyledDropdownListItem = styled.div`
+ padding: 8px 16px;
+ font-size: 12px;
+ color: ${props => props.theme.textColor};
+ cursor: pointer;
+
+ &:hover {
+ background-color: ${props => props.theme.dropdownListHighlightBg};
+ color: ${props => props.theme.textColorHl};
+ }
+`;
+
+const getDisplayOption = (op: ChartTypeOption) => op.label;
+const getOptionValue = (op: ChartTypeOption) => op.id;
+
+function ChartTypeListItem({value}: {value: ChartTypeOption; isTile?: boolean}) {
+ if (value?.id === CHART_TYPE_DUMMY_ID) {
+ return (
+ <StyledPlaceholderButton>
+ <StyledAddButton />
+ <FormattedMessage id="chartPanel.add" defaultMessage="Add" />
+ </StyledPlaceholderButton>
+ );
+ }
+
+ return <span>{value.label}</span>;
+}
+
+function ChartTypeDropdownList({
+ onOptionSelected,
+ options,
+ selectionIndex
+}: {
+ onOptionSelected: (value: ChartTypeOption) => void;
+ options: ChartTypeOption[];
+ selectedItems?: ChartTypeOption[];
+ selectionIndex: number;
+ customListItemComponent?: React.FC<{value: ChartTypeOption; isTile?: boolean}>;
+}) {
+ return (
+ <DropdownListWrapper className={classList.list}>
+ {options.map((value, i) => (
+ <StyledDropdownListItem
+ key={`${value.id}_${i}`}
+ className={classNames({hover: selectionIndex === i})}
+ onMouseDown={e => {
+ e.preventDefault();
+ onOptionSelected(value);
+ }}
+ >
+ {value.label}
+ </StyledDropdownListItem>
+ ))}
+ </DropdownListWrapper>
+ );
+}
+
+ChartTypeSelectorFactory.deps = [];
+
+export default function ChartTypeSelectorFactory(): React.FC<
+ Omit<ChartTypeSelectorProps, 'theme'>
+> {
+ const ChartTypeSelector: React.FC<ChartTypeSelectorProps> = ({onSelect, onBlur, onOpen}) => {
+ const selectedItems = useMemo(
+ () => [{id: CHART_TYPE_DUMMY_ID, label: CHART_TYPE_DUMMY_ID} as ChartTypeOption],
+ []
+ );
+
+ const options = useMemo(
+ () =>
+ DEFAULT_CHART_TYPE_OPTIONS.map(option => ({
+ id: option.id,
+ label: option.label
+ })),
+ []
+ );
+
+ return (
+ <StyledChartTypeSelector className="chart-config__type">
+ <ItemSelector
+ selectedItems={selectedItems}
+ options={options}
+ multiSelect={false}
+ searchable={false}
+ placeholder="chartPanel.add"
+ onChange={value => {
+ const type =
+ typeof value === 'string' ? value : (value as ChartTypeOption | null | undefined)?.id;
+ if (type && type !== CHART_TYPE_DUMMY_ID) {
+ onSelect(type as ChartType | LayerChartType);
+ }
+ }}
+ onBlur={onBlur}
+ onOpen={onOpen}
+ getOptionValue={getOptionValue}
+ displayOption={getDisplayOption}
+ DropDownLineItemRenderComponent={ChartTypeListItem}
+ DropDownRenderComponent={ChartTypeDropdownList}
+ DropDownWrapperComponent={DropdownWrapper}
+ />
+ </StyledChartTypeSelector>
+ );
+ };
+
+ return withTheme(ChartTypeSelector) as React.FC<Omit<ChartTypeSelectorProps, 'theme'>>;
+}
diff --git a/src/components/src/map/charts/layer-chart-hover.tsx b/src/components/src/map/charts/layer-chart-hover.tsx
new file mode 100644
index 000000000..fc749c1be
--- /dev/null
+++ b/src/components/src/map/charts/layer-chart-hover.tsx
@@ -0,0 +1,79 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import React, {useMemo} from 'react';
+import styled from 'styled-components';
+
+import {
+ ChartConfig,
+ ChartRenderer,
+ computeLayerChart,
+ getHoverRowIndexes,
+ isLayerChartConfig,
+ toChartableDataset
+} from '@kepler.gl/charts';
+import {LayerHoverProp} from '@kepler.gl/reducers';
+import {Datasets} from '@kepler.gl/table';
+import {getApplicationConfig} from '@kepler.gl/utils';
+
+const HoverChartWrap = styled.div`
+ min-width: 180px;
+ max-width: 260px;
+ margin-top: 8px;
+`;
+
+const HoverTitle = styled.div`
+ font-size: 11px;
+ color: ${props => props.theme.subtextColor};
+ margin-bottom: 4px;
+`;
+
+export type LayerChartHoverProps = {
+ charts?: ChartConfig[];
+ datasets?: Datasets;
+ layerHoverProp: LayerHoverProp | null;
+};
+
+export default function LayerChartHover({
+ charts,
+ datasets,
+ layerHoverProp
+}: LayerChartHoverProps): React.ReactElement | null {
+ const hoverCharts = useMemo(() => {
+ if (!getApplicationConfig().enableChartsPanel || !layerHoverProp?.layer || !charts?.length) {
+ return [];
+ }
+ return charts.filter(
+ chart => isLayerChartConfig(chart) && chart.layerId === layerHoverProp.layer.id
+ );
+ }, [charts, layerHoverProp]);
+
+ if (!hoverCharts.length || !datasets || !layerHoverProp) {
+ return null;
+ }
+
+ const dataId = layerHoverProp.layer.config.dataId;
+ const dataset = dataId ? toChartableDataset(datasets[dataId]) : null;
+ if (!dataset) {
+ return null;
+ }
+ const hoverRowIndex = (layerHoverProp.data as {_rowIndex?: number} | null)?._rowIndex;
+
+ return (
+ <>
+ {hoverCharts.map(chart => {
+ if (!isLayerChartConfig(chart)) {
+ return null;
+ }
+ const indexes = getHoverRowIndexes(dataset, chart, hoverRowIndex);
+ const view = computeLayerChart(chart, dataset, indexes);
+ return (
+ <HoverChartWrap key={chart.id} className="map-popover__layer-chart">
+ <HoverTitle>{chart.title}</HoverTitle>
+ <ChartRenderer data={view} />
+ </HoverChartWrap>
+ );
+ })}
+ </>
+ );
+}
diff --git a/src/components/src/map/map-control.tsx b/src/components/src/map/map-control.tsx
index 122932e34..324bc944a 100644
--- a/src/components/src/map/map-control.tsx
+++ b/src/components/src/map/map-control.tsx
@@ -14,9 +14,16 @@ import LocalePanelFactory from './locale-panel';
import ThemeToggleButtonFactory from './theme-toggle-button';
import MapNavigationControlFactory from './map-navigation-control';
import {Layer} from '@kepler.gl/layers';
-import {Editor, LayerVisConfig, LayerOrder, MapControls, MapState} from '@kepler.gl/types';
+import {
+ Editor,
+ LayerVisConfig,
+ LayerOrder,
+ MapControls,
+ MapState,
+ ChartConfig
+} from '@kepler.gl/types';
import {Datasets} from '@kepler.gl/table';
-import {MapStateActions, UIStateActions} from '@kepler.gl/actions';
+import {MapStateActions, UIStateActions, VisStateActions} from '@kepler.gl/actions';
import {getApplicationConfig} from '@kepler.gl/utils';
import {MapViewMode} from '@kepler.gl/constants';
@@ -97,6 +104,8 @@ export type MapControlProps = {
mapHeight?: number;
splitMaps?: {layers: {[key: string]: boolean}}[];
onToggleLayerForMap?: (mapIndex: number, layerId: string) => void;
+ charts?: ChartConfig[];
+ visStateActions?: typeof VisStateActions;
};
MapControlFactory.deps = [
diff --git a/src/components/src/map/map-popover-content.tsx b/src/components/src/map/map-popover-content.tsx
index f2aed60a4..24ec31ab4 100644
--- a/src/components/src/map/map-popover-content.tsx
+++ b/src/components/src/map/map-popover-content.tsx
@@ -1,11 +1,16 @@
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project
-import React from 'react';
+import React, {lazy, Suspense} from 'react';
import {injectIntl, IntlShape} from 'react-intl';
import {LayerHoverProp} from '@kepler.gl/reducers';
import LayerHoverInfoFactory from './layer-hover-info';
import CoordinateInfoFactory from './coordinate-info';
+import {ChartConfig} from '@kepler.gl/types';
+import {Datasets} from '@kepler.gl/table';
+import {getApplicationConfig} from '@kepler.gl/utils';
+
+const LayerChartHover = lazy(() => import('./charts/layer-chart-hover'));
MapPopoverContentFactory.deps = [LayerHoverInfoFactory, CoordinateInfoFactory];
@@ -13,12 +18,25 @@ type MapPopoverContentProps = {
coordinate: [number, number] | boolean;
layerHoverProp: LayerHoverProp | null;
zoom: number;
+ charts?: ChartConfig[];
+ datasets?: Datasets;
};
type IntlProps = {
intl: IntlShape;
};
+function hasHoverLayerChart(
+ charts: ChartConfig[] | undefined,
+ layerHoverProp: LayerHoverProp | null
+): boolean {
+ if (!getApplicationConfig().enableChartsPanel || !layerHoverProp?.layer || !charts?.length) {
+ return false;
+ }
+ const layerId = layerHoverProp.layer.id;
+ return charts.some(chart => 'layerId' in chart && chart.layerId === layerId);
+}
+
export default function MapPopoverContentFactory(
LayerHoverInfo: ReturnType<typeof LayerHoverInfoFactory>,
CoordinateInfo: ReturnType<typeof CoordinateInfoFactory>
@@ -26,12 +44,19 @@ export default function MapPopoverContentFactory(
const MapPopoverContent: React.FC<MapPopoverContentProps & IntlProps> = ({
coordinate,
layerHoverProp,
- zoom
+ zoom,
+ charts,
+ datasets
}) => {
return (
<>
{Array.isArray(coordinate) && <CoordinateInfo coordinate={coordinate} zoom={zoom} />}
{layerHoverProp && <LayerHoverInfo {...layerHoverProp} />}
+ {hasHoverLayerChart(charts, layerHoverProp) ? (
+ <Suspense fallback={null}>
+ <LayerChartHover charts={charts} datasets={datasets} layerHoverProp={layerHoverProp} />
+ </Suspense>
+ ) : null}
</>
);
};
diff --git a/src/components/src/map/map-popover.tsx b/src/components/src/map/map-popover.tsx
index f76dbf3d3..8ade108da 100644
--- a/src/components/src/map/map-popover.tsx
+++ b/src/components/src/map/map-popover.tsx
@@ -12,7 +12,8 @@ import {parseGeoJsonRawFeature} from '@kepler.gl/layers';
import {generateHashId, idToPolygonGeo} from '@kepler.gl/common-utils';
import {LAYER_TYPES} from '@kepler.gl/constants';
import {LayerHoverProp, getLayerHoverPropValue} from '@kepler.gl/reducers';
-import {Feature, FeatureSelectionContext} from '@kepler.gl/types';
+import {ChartConfig, Feature, FeatureSelectionContext} from '@kepler.gl/types';
+import {Datasets} from '@kepler.gl/table';
import {
FloatingPortal,
flip,
@@ -189,6 +190,8 @@ export type MapPopoverProps = {
type: string;
features: Feature[];
};
+ charts?: ChartConfig[];
+ datasets?: Datasets;
};
type IntlProps = {
@@ -210,7 +213,9 @@ export default function MapPopoverFactory(
onClose,
onSetFeatures,
setSelectedFeature,
- featureCollection
+ featureCollection,
+ charts,
+ datasets
}) => {
const [horizontalPlacement, setHorizontalPlacement] = useState('start');
const moveLeft = () => setHorizontalPlacement('end');
@@ -279,6 +284,8 @@ export default function MapPopoverFactory(
coordinate={coordinate}
zoom={zoom}
layerHoverProp={layerHoverProp}
+ charts={charts}
+ datasets={datasets}
/>
</PopoverContent>
{layerHoverProp?.layer?.type &&
diff --git a/src/components/src/modals/export-image-modal.tsx b/src/components/src/modals/export-image-modal.tsx
index 95a676d3f..ea0910b84 100644
--- a/src/components/src/modals/export-image-modal.tsx
+++ b/src/components/src/modals/export-image-modal.tsx
@@ -26,6 +26,7 @@ import {StyledModalContent, SelectionButton, CheckMark} from '../common/styled-c
import Switch from '../common/switch';
import {injectIntl, IntlShape} from 'react-intl';
import {FormattedMessage} from '@kepler.gl/localization';
+import {getApplicationConfig} from '@kepler.gl/utils';
const ImageOptionList = styled.div`
display: flex;
@@ -124,7 +125,8 @@ const ExportImageModalFactory = () => {
cleanupExportImage,
intl
}) => {
- const {legend, ratio, resolution} = exportImage;
+ const {legend, charts, ratio, resolution} = exportImage;
+ const chartsEnabled = Boolean(getApplicationConfig().enableChartsPanel);
// Filter resolutions based on selected ratio
const filteredResolutions = useMemo(() => {
@@ -253,6 +255,20 @@ const ExportImageModalFactory = () => {
onChange={() => onUpdateImageSetting({legend: !legend})}
/>
</div>
+ {chartsEnabled ? (
+ <div className="image-option-section">
+ <div className="image-option-section-title">
+ <FormattedMessage id={'modal.exportImage.chartsTitle'} />
+ </div>
+ <Switch
+ type="checkbox"
+ id="add-map-charts"
+ checked={Boolean(charts)}
+ label={intl.formatMessage({id: 'modal.exportImage.chartsAdd'})}
+ onChange={() => onUpdateImageSetting({charts: !charts})}
+ />
+ </div>
+ ) : null}
</ImageOptionList>
<ImagePreview exportImage={exportImage} />
</StyledModalContent>
diff --git a/src/components/src/modals/image-modal-container.tsx b/src/components/src/modals/image-modal-container.tsx
index 5be8a079f..292890718 100644
--- a/src/components/src/modals/image-modal-container.tsx
+++ b/src/components/src/modals/image-modal-container.tsx
@@ -41,7 +41,8 @@ const ImageModalContainer: React.FC<ImageModalContainerProps> = ({
mapW: get(provider, ['thumbnail', 'width']) || MAP_THUMBNAIL_DIMENSION.width,
mapH: get(provider, ['thumbnail', 'height']) || MAP_THUMBNAIL_DIMENSION.height,
ratio: EXPORT_IMG_RATIOS.CUSTOM,
- legend: false
+ legend: false,
+ charts: false
});
}
} else {
@@ -49,7 +50,8 @@ const ImageModalContainer: React.FC<ImageModalContainerProps> = ({
mapW: MAP_THUMBNAIL_DIMENSION.width,
mapH: MAP_THUMBNAIL_DIMENSION.height,
ratio: EXPORT_IMG_RATIOS.CUSTOM,
- legend: false
+ legend: false,
+ charts: false
});
}
}, [provider, onUpdateImageSetting]);
diff --git a/src/components/src/plot-container.tsx b/src/components/src/plot-container.tsx
index 1bb6095d3..66fb551d2 100644
--- a/src/components/src/plot-container.tsx
+++ b/src/components/src/plot-container.tsx
@@ -92,8 +92,9 @@ const StyledPlotContainer = styled.div<StyledPlotContainerProps>`
top: ${OUT_OF_SCREEN_POSITION}px;
left: ${OUT_OF_SCREEN_POSITION}px;
- /* Apply zoom to legend panel based on export height */
- .map-control-panel {
+ /* Apply zoom to legend/chart panels based on export height */
+ .map-control-panel,
+ .chart-manager {
zoom: ${props => props.$legendZoom || 1} !important;
}
`;
@@ -114,6 +115,7 @@ interface PlotContainerProps {
ratio?: string;
resolution?: string;
legend?: boolean;
+ charts?: boolean;
center?: boolean;
imageSize: ExportImage['imageSize'];
escapeXhtmlForWebpack?: boolean;
@@ -144,6 +146,7 @@ export default function PlotContainerFactory(
ratio,
resolution,
legend = false,
+ charts = false,
center,
imageSize,
escapeXhtmlForWebpack,
@@ -299,11 +302,16 @@ export default function PlotContainerFactory(
// Screenshot update effect
useEffect(() => {
- if (ratio !== undefined || resolution !== undefined || legend !== undefined) {
+ if (
+ ratio !== undefined ||
+ resolution !== undefined ||
+ legend !== undefined ||
+ charts !== undefined
+ ) {
setExportImageSetting({processing: true});
tryScreenshot();
}
- }, [ratio, resolution, legend, setExportImageSetting, tryScreenshot]);
+ }, [ratio, resolution, legend, charts, setExportImageSetting, tryScreenshot]);
// Memoize size calculations
const {size, width, height} = useMemo(() => {
@@ -363,6 +371,10 @@ export default function PlotContainerFactory(
show: Boolean(legend),
active: true,
settings: mapFields.mapControls?.mapLegend?.settings
+ },
+ chart: {
+ show: false,
+ active: Boolean(charts)
}
},
onMapRender,
@@ -390,6 +402,7 @@ export default function PlotContainerFactory(
scaledMapStyle,
newMapState,
legend,
+ charts,
onMapRender,
deckRenderCallbacks,
plotEffects,
diff --git a/src/constants/src/default-settings.ts b/src/constants/src/default-settings.ts
index 73d594265..e13b25d49 100644
--- a/src/constants/src/default-settings.ts
+++ b/src/constants/src/default-settings.ts
@@ -1365,6 +1365,7 @@ export const MAP_CONTROLS = keyMirror({
mapTheme: null,
effect: null,
annotation: null,
+ chart: null,
viewportJson: null
});
diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.ts
index b52e5ee3c..50f279fbf 100644
--- a/src/localization/src/translations/ca.ts
+++ b/src/localization/src/translations/ca.ts
@@ -379,6 +379,8 @@ export default {
syncTimelineEnd: 'Fi del període de temps del filtre actual',
showEffectPanel: "Mostra el panell d'efectes",
hideEffectPanel: "Amaga el panell d'efectes",
+ showChartPanel: 'Mostra els gràfics',
+ hideChartPanel: 'Amaga els gràfics',
showAnnotationPanel: 'Mostra les anotacions',
hideAnnotationPanel: 'Amaga les anotacions',
removeAnnotation: "Elimina l'anotació",
@@ -464,7 +466,9 @@ export default {
resolutionDescription: 'Alta resolució és millor per a les impressions.',
resolutionPlaceholder: 'Selecciona resolució...',
mapLegendTitle: 'Llegenda del mapa',
- mapLegendAdd: 'Afegir llegenda al mapa'
+ mapLegendAdd: 'Afegir llegenda al mapa',
+ chartsTitle: 'Gràfics',
+ chartsAdd: 'Afegir gràfics al mapa'
},
exportVideo: {
animation: 'Animació',
@@ -626,7 +630,8 @@ export default {
header: {
visibleLayers: 'Capes visibles',
layerLegend: 'Llegenda de capes',
- annotations: 'Anotacions'
+ annotations: 'Anotacions',
+ charts: 'Gràfics'
},
interactions: {
tooltip: 'Suggeriment',
diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.ts
index 31dc4bbad..9c5c6f078 100644
--- a/src/localization/src/translations/cn.ts
+++ b/src/localization/src/translations/cn.ts
@@ -364,6 +364,8 @@ export default {
syncTimelineEnd: '当前过滤时间段的结束',
showEffectPanel: '显示效果面板',
hideEffectPanel: '隐藏效果面板',
+ showChartPanel: '显示图表',
+ hideChartPanel: '隐藏图表',
showAnnotationPanel: '显示注释',
hideAnnotationPanel: '隐藏注释',
removeAnnotation: '删除注释',
@@ -449,7 +451,9 @@ export default {
resolutionDescription: '高分辨率更适合打印。',
resolutionPlaceholder: '选择分辨率...',
mapLegendTitle: '地图图例',
- mapLegendAdd: '在地图上添加图例'
+ mapLegendAdd: '在地图上添加图例',
+ chartsTitle: '图表',
+ chartsAdd: '在地图上添加图表'
},
exportVideo: {
animation: '动画',
@@ -607,7 +611,8 @@ export default {
header: {
visibleLayers: '可见图层',
layerLegend: '图层图例',
- annotations: '注释'
+ annotations: '注释',
+ charts: '图表'
},
interactions: {
tooltip: '工具提示',
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index 8f9aa13b2..468cb0e3b 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -468,6 +468,8 @@ export default {
syncTimelineEnd: 'End of current filter timeframe',
showEffectPanel: 'Show effect panel',
hideEffectPanel: 'Hide effect panel',
+ showChartPanel: 'Show charts',
+ hideChartPanel: 'Hide charts',
showAnnotationPanel: 'Show annotations',
hideAnnotationPanel: 'Hide annotations',
removeAnnotation: 'Remove annotation',
@@ -478,6 +480,12 @@ export default {
removeEffect: 'Remove effect',
disableEffect: 'Disable effect',
effectSettings: 'Effect settings',
+ chartSettings: 'Chart settings',
+ removeChart: 'Remove chart',
+ pinChart: 'Pin chart',
+ unpinChart: 'Unpin chart',
+ showChartCaption: 'Show caption',
+ hideChartCaption: 'Hide caption',
editLayerJson: 'Edit layer JSON',
editFilterJson: 'Edit filter JSON',
editEffectJson: 'Edit effect JSON',
@@ -518,6 +526,31 @@ export default {
noLayersToExtract: 'No layers to extract'
},
+ chartPanel: {
+ add: 'Add',
+ addChart: 'Add chart',
+ selectType: 'Select chart type',
+ empty: 'Add a chart to summarize the current map data.',
+ dataset: 'Dataset',
+ layer: 'Layer',
+ field: 'Field',
+ xAxis: 'X axis',
+ yAxis: 'Y axis',
+ value: 'Value',
+ idField: 'Feature id field',
+ aggregation: 'Aggregation',
+ period: 'Period',
+ color: 'Color',
+ colorBy: 'Color by',
+ colors: 'Colors',
+ options: 'Options',
+ pinned: 'Pinned',
+ formatTicks: 'Format Ticks',
+ applyFilters: 'Apply map filters',
+ crossFilter: 'Cross-filter map',
+ configure: 'Configure'
+ },
+
exportVideoModal: {
animation: 'Animation',
settings: 'Settings'
@@ -555,7 +588,9 @@ export default {
resolutionDescription: 'High resolution is better for prints.',
resolutionPlaceholder: 'Select resolution...',
mapLegendTitle: 'Map Legend',
- mapLegendAdd: 'Add legend on map'
+ mapLegendAdd: 'Add legend on map',
+ chartsTitle: 'Charts',
+ chartsAdd: 'Add charts on map'
},
exportVideo: {
animation: 'Animation',
@@ -776,7 +811,8 @@ ${'```'}
header: {
visibleLayers: 'Visible layers',
layerLegend: 'Legend',
- annotations: 'Annotations'
+ annotations: 'Annotations',
+ charts: 'Charts'
},
interactions: {
tooltip: 'Tooltip',
diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.ts
index 7b5e7c521..442baf9c3 100644
--- a/src/localization/src/translations/es.ts
+++ b/src/localization/src/translations/es.ts
@@ -380,6 +380,8 @@ export default {
syncTimelineEnd: 'Fin del período de tiempo del filtro actual',
showEffectPanel: 'Mostrar panel de efectos',
hideEffectPanel: 'Ocultar panel de efectos',
+ showChartPanel: 'Mostrar gráficos',
+ hideChartPanel: 'Ocultar gráficos',
showAnnotationPanel: 'Mostrar anotaciones',
hideAnnotationPanel: 'Ocultar anotaciones',
removeAnnotation: 'Eliminar anotación',
@@ -465,7 +467,9 @@ export default {
resolutionDescription: 'Una alta resolución es mejor para las impresiones.',
resolutionPlaceholder: 'Seleccionar resolución...',
mapLegendTitle: 'Leyenda del mapa',
- mapLegendAdd: 'Añadir leyenda al mapa'
+ mapLegendAdd: 'Añadir leyenda al mapa',
+ chartsTitle: 'Gráficos',
+ chartsAdd: 'Añadir gráficos al mapa'
},
exportVideo: {
animation: 'Animación',
@@ -627,7 +631,8 @@ export default {
header: {
visibleLayers: 'Capas visibles',
layerLegend: 'Capa de leyenda',
- annotations: 'Anotaciones'
+ annotations: 'Anotaciones',
+ charts: 'Gráficos'
},
interactions: {
tooltip: 'Sugerencias',
diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.ts
index 57a6e3c16..9d7696d63 100644
--- a/src/localization/src/translations/fi.ts
+++ b/src/localization/src/translations/fi.ts
@@ -376,6 +376,8 @@ export default {
syncTimelineEnd: 'Nykyisen suodattimen aikajakson loppu',
showEffectPanel: 'Näytä efektipaneeli',
hideEffectPanel: 'Piilota efektipaneeli',
+ showChartPanel: 'Näytä kaaviot',
+ hideChartPanel: 'Piilota kaaviot',
showAnnotationPanel: 'Näytä merkinnät',
hideAnnotationPanel: 'Piilota merkinnät',
removeAnnotation: 'Poista merkintä',
@@ -463,7 +465,9 @@ export default {
resolutionDescription: 'Korkea resoluutio on parempi tulostamista varten.',
resolutionPlaceholder: 'Valitse resoluutio...',
mapLegendTitle: 'Kartan selite',
- mapLegendAdd: 'Lisää selite karttaan'
+ mapLegendAdd: 'Lisää selite karttaan',
+ chartsTitle: 'Kaaviot',
+ chartsAdd: 'Lisää kaaviot karttaan'
},
exportVideo: {
animation: 'Animaatio',
@@ -624,7 +628,8 @@ export default {
header: {
visibleLayers: 'Näkyvissä olevat tasot',
layerLegend: 'Tason selite',
- annotations: 'Merkinnät'
+ annotations: 'Merkinnät',
+ charts: 'Kaaviot'
},
interactions: {
tooltip: 'Vihje',
diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.ts
index ed165ae6d..7f0e15165 100644
--- a/src/localization/src/translations/ja.ts
+++ b/src/localization/src/translations/ja.ts
@@ -374,6 +374,8 @@ export default {
syncTimelineEnd: '現在のフィルタ期間の終了',
showEffectPanel: 'エフェクトパネルを表示',
hideEffectPanel: 'エフェクトパネルを非表示',
+ showChartPanel: 'チャートを表示',
+ hideChartPanel: 'チャートを非表示',
showAnnotationPanel: 'アノテーションを表示',
hideAnnotationPanel: 'アノテーションを非表示',
removeAnnotation: 'アノテーションを削除',
@@ -461,7 +463,9 @@ export default {
resolutionDescription: '印刷には高解像度が適しています。',
resolutionPlaceholder: '解像度を選択...',
mapLegendTitle: '地図の凡例',
- mapLegendAdd: '地図に判例を追加'
+ mapLegendAdd: '地図に判例を追加',
+ chartsTitle: 'チャート',
+ chartsAdd: '地図にチャートを追加'
},
exportVideo: {
animation: 'アニメーション',
@@ -623,7 +627,8 @@ export default {
header: {
visibleLayers: '表示中のレイヤ',
layerLegend: 'レイヤ判例',
- annotations: 'アノテーション'
+ annotations: 'アノテーション',
+ charts: 'チャート'
},
interactions: {
tooltip: 'ツールチップ',
diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.ts
index 036a7ec69..107d8211b 100644
--- a/src/localization/src/translations/pt.ts
+++ b/src/localization/src/translations/pt.ts
@@ -380,6 +380,8 @@ export default {
syncTimelineEnd: 'Fim do período de tempo do filtro atual',
showEffectPanel: 'Mostrar painel de efeitos',
hideEffectPanel: 'Ocultar painel de efeitos',
+ showChartPanel: 'Mostrar gráficos',
+ hideChartPanel: 'Ocultar gráficos',
showAnnotationPanel: 'Mostrar anotações',
hideAnnotationPanel: 'Ocultar anotações',
removeAnnotation: 'Remover anotação',
@@ -465,7 +467,9 @@ export default {
resolutionDescription: 'Alta resolução é melhor para impressões.',
resolutionPlaceholder: 'Selecionar resolução...',
mapLegendTitle: 'Legenda do Mapa',
- mapLegendAdd: 'Adicionar Legenda no mapa'
+ mapLegendAdd: 'Adicionar Legenda no mapa',
+ chartsTitle: 'Gráficos',
+ chartsAdd: 'Adicionar gráficos no mapa'
},
exportVideo: {
animation: 'Animação',
@@ -628,7 +632,8 @@ export default {
header: {
visibleLayers: 'Camadas Visíveis',
layerLegend: 'Legenda da Camada',
- annotations: 'Anotações'
+ annotations: 'Anotações',
+ charts: 'Gráficos'
},
interactions: {
tooltip: 'Dica de contexto',
diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.ts
index 6b2189938..d4d2506ea 100644
--- a/src/localization/src/translations/ru.ts
+++ b/src/localization/src/translations/ru.ts
@@ -377,6 +377,8 @@ export default {
syncTimelineEnd: 'Конец текущего периода фильтра',
showEffectPanel: 'Показать панель эффектов',
hideEffectPanel: 'Скрыть панель эффектов',
+ showChartPanel: 'Показать графики',
+ hideChartPanel: 'Скрыть графики',
showAnnotationPanel: 'Показать аннотации',
hideAnnotationPanel: 'Скрыть аннотации',
removeAnnotation: 'Удалить аннотацию',
@@ -465,7 +467,9 @@ export default {
resolutionDescription: 'Для печати лучше использовать высокое разрешение',
resolutionPlaceholder: 'Выберите разрешение...',
mapLegendTitle: 'Легенда карты',
- mapLegendAdd: 'Добавить легенду на карту'
+ mapLegendAdd: 'Добавить легенду на карту',
+ chartsTitle: 'Графики',
+ chartsAdd: 'Добавить графики на карту'
},
exportVideo: {
animation: 'Анимация',
@@ -628,7 +632,8 @@ export default {
header: {
visibleLayers: 'Видимые слои',
layerLegend: 'Легенда слоя',
- annotations: 'Аннотации'
+ annotations: 'Аннотации',
+ charts: 'Графики'
},
interactions: {
tooltip: 'Подсказка',
diff --git a/src/reducers/src/ui-state-updaters.ts b/src/reducers/src/ui-state-updaters.ts
index d4019c33a..2131f5550 100644
--- a/src/reducers/src/ui-state-updaters.ts
+++ b/src/reducers/src/ui-state-updaters.ts
@@ -133,6 +133,7 @@ export const DEFAULT_MAP_CONTROLS: MapControls = (
* @property ratio Default: `'SCREEN'`,
* @property resolution Default: `'ONE_X'`,
* @property legend Default: `false`,
+ * @property charts Default: `false`,
* @property mapH Default: 0,
* @property mapW Default: 0,
* @property imageSize Default: {zoomOffset: 0, scale: 1, imageW: 0, imageH: 0},
@@ -147,6 +148,7 @@ export const DEFAULT_EXPORT_IMAGE: ExportImage = {
ratio: EXPORT_IMG_RATIOS.SCREEN,
resolution: RESOLUTIONS.ONE_X,
legend: false,
+ charts: false,
mapH: 0,
mapW: 0,
imageSize: {
@@ -529,7 +531,7 @@ export const openDeleteModalUpdater = (
});
/**
- * Set `exportImage.legend` to `true` or `false`
+ * Set `exportImage` options such as `legend` and `charts` to `true` or `false`
* @memberof uiStateUpdaters
* @param state `uiState`
* @returns nextState
@@ -1032,6 +1034,22 @@ export const receiveMapConfigUpdater = (
};
}
+ if (uiState.mapControls?.chart?.active) {
+ const currentChart = newState.mapControls.chart;
+ newState = {
+ ...newState,
+ mapControls: {
+ ...newState.mapControls,
+ chart: {
+ show: true,
+ ...currentChart,
+ active: true,
+ activeMapIndex: 0
+ }
+ }
+ };
+ }
+
if (uiState.mapControls?.mapLegend?.settings) {
newState = setMapControlSettingsUpdater(newState, {
payload: {panelId: 'mapLegend', settings: uiState.mapControls.mapLegend.settings}
diff --git a/src/reducers/src/vis-state-merger.ts b/src/reducers/src/vis-state-merger.ts
index 4f354b2a7..c6ff0c44b 100644
--- a/src/reducers/src/vis-state-merger.ts
+++ b/src/reducers/src/vis-state-merger.ts
@@ -45,7 +45,8 @@ import {
NestedPartial,
SavedAnimationConfig,
LayerOrder,
- LayerOrderGroup
+ LayerOrderGroup,
+ ChartConfig
} from '@kepler.gl/types';
import {KeplerTable, Datasets, assignGpuChannels, resetFilterGpuMode} from '@kepler.gl/table';
@@ -692,8 +693,75 @@ export function mergeSplitMaps<S extends VisState>(
}
/**
- * Merge effects with saved config
+ * Merge charts with saved config. Charts whose dataset is not loaded yet are
+ * parked on `chartsToBeMerged` (same as filters) so dataset replace can remap
+ * `dataId` and restore them after the new table lands.
*/
+export function mergeCharts<S extends VisState>(
+ state: S,
+ charts: ChartConfig[] | undefined,
+ fromConfig?: boolean
+): S {
+ if (!Array.isArray(charts) || !charts.length) {
+ return state;
+ }
+ const incomingIds = new Set(
+ charts.map(chart => chart?.id).filter((id): id is string => Boolean(id))
+ );
+ const existingIds = new Set((state.charts || []).map(chart => chart.id));
+ const nextCharts: ChartConfig[] = [];
+ const failed: ChartConfig[] = [];
+ charts.forEach(chart => {
+ if (!chart || !chart.id || existingIds.has(chart.id)) {
+ return;
+ }
+ const normalized: ChartConfig = fromConfig
+ ? {
+ ...chart,
+ // Older configs omit `pinned`; keep charts visible like the legend.
+ pinned: chart.pinned !== false,
+ display: {
+ ...chart.display,
+ isConfigActive: false
+ }
+ }
+ : chart;
+ if (
+ normalized.dataId &&
+ (!state.datasets[normalized.dataId] || state.isMergingDatasets[normalized.dataId])
+ ) {
+ failed.push(normalized);
+ return;
+ }
+ existingIds.add(normalized.id);
+ nextCharts.push(normalized);
+ });
+ if (!nextCharts.length && !failed.length) {
+ return state;
+ }
+ return {
+ ...state,
+ charts: nextCharts.length ? [...(state.charts || []), ...nextCharts] : state.charts,
+ chartsToBeMerged: [
+ ...(state.chartsToBeMerged || []).filter(chart => !incomingIds.has(chart.id)),
+ ...failed
+ ]
+ };
+}
+
+export function replaceChartDatasetIds(
+ savedCharts: ChartConfig[] | undefined,
+ dataId: string,
+ dataIdToUse: string
+): ChartConfig[] | null {
+ if (!Array.isArray(savedCharts) || !savedCharts.length) {
+ return null;
+ }
+ const replaced = savedCharts
+ .filter(chart => chart?.dataId === dataId)
+ .map(chart => ({...chart, dataId: dataIdToUse}));
+ return replaced.length ? replaced : null;
+}
export function mergeEffects<S extends VisState>(
state: S,
effects: NonNullable<ParsedConfig['visState']>['effects'],
@@ -1342,6 +1410,12 @@ export const VIS_STATE_MERGERS: VisStateMergers<any> = [
merge: mergeEffects,
prop: 'effects'
},
+ {
+ merge: mergeCharts,
+ prop: 'charts',
+ toMergeProp: 'chartsToBeMerged',
+ replaceParentDatasetIds: replaceChartDatasetIds
+ },
{
merge: mergeAnnotations,
prop: 'annotations',
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index eb26e3165..5471d3eba 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -167,7 +167,9 @@ import {
TimeRangeFilter,
Annotation,
AnnotationPropsPartial,
- ProtoDataset
+ ProtoDataset,
+ ChartConfig,
+ LayerChartConfig
} from '@kepler.gl/types';
import {Loader} from '@loaders.gl/loader-utils';
@@ -352,6 +354,10 @@ export const INITIAL_VIS_STATE: VisState = {
effects: [],
effectOrder: [],
+ // charts (enabled by default; gated by enableChartsPanel)
+ charts: [],
+ chartsToBeMerged: [],
+
// annotations
annotations: [],
annotationsToBeMerged: [],
@@ -2027,7 +2033,12 @@ export function removeLayerUpdater<T extends VisState>(
// TODO: update filters, create helper to remove layer form filter (remove layerid and dataid) if mapped
};
- return updateAnimationDomain(newState);
+ return updateAnimationDomain(
+ removeChartsAndFilters(
+ newState,
+ chart => isLayerChartConfig(chart) && chart.layerId === layerToRemove.id
+ )
+ );
}
/**
@@ -2509,6 +2520,175 @@ export const updateEffectUpdater = (
};
};
+function isLayerChartConfig(chart: ChartConfig): chart is LayerChartConfig {
+ return chart.type === 'layerChart';
+}
+
+function mergeChartConfig(chart: ChartConfig, props: Partial<ChartConfig>): ChartConfig {
+ return {
+ ...chart,
+ ...props,
+ display: {
+ ...chart.display,
+ ...(props.display || {})
+ },
+ chartDisplay: {
+ ...chart.chartDisplay,
+ ...((props as ChartConfig).chartDisplay || {})
+ }
+ } as ChartConfig;
+}
+
+function axisFieldIfPresent<T extends {field?: {name: string} | null; title?: string | null}>(
+ axis: T | undefined,
+ fieldNames: Set<string>
+): T | undefined {
+ if (!axis?.field?.name || fieldNames.has(axis.field.name)) {
+ return axis;
+ }
+ return {...axis, field: null, title: null};
+}
+
+function dropMissingChartFields(
+ chart: ChartConfig,
+ dataset: {fields?: {name: string}[]} | undefined
+): ChartConfig {
+ const fieldNames = new Set((dataset?.fields || []).map(field => field.name));
+ const next = chart as ChartConfig & {
+ xAxis?: {field?: {name: string} | null};
+ yAxis?: {field?: {name: string} | null};
+ axis?: {field?: {name: string} | null};
+ groupBy?: {field?: {name: string} | null};
+ value?: {field?: {name: string} | null};
+ };
+ return mergeChartConfig(chart, {
+ xAxis: axisFieldIfPresent(next.xAxis, fieldNames),
+ yAxis: axisFieldIfPresent(next.yAxis, fieldNames),
+ axis: axisFieldIfPresent(next.axis, fieldNames),
+ groupBy: axisFieldIfPresent(next.groupBy, fieldNames),
+ value: axisFieldIfPresent(next.value, fieldNames)
+ } as Partial<ChartConfig>);
+}
+
+function removeChartsAndFilters<T extends VisState>(
+ state: T,
+ shouldRemove: (chart: ChartConfig) => boolean
+): T {
+ const charts = state.charts || [];
+ const removed = charts.filter(shouldRemove);
+ if (!removed.length) {
+ return state;
+ }
+ const removedIds = new Set(removed.map(chart => chart.id));
+ const filterIds = new Set(
+ removed.flatMap(chart => {
+ const id = chart.crossFilter?.filterId;
+ return id ? [id, `${id}-x`, `${id}-y`] : [];
+ })
+ );
+ let nextState: VisState = {
+ ...state,
+ charts: charts.filter(chart => !removedIds.has(chart.id))
+ };
+ if (filterIds.size) {
+ nextState = nextState.filters.reduceRight((accu, filter, idx) => {
+ return filterIds.has(filter.id) ? removeFilterUpdater(accu, {idx}) : accu;
+ }, nextState);
+ }
+ return nextState as T;
+}
+
+/**
+ * Add a chart
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const addChartUpdater = (
+ state: VisState,
+ {chart}: VisStateActions.AddChartUpdaterAction
+): VisState => {
+ if (!chart?.id) {
+ return state;
+ }
+ if ((state.charts || []).some(existing => existing.id === chart.id)) {
+ return state;
+ }
+ return {
+ ...state,
+ charts: [
+ ...(state.charts || []).map(existing => ({
+ ...existing,
+ display: {
+ ...existing.display,
+ isConfigActive: false
+ }
+ })),
+ {
+ ...chart,
+ display: {
+ ...chart.display,
+ isConfigActive: chart.display?.isConfigActive ?? false
+ }
+ }
+ ]
+ };
+};
+
+/**
+ * Update a chart
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const updateChartUpdater = (
+ state: VisState,
+ {id, props}: VisStateActions.UpdateChartUpdaterAction
+): VisState => {
+ const idx = (state.charts || []).findIndex(chart => chart.id === id);
+ if (idx < 0) {
+ return state;
+ }
+ const prev = state.charts[idx];
+ const dataIdChanged = typeof props.dataId === 'string' && props.dataId !== prev.dataId;
+ const layerIdChanged =
+ isLayerChartConfig(prev) &&
+ typeof (props as LayerChartConfig).layerId === 'string' &&
+ (props as LayerChartConfig).layerId !== prev.layerId;
+ let next = mergeChartConfig(prev, props);
+ if (dataIdChanged || layerIdChanged) {
+ const dataId = next.dataId || undefined;
+ next = dropMissingChartFields(next, dataId ? state.datasets[dataId] : undefined);
+ if (next.crossFilter?.enabled) {
+ next = mergeChartConfig(next, {
+ crossFilter: {...next.crossFilter, enabled: false, value: {}, fieldNames: {}}
+ });
+ }
+ }
+ const charts = [...state.charts];
+ charts[idx] = next;
+ let nextState: VisState = {
+ ...state,
+ charts
+ };
+ const filterId = next.crossFilter?.filterId || prev.crossFilter?.filterId;
+ if (prev.crossFilter?.enabled && !next.crossFilter?.enabled && filterId) {
+ const ownedFilterIds = new Set([filterId, `${filterId}-x`, `${filterId}-y`]);
+ nextState = nextState.filters.reduceRight((accu, filter, idx) => {
+ return ownedFilterIds.has(filter.id) ? removeFilterUpdater(accu, {idx}) : accu;
+ }, nextState);
+ }
+ return nextState;
+};
+
+/**
+ * Remove a chart and any cross-filter it owns
+ * @memberof visStateUpdaters
+ * @public
+ */
+export const removeChartUpdater = (
+ state: VisState,
+ {id}: VisStateActions.RemoveChartUpdaterAction
+): VisState => removeChartsAndFilters(state, chart => chart.id === id);
+
// ANNOTATION UPDATERS
function makeNewAnnotation(config?: AnnotationPropsPartial): Annotation {
@@ -2742,7 +2922,18 @@ export function removeDatasetUpdater<T extends VisState>(
newState = {...newState, filters};
- return removeDatasetFromInteractionConfig(newState, {dataId: datasetKey});
+ return removeChartsAndFilters(
+ removeDatasetFromInteractionConfig(newState, {dataId: datasetKey}),
+ chart => {
+ if (chart.dataId === datasetKey) {
+ return true;
+ }
+ if (isLayerChartConfig(chart)) {
+ return layersToRemove.includes(chart.layerId);
+ }
+ return false;
+ }
+ );
}
function removeDatasetFromInteractionConfig(state, {dataId}) {
@@ -5691,6 +5882,9 @@ function adjustTimeFilterInterval(state, filter) {
// layers, filters, interactions, layerBlending, overlayBlending, splitMaps, animationConfig, editor
// replace it with another dataId
function defaultReplaceParentDatasetIds(value: any, dataId: string, dataIdToReplace: string) {
+ if (value == null) {
+ return null;
+ }
if (Array.isArray(value)) {
// for layers, filters, call defaultReplaceParentDatasetIds on each item in array
const replaced = value
@@ -5870,6 +6064,9 @@ export function replaceDatasetDepsInState<T extends VisState>(
let replacedState = accuState;
savedProps.forEach((propValue, i) => {
+ if (propValue == null) {
+ return;
+ }
const mergerOptions = {
prop: props[i],
toMergeProp: toMergeProps[i],
diff --git a/src/reducers/src/vis-state.ts b/src/reducers/src/vis-state.ts
index 09e824f8b..8475633fb 100644
--- a/src/reducers/src/vis-state.ts
+++ b/src/reducers/src/vis-state.ts
@@ -204,6 +204,12 @@ const actionHandler = {
[ActionTypes.UPDATE_EFFECT]: visStateUpdaters.updateEffectUpdater,
+ [ActionTypes.ADD_CHART]: visStateUpdaters.addChartUpdater,
+
+ [ActionTypes.UPDATE_CHART]: visStateUpdaters.updateChartUpdater,
+
+ [ActionTypes.REMOVE_CHART]: visStateUpdaters.removeChartUpdater,
+
[ActionTypes.ADD_ANNOTATION]: visStateUpdaters.addAnnotationUpdater,
[ActionTypes.REMOVE_ANNOTATION]: visStateUpdaters.removeAnnotationUpdater,
diff --git a/src/schemas/src/index.ts b/src/schemas/src/index.ts
index 277241cba..39bba6885 100644
--- a/src/schemas/src/index.ts
+++ b/src/schemas/src/index.ts
@@ -23,7 +23,8 @@ export {
default as visStateSchema,
layerPropsV1,
layerPropsV0,
- effectPropsV1
+ effectPropsV1,
+ chartPropsV1
} from './vis-state-schema';
export type {SavedField, ParsedField, SavedDatasetV1, ParsedDataset} from './dataset-schema';
export {
diff --git a/src/schemas/src/ui-state-schema.ts b/src/schemas/src/ui-state-schema.ts
index 51a577091..e63db1978 100644
--- a/src/schemas/src/ui-state-schema.ts
+++ b/src/schemas/src/ui-state-schema.ts
@@ -22,6 +22,13 @@ export const propertiesV1 = {
})
},
key: 'mapLegend'
+ }),
+ chart: new Schema({
+ version: VERSIONS.v1,
+ properties: {
+ active: null
+ },
+ key: 'chart'
})
},
key: 'mapControls'
diff --git a/src/schemas/src/vis-state-schema.ts b/src/schemas/src/vis-state-schema.ts
index daeb8a9e9..987071672 100644
--- a/src/schemas/src/vis-state-schema.ts
+++ b/src/schemas/src/vis-state-schema.ts
@@ -35,7 +35,8 @@ import {
SplitMap,
ValueOf,
Effect,
- Annotation
+ Annotation,
+ ChartConfig
} from '@kepler.gl/types';
import {Datasets} from '@kepler.gl/table';
import {Layer, LayerClassesType} from '@kepler.gl/layers';
@@ -64,6 +65,8 @@ export interface VisState {
layerOrderToBeMerged: any[] | null;
effects: Effect[];
effectOrder: string[];
+ charts: ChartConfig[];
+ chartsToBeMerged: ChartConfig[];
annotations: Annotation[];
annotationsToBeMerged: any[];
selectedAnnotationId: string | null;
@@ -819,6 +822,67 @@ export const effectPropsV1 = {
isEnabled: null,
parameters: null
};
+
+export const chartPropsV1 = {
+ id: null,
+ title: null,
+ type: null,
+ dataId: null,
+ applyFilters: null,
+ pinned: null,
+ display: null,
+ crossFilter: null,
+ xAxis: null,
+ yAxis: null,
+ groupBy: null,
+ value: null,
+ axis: null,
+ numGroups: null,
+ groupOthers: null,
+ colorBy: null,
+ chartDisplay: null,
+ layerId: null,
+ layerChartType: null
+};
+
+export class ChartsSchema extends Schema {
+ key = 'charts';
+
+ save(charts) {
+ if (!Array.isArray(charts) || !charts.length) {
+ // Keep saved maps unchanged when the charts panel is unused.
+ return {};
+ }
+ return {
+ [this.key]: charts.map(
+ chart =>
+ this.savePropertiesOrApplySchema({
+ ...chart,
+ display: {
+ ...chart.display,
+ isConfigActive: false
+ }
+ }).charts
+ )
+ };
+ }
+
+ load(charts) {
+ if (!Array.isArray(charts)) {
+ return {[this.key]: []};
+ }
+ return {
+ [this.key]: charts.map(chart => {
+ const loaded = this.loadPropertiesOrApplySchema(chart, charts).charts;
+ // Older saved maps omit `pinned`; keep charts visible like the legend.
+ return {
+ ...loaded,
+ pinned: loaded.pinned !== false
+ };
+ })
+ };
+ }
+}
export class EffectsSchema extends Schema {
key = 'effects';
@@ -963,6 +1027,10 @@ export const propertiesV1 = {
version: VERSIONS.v1,
properties: effectPropsV1
}),
+ charts: new ChartsSchema({
+ version: VERSIONS.v1,
+ properties: chartPropsV1
+ }),
annotations: new AnnotationsSchema({
version: VERSIONS.v1,
properties: annotationPropsV1
diff --git a/src/sqlrooms/src/components/KeplerImageExport.tsx b/src/sqlrooms/src/components/KeplerImageExport.tsx
index 3625be1c4..9c32421cc 100644
--- a/src/sqlrooms/src/components/KeplerImageExport.tsx
+++ b/src/sqlrooms/src/components/KeplerImageExport.tsx
@@ -58,7 +58,7 @@ export const KeplerImageExport: React.FC<KeplerImageExportProps> = ({
fileName,
onExportStart
}) => {
- const {legend, resolution, processing, imageDataUri} = exportImageSettings;
+ const {legend, charts, resolution, processing, imageDataUri} = exportImageSettings;
useEffect(() => {
// hardcode default resolution only when incoming resolution is not a supported custom option
@@ -130,6 +130,17 @@ export const KeplerImageExport: React.FC<KeplerImageExportProps> = ({
}
disabled={processing}
/>
+
+ <Label className="font-normal">Show charts</Label>
+ <Switch
+ checked={Boolean(charts)}
+ onCheckedChange={checked =>
+ setExportImageSetting({
+ charts: checked === true
+ })
+ }
+ disabled={processing}
+ />
</div>
<div className="flex flex-col gap-2">
diff --git a/src/types/charts.d.ts b/src/types/charts.d.ts
new file mode 100644
index 000000000..d2efb90f4
--- /dev/null
+++ b/src/types/charts.d.ts
@@ -0,0 +1,86 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+export type ChartAggregation =
+ | 'count'
+ | 'sum'
+ | 'average'
+ | 'maximum'
+ | 'minimum'
+ | 'median'
+ | 'stdev'
+ | 'variance'
+ | 'p05'
+ | 'p25'
+ | 'p50'
+ | 'p75'
+ | 'p95'
+ | 'mode'
+ | 'countUnique';
+
+export type ChartAxisField = {
+ name: string;
+ type: string;
+};
+
+export type ChartAxis = {
+ field: ChartAxisField | null;
+ aggregation: ChartAggregation | string | null;
+ title?: string | null;
+ /** Time binning period for timestamp/date axes: hour | day | week | month | year */
+ interval?: string | null;
+};
+
+export type ChartCrossFilter = {
+ enabled: boolean;
+ filterId: string;
+ fieldNames: Record<string, string>;
+ value: Record<string, string | number>;
+};
+
+export type BaseChartConfig = {
+ id: string;
+ title: string;
+ type: string;
+ dataId: string | null;
+ applyFilters: boolean;
+ /**
+ * When true, the chart stays visible on the map even if the charts panel
+ * control is inactive (similar to a pinned legend). Persisted in saved maps.
+ */
+ pinned?: boolean;
+ display: {
+ isConfigActive?: boolean;
+ };
+ crossFilter?: ChartCrossFilter;
+};
+
+export type DatasetChartConfig = BaseChartConfig & {
+ xAxis?: ChartAxis;
+ yAxis?: ChartAxis;
+ groupBy?: ChartAxis;
+ value?: ChartAxis;
+ axis?: ChartAxis;
+ numGroups?: number;
+ groupOthers?: boolean;
+ /** How bar/series colors are assigned. */
+ colorBy?: 'none' | 'category' | string;
+ chartDisplay: Record<string, any>;
+};
+
+export type LayerChartConfig = BaseChartConfig & {
+ type: 'layerChart';
+ layerId: string;
+ layerChartType: string;
+ axis?: ChartAxis;
+ xAxis?: ChartAxis;
+ yAxis?: ChartAxis;
+ chartDisplay: {
+ idField?: string | null;
+ numEntries?: number;
+ interval?: string;
+ format?: string;
+ };
+};
+
+export type ChartConfig = DatasetChartConfig | LayerChartConfig;
diff --git a/src/types/index.d.ts b/src/types/index.d.ts
index aa5b23e7f..5349a28a1 100644
--- a/src/types/index.d.ts
+++ b/src/types/index.d.ts
@@ -8,6 +8,7 @@ export * from './schemas';
export * from './types';
export * from './components';
export * from './effects';
+export * from './charts';
export * from './annotations';
export * from './datasets';
diff --git a/src/types/reducers.d.ts b/src/types/reducers.d.ts
index 322efac32..dfa4b174f 100644
--- a/src/types/reducers.d.ts
+++ b/src/types/reducers.d.ts
@@ -461,6 +461,8 @@ export declare type ExportImage = {
ratio: EXPORT_IMG_RATIOS;
resolution: ExportResolutionOption;
legend: boolean;
+ /** When true, include the charts panel in the exported image. */
+ charts: boolean;
mapH: number;
mapW: number;
imageSize: {
@@ -539,6 +541,7 @@ export type MapControls = {
mapTheme?: MapControlItem;
effect?: MapControlItem;
annotation?: MapControlItem;
+ chart?: MapControlItem;
viewportJson?: MapControlItem;
sqlPanel?: MapControlItem;
aiAssistant?: MapControlItem;
diff --git a/src/types/schemas.d.ts b/src/types/schemas.d.ts
index eaad4540b..3f9029bb3 100644
--- a/src/types/schemas.d.ts
+++ b/src/types/schemas.d.ts
@@ -6,6 +6,7 @@ import {RGBColor, Merge, RequireFrom} from './types';
import {Filter, InteractionConfig, AnimationConfig, SplitMap, Feature} from './reducers';
import {LayerTextLabel} from './layers';
+import {ChartConfig} from './charts';
export type SavedFilter = {
dataId: Filter['dataId'];
@@ -102,6 +103,7 @@ export type SavedVisState = {
filters: SavedFilter[];
layers: SavedLayer[];
effects: SavedEffect[];
+ charts?: ChartConfig[];
interactionConfig: SavedInteractionConfig;
layerBlending: string;
overlayBlending?: string;
@@ -116,6 +118,7 @@ export type MinSavedVisStateV1 = {
filters?: MinSavedFilter[];
layers?: MinSavedLayer[];
effects?: SavedEffect[];
+ charts?: ChartConfig[];
interactionConfig?: Partial<SavedInteractionConfig>;
layerBlending?: string;
overlayBlending?: string;
@@ -127,8 +130,8 @@ export type MinSavedVisStateV1 = {
export type ParsedVisState = {
layers?: ParsedLayer[];
effects?: ParsedEffect[];
+ charts?: ChartConfig[];
filters?: ParsedFilter[];
- effects?: ParsedEffect[];
interactionConfig?: Partial<SavedInteractionConfig>;
layerBlending?: string;
overlayBlending?: string;
@@ -151,6 +154,9 @@ export type ParsedUiState = {
contentHeight?: number;
};
};
+ chart?: {
+ active?: boolean;
+ };
};
locale?: string;
theme?: string;
diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.ts
index 7ead52918..f77a1cc46 100644
--- a/src/utils/src/application-config.ts
+++ b/src/utils/src/application-config.ts
@@ -220,6 +220,13 @@ export type KeplerApplicationConfig = {
/** Whether to show column statistics in the data table modal. Enabled by default. */
enableColumnStats?: boolean;
+ /**
+ * Whether to show the charts map-control panel (big number, bar, line,
+ * heatmap, pivot table, tooltip charts, and chart cross-filters).
+ * Enabled by default. Disable with {@link initApplicationConfig}.
+ */
+ enableChartsPanel?: boolean;
+
/**
* Master switch for power-user JSON editors. When false, every section editor is hidden.
* Defaults to true; each section also has its own flag.
@@ -419,6 +426,8 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
enableColumnStats: true,
+ enableChartsPanel: true,
+
enableJsonEditors: true,
enableLayerJsonEditor: true,
enableFilterJsonEditor: true,
diff --git a/src/utils/src/plot.ts b/src/utils/src/plot.ts
index 475769d32..ea8ce48e9 100644
--- a/src/utils/src/plot.ts
+++ b/src/utils/src/plot.ts
@@ -337,13 +337,15 @@ export function getBinThresholds(interval: string, domain: number[]): number[] {
* Run GPU filter on current filter result to generate indexes for ploting chart
* Skip ruuning for the same field
* @param dataset
- * @param filter
+ * @param filter Histogram filter whose dataId-paired column should be skipped
+ * @param skipFieldNames Extra GPU field names to skip (charts cross-filter). Histogram callers omit this.
*/
export function runGpuFilterForPlot<K extends KeplerTableModel<K, L>, L>(
dataset: K,
- filter?: Filter
+ filter?: Filter,
+ skipFieldNames?: string[]
): number[] {
- const skipIndexes = getSkipIndexes(dataset, filter);
+ const skipIndexes = getSkipIndexes(dataset, filter, skipFieldNames);
const {
gpuFilter: {filterValueUpdateTriggers, filterRange, filterValueAccessor},
@@ -372,14 +374,27 @@ export function runGpuFilterForPlot<K extends KeplerTableModel<K, L>, L>(
return plotFilteredIndex.filter(filterData);
}
-function getSkipIndexes(dataset, filter) {
+function getSkipIndexes(dataset, filter, skipFieldNames?: string[]) {
// array of gpu filter names
- if (!filter) {
- return [];
- }
const gpuFilters = Object.values(dataset.gpuFilter.filterValueUpdateTriggers) as ({
name: string;
} | null)[];
+
+ // Charts pass extra field names so a cross-filter does not hide its own bins.
+ // Histogram plots never pass this list and keep the original dataId pairing.
+ if (skipFieldNames?.length) {
+ const skipNames = new Set(skipFieldNames.filter((name): name is string => Boolean(name)));
+ return gpuFilters.reduce((accu, item, idx) => {
+ if (item && skipNames.has(item.name)) {
+ accu.push(idx);
+ }
+ return accu;
+ }, [] as number[]);
+ }
+
+ if (!filter) {
+ return [];
+ }
const valueIndex = filter.dataId.findIndex(id => id === dataset.id);
const filterColumn = filter.name[valueIndex];
diff --git a/test/browser/components/map/map-control-test.js b/test/browser/components/map/map-control-test.js
index ba47a393d..b53c20b65 100644
--- a/test/browser/components/map/map-control-test.js
+++ b/test/browser/components/map/map-control-test.js
@@ -81,6 +81,58 @@ test('MapControlFactory - display all options', t => {
</IntlWrapper>
);
t.equal($.find('.map-control-action').length, 9, 'Should show 9 action panels');
+ t.equal(
+ $.find('.toggle-chart-panel').length,
+ 0,
+ 'Should not show a charts button on default MapControl'
+ );
+ t.end();
+});
+
+test('MapControlFactory - chart control is not a default action', t => {
+ initApplicationConfig({enableChartsPanel: true});
+ const $ = mountWithTheme(
+ <IntlWrapper>
+ <MapViewStateContextProvider mapState={{latitude: 0, longitude: 0, zoom: 1}}>
+ <MapControl
+ mapControls={{
+ splitMap: {show: true},
+ visibleLayers: {show: true},
+ toggle3d: {show: true},
+ mapLegend: {show: true},
+ mapDraw: {show: true},
+ mapLocale: {show: true},
+ effect: {show: true},
+ chart: {show: true, active: true}
+ }}
+ datasets={{}}
+ layers={[]}
+ locale={'en'}
+ layersToRender={{}}
+ dragRotate={true}
+ mapIndex={0}
+ onToggleSplitMap={() => {}}
+ onTogglePerspective={() => {}}
+ onToggleMapControl={() => {}}
+ onSetEditorMode={() => {}}
+ onToggleEditorVisibility={() => {}}
+ onSetLocale={() => {}}
+ charts={[]}
+ />
+ </MapViewStateContextProvider>
+ </IntlWrapper>
+ );
+ t.equal(
+ $.find('.toggle-chart-panel').length,
+ 0,
+ 'Should not show a charts button on default MapControl'
+ );
+ t.equal(
+ $.find('.chart-manager').length,
+ 0,
+ 'Should not mount a charts panel on default MapControl'
+ );
+ initApplicationConfig({enableChartsPanel: true});
t.end();
});
diff --git a/test/node/reducers/chart-updater-test.js b/test/node/reducers/chart-updater-test.js
new file mode 100644
index 000000000..2b76e642d
--- /dev/null
+++ b/test/node/reducers/chart-updater-test.js
@@ -0,0 +1,194 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape-catch';
+
+import {VisStateActions} from '@kepler.gl/actions';
+import {ChartType, createBigNumberChart, createBarChart} from '@kepler.gl/charts';
+import {
+ visStateReducer as reducer,
+ INITIAL_VIS_STATE,
+ mergeCharts,
+ prepareStateForDatasetReplace
+} from '@kepler.gl/reducers';
+
+test('#VisStateUpdater -> add/update/remove chart', t => {
+ const chart = createBigNumberChart({id: 'c1', dataId: 'd1', title: 'Count'});
+ let nextState = reducer(INITIAL_VIS_STATE, VisStateActions.addChart(chart));
+ t.equal(nextState.charts.length, 1, 'should add a chart');
+ t.equal(nextState.charts[0].id, 'c1');
+
+ nextState = reducer(nextState, VisStateActions.addChart(chart));
+ t.equal(nextState.charts.length, 1, 'should ignore duplicate chart ids');
+
+ nextState = reducer(
+ nextState,
+ VisStateActions.updateChart('c1', {title: 'Updated', applyFilters: false})
+ );
+ t.equal(nextState.charts[0].title, 'Updated');
+ t.equal(nextState.charts[0].applyFilters, false);
+
+ nextState = reducer(nextState, VisStateActions.removeChart('c1'));
+ t.equal(nextState.charts.length, 0, 'should remove the chart');
+ t.end();
+});
+
+test('#VisStateUpdater -> removeDataset drops charts', t => {
+ let nextState = {
+ ...INITIAL_VIS_STATE,
+ datasets: {
+ d1: {id: 'd1', label: 'one'},
+ d2: {id: 'd2', label: 'two'}
+ },
+ charts: [createBarChart({id: 'c1', dataId: 'd1'}), createBarChart({id: 'c2', dataId: 'd2'})]
+ };
+ nextState = reducer(nextState, VisStateActions.removeDataset('d1'));
+ t.equal(nextState.charts.length, 1);
+ t.equal(nextState.charts[0].id, 'c2');
+ t.end();
+});
+
+test('#VisStateUpdater -> charts stay empty by default', t => {
+ t.deepEqual(INITIAL_VIS_STATE.charts, []);
+ t.equal(createBarChart().type, ChartType.barChart);
+ t.equal(createBarChart().pinned, false, 'new charts are unpinned by default');
+ t.end();
+});
+
+test('#VisStateUpdater -> updateChart can pin a chart', t => {
+ const chart = createBarChart({id: 'c1', dataId: 'd1'});
+ let nextState = reducer(INITIAL_VIS_STATE, VisStateActions.addChart(chart));
+ t.equal(nextState.charts[0].pinned, false);
+ nextState = reducer(nextState, VisStateActions.updateChart('c1', {pinned: true}));
+ t.equal(nextState.charts[0].pinned, true);
+ t.end();
+});
+
+test('#VisStateUpdater -> disabling cross-filter removes owned filter', t => {
+ const chart = {
+ ...createBarChart({id: 'c1', dataId: 'd1'}),
+ crossFilter: {enabled: true, filterId: 'chart-c1-f', fieldNames: {x: 'cat'}, value: {x: 'A'}}
+ };
+ let nextState = {
+ ...INITIAL_VIS_STATE,
+ charts: [chart],
+ filters: [{id: 'chart-c1-f', dataId: [], name: ['cat'], value: ['A']}]
+ };
+ nextState = reducer(
+ nextState,
+ VisStateActions.updateChart('c1', {
+ crossFilter: {enabled: false, filterId: 'chart-c1-f', fieldNames: {x: 'cat'}, value: {}}
+ })
+ );
+ t.equal(nextState.charts[0].crossFilter.enabled, false);
+ t.equal(nextState.filters.length, 0, 'should drop the chart-owned filter');
+ t.end();
+});
+
+function mockChartDataset(id, fields) {
+ const dataset = {id, fields};
+ dataset.filterTable = () => dataset;
+ return dataset;
+}
+
+test('#VisStateUpdater -> switching chart dataId drops fields missing from the new dataset', t => {
+ const chart = createBarChart({
+ id: 'c1',
+ dataId: 'd1',
+ xAxis: {field: {name: 'Join_Count', type: 'integer'}, aggregation: 'uniqueBin'},
+ yAxis: {field: {name: 'Join_Count', type: 'integer'}, aggregation: 'sum'}
+ });
+ let nextState = {
+ ...INITIAL_VIS_STATE,
+ datasets: {
+ d1: mockChartDataset('d1', [{name: 'Join_Count'}]),
+ d2: mockChartDataset('d2', [{name: 'mag'}, {name: 'place'}])
+ },
+ charts: [chart],
+ filters: [{id: 'chart-c1-f', dataId: ['d1'], name: ['Join_Count'], value: [1]}]
+ };
+ nextState.charts[0] = {
+ ...nextState.charts[0],
+ crossFilter: {
+ enabled: true,
+ filterId: 'chart-c1-f',
+ fieldNames: {x: 'Join_Count'},
+ value: {x: 1}
+ }
+ };
+ nextState = reducer(nextState, VisStateActions.updateChart('c1', {dataId: 'd2'}));
+ t.equal(nextState.charts[0].dataId, 'd2');
+ t.equal(nextState.charts[0].xAxis.field, null, 'stale x field should be cleared');
+ t.equal(nextState.charts[0].yAxis.field, null, 'stale y field should be cleared');
+ t.equal(nextState.charts[0].crossFilter.enabled, false);
+ t.equal(nextState.filters.length, 0, 'owned cross-filter should be removed');
+ t.end();
+});
+
+test('#VisStateUpdater -> mergeCharts skips duplicate ids in the loaded array', t => {
+ const first = createBarChart({id: 'dup', dataId: 'd1', title: 'First'});
+ const second = createBarChart({id: 'dup', dataId: 'd1', title: 'Second'});
+ const other = createBarChart({id: 'other', dataId: 'd1', title: 'Other'});
+ const state = {
+ ...INITIAL_VIS_STATE,
+ datasets: {d1: {id: 'd1', fields: []}}
+ };
+ const nextState = mergeCharts(state, [first, second, other], true);
+ t.equal(nextState.charts.length, 2);
+ t.equal(nextState.charts[0].id, 'dup');
+ t.equal(nextState.charts[0].title, 'First');
+ t.equal(nextState.charts[1].id, 'other');
+ t.end();
+});
+
+test('#VisStateUpdater -> mergeCharts parks charts until the dataset exists', t => {
+ const chart = createBarChart({id: 'c1', dataId: 'd1', title: 'Pending'});
+ const parked = mergeCharts(INITIAL_VIS_STATE, [chart], true);
+ t.equal(parked.charts.length, 0, 'should not add a chart for a missing dataset');
+ t.equal(parked.chartsToBeMerged.length, 1);
+ t.equal(parked.chartsToBeMerged[0].id, 'c1');
+
+ const withDataset = {
+ ...parked,
+ datasets: {d1: {id: 'd1', fields: []}}
+ };
+ const merged = mergeCharts(withDataset, withDataset.chartsToBeMerged);
+ t.equal(merged.charts.length, 1);
+ t.equal(merged.charts[0].id, 'c1');
+ t.equal(merged.chartsToBeMerged.length, 0, 'should clear parked charts after merge');
+ t.end();
+});
+
+test('#VisStateUpdater -> prepareStateForDatasetReplace remaps charts', t => {
+ const chartMove = createBarChart({id: 'c-move', dataId: 'old'});
+ const chartKeep = createBarChart({id: 'c-keep', dataId: 'other'});
+ const state = {
+ ...INITIAL_VIS_STATE,
+ datasets: {
+ old: {id: 'old', fields: [{name: 'a'}]},
+ other: {id: 'other', fields: [{name: 'b'}]}
+ },
+ charts: [chartMove, chartKeep]
+ };
+ const next = prepareStateForDatasetReplace(state, 'old', 'new');
+ t.equal(next.charts.length, 1, 'should keep charts of other datasets');
+ t.equal(next.charts[0].id, 'c-keep');
+ t.equal(next.chartsToBeMerged.length, 1, 'should park remapped charts');
+ t.equal(next.chartsToBeMerged[0].id, 'c-move');
+ t.equal(next.chartsToBeMerged[0].dataId, 'new', 'should replace chart dataId');
+
+ const restored = mergeCharts(
+ {
+ ...next,
+ datasets: {
+ ...next.datasets,
+ new: {id: 'new', fields: [{name: 'a'}]}
+ }
+ },
+ next.chartsToBeMerged
+ );
+ t.equal(restored.charts.length, 2, 'should restore remapped charts after the new dataset lands');
+ t.equal(restored.charts.find(chart => chart.id === 'c-move')?.dataId, 'new');
+ t.equal(restored.chartsToBeMerged.length, 0);
+ t.end();
+});
diff --git a/test/node/reducers/index.js b/test/node/reducers/index.js
index 4e895c2d4..a80db9f0f 100644
--- a/test/node/reducers/index.js
+++ b/test/node/reducers/index.js
@@ -17,6 +17,9 @@ import './annotation-merger-test';
// test annotation updaters
import './annotation-updater-test';
+// test charts
+import './chart-updater-test';
+
// test layer groups
import './layer-group-test';
import './layer-group-updaters-test';
diff --git a/test/node/schemas/ui-state-schema-test.js b/test/node/schemas/ui-state-schema-test.js
index f854d6232..5dec4a1d1 100644
--- a/test/node/schemas/ui-state-schema-test.js
+++ b/test/node/schemas/ui-state-schema-test.js
@@ -23,8 +23,8 @@ test('#uiStateSchema -> v1 -> save load uiState', t => {
t.equal(uiToSave.theme, 'dark', 'default theme should be dark');
t.deepEqual(
uiToSave.mapControls,
- {mapLegend: {active: false}},
- 'default mapLegend should be inactive with no settings'
+ {mapLegend: {active: false}, chart: {active: false}},
+ 'default mapLegend and chart should be inactive with no settings'
);
t.deepEqual(uiLoaded, uiToSave, 'loaded uiState should match saved uiState');
diff --git a/test/node/schemas/vis-state-schema-test.js b/test/node/schemas/vis-state-schema-test.js
index 91876cb2d..1695603b6 100644
--- a/test/node/schemas/vis-state-schema-test.js
+++ b/test/node/schemas/vis-state-schema-test.js
@@ -494,3 +494,39 @@ test('#visStateSchema -> create point and arc layers', t => {
t.equal(state.visState.layers[2].type, 'arc', 'should create arc layer');
t.end();
});
+
+test('#visStateSchema -> v1 -> charts are optional', t => {
+ const initialState = cloneDeep(StateWFiles);
+ const vsToSave = SchemaManager.getConfigToSave(initialState).config.visState;
+ t.false('charts' in vsToSave, 'should omit empty charts from saved config');
+
+ const stateWithChart = {
+ ...initialState,
+ visState: {
+ ...initialState.visState,
+ charts: [
+ {
+ id: 'c1',
+ type: 'bigNumber',
+ title: 'Count',
+ dataId: testCsvDataId,
+ applyFilters: true,
+ display: {isConfigActive: true}
+ }
+ ]
+ }
+ };
+ const savedConfig = SchemaManager.getConfigToSave(stateWithChart);
+ const savedWithChart = savedConfig.config.visState;
+ t.equal(savedWithChart.charts.length, 1, 'should persist charts when present');
+ t.equal(savedWithChart.charts[0].id, 'c1');
+ t.equal(
+ savedWithChart.charts[0].display.isConfigActive,
+ false,
+ 'should collapse chart config on save'
+ );
+
+ const loaded = SchemaManager.parseSavedConfig(savedConfig).visState;
+ t.equal(loaded.charts.length, 1, 'should load saved charts');
+ t.end();
+});
diff --git a/test/node/utils/chart-aggregation-test.js b/test/node/utils/chart-aggregation-test.js
new file mode 100644
index 000000000..02b1deeeb
--- /dev/null
+++ b/test/node/utils/chart-aggregation-test.js
@@ -0,0 +1,382 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape-catch';
+
+import {
+ ChartType,
+ LayerChartType,
+ BinType,
+ buildBigNumber,
+ buildGroupedBins,
+ buildHeatmapCells,
+ buildPivotTable,
+ buildTimeSeries,
+ createChart,
+ propsForChartDatasetChange,
+ toChartableDataset,
+ computeDatasetChart,
+ formatNumber,
+ displayBinKey,
+ getHoverRowIndexes
+} from '@kepler.gl/charts';
+
+function mockDataset(rows) {
+ const fields = [
+ {name: 'category', type: 'string'},
+ {name: 'value', type: 'real'},
+ {name: 'time', type: 'timestamp'},
+ {name: 'id', type: 'string'}
+ ];
+ return {
+ id: 'test',
+ label: 'Test',
+ color: [18, 147, 154],
+ allIndexes: rows.map((_, i) => i),
+ filteredIndex: rows.map((_, i) => i),
+ fields,
+ getValue: (name, idx) => rows[idx][name]
+ };
+}
+
+test('charts -> createChart builders', t => {
+ const dataset = mockDataset([{category: 'A', value: 10, time: new Date('2020-01-01'), id: '1'}]);
+ t.equal(createChart({type: ChartType.bigNumber, dataset}).type, ChartType.bigNumber);
+ t.equal(createChart({type: ChartType.barChart, dataset}).type, ChartType.barChart);
+ t.equal(createChart({type: ChartType.horizontalBar, dataset}).type, ChartType.horizontalBar);
+ t.equal(createChart({type: ChartType.lineChart, dataset}).type, ChartType.lineChart);
+ t.equal(createChart({type: ChartType.heatmapChart, dataset}).type, ChartType.heatmapChart);
+ t.equal(createChart({type: ChartType.pivotTable, dataset}).type, ChartType.pivotTable);
+ t.equal(
+ createChart({type: LayerChartType.BREAKDOWN_BY_CATEGORY, dataset, layerId: 'l1'})
+ .layerChartType,
+ LayerChartType.BREAKDOWN_BY_CATEGORY
+ );
+ t.equal(createChart({type: LayerChartType.TIME_SERIES, dataset}), null);
+ t.end();
+});
+
+test('charts -> boolean unique bins keep scalar boolean filter values', t => {
+ const rows = [
+ {flag: true, value: 1},
+ {flag: false, value: 2},
+ {flag: true, value: 3}
+ ];
+ const dataset = {
+ id: 'bools',
+ label: 'Bools',
+ allIndexes: [0, 1, 2],
+ filteredIndex: [0, 1, 2],
+ fields: [
+ {name: 'flag', type: 'boolean'},
+ {name: 'value', type: 'real'}
+ ],
+ getValue: (name, idx) => rows[idx][name]
+ };
+ const bins = buildGroupedBins({
+ dataset,
+ applyFilters: true,
+ binAxis: {field: {name: 'flag', type: 'boolean'}, aggregation: BinType.uniqueBin},
+ valueAxis: {field: {name: 'value', type: 'real'}, aggregation: 'sum'}
+ });
+ const byKey = Object.fromEntries(bins.map(bin => [String(bin.key), bin]));
+ t.deepEqual(byKey.true.filterValue, [true]);
+ t.deepEqual(byKey.false.filterValue, [false]);
+ t.equal(byKey.true.value, 4);
+ t.end();
+});
+
+test('charts -> bar without category field is empty', t => {
+ const dataset = mockDataset([{category: 'A', value: 10, time: new Date('2020-01-01'), id: '1'}]);
+ const chart = createChart({type: ChartType.barChart, dataset});
+ chart.xAxis = {field: null, aggregation: BinType.uniqueBin};
+ const view = computeDatasetChart(chart, dataset);
+ t.equal(view.kind, 'bars');
+ t.deepEqual(view.bins, []);
+ t.end();
+});
+
+test('charts -> buildBigNumber count and sum', t => {
+ const dataset = mockDataset([
+ {category: 'A', value: 10, time: new Date('2020-01-01'), id: '1'},
+ {category: 'B', value: 5, time: new Date('2020-01-02'), id: '1'}
+ ]);
+ t.equal(buildBigNumber({dataset, applyFilters: true}).value, 2);
+ t.equal(
+ buildBigNumber({
+ dataset,
+ applyFilters: true,
+ axis: {field: {name: 'value', type: 'real'}, aggregation: 'sum'}
+ }).value,
+ 15
+ );
+ t.end();
+});
+
+test('charts -> buildBigNumber percentiles and countUnique', t => {
+ const dataset = mockDataset([
+ {category: 'A', value: 10, time: new Date('2020-01-01'), id: '1'},
+ {category: 'A', value: 20, time: new Date('2020-01-01'), id: '2'},
+ {category: 'B', value: 30, time: new Date('2020-01-02'), id: '3'},
+ {category: 'C', value: 40, time: new Date('2020-01-02'), id: '4'}
+ ]);
+ t.equal(
+ buildBigNumber({
+ dataset,
+ applyFilters: true,
+ axis: {field: {name: 'value', type: 'real'}, aggregation: 'p50'}
+ }).value,
+ 25
+ );
+ t.equal(
+ buildBigNumber({
+ dataset,
+ applyFilters: true,
+ axis: {field: {name: 'category', type: 'string'}, aggregation: 'countUnique'}
+ }).value,
+ 3
+ );
+ t.end();
+});
+
+test('charts -> buildGroupedBins unique categories', t => {
+ const dataset = mockDataset([
+ {category: 'A', value: 10, time: new Date('2020-01-01'), id: '1'},
+ {category: 'A', value: 2, time: new Date('2020-01-01'), id: '1'},
+ {category: 'B', value: 5, time: new Date('2020-01-02'), id: '2'}
+ ]);
+ const bins = buildGroupedBins({
+ dataset,
+ applyFilters: true,
+ binAxis: {field: {name: 'category', type: 'string'}, aggregation: BinType.uniqueBin},
+ valueAxis: {field: {name: 'value', type: 'real'}, aggregation: 'sum'}
+ });
+ const byKey = Object.fromEntries(bins.map(bin => [bin.key, bin.value]));
+ t.equal(byKey.A, 12);
+ t.equal(byKey.B, 5);
+ t.end();
+});
+
+test('charts -> numeric bin axis spans full domain', t => {
+ const dataset = mockDataset([
+ {category: 'A', value: 2.54, time: new Date('2020-01-01'), id: '1'},
+ {category: 'A', value: 2.55, time: new Date('2020-01-01'), id: '2'},
+ {category: 'A', value: 2.56, time: new Date('2020-01-01'), id: '3'},
+ {category: 'B', value: 5, time: new Date('2020-01-02'), id: '4'},
+ {category: 'C', value: 8, time: new Date('2020-01-02'), id: '5'}
+ ]);
+ const bins = buildGroupedBins({
+ dataset,
+ applyFilters: true,
+ // uniqueBin leftover should still histogram real fields
+ binAxis: {field: {name: 'value', type: 'real'}, aggregation: BinType.uniqueBin},
+ valueAxis: {field: null, aggregation: 'count'},
+ numGroups: 5,
+ sort: 'dataOrder',
+ truncate: false
+ });
+ t.ok(bins.length >= 2, 'should produce multiple numeric bins');
+ const first = displayBinKey(String(bins[0].key));
+ const last = displayBinKey(String(bins[bins.length - 1].key));
+ t.ok(/2(\.\d+)?/.test(first), `first bin starts near min, got ${first}`);
+ t.ok(/[78]/.test(last), `last bin reaches max, got ${last}`);
+ t.end();
+});
+
+test('charts -> numeric bins keep distinct keys when compact labels collide', t => {
+ const rows = Array.from({length: 20}, (_, i) => ({
+ category: 'A',
+ value: 1e6 + i * 500,
+ time: new Date('2020-01-01'),
+ id: String(i)
+ }));
+ const dataset = mockDataset(rows);
+ const bins = buildGroupedBins({
+ dataset,
+ applyFilters: true,
+ binAxis: {field: {name: 'value', type: 'real'}, aggregation: BinType.numericBin},
+ valueAxis: {field: null, aggregation: 'count'},
+ numGroups: 10,
+ sort: 'dataOrder',
+ truncate: false
+ });
+ const keys = bins.map(bin => bin.key);
+ t.equal(new Set(keys).size, keys.length, 'numeric bin keys must be unique');
+ t.ok(bins.length >= 8, `expected ~10 bins, got ${bins.length}`);
+ t.end();
+});
+
+test('charts -> heatmap and pivot table', t => {
+ const dataset = mockDataset([
+ {category: 'A', value: 10, time: new Date('2020-01-01'), id: 'x'},
+ {category: 'B', value: 4, time: new Date('2020-01-01'), id: 'x'},
+ {category: 'A', value: 1, time: new Date('2020-01-01'), id: 'y'}
+ ]);
+ const cells = buildHeatmapCells({
+ dataset,
+ applyFilters: true,
+ xAxis: {field: {name: 'id', type: 'string'}, aggregation: BinType.uniqueBin},
+ yAxis: {field: {name: 'category', type: 'string'}, aggregation: BinType.uniqueBin},
+ valueAxis: {field: {name: 'value', type: 'real'}, aggregation: 'sum'}
+ });
+ t.ok(cells.some(cell => cell.x === 'x' && cell.y === 'A' && cell.value === 10));
+ const table = buildPivotTable({
+ dataset,
+ applyFilters: true,
+ xAxis: {field: {name: 'id', type: 'string'}, aggregation: BinType.uniqueBin},
+ yAxis: {field: {name: 'category', type: 'string'}, aggregation: BinType.uniqueBin},
+ valueAxis: {field: {name: 'value', type: 'real'}, aggregation: 'sum'}
+ });
+ t.equal(table.values.A.x, 10);
+ t.equal(table.values.A.y, 1);
+ t.end();
+});
+
+test('charts -> time series and hover indexes', t => {
+ const dataset = mockDataset([
+ {category: 'A', value: 10, time: new Date('2020-01-01T00:00:00Z'), id: '1'},
+ {category: 'A', value: 5, time: new Date('2020-01-02T00:00:00Z'), id: '1'},
+ {category: 'B', value: 99, time: new Date('2020-01-02T00:00:00Z'), id: '2'}
+ ]);
+ const bins = buildTimeSeries({
+ dataset,
+ indexes: [0, 1],
+ xAxis: {field: {name: 'time', type: 'timestamp'}, aggregation: BinType.timeBin},
+ yAxis: {field: {name: 'value', type: 'real'}, aggregation: 'sum'},
+ interval: 'day'
+ });
+ t.equal(bins.length, 2);
+ const chart = createChart({
+ type: LayerChartType.BREAKDOWN_BY_CATEGORY,
+ dataset,
+ layerId: 'l1'
+ });
+ chart.chartDisplay.idField = 'id';
+ t.deepEqual(getHoverRowIndexes(dataset, chart, 0), [0, 1]);
+ t.end();
+});
+
+test('charts -> extra aggregations', t => {
+ const dataset = mockDataset([
+ {category: 'A', value: 10, time: new Date('2020-01-01'), id: '1'},
+ {category: 'A', value: 2, time: new Date('2020-01-01'), id: '1'},
+ {category: 'B', value: 5, time: new Date('2020-01-02'), id: '2'}
+ ]);
+ const unique = buildGroupedBins({
+ dataset,
+ applyFilters: true,
+ binAxis: {field: {name: 'category', type: 'string'}, aggregation: BinType.uniqueBin},
+ valueAxis: {field: {name: 'value', type: 'real'}, aggregation: 'countUnique'}
+ });
+ t.equal(unique.find(bin => bin.key === 'A').value, 2);
+ const mode = buildGroupedBins({
+ dataset,
+ applyFilters: true,
+ binAxis: {field: {name: 'category', type: 'string'}, aggregation: BinType.uniqueBin},
+ valueAxis: {field: {name: 'value', type: 'real'}, aggregation: 'mode'}
+ });
+ t.ok(mode.find(bin => bin.key === 'A'));
+ const stdev = buildGroupedBins({
+ dataset,
+ applyFilters: true,
+ binAxis: {field: {name: 'category', type: 'string'}, aggregation: BinType.uniqueBin},
+ valueAxis: {field: {name: 'value', type: 'real'}, aggregation: 'stdev'}
+ });
+ t.ok(stdev.find(bin => bin.key === 'A').value > 0);
+ t.end();
+});
+
+test('charts -> integer categorical fields', t => {
+ const fields = [
+ {name: 'code', type: 'integer'},
+ {name: 'value', type: 'real'}
+ ];
+ const rows = [
+ {code: 1, value: 10},
+ {code: 2, value: 5}
+ ];
+ const dataset = {
+ id: 'codes',
+ label: 'Codes',
+ allIndexes: [0, 1],
+ filteredIndex: [0, 1],
+ fields,
+ getValue: (name, idx) => rows[idx][name]
+ };
+ const chart = createChart({type: ChartType.barChart, dataset});
+ t.equal(chart.xAxis.field.name, 'code');
+ t.end();
+});
+
+test('charts -> computeDatasetChart big number', t => {
+ const dataset = mockDataset([{category: 'A', value: 3, time: new Date('2020-01-01'), id: '1'}]);
+ const chart = createChart({type: ChartType.bigNumber, dataset});
+ const view = computeDatasetChart(chart, dataset);
+ t.equal(view.kind, 'bigNumber');
+ t.ok(typeof view.value === 'number');
+ t.end();
+});
+
+test('charts -> formatNumber uses compact SI instead of scientific notation', t => {
+ t.equal(formatNumber(767000), '767k');
+ t.equal(formatNumber(123456), '123.5k');
+ t.equal(formatNumber(1500000), '1.5M');
+ t.equal(formatNumber(9999), '9,999');
+ t.equal(formatNumber(42), '42');
+ t.equal(formatNumber(3.14159), '3.142');
+ t.equal(formatNumber(-1500000), '-1.5M');
+ t.end();
+});
+
+test('charts -> toChartableDataset does not look up missing fields', t => {
+ const missingLookups = [];
+ const raw = {
+ id: 'new-ds',
+ allIndexes: [0, 1, 2],
+ filteredIndex: [0, 1, 2],
+ fields: [{name: 'mag', type: 'real'}],
+ getValue: name => {
+ missingLookups.push(name);
+ return null;
+ }
+ };
+ const dataset = toChartableDataset(raw);
+ t.equal(dataset.getValue('Join_Count', 0), null);
+ t.equal(dataset.getValue('Join_Count', 1), null);
+ t.deepEqual(missingLookups, [], 'KeplerTable.getValue must not run for unknown fields');
+ t.equal(dataset.getValue('mag', 0), null);
+ t.deepEqual(missingLookups, ['mag']);
+ t.end();
+});
+
+test('charts -> switching dataset rebuilds line-chart axes from the new table', t => {
+ const oldDataset = mockDataset([
+ {category: 'A', value: 1, time: new Date('2020-01-01'), id: '1'}
+ ]);
+ const chart = createChart({type: ChartType.lineChart, dataset: oldDataset, dataId: 'old'});
+ chart.xAxis = {field: {name: 'Join_Count', type: 'integer'}, aggregation: BinType.uniqueBin};
+ chart.yAxis = {field: {name: 'Join_Count', type: 'integer'}, aggregation: 'sum'};
+ const nextDataset = mockDataset([
+ {category: 'B', value: 2, time: new Date('2021-01-01'), id: '2'}
+ ]);
+ nextDataset.id = 'new';
+ const props = propsForChartDatasetChange(chart, nextDataset, {dataId: 'new'});
+ t.equal(props.dataId, 'new');
+ t.notEqual(props.xAxis.field.name, 'Join_Count');
+ t.ok(nextDataset.fields.some(field => field.name === props.xAxis.field.name));
+ t.notEqual(props.yAxis.field && props.yAxis.field.name, 'Join_Count');
+ const view = computeDatasetChart({...chart, ...props}, nextDataset);
+ t.equal(view.kind, 'line');
+ t.ok(view.bins.length > 0);
+ t.end();
+});
+
+test('charts -> stale line-chart field does not emit bins', t => {
+ const dataset = mockDataset([{category: 'A', value: 1, time: new Date('2020-01-01'), id: '1'}]);
+ const chart = createChart({type: ChartType.lineChart, dataset});
+ chart.xAxis = {field: {name: 'Join_Count', type: 'integer'}, aggregation: BinType.uniqueBin};
+ const view = computeDatasetChart(chart, dataset);
+ t.equal(view.kind, 'line');
+ t.deepEqual(view.bins, []);
+ t.end();
+});
diff --git a/test/node/utils/index.js b/test/node/utils/index.js
index 1966dd9c7..1643774b1 100644
--- a/test/node/utils/index.js
+++ b/test/node/utils/index.js
@@ -34,6 +34,7 @@ import './composer-helpers-test';
import './dom-to-image';
import './wms-utils-test';
import './effect-utils-test';
+import './chart-aggregation-test';
import './duckdb-utils-test';
import './annotation-utils-test';
import './slider-scale-utils-test';
diff --git a/test/node/utils/plot-test.js b/test/node/utils/plot-test.js
index 31eeab2e8..d28df8fc0 100644
--- a/test/node/utils/plot-test.js
+++ b/test/node/utils/plot-test.js
@@ -42,6 +42,30 @@ test('Utils -> mergePolygonLayerIndexes', t => {
t.end();
});
+function mockGpuPlotDataset(rows) {
+ return {
+ id: 'dsA',
+ filteredIndex: rows.map((_, i) => i),
+ filteredIndexByLayer: {},
+ dataContainer: {},
+ gpuFilter: {
+ filterRange: [
+ [0, 10],
+ [0, 10]
+ ],
+ filterValueUpdateTriggers: {
+ gpu0: {name: 'colA'},
+ gpu1: {name: 'colB'}
+ },
+ filterValueAccessor:
+ () =>
+ () =>
+ ({index}) =>
+ rows[index]
+ }
+ };
+}
+
test('Utils -> runGpuFilterForPlot applies polygon layer indexes', t => {
const dataset = {
id: 'puppy',
@@ -70,6 +94,43 @@ test('Utils -> runGpuFilterForPlot applies polygon layer indexes', t => {
t.end();
});
+test('Utils -> runGpuFilterForPlot skips only this dataset column on multi-dataset filters', t => {
+ // GPU channel 0 = colA, channel 1 = colB. Range [0, 10] on both.
+ // Row 0: both in range. Row 1: colB out. Row 2: colA out. Row 3: both out.
+ const dataset = mockGpuPlotDataset([
+ [5, 5],
+ [5, 100],
+ [100, 5],
+ [100, 100]
+ ]);
+
+ t.deepEqual(
+ runGpuFilterForPlot(dataset, {
+ dataId: ['dsA', 'dsB'],
+ name: ['colA', 'colB']
+ }),
+ [0, 2],
+ 'should skip only this dataset column and still apply sibling GPU channels'
+ );
+
+ t.deepEqual(
+ runGpuFilterForPlot(dataset, {
+ dataId: ['dsA'],
+ name: ['colA']
+ }),
+ [0, 2],
+ 'should skip the plotted field on a single-dataset filter and still apply other GPU channels'
+ );
+
+ t.deepEqual(
+ runGpuFilterForPlot(dataset, undefined, ['colA', 'colB']),
+ [0, 1, 2, 3],
+ 'should skip every extra field name passed by charts without changing filter pairing'
+ );
+
+ t.end();
+});
+
test('Utils -> histogramFromThreshold', t => {
const thresholds1 = [1, 3, 6, 13];
diff --git a/yarn.lock b/yarn.lock
index cabb81d3b..aae13dcbc 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -3964,6 +3964,23 @@ __metadata:
languageName: unknown
linkType: soft
+"@kepler.gl/charts@npm:3.3.0-alpha.13, @kepler.gl/charts@workspace:src/charts":
+ version: 0.0.0-use.local
+ resolution: "@kepler.gl/charts@workspace:src/charts"
+ dependencies:
+ "@kepler.gl/types": "npm:3.3.0-alpha.13"
+ "@types/d3-array": "npm:^2.8.0"
+ "@types/d3-time": "npm:^2"
+ "@types/react": "npm:^19.0.0"
+ "@types/styled-components": "npm:^5.1.32"
+ d3-array: "npm:^2.8.0"
+ d3-time: "npm:^2.1.1"
+ styled-components: "npm:6.4.3"
+ peerDependencies:
+ react: ">=18"
+ languageName: unknown
+ linkType: soft
+
"@kepler.gl/cloud-providers@npm:3.3.0-alpha.13, @kepler.gl/cloud-providers@workspace:src/cloud-providers":
version: 0.0.0-use.local
resolution: "@kepler.gl/cloud-providers@workspace:src/cloud-providers"
@@ -4003,6 +4020,7 @@ __metadata:
"@hubble.gl/core": "npm:2.0.0-alpha.4"
"@hubble.gl/react": "npm:2.0.0-alpha.4"
"@kepler.gl/actions": "npm:3.3.0-alpha.13"
+ "@kepler.gl/charts": "npm:3.3.0-alpha.13"
"@kepler.gl/cloud-providers": "npm:3.3.0-alpha.13"
"@kepler.gl/common-utils": "npm:3.3.0-alpha.13"
"@kepler.gl/constants": "npm:3.3.0-alpha.13"
@@ -15232,7 +15250,7 @@ __metadata:
languageName: node
linkType: hard
-"d3-time@npm:^2.0.0":
+"d3-time@npm:^2.0.0, d3-time@npm:^2.1.1":
version: 2.1.1
resolution: "d3-time@npm:2.1.1"
dependencies: