/
Calculator.jsx
109 lines (100 loc) · 3 KB
/
Calculator.jsx
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
import React, { useReducer, useEffect, useRef } from "react";
import { useWindowContext } from "../WindowContext";
import DilationForm from "./DilationForm";
import Result from "./Result";
import WasmLoader from "../WasmLoader";
const initialState = {
isLoading: false,
dilation: null,
validationError: false,
runtimeError: false,
ready: false,
};
function reducer(state, action) {
switch (action.type) {
case "WASM_INITIALIZED":
return { ...state, ready: true };
case "CALCULATE_START":
return {
...state,
isLoading: true,
dilation: null,
runtimeError: false,
validationError: false,
};
case "CALCULATE_OK":
return {
...state,
isLoading: false,
dilation: action.payload,
error: null,
};
case "VALIDATION_ERROR":
return {
...state,
isLoading: false,
dilation: null,
runtimeError: false,
validationError: true,
};
case "CALCULATE_ERROR":
return {
...state,
ready: false,
isLoading: false,
dilation: null,
runtimeError: true,
validationError: false,
};
default:
return state;
}
}
const createOnSubmitHandler = (unitaryNDilationAsync, dispatch) => async (
matrix,
degree
) => {
try {
dispatch({ type: "CALCULATE_START" });
const { error, value } = await unitaryNDilationAsync(matrix, degree);
if (!error) {
dispatch({ type: "CALCULATE_OK", payload: value });
} else {
dispatch({ type: "VALIDATION_ERROR", payload: error });
}
} catch (e) {
dispatch({ type: "CALCULATE_ERROR", payload: e });
}
};
const Calculator = () => {
const [
{ isLoading, dilation, validationError, runtimeError },
dispatch,
] = useReducer(reducer, initialState);
const onSubmitHandler = useRef(null);
const window = useWindowContext();
useEffect(() => {
if (!onSubmitHandler.current) {
const unitaryNDilationAsync = (matrix, degree) =>
Promise.resolve(window.UnitaryNDilation(matrix, degree));
onSubmitHandler.current = createOnSubmitHandler(
unitaryNDilationAsync,
dispatch
);
dispatch({ type: "WASM_INITIALIZED" });
}
}, [window && window.UnitaryNDilation]);
return (
<div>
<WasmLoader />
<DilationForm onSubmit={onSubmitHandler.current} />
<Result
isLoading={isLoading}
validationError={validationError}
runtimeError={runtimeError}
dilation={dilation}
/>
</div>
);
};
export default Calculator;