@opendata-ai/openchart-react 8.0.0-rc.12 → 8.0.0-rc.3

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.
@@ -0,0 +1,218 @@
1
+ /**
2
+ * Tests for useTableState hook.
3
+ *
4
+ * Uses thin wrapper components that expose hook state via the DOM,
5
+ * since renderHook is broken by bun's React dual-instance issue.
6
+ */
7
+
8
+ import { fireEvent, render, waitFor } from '@testing-library/react';
9
+ import { describe, expect, it } from 'vitest';
10
+ import { type UseTableStateOptions, useTableState } from '../hooks/useTableState';
11
+
12
+ // ---------------------------------------------------------------------------
13
+ // Test harness: renders hook state to the DOM
14
+ // ---------------------------------------------------------------------------
15
+
16
+ interface HarnessProps {
17
+ initialState?: UseTableStateOptions;
18
+ }
19
+
20
+ function TableStateHarness({ initialState }: HarnessProps) {
21
+ const { sort, search, page, setSort, setSearch, setPage, resetState } =
22
+ useTableState(initialState);
23
+
24
+ return (
25
+ <div>
26
+ <span data-testid="sort">{sort ? `${sort.column}:${sort.direction}` : 'null'}</span>
27
+ <span data-testid="search">{search}</span>
28
+ <span data-testid="page">{String(page)}</span>
29
+ <button
30
+ type="button"
31
+ data-testid="set-sort-name-asc"
32
+ onClick={() => setSort({ column: 'name', direction: 'asc' })}
33
+ >
34
+ sort name asc
35
+ </button>
36
+ <button
37
+ type="button"
38
+ data-testid="set-sort-age-desc"
39
+ onClick={() => setSort({ column: 'age', direction: 'desc' })}
40
+ >
41
+ sort age desc
42
+ </button>
43
+ <button type="button" data-testid="clear-sort" onClick={() => setSort(null)}>
44
+ clear sort
45
+ </button>
46
+ <button type="button" data-testid="set-search" onClick={() => setSearch('filter text')}>
47
+ set search
48
+ </button>
49
+ <button type="button" data-testid="set-page-5" onClick={() => setPage(5)}>
50
+ page 5
51
+ </button>
52
+ <button type="button" data-testid="reset" onClick={() => resetState()}>
53
+ reset
54
+ </button>
55
+ </div>
56
+ );
57
+ }
58
+
59
+ // ---------------------------------------------------------------------------
60
+ // Helper
61
+ // ---------------------------------------------------------------------------
62
+
63
+ async function renderHarness(initialState?: UseTableStateOptions) {
64
+ const result = render(<TableStateHarness initialState={initialState} />);
65
+ // Wait for initial render to complete
66
+ await waitFor(() => {
67
+ expect(result.container.querySelector('[data-testid="page"]')).not.toBeNull();
68
+ });
69
+ return result;
70
+ }
71
+
72
+ function getState(container: HTMLElement) {
73
+ return {
74
+ sort: container.querySelector('[data-testid="sort"]')?.textContent ?? '',
75
+ search: container.querySelector('[data-testid="search"]')?.textContent ?? '',
76
+ page: container.querySelector('[data-testid="page"]')?.textContent ?? '',
77
+ };
78
+ }
79
+
80
+ // ---------------------------------------------------------------------------
81
+ // Tests
82
+ // ---------------------------------------------------------------------------
83
+
84
+ describe('useTableState', () => {
85
+ // -------------------------------------------------------------------------
86
+ // Default initial state
87
+ // -------------------------------------------------------------------------
88
+
89
+ it('initializes with default values when no options provided', async () => {
90
+ const { container } = await renderHarness();
91
+ const state = getState(container);
92
+
93
+ expect(state.sort).toBe('null');
94
+ expect(state.search).toBe('');
95
+ expect(state.page).toBe('0');
96
+ });
97
+
98
+ // -------------------------------------------------------------------------
99
+ // Custom initial state
100
+ // -------------------------------------------------------------------------
101
+
102
+ it('initializes with provided sort state', async () => {
103
+ const { container } = await renderHarness({
104
+ sort: { column: 'name', direction: 'asc' },
105
+ });
106
+ expect(getState(container).sort).toBe('name:asc');
107
+ });
108
+
109
+ it('initializes with provided search string', async () => {
110
+ const { container } = await renderHarness({ search: 'hello' });
111
+ expect(getState(container).search).toBe('hello');
112
+ });
113
+
114
+ it('initializes with provided page number', async () => {
115
+ const { container } = await renderHarness({ page: 3 });
116
+ expect(getState(container).page).toBe('3');
117
+ });
118
+
119
+ // -------------------------------------------------------------------------
120
+ // State setters
121
+ // -------------------------------------------------------------------------
122
+
123
+ it('setSort updates the sort state', async () => {
124
+ const { container } = await renderHarness();
125
+
126
+ fireEvent.click(container.querySelector('[data-testid="set-sort-age-desc"]')!);
127
+ await waitFor(() => {
128
+ expect(getState(container).sort).toBe('age:desc');
129
+ });
130
+ });
131
+
132
+ it('setSort can clear sort by passing null', async () => {
133
+ const { container } = await renderHarness({
134
+ sort: { column: 'name', direction: 'asc' },
135
+ });
136
+ expect(getState(container).sort).toBe('name:asc');
137
+
138
+ fireEvent.click(container.querySelector('[data-testid="clear-sort"]')!);
139
+ await waitFor(() => {
140
+ expect(getState(container).sort).toBe('null');
141
+ });
142
+ });
143
+
144
+ it('setSearch updates the search query', async () => {
145
+ const { container } = await renderHarness();
146
+
147
+ fireEvent.click(container.querySelector('[data-testid="set-search"]')!);
148
+ await waitFor(() => {
149
+ expect(getState(container).search).toBe('filter text');
150
+ });
151
+ });
152
+
153
+ it('setPage updates the current page', async () => {
154
+ const { container } = await renderHarness();
155
+
156
+ fireEvent.click(container.querySelector('[data-testid="set-page-5"]')!);
157
+ await waitFor(() => {
158
+ expect(getState(container).page).toBe('5');
159
+ });
160
+ });
161
+
162
+ // -------------------------------------------------------------------------
163
+ // resetState
164
+ // -------------------------------------------------------------------------
165
+
166
+ it('resetState restores default initial values', async () => {
167
+ const { container } = await renderHarness();
168
+
169
+ // Change all values
170
+ fireEvent.click(container.querySelector('[data-testid="set-sort-name-asc"]')!);
171
+ fireEvent.click(container.querySelector('[data-testid="set-search"]')!);
172
+ fireEvent.click(container.querySelector('[data-testid="set-page-5"]')!);
173
+
174
+ await waitFor(() => {
175
+ expect(getState(container).sort).toBe('name:asc');
176
+ expect(getState(container).search).toBe('filter text');
177
+ expect(getState(container).page).toBe('5');
178
+ });
179
+
180
+ // Reset
181
+ fireEvent.click(container.querySelector('[data-testid="reset"]')!);
182
+
183
+ await waitFor(() => {
184
+ expect(getState(container).sort).toBe('null');
185
+ expect(getState(container).search).toBe('');
186
+ expect(getState(container).page).toBe('0');
187
+ });
188
+ });
189
+
190
+ it('resetState restores custom initial values', async () => {
191
+ const initialState = {
192
+ sort: { column: 'age', direction: 'desc' as const },
193
+ search: 'initial',
194
+ page: 1,
195
+ };
196
+ const { container } = await renderHarness(initialState);
197
+
198
+ // Change all values
199
+ fireEvent.click(container.querySelector('[data-testid="clear-sort"]')!);
200
+ fireEvent.click(container.querySelector('[data-testid="set-search"]')!);
201
+ fireEvent.click(container.querySelector('[data-testid="set-page-5"]')!);
202
+
203
+ await waitFor(() => {
204
+ expect(getState(container).sort).toBe('null');
205
+ expect(getState(container).search).toBe('filter text');
206
+ expect(getState(container).page).toBe('5');
207
+ });
208
+
209
+ // Reset to initial
210
+ fireEvent.click(container.querySelector('[data-testid="reset"]')!);
211
+
212
+ await waitFor(() => {
213
+ expect(getState(container).sort).toBe('age:desc');
214
+ expect(getState(container).search).toBe('initial');
215
+ expect(getState(container).page).toBe('1');
216
+ });
217
+ });
218
+ });
@@ -0,0 +1,87 @@
1
+ /**
2
+ * useGraph: hook for imperative graph control.
3
+ *
4
+ * Provides a ref to pass to <Graph /> and exposes graph methods
5
+ * (search, zoom, select) for programmatic control of the graph instance.
6
+ */
7
+
8
+ import type { GraphInstance } from '@opendata-ai/openchart-vanilla';
9
+ import { useCallback, useRef } from 'react';
10
+
11
+ export interface UseGraphReturn {
12
+ /** Ref to pass to <Graph ref={ref} />. */
13
+ ref: React.RefObject<GraphHandle | null>;
14
+ /** Search for nodes matching a query string. */
15
+ search: (query: string) => void;
16
+ /** Clear the current search. */
17
+ clearSearch: () => void;
18
+ /** Zoom to fit all nodes in view. */
19
+ zoomToFit: () => void;
20
+ /** Zoom and center on a specific node. */
21
+ zoomToNode: (nodeId: string) => void;
22
+ /** Select a node by id. */
23
+ selectNode: (nodeId: string) => void;
24
+ /** Get the currently selected node ids. */
25
+ getSelectedNodes: () => string[];
26
+ }
27
+
28
+ /** Handle exposed by Graph component via forwardRef. */
29
+ export interface GraphHandle {
30
+ search: (query: string) => void;
31
+ clearSearch: () => void;
32
+ zoomToFit: () => void;
33
+ zoomToNode: (nodeId: string) => void;
34
+ selectNode: (nodeId: string) => void;
35
+ getSelectedNodes: () => string[];
36
+ /** Re-compile encoding/legend/chrome without restarting the simulation. */
37
+ updateVisuals: (spec: import('@opendata-ai/openchart-core').GraphSpec) => void;
38
+ /** The underlying GraphInstance from the vanilla adapter. */
39
+ instance: GraphInstance | null;
40
+ }
41
+
42
+ /**
43
+ * Hook for imperative graph control.
44
+ *
45
+ * Usage:
46
+ * ```tsx
47
+ * const { ref, search, zoomToFit } = useGraph();
48
+ * return <Graph ref={ref} spec={spec} />;
49
+ * ```
50
+ */
51
+ export function useGraph(): UseGraphReturn {
52
+ const ref = useRef<GraphHandle | null>(null);
53
+
54
+ const search = useCallback((query: string) => {
55
+ ref.current?.search(query);
56
+ }, []);
57
+
58
+ const clearSearch = useCallback(() => {
59
+ ref.current?.clearSearch();
60
+ }, []);
61
+
62
+ const zoomToFit = useCallback(() => {
63
+ ref.current?.zoomToFit();
64
+ }, []);
65
+
66
+ const zoomToNode = useCallback((nodeId: string) => {
67
+ ref.current?.zoomToNode(nodeId);
68
+ }, []);
69
+
70
+ const selectNode = useCallback((nodeId: string) => {
71
+ ref.current?.selectNode(nodeId);
72
+ }, []);
73
+
74
+ const getSelectedNodes = useCallback((): string[] => {
75
+ return ref.current?.getSelectedNodes() ?? [];
76
+ }, []);
77
+
78
+ return {
79
+ ref,
80
+ search,
81
+ clearSearch,
82
+ zoomToFit,
83
+ zoomToNode,
84
+ selectNode,
85
+ getSelectedNodes,
86
+ };
87
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * useTable: hook for manual table lifecycle control.
3
+ *
4
+ * Attaches to a container ref, mounts a vanilla table instance,
5
+ * and exposes the instance and current state.
6
+ */
7
+
8
+ import type { TableSpec } from '@opendata-ai/openchart-core';
9
+ import {
10
+ createTable,
11
+ type TableInstance,
12
+ type TableMountOptions,
13
+ type TableState,
14
+ } from '@opendata-ai/openchart-vanilla';
15
+ import { useCallback, useEffect, useRef, useState } from 'react';
16
+
17
+ export interface UseTableReturn {
18
+ /** Ref to attach to the container div. */
19
+ ref: React.RefObject<HTMLDivElement | null>;
20
+ /** The table instance (null until mounted). */
21
+ table: TableInstance | null;
22
+ /** The current table state (sort, search, page). */
23
+ state: TableState;
24
+ }
25
+
26
+ /**
27
+ * Hook for manual table lifecycle control.
28
+ *
29
+ * Attach the returned ref to a container div. The table mounts
30
+ * automatically and updates when the spec changes.
31
+ *
32
+ * @param spec - The table spec.
33
+ * @param options - Mount options.
34
+ * @returns { ref, table, state }
35
+ */
36
+ export function useTable(spec: TableSpec, options?: TableMountOptions): UseTableReturn {
37
+ const ref = useRef<HTMLDivElement | null>(null);
38
+ const tableRef = useRef<TableInstance | null>(null);
39
+ const [state, setState] = useState<TableState>({
40
+ sort: null,
41
+ search: '',
42
+ page: 0,
43
+ });
44
+
45
+ const originalOnStateChange = options?.onStateChange;
46
+
47
+ const handleStateChange = useCallback(
48
+ (newState: TableState) => {
49
+ setState(newState);
50
+ originalOnStateChange?.(newState);
51
+ },
52
+ [originalOnStateChange],
53
+ );
54
+
55
+ // Mount / unmount
56
+ useEffect(() => {
57
+ const container = ref.current;
58
+ if (!container) return;
59
+
60
+ const mountOpts: TableMountOptions = {
61
+ ...options,
62
+ onStateChange: handleStateChange,
63
+ };
64
+
65
+ const table = createTable(container, spec, mountOpts);
66
+ tableRef.current = table;
67
+ setState(table.getState());
68
+
69
+ return () => {
70
+ table.destroy();
71
+ tableRef.current = null;
72
+ };
73
+ // eslint-disable-next-line react-hooks/exhaustive-deps
74
+ }, [
75
+ options?.theme,
76
+ options?.darkMode,
77
+ options?.onRowClick,
78
+ options?.responsive,
79
+ handleStateChange,
80
+ options,
81
+ spec,
82
+ ]);
83
+
84
+ // Update on spec change
85
+ useEffect(() => {
86
+ const table = tableRef.current;
87
+ if (!table) return;
88
+
89
+ table.update(spec);
90
+ setState(table.getState());
91
+ }, [spec]);
92
+
93
+ return {
94
+ ref,
95
+ table: tableRef.current,
96
+ state,
97
+ };
98
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * useTableState: managed state hook for controlled table usage.
3
+ *
4
+ * Provides individual sort/search/page state with setters and a
5
+ * resetState function to return to initial values.
6
+ */
7
+
8
+ import type { SortState } from '@opendata-ai/openchart-core';
9
+ import { useCallback, useState } from 'react';
10
+
11
+ export interface UseTableStateReturn {
12
+ sort: SortState | null;
13
+ setSort: (sort: SortState | null) => void;
14
+ search: string;
15
+ setSearch: (query: string) => void;
16
+ page: number;
17
+ setPage: (page: number) => void;
18
+ resetState: () => void;
19
+ }
20
+
21
+ export interface UseTableStateOptions {
22
+ sort?: SortState | null;
23
+ search?: string;
24
+ page?: number;
25
+ }
26
+
27
+ /**
28
+ * Hook for managing table state (sort, search, page).
29
+ *
30
+ * Use with the DataTable component's controlled props:
31
+ * ```tsx
32
+ * const { sort, search, page, setSort, setSearch, setPage } = useTableState();
33
+ * <DataTable
34
+ * spec={spec}
35
+ * sort={sort}
36
+ * search={search}
37
+ * page={page}
38
+ * onSortChange={setSort}
39
+ * onSearchChange={setSearch}
40
+ * onPageChange={setPage}
41
+ * />
42
+ * ```
43
+ */
44
+ export function useTableState(initialState?: UseTableStateOptions): UseTableStateReturn {
45
+ const [sort, setSortInternal] = useState<SortState | null>(initialState?.sort ?? null);
46
+ const [search, setSearchInternal] = useState(initialState?.search ?? '');
47
+ const [page, setPageInternal] = useState(initialState?.page ?? 0);
48
+
49
+ const setSort = useCallback((newSort: SortState | null) => {
50
+ setSortInternal(newSort);
51
+ }, []);
52
+
53
+ const setSearch = useCallback((query: string) => {
54
+ setSearchInternal(query);
55
+ }, []);
56
+
57
+ const setPage = useCallback((newPage: number) => {
58
+ setPageInternal(newPage);
59
+ }, []);
60
+
61
+ const resetState = useCallback(() => {
62
+ setSortInternal(initialState?.sort ?? null);
63
+ setSearchInternal(initialState?.search ?? '');
64
+ setPageInternal(initialState?.page ?? 0);
65
+ }, [initialState?.sort, initialState?.search, initialState?.page]);
66
+
67
+ return {
68
+ sort,
69
+ setSort,
70
+ search,
71
+ setSearch,
72
+ page,
73
+ setPage,
74
+ resetState,
75
+ };
76
+ }
package/src/hooks.ts ADDED
@@ -0,0 +1,154 @@
1
+ /**
2
+ * React hooks for chart lifecycle and dark mode resolution.
3
+ *
4
+ * useChart: manual control over a chart instance (for advanced usage).
5
+ * useDarkMode: resolves the DarkMode preference to a boolean.
6
+ */
7
+
8
+ import type {
9
+ ChartLayout,
10
+ ChartSpec,
11
+ DarkMode,
12
+ GraphSpec,
13
+ LayerSpec,
14
+ } from '@opendata-ai/openchart-core';
15
+ import { type ChartInstance, createChart, type MountOptions } from '@opendata-ai/openchart-vanilla';
16
+ import { useEffect, useRef, useState } from 'react';
17
+
18
+ // ---------------------------------------------------------------------------
19
+ // useChart
20
+ // ---------------------------------------------------------------------------
21
+
22
+ export interface UseChartOptions {
23
+ /** Theme overrides. */
24
+ theme?: MountOptions['theme'];
25
+ /** Dark mode setting. */
26
+ darkMode?: MountOptions['darkMode'];
27
+ /** Data point click handler. */
28
+ onDataPointClick?: MountOptions['onDataPointClick'];
29
+ /** Enable responsive resizing. Defaults to true. */
30
+ responsive?: boolean;
31
+ }
32
+
33
+ export interface UseChartReturn {
34
+ /** Ref to attach to the container div. */
35
+ ref: React.RefObject<HTMLDivElement | null>;
36
+ /** The chart instance (null until mounted). */
37
+ chart: ChartInstance | null;
38
+ /** The current compiled layout (null until mounted). */
39
+ layout: ChartLayout | null;
40
+ }
41
+
42
+ /**
43
+ * Hook for manual chart lifecycle control.
44
+ *
45
+ * Attach the returned ref to a container div. The chart mounts
46
+ * automatically and updates when the spec changes.
47
+ *
48
+ * @param spec - The visualization spec.
49
+ * @param options - Mount options.
50
+ * @returns { ref, chart, layout }
51
+ */
52
+ export function useChart(
53
+ spec: ChartSpec | LayerSpec | GraphSpec,
54
+ options?: UseChartOptions,
55
+ ): UseChartReturn {
56
+ const ref = useRef<HTMLDivElement | null>(null);
57
+ const chartRef = useRef<ChartInstance | null>(null);
58
+ const [layout, setLayout] = useState<ChartLayout | null>(null);
59
+ const specRef = useRef<string>('');
60
+
61
+ // Mount / unmount
62
+ // biome-ignore lint/correctness/useExhaustiveDependencies: spec intentionally excluded - spec changes handled via update() in the update effect
63
+ useEffect(() => {
64
+ const container = ref.current;
65
+ if (!container) return;
66
+
67
+ const mountOpts: MountOptions = {
68
+ theme: options?.theme,
69
+ darkMode: options?.darkMode,
70
+ onDataPointClick: options?.onDataPointClick,
71
+ responsive: options?.responsive,
72
+ };
73
+
74
+ const chart = createChart(container, spec, mountOpts);
75
+ chartRef.current = chart;
76
+ setLayout(chart.layout);
77
+ specRef.current = JSON.stringify(spec);
78
+
79
+ return () => {
80
+ chart.destroy();
81
+ chartRef.current = null;
82
+ setLayout(null);
83
+ };
84
+ // eslint-disable-next-line react-hooks/exhaustive-deps
85
+ }, [options?.theme, options?.darkMode, options?.onDataPointClick, options?.responsive]);
86
+
87
+ // Update on spec change
88
+ useEffect(() => {
89
+ const chart = chartRef.current;
90
+ if (!chart) return;
91
+
92
+ const specString = JSON.stringify(spec);
93
+ if (specString !== specRef.current) {
94
+ specRef.current = specString;
95
+ chart.update(spec);
96
+ setLayout(chart.layout);
97
+ }
98
+ }, [spec]);
99
+
100
+ return {
101
+ ref,
102
+ chart: chartRef.current,
103
+ layout,
104
+ };
105
+ }
106
+
107
+ // ---------------------------------------------------------------------------
108
+ // useDarkMode
109
+ // ---------------------------------------------------------------------------
110
+
111
+ /**
112
+ * Resolve a DarkMode preference to a boolean.
113
+ *
114
+ * - "force" -> true
115
+ * - "off" -> false
116
+ * - "auto" -> matches system preference (reactive to changes)
117
+ *
118
+ * @param mode - The dark mode preference.
119
+ * @returns Whether dark mode is active.
120
+ */
121
+ export function useDarkMode(mode?: DarkMode): boolean {
122
+ const [isDark, setIsDark] = useState(() => resolveInitial(mode));
123
+
124
+ useEffect(() => {
125
+ if (mode !== 'auto') {
126
+ setIsDark(mode === 'force');
127
+ return;
128
+ }
129
+
130
+ if (typeof window === 'undefined' || !window.matchMedia) {
131
+ setIsDark(false);
132
+ return;
133
+ }
134
+
135
+ const mq = window.matchMedia('(prefers-color-scheme: dark)');
136
+ setIsDark(mq.matches);
137
+
138
+ const handler = (e: MediaQueryListEvent) => setIsDark(e.matches);
139
+ mq.addEventListener('change', handler);
140
+ return () => mq.removeEventListener('change', handler);
141
+ }, [mode]);
142
+
143
+ return isDark;
144
+ }
145
+
146
+ function resolveInitial(mode?: DarkMode): boolean {
147
+ if (mode === 'force') return true;
148
+ if (mode === 'off' || mode === undefined) return false;
149
+ // "auto"
150
+ if (typeof window !== 'undefined' && window.matchMedia) {
151
+ return window.matchMedia('(prefers-color-scheme: dark)').matches;
152
+ }
153
+ return false;
154
+ }