Skip to content

Commit 41965e7

Browse files
committed
handle typed array input conversion to plain array for json stringify
1 parent 94c48f3 commit 41965e7

File tree

1 file changed

+38
-2
lines changed

1 file changed

+38
-2
lines changed

src/components/ChartUPlot.tsx

Lines changed: 38 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,36 @@ const stringify = (obj: any): string => {
2727
);
2828
};
2929

30+
type AnyTypedArray =
31+
| Int8Array
32+
| Uint8Array
33+
| Uint8ClampedArray
34+
| Int16Array
35+
| Uint16Array
36+
| Int32Array
37+
| Uint32Array
38+
| Float32Array
39+
| Float64Array
40+
| BigInt64Array
41+
| BigUint64Array;
42+
43+
function isTypedArray(x: unknown): x is AnyTypedArray {
44+
return ArrayBuffer.isView(x) && !(x instanceof DataView);
45+
}
46+
47+
/**
48+
* Converts typed arrays to plain arrays for JSON serialization.
49+
* This is necessary because typed arrays cannot be directly serialized to JSON.
50+
*
51+
* @param {Array} arrays - Array of arrays, which may include typed arrays.
52+
* @returns {Array} - A new array with all typed arrays converted to plain arrays.
53+
*/
54+
function toPlainArrays(arrays: any[]): any[] {
55+
return arrays.map((arr) =>
56+
isTypedArray(arr) ? Array.from(arr as ArrayLike<number | bigint>) : arr,
57+
);
58+
}
59+
3060
/**
3161
* Slices a multi-series dataset to only the window where the given axis lies within [min, max].
3262
*
@@ -285,9 +315,15 @@ const ChartUPlot = forwardRef<any, UPlotProps>(
285315
}
286316

287317
webref.current.injectJavaScript(`
318+
var item = ${JSON.stringify(toPlainArrays(newData))};
319+
288320
if (window._chart) {
289-
console.debug('Setting new data for uPlot chart');
290-
window._data = ${JSON.stringify(newData)};
321+
window._data = item;
322+
var size = [
323+
item.length,
324+
item[0].length,
325+
item[1].length,
326+
]
291327
window._chart.setData(window._data);
292328
} else {
293329
console.error('Chart not initialized');

0 commit comments

Comments
 (0)