@opendata-ai/openchart-react 8.0.0-rc.9 → 8.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/TileMap.tsx DELETED
@@ -1,165 +0,0 @@
1
- /**
2
- * React TileMap component: thin wrapper around the vanilla adapter.
3
- *
4
- * Mounts a tilemap instance on render, updates when spec changes,
5
- * and cleans up on unmount. All heavy lifting is done by the vanilla
6
- * createTileMap() function.
7
- *
8
- * Supports forwardRef for imperative control via the instance getter.
9
- */
10
-
11
- import type { DarkMode, ThemeConfig, TileMapSpec } from '@opendata-ai/openchart-core';
12
- import {
13
- createTileMap,
14
- type TileMapInstance,
15
- type TileMapMountOptions,
16
- } from '@opendata-ai/openchart-vanilla';
17
- import {
18
- type CSSProperties,
19
- forwardRef,
20
- useCallback,
21
- useEffect,
22
- useImperativeHandle,
23
- useRef,
24
- } from 'react';
25
- import { useVizDarkMode, useVizTheme } from './ThemeContext';
26
-
27
- export interface TileMapProps {
28
- /** The tilemap spec to render. */
29
- spec: TileMapSpec;
30
- /** Theme overrides. */
31
- theme?: ThemeConfig;
32
- /** Dark mode: "auto", "force", or "off". */
33
- darkMode?: DarkMode;
34
- /** Callback when a tile is clicked. */
35
- onTileClick?: (tile: {
36
- stateCode: string;
37
- stateName: string;
38
- value: number | null;
39
- data: Record<string, unknown>;
40
- }) => void;
41
- /** Callback when a tile is hovered (null when hover ends). */
42
- onTileHover?: (
43
- tile: {
44
- stateCode: string;
45
- stateName: string;
46
- value: number | null;
47
- data: Record<string, unknown>;
48
- } | null,
49
- ) => void;
50
- /** CSS class name for the wrapper div. */
51
- className?: string;
52
- /** Inline styles for the wrapper div. */
53
- style?: CSSProperties;
54
- }
55
-
56
- export interface TileMapHandle {
57
- /** The underlying tilemap instance (null until mounted). */
58
- readonly instance: TileMapInstance | null;
59
- }
60
-
61
- /**
62
- * React component that renders a tilemap from a TileMapSpec.
63
- *
64
- * Uses the vanilla adapter internally. The spec is compiled and rendered
65
- * as SVG inside a wrapper div. Spec changes trigger re-renders via the
66
- * vanilla adapter's update() method.
67
- */
68
- export const TileMap = forwardRef<TileMapHandle, TileMapProps>(function TileMap(
69
- { spec, theme: themeProp, darkMode, onTileClick, onTileHover, className, style },
70
- ref,
71
- ) {
72
- const contextTheme = useVizTheme();
73
- const contextDarkMode = useVizDarkMode();
74
- const theme = themeProp ?? contextTheme;
75
- const resolvedDarkMode = darkMode ?? contextDarkMode;
76
- const containerRef = useRef<HTMLDivElement>(null);
77
- const instanceRef = useRef<TileMapInstance | null>(null);
78
- const specRef = useRef<string>('');
79
-
80
- // Store event handlers in refs so they don't trigger recreation.
81
- const handlersRef = useRef<{
82
- onTileClick?: TileMapProps['onTileClick'];
83
- onTileHover?: TileMapProps['onTileHover'];
84
- }>({});
85
- handlersRef.current = {
86
- onTileClick,
87
- onTileHover,
88
- };
89
-
90
- // Stable callback wrappers that read from refs
91
- const stableOnTileClick = useCallback(
92
- (tile: {
93
- stateCode: string;
94
- stateName: string;
95
- value: number | null;
96
- data: Record<string, unknown>;
97
- }) => handlersRef.current.onTileClick?.(tile),
98
- [],
99
- );
100
- const stableOnTileHover = useCallback(
101
- (
102
- tile: {
103
- stateCode: string;
104
- stateName: string;
105
- value: number | null;
106
- data: Record<string, unknown>;
107
- } | null,
108
- ) => handlersRef.current.onTileHover?.(tile),
109
- [],
110
- );
111
-
112
- // Expose imperative handle
113
- useImperativeHandle(
114
- ref,
115
- () => ({
116
- get instance() {
117
- return instanceRef.current;
118
- },
119
- }),
120
- [],
121
- );
122
-
123
- // Mount tilemap and recreate when theme/darkMode change.
124
- // biome-ignore lint/correctness/useExhaustiveDependencies: spec intentionally excluded - spec changes handled via update() in Effect 2
125
- useEffect(() => {
126
- const container = containerRef.current;
127
- if (!container) return;
128
-
129
- const options: TileMapMountOptions = {
130
- theme,
131
- darkMode: resolvedDarkMode,
132
- onTileClick: stableOnTileClick,
133
- onTileHover: stableOnTileHover,
134
- responsive: true,
135
- };
136
-
137
- instanceRef.current = createTileMap(container, spec, options);
138
- specRef.current = JSON.stringify(spec);
139
-
140
- return () => {
141
- instanceRef.current?.destroy();
142
- instanceRef.current = null;
143
- };
144
- }, [theme, resolvedDarkMode, stableOnTileClick, stableOnTileHover]);
145
-
146
- // Update tilemap when spec changes.
147
- useEffect(() => {
148
- const instance = instanceRef.current;
149
- if (!instance) return;
150
-
151
- const specString = JSON.stringify(spec);
152
- if (specString === specRef.current) return;
153
-
154
- specRef.current = specString;
155
- instance.update(spec);
156
- }, [spec]);
157
-
158
- return (
159
- <div
160
- ref={containerRef}
161
- className={className ? `oc-tilemap-root ${className}` : 'oc-tilemap-root'}
162
- style={style}
163
- />
164
- );
165
- });
@@ -1,85 +0,0 @@
1
- /**
2
- * Visualization routing component: renders Chart, DataTable, or Graph
3
- * based on the spec type. Use this when rendering arbitrary VizSpec values.
4
- *
5
- * For event handlers, use the specific component (Chart, DataTable, Graph) directly.
6
- */
7
-
8
- import type { DarkMode, ThemeConfig, VizSpec } from '@opendata-ai/openchart-core';
9
- import {
10
- isBarListSpec,
11
- isGraphSpec,
12
- isMapSpec,
13
- isSankeySpec,
14
- isTableSpec,
15
- isTileMapSpec,
16
- } from '@opendata-ai/openchart-core';
17
- import type { CSSProperties } from 'react';
18
- import { BarList } from './BarList';
19
- import { Chart } from './Chart';
20
- import { DataTable } from './DataTable';
21
- import { Graph } from './Graph';
22
- import { GeoMap } from './Map';
23
- import { Sankey } from './Sankey';
24
- import { TileMap } from './TileMap';
25
-
26
- export interface VisualizationProps {
27
- /** The visualization spec to render. */
28
- spec: VizSpec;
29
- /** Theme overrides. */
30
- theme?: ThemeConfig;
31
- /** Dark mode: "auto", "force", or "off". */
32
- darkMode?: DarkMode;
33
- /** CSS class name for the wrapper div. */
34
- className?: string;
35
- /** Inline styles for the wrapper div. */
36
- style?: CSSProperties;
37
- }
38
-
39
- /**
40
- * Routes a VizSpec to the appropriate rendering component.
41
- *
42
- * Accepts any VizSpec and renders it with the correct component based on the
43
- * spec's type field. For event handlers, use Chart, DataTable, or Graph directly.
44
- */
45
- export function Visualization({ spec, theme, darkMode, className, style }: VisualizationProps) {
46
- if (isTableSpec(spec)) {
47
- return (
48
- <DataTable
49
- spec={spec}
50
- theme={theme}
51
- darkMode={darkMode}
52
- className={className}
53
- style={style}
54
- />
55
- );
56
- }
57
- if (isGraphSpec(spec)) {
58
- return (
59
- <Graph spec={spec} theme={theme} darkMode={darkMode} className={className} style={style} />
60
- );
61
- }
62
- if (isSankeySpec(spec)) {
63
- return (
64
- <Sankey spec={spec} theme={theme} darkMode={darkMode} className={className} style={style} />
65
- );
66
- }
67
- if (isTileMapSpec(spec)) {
68
- return (
69
- <TileMap spec={spec} theme={theme} darkMode={darkMode} className={className} style={style} />
70
- );
71
- }
72
- if (isBarListSpec(spec)) {
73
- return (
74
- <BarList spec={spec} theme={theme} darkMode={darkMode} className={className} style={style} />
75
- );
76
- }
77
- if (isMapSpec(spec)) {
78
- return (
79
- <GeoMap spec={spec} theme={theme} darkMode={darkMode} className={className} style={style} />
80
- );
81
- }
82
- return (
83
- <Chart spec={spec} theme={theme} darkMode={darkMode} className={className} style={style} />
84
- );
85
- }
@@ -1,134 +0,0 @@
1
- import type { ChartSpec } from '@opendata-ai/openchart-core';
2
- import { cleanup, render, waitFor } from '@testing-library/react';
3
- import { afterEach, describe, expect, it } from 'vitest';
4
- import { Chart } from '../Chart';
5
-
6
- // ---------------------------------------------------------------------------
7
- // Test data
8
- // ---------------------------------------------------------------------------
9
-
10
- const lineSpec: ChartSpec = {
11
- mark: 'line',
12
- data: [
13
- { date: '2020-01-01', value: 10, country: 'US' },
14
- { date: '2021-01-01', value: 40, country: 'US' },
15
- { date: '2020-01-01', value: 15, country: 'UK' },
16
- { date: '2021-01-01', value: 35, country: 'UK' },
17
- ],
18
- encoding: {
19
- x: { field: 'date', type: 'temporal' },
20
- y: { field: 'value', type: 'quantitative' },
21
- color: { field: 'country', type: 'nominal' },
22
- },
23
- chrome: {
24
- title: 'GDP Growth',
25
- subtitle: 'US vs UK over time',
26
- source: 'World Bank',
27
- },
28
- };
29
-
30
- const barSpec: ChartSpec = {
31
- mark: 'bar',
32
- data: [
33
- { name: 'A', value: 10 },
34
- { name: 'B', value: 30 },
35
- { name: 'C', value: 20 },
36
- ],
37
- encoding: {
38
- x: { field: 'value', type: 'quantitative' },
39
- y: { field: 'name', type: 'nominal' },
40
- },
41
- chrome: {
42
- title: 'Updated Title',
43
- },
44
- };
45
-
46
- // ---------------------------------------------------------------------------
47
- // Helper: render Chart and wait for SVG to appear (useEffect is deferred)
48
- // ---------------------------------------------------------------------------
49
-
50
- async function renderChart(props: React.ComponentProps<typeof Chart>) {
51
- const result = render(<Chart {...props} />);
52
- await waitFor(() => {
53
- expect(result.container.querySelector('svg')).not.toBeNull();
54
- });
55
- return result;
56
- }
57
-
58
- // ---------------------------------------------------------------------------
59
- // Tests
60
- // ---------------------------------------------------------------------------
61
-
62
- afterEach(() => {
63
- cleanup();
64
- });
65
-
66
- describe('<Chart />', () => {
67
- it('renders an SVG element', async () => {
68
- const { container } = await renderChart({ spec: lineSpec });
69
- const svg = container.querySelector('svg');
70
- expect(svg).not.toBeNull();
71
- expect(svg?.getAttribute('class')).toBe('oc-chart');
72
- });
73
-
74
- it('renders chrome text elements', async () => {
75
- const { container } = await renderChart({ spec: lineSpec });
76
-
77
- const title = container.querySelector('.oc-title');
78
- expect(title).not.toBeNull();
79
- expect(title?.textContent).toBe('GDP Growth');
80
-
81
- const subtitle = container.querySelector('.oc-subtitle');
82
- expect(subtitle?.textContent).toBe('US vs UK over time');
83
-
84
- const source = container.querySelector('.oc-source');
85
- expect(source?.textContent).toBe('World Bank');
86
- });
87
-
88
- it('spec changes trigger re-render', async () => {
89
- const { container, rerender } = await renderChart({ spec: lineSpec });
90
-
91
- const titleBefore = container.querySelector('.oc-title');
92
- expect(titleBefore?.textContent).toBe('GDP Growth');
93
-
94
- rerender(<Chart spec={barSpec} />);
95
- await waitFor(() => {
96
- expect(container.querySelector('.oc-title')?.textContent).toBe('Updated Title');
97
- });
98
- });
99
-
100
- it('unmounting cleans up chart instance', async () => {
101
- const { container, unmount } = await renderChart({ spec: lineSpec });
102
-
103
- const svgBefore = container.querySelector('svg');
104
- expect(svgBefore).not.toBeNull();
105
-
106
- unmount();
107
-
108
- expect(container.querySelector('svg')).toBeNull();
109
- });
110
-
111
- it('className prop passes through to wrapper div', async () => {
112
- const { container } = await renderChart({ spec: lineSpec, className: 'my-chart' });
113
-
114
- const wrapper = container.firstElementChild as HTMLElement;
115
- expect(wrapper?.className).toContain('my-chart');
116
- });
117
-
118
- it('renders with dark mode option', async () => {
119
- const { container } = await renderChart({ spec: lineSpec, darkMode: 'force' });
120
-
121
- const svg = container.querySelector('svg');
122
- expect(svg).not.toBeNull();
123
- });
124
-
125
- it('style prop passes through to wrapper div', async () => {
126
- const { container } = await renderChart({
127
- spec: lineSpec,
128
- style: { border: '1px solid red' },
129
- });
130
-
131
- const wrapper = container.firstElementChild as HTMLElement;
132
- expect(wrapper?.style.border).toBe('1px solid red');
133
- });
134
- });
@@ -1,92 +0,0 @@
1
- import type { ChartSpec } from '@opendata-ai/openchart-core';
2
- import { cleanup, render, waitFor } from '@testing-library/react';
3
- import { createRef } from 'react';
4
- import { afterEach, describe, expect, it } from 'vitest';
5
- import { ChartStory, type ChartStoryHandle } from '../ChartStory';
6
-
7
- const baseSpec: ChartSpec = {
8
- mark: 'line',
9
- data: [
10
- { year: '2008', value: 10, country: 'US' },
11
- { year: '2012', value: 40, country: 'US' },
12
- { year: '2016', value: 25, country: 'US' },
13
- ],
14
- encoding: {
15
- x: { field: 'year', type: 'ordinal' },
16
- y: { field: 'value', type: 'quantitative' },
17
- },
18
- chrome: { title: 'Base' },
19
- };
20
-
21
- const steps = [
22
- {},
23
- { spec: { chrome: { title: 'One' } } },
24
- { spec: { chrome: { subtitle: 'Two' } } },
25
- ];
26
- const narrative = [<p key="a">Intro</p>, <p key="b">Middle</p>, <p key="c">End</p>];
27
-
28
- describe('ChartStory', () => {
29
- afterEach(cleanup);
30
-
31
- it('renders the sticky chart panel and one block per step', async () => {
32
- const { container } = render(
33
- <ChartStory spec={baseSpec} steps={steps} narrative={narrative} />,
34
- );
35
-
36
- await waitFor(() => {
37
- expect(container.querySelector('svg')).not.toBeNull();
38
- });
39
-
40
- // The chart mounts and a title renders (self-driving scroll may advance
41
- // the step in a headless layout; the block count is the stable assertion).
42
- expect(container.querySelector('.oc-title')).not.toBeNull();
43
- // One narrative block per step.
44
- expect(container.querySelectorAll('[data-oc-story-step]')).toHaveLength(3);
45
- });
46
-
47
- it('drives the story from the controlled step prop', async () => {
48
- const { container, rerender } = render(
49
- <ChartStory spec={baseSpec} steps={steps} narrative={narrative} step={0} />,
50
- );
51
-
52
- await waitFor(() => {
53
- expect(container.querySelector('svg')).not.toBeNull();
54
- });
55
-
56
- rerender(<ChartStory spec={baseSpec} steps={steps} narrative={narrative} step={2} />);
57
-
58
- await waitFor(() => {
59
- expect(container.querySelector('.oc-title')?.textContent).toBe('One');
60
- expect(container.querySelector('.oc-subtitle')?.textContent).toBe('Two');
61
- });
62
- });
63
-
64
- it('exposes goTo and the underlying instance through the ref', async () => {
65
- const ref = createRef<ChartStoryHandle>();
66
- const { container } = render(
67
- <ChartStory ref={ref} spec={baseSpec} steps={steps} narrative={narrative} />,
68
- );
69
-
70
- await waitFor(() => {
71
- expect(container.querySelector('svg')).not.toBeNull();
72
- });
73
-
74
- expect(ref.current?.instance).not.toBeNull();
75
- ref.current?.goTo(1);
76
- expect(container.querySelector('.oc-title')?.textContent).toBe('One');
77
- });
78
-
79
- it('tears down the story instance on unmount', async () => {
80
- const ref = createRef<ChartStoryHandle>();
81
- const { container, unmount } = render(
82
- <ChartStory ref={ref} spec={baseSpec} steps={steps} narrative={narrative} />,
83
- );
84
-
85
- await waitFor(() => {
86
- expect(container.querySelector('svg')).not.toBeNull();
87
- });
88
-
89
- unmount();
90
- expect(container.querySelector('svg')).toBeNull();
91
- });
92
- });
@@ -1,126 +0,0 @@
1
- import type { TableSpec } from '@opendata-ai/openchart-core';
2
- import { cleanup, render, waitFor } from '@testing-library/react';
3
- import { afterEach, describe, expect, it } from 'vitest';
4
- import { DataTable } from '../DataTable';
5
-
6
- // ---------------------------------------------------------------------------
7
- // Test data
8
- // ---------------------------------------------------------------------------
9
-
10
- const tableSpec: TableSpec = {
11
- type: 'table',
12
- data: [
13
- { name: 'Alice', age: 30, city: 'Portland' },
14
- { name: 'Bob', age: 25, city: 'Seattle' },
15
- { name: 'Charlie', age: 35, city: 'Denver' },
16
- ],
17
- columns: [
18
- { key: 'name', label: 'Name' },
19
- { key: 'age', label: 'Age' },
20
- { key: 'city', label: 'City' },
21
- ],
22
- chrome: { title: 'People Table' },
23
- };
24
-
25
- const updatedSpec: TableSpec = {
26
- type: 'table',
27
- data: [
28
- { x: 1, y: 2 },
29
- { x: 3, y: 4 },
30
- ],
31
- columns: [
32
- { key: 'x', label: 'X Value' },
33
- { key: 'y', label: 'Y Value' },
34
- ],
35
- chrome: { title: 'Updated Table' },
36
- };
37
-
38
- // ---------------------------------------------------------------------------
39
- // Helper: render DataTable and wait for the table to mount (useEffect is deferred)
40
- // ---------------------------------------------------------------------------
41
-
42
- async function renderTable(props: React.ComponentProps<typeof DataTable>) {
43
- const result = render(<DataTable {...props} />);
44
- await waitFor(() => {
45
- expect(result.container.querySelector('table')).not.toBeNull();
46
- });
47
- return result;
48
- }
49
-
50
- // ---------------------------------------------------------------------------
51
- // Tests
52
- // ---------------------------------------------------------------------------
53
-
54
- afterEach(() => {
55
- cleanup();
56
- });
57
-
58
- describe('<DataTable />', () => {
59
- it('renders a table', async () => {
60
- const { container } = await renderTable({ spec: tableSpec });
61
- const table = container.querySelector('table');
62
- expect(table).not.toBeNull();
63
- });
64
-
65
- it('renders correct number of columns', async () => {
66
- const { container } = await renderTable({ spec: tableSpec });
67
- const headers = container.querySelectorAll('thead th');
68
- expect(headers.length).toBe(3);
69
- });
70
-
71
- it('renders correct number of rows', async () => {
72
- const { container } = await renderTable({ spec: tableSpec });
73
- const rows = container.querySelectorAll('tbody tr');
74
- expect(rows.length).toBe(3);
75
- });
76
-
77
- it('spec changes trigger re-render', async () => {
78
- const { container, rerender } = await renderTable({ spec: tableSpec });
79
-
80
- const titleBefore = container.querySelector('.oc-table-title');
81
- expect(titleBefore?.textContent).toBe('People Table');
82
-
83
- rerender(<DataTable spec={updatedSpec} />);
84
- await waitFor(() => {
85
- expect(container.querySelector('.oc-table-title')?.textContent).toBe('Updated Table');
86
- });
87
-
88
- const headersAfter = container.querySelectorAll('thead th');
89
- expect(headersAfter.length).toBe(2);
90
- });
91
-
92
- it('unmounting cleans up', async () => {
93
- const { container, unmount } = await renderTable({ spec: tableSpec });
94
-
95
- const tableBefore = container.querySelector('table');
96
- expect(tableBefore).not.toBeNull();
97
-
98
- unmount();
99
-
100
- expect(container.querySelector('table')).toBeNull();
101
- });
102
-
103
- it('className passes through', async () => {
104
- const { container } = await renderTable({ spec: tableSpec, className: 'my-table' });
105
-
106
- const wrapper = container.firstElementChild as HTMLElement;
107
- expect(wrapper?.className).toContain('my-table');
108
- });
109
-
110
- it('renders with dark mode option', async () => {
111
- const { container } = await renderTable({ spec: tableSpec, darkMode: 'force' });
112
-
113
- const table = container.querySelector('table');
114
- expect(table).not.toBeNull();
115
- });
116
-
117
- it('style prop passes through to wrapper div', async () => {
118
- const { container } = await renderTable({
119
- spec: tableSpec,
120
- style: { border: '1px solid red' },
121
- });
122
-
123
- const wrapper = container.firstElementChild as HTMLElement;
124
- expect(wrapper?.style.border).toBe('1px solid red');
125
- });
126
- });