Repository navigation
Expand file tree
/
Copy pathChartBuilderWrapper.tsx
More file actions
executable file
·161 lines (150 loc) · 5.29 KB
/
Copy pathChartBuilderWrapper.tsx
File metadata and controls
executable file
·161 lines (150 loc) · 5.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
// External dependencies
import { ErrorBoundary } from 'react-error-boundary';
import { useMemo } from 'react';
// Internal dependencies
import ChartBuilder from './ChartBuilder';
import {
DataProvider,
selectPlotRows,
useSeriesMask,
type BaseConfig,
type ChartLayoutType,
type LegendItemsController,
type TableData,
} from '@prc/charting-utilities';
import useChartStore, { ChartStoreSlice, toggleHiddenSeries } from '../store/useChartStore';
type WrapperProps = {
data?: any;
config?: BaseConfig;
tableData?: TableData;
fallbackImg?: string;
wpEditorFunctions?: any;
/**
* Editor-only animation preview flag (PRC-17). Forwarded into
* `DataContext` so `useAnimationConfig` lifts its editor-forced
* `immediate` for one entrance when the author clicks "Preview
* animation". The frontend (`view.js`) never passes this.
*/
animationPreview?: boolean;
/**
* When provided, the wrapper subscribes to `state.charts[chartId]` in
* the named Interactivity store and overrides the `data`, `config`,
* and `tableData` props with whatever the store currently has. The
* props remain the source of truth on first mount and when the hook
* returns undefined (editor build, store slice missing, etc.).
*/
interactivityNamespace?: string;
chartId?: string;
};
/**
* Test-only render-count spy (PRC-17 slice 4). Completely inert in production:
* it does nothing unless a test harness has first installed a counter map at
* `window.__PRC_CHART_RENDER_COUNTS__`. The robustness gate uses it to assert
* that an atomic `actions.setChart()` collapses a multi-field update (e.g. new
* data + new config introducing a category) into a SINGLE wrapper render — a
* torn render that self-heals on the next pass is invisible to final-DOM
* assertions, so render count is the only reliable signal of atomicity.
*
* @param chartId Chart id whose renders to tally.
*/
function recordRender(chartId?: string) {
if (typeof window === 'undefined' || !chartId) {
return;
}
const counts = (window as any).__PRC_CHART_RENDER_COUNTS__;
if (!counts) {
return;
}
counts[chartId] = (counts[chartId] || 0) + 1;
}
function ErrorFallback(props: any) {
const { error, fallbackImg } = props;
// eslint-disable-next-line no-console
console.log({ 'Error:': error.message });
return (
<>
{fallbackImg && <img src={fallbackImg} alt="fallback" style={{ width: '100%', height: 'auto' }} />}
{!fallbackImg && (
<div role="alert">
<p>This chart is currently unavailable. Please try again later</p>
</div>
)}
</>
);
}
const ChartBuilderWrapper = ({
data,
config,
tableData,
fallbackImg,
wpEditorFunctions,
animationPreview,
interactivityNamespace,
chartId,
}: WrapperProps) => {
// useChartStore is a no-op stub in the editor build (webpack alias),
// so this hook call is safe to run unconditionally. In the Preact view
// bundle it subscribes to the live signal proxy and re-renders the
// wrapper whenever any leaf of `state.charts[chartId]` mutates.
const slice = useChartStore<ChartStoreSlice>(interactivityNamespace, chartId);
// Tally this render for the atomicity gate (no-op in production).
recordRender(chartId);
// Slice always wins when present. The props are the seed values written
// by `view.js`'s renderChart action before mount, which is also the
// value the slice carries on first read, so the slice/prop selection is
// identity-preserving until an external caller writes to the store.
const resolvedData = slice?.data !== undefined ? slice.data : data;
const resolvedConfig = slice?.config !== undefined ? (slice.config as BaseConfig) : config;
const resolvedTableData = slice?.tableData !== undefined ? (slice.tableData as TableData) : tableData;
const seriesMask = useSeriesMask({
chartId,
chartType: (resolvedConfig?.layout?.type ?? 'bar') as ChartLayoutType,
clickToHide: resolvedConfig?.legend?.clickToHide,
clickToHideGroups: resolvedConfig?.legend?.clickToHideGroups,
isEditor: wpEditorFunctions !== undefined,
hiddenSeries: slice ? (slice.hiddenSeries ?? []) : undefined,
onToggle:
interactivityNamespace && chartId
? (key: string) => {
toggleHiddenSeries(interactivityNamespace, chartId, key);
}
: undefined,
});
const legendItems: LegendItemsController | undefined = useMemo(() => {
if (!seriesMask.armed) {
return undefined;
}
return {
onClick: (key: string) => {
seriesMask.toggle(key);
},
getItemOpacity: (key: string) => seriesMask.legendOpacity(key),
};
}, [seriesMask]);
// Config is required to render any chart — caller (view.js's renderChart
// or editor-mounted ChartBuilder) must always provide one via either prop
// or store seed. If neither is present, surface the fallback so we don't
// crash mid-render.
if (!resolvedConfig) {
return <ErrorFallback error={new Error('ChartBuilderWrapper: missing config')} fallbackImg={fallbackImg} />;
}
return (
// @ts-ignore
<DataProvider
value={{
data: selectPlotRows(resolvedData, resolvedConfig.dataRender),
config: resolvedConfig,
tableData: resolvedTableData,
wpEditorFunctions,
animationPreview,
seriesMask,
legendItems,
}}
>
<ErrorBoundary FallbackComponent={(props) => <ErrorFallback {...props} fallbackImg={fallbackImg} />}>
<ChartBuilder />
</ErrorBoundary>
</DataProvider>
);
};
export default ChartBuilderWrapper;