File size: 1,009 Bytes
779968d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState, useRef, useEffect } from "react";
import WebSocketApi from "./websocket.ts";
import type { PlotData, Settings } from "./types.ts";

export default function useApi(url: string) {
  const api = useRef<WebSocketApi>(new WebSocketApi());
  const [plotData, setPlotData] = useState<PlotData>({});

  api.current.onMessage(
    (data: unknown) => {
      // todo data validation / type
      setPlotData((prevData) => ({ ...prevData, ...(data as PlotData) }));
    }
  )

  useEffect(() => {
    api.current.connect(url);
    return () => api.current.disconnect();
  }, [url]);

  return {
    plotData,
    sendInit: (settings: Settings) => api.current.sendInit(settings),
    sendReset: () => api.current.sendReset(),
    sendNextStep: () => api.current.sendNextStep(),
    sendPrevStep: () => api.current.sendPrevStep(),
    sendPlay: () => api.current.sendPlay(),
    sendPause: () => api.current.sendPause(),
    onReconnect: (handler: () => void) => api.current.onReconnect(handler),
  };
}