Spaces:
Running
Running
| import { useCallback, useEffect, useRef, useState } from "react"; | |
| import * as Comlink from "comlink"; | |
| import type { PyodideBackend } from "./PyodideBackend.ts"; | |
| export default function usePyodideBackend() { | |
| const backendRef = useRef<Comlink.Remote<PyodideBackend> | null>(null); | |
| const workerRef = useRef<Worker | null>(null); | |
| const [isReady, setIsReady] = useState<boolean>(false); | |
| useEffect(() => { | |
| const worker = new Worker( | |
| new URL("./pyodide.worker.ts", import.meta.url), | |
| { type: "module" } | |
| ); | |
| const backend = Comlink.wrap<PyodideBackend>(worker); | |
| backendRef.current = backend; | |
| workerRef.current = worker; | |
| (async () => { | |
| try { | |
| await backend.init(); | |
| console.log("Pyodide intialized") | |
| setIsReady(true); | |
| } catch (error) { | |
| console.error("Failed to initialize Pyodide backend:", error); | |
| } | |
| })(); | |
| return () => { | |
| if (backendRef.current) { | |
| backendRef.current[Comlink.releaseProxy](); | |
| backendRef.current = null; | |
| } | |
| workerRef.current?.terminate(); | |
| workerRef.current = null; | |
| setIsReady(false); | |
| }; | |
| }, []); | |
| const getBackend = useCallback((): Comlink.Remote<PyodideBackend> => { | |
| if (!backendRef.current) { | |
| throw new Error("Pyodide backend is not ready"); | |
| } | |
| return backendRef.current; | |
| }, []); | |
| return { getBackend, backendReady: isReady }; | |
| } |