File size: 1,803 Bytes
60943f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useEffect, useRef, useState } from "react";
import PyodideWorker from "./pyodide.worker.ts?worker";
import type { PlotData, Settings, WorkerMessage } from "./types.ts";


export default function usePyodide(initialSettings: Settings) {
  const [plotData, setPlotData] = useState<PlotData>({});
  const [isLoading, setIsLoading] = useState<boolean>(true);
  const workerRef = useRef<Worker | null>(null);

  function sendInit(settings: Settings) {
    if (workerRef.current) {
      workerRef.current.postMessage({ type: "INIT", settings });
    }
  }

  function sendNextStep() {
    if (workerRef.current) {
      workerRef.current.postMessage({ type: "NEXT_STEP" });
    }
  }

  function sendPrevStep() {
    if (workerRef.current) {
      workerRef.current.postMessage({ type: "PREV_STEP" });
    }
  }

  function sendReset() {
    if (workerRef.current) {
      workerRef.current.postMessage({ type: "RESET" });
    }
  }

  useEffect(() => {
    const worker = new PyodideWorker();
    workerRef.current = worker;

    worker.onmessage = (event) => {
      const message = event.data as WorkerMessage;
      if (message.type === "READY") {
        console.log("Pyodide is ready");
        setIsLoading(false);
        sendInit(initialSettings);
      } else if (message.type === "RESULT") {
        // todo data validation / type
        setPlotData((prevData) => ({
          functionValues: message.data.functionValues || prevData.functionValues,
          trajectoryValues: message.data.trajectoryValues || prevData.trajectoryValues,
        }))
      }
    };

    return () => {
      worker.terminate();
    };

  }, []);

  return {
    isLoading,
    plotData,
    sendInit: sendInit,
    sendReset: sendReset,
    sendNextStep: sendNextStep,
    sendPrevStep: sendPrevStep,
  }
}