-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuseDataStream.ts
More file actions
87 lines (71 loc) · 2.5 KB
/
Copy pathuseDataStream.ts
File metadata and controls
87 lines (71 loc) · 2.5 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
import { useState, useCallback, useEffect, useRef } from 'react';
import { DataPoint } from '@/types';
type DataStreamStatus = 'idle' | 'processing';
export function useDataStream() {
const [data, setData] = useState<DataPoint[]>([]);
const [status, setStatus] = useState<DataStreamStatus>('idle');
const [progress, setProgress] = useState(0);
const [error, setError] = useState<string | null>(null);
const workerRef = useRef<Worker | null>(null);
const pointsCollectionRef = useRef<DataPoint[]>([]);
useEffect(() => {
return () => {
if (workerRef.current) {
workerRef.current.terminate();
workerRef.current = null;
}
};
}, []);
const processFile = useCallback(async (file: File) => {
setStatus('processing');
setError(null);
setProgress(0);
setData([]);
pointsCollectionRef.current = [];
try {
if (workerRef.current) {
workerRef.current.terminate();
}
workerRef.current = new Worker(
new URL('@/workers/csvParser.worker.ts', import.meta.url).href,
);
workerRef.current.onmessage = (event) => {
const { action } = event.data;
if (action === 'progress') {
const { percentComplete } = event.data;
setProgress(percentComplete);
} else if (action === 'result') {
const { points } = event.data;
if (points && points.length > 0) {
pointsCollectionRef.current.push(...points);
}
} else if (action === 'complete') {
const { totalPoints } = event.data;
if (pointsCollectionRef.current.length !== totalPoints) {
console.warn(
`Worker reported ${totalPoints} points, but ${pointsCollectionRef.current.length} were collected.`,
);
}
pointsCollectionRef.current.sort((a, b) => a.x - b.x);
setData([...pointsCollectionRef.current]);
setStatus('idle');
}
};
workerRef.current.onerror = (e) => {
setError(`Worker error: ${e.message}`);
setStatus('idle');
};
const arrayBuffer = await file.arrayBuffer();
workerRef.current.postMessage({
action: 'parse',
file: arrayBuffer,
});
} catch (err) {
const message = err instanceof Error ? err.message : String(err);
setError(`Error processing file: ${message}`);
setStatus('idle');
}
}, []);
const isLoading = status === 'processing';
return { data, isLoading, progress, error, processFile };
}