import { useState, useEffect, useCallback } from 'react';
export function useScirs2(wasmUrl) {
const [wasm, setWasm] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
let cancelled = false;
async function load() {
try {
const mod = await import(wasmUrl);
if (typeof mod.default === 'function') {
await mod.default();
}
if (!cancelled) {
setWasm(mod);
setIsLoading(false);
}
} catch (err) {
if (!cancelled) {
setError(err instanceof Error ? err : new Error(String(err)));
setIsLoading(false);
}
}
}
load();
return () => {
cancelled = true;
};
}, [wasmUrl]);
return { wasm, isLoading, error };
}
export function useScirs2Compute(wasm, fnName) {
const [result, setResult] = useState(null);
const [isComputing, setIsComputing] = useState(false);
const compute = useCallback(
async (...args) => {
if (wasm === null || typeof wasm[fnName] !== 'function') return;
setIsComputing(true);
try {
const res = await Promise.resolve(wasm[fnName](...args));
setResult(res);
} catch (_err) {
throw _err;
} finally {
setIsComputing(false);
}
},
[wasm, fnName],
);
return [result, compute, isComputing];
}
export function useScirs2Array(wasm, size) {
const [array, setArray] = useState(null);
useEffect(() => {
if (wasm === null) {
setArray(null);
return;
}
let ptr = 0;
let buf;
if (typeof wasm.alloc_f64_array === 'function') {
ptr = wasm.alloc_f64_array(size);
if (typeof wasm.view_f64_array === 'function') {
buf = wasm.view_f64_array(ptr, size);
} else if (wasm.memory && wasm.memory.buffer) {
buf = new Float64Array(wasm.memory.buffer, ptr, size);
} else {
buf = new Float64Array(size);
ptr = 0;
}
} else {
buf = new Float64Array(size);
}
setArray({ size, data: buf, ptr });
return () => {
if (ptr !== 0 && typeof wasm.free_f64_array === 'function') {
wasm.free_f64_array(ptr, size);
}
setArray(null);
};
}, [wasm, size]);
return array;
}