-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathFormula.tsx
86 lines (82 loc) · 2.37 KB
/
Formula.tsx
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
import { highlight, languages } from 'prismjs';
import * as React from 'react';
import Editor from 'react-simple-code-editor';
import styled from 'styled-components';
import { Formula } from '../lib/graphtoy/types';
import { useStore } from '../store';
import VisualizerOptions from './VisualizerOptions';
const Wrapper = styled.div`
width: 100%;
display: grid;
grid-template-columns: 80px auto 150px;
padding-bottom: 4px;
`;
const FormulaInputField = styled(Editor)<{ error?: string }>`
width: 100%;
border: ${({ error }) => (error ? 'red' : 'transparent')} 2px solid;
`;
interface Props {
formula: Formula;
}
const FormulaComponent: React.FC<Props> = ({
formula: { id, value, visualizer, enabled },
}) => {
const [error, setError] = React.useState('');
const [r, g, b] = visualizer;
const { setFormulaValue, formulaColors, toggleFormulaVisibility, grapher } =
useStore();
// Handle our Errors here
React.useEffect(() => {
grapher.events.on('formulaError', (err) => {
if (err.formula.id === id) {
if (err.error.startsWith('Unexpected token ')) {
setError('Failed to parse expression.');
} else {
setError(err.error);
}
}
});
grapher.events.on('formulaCompiled', (_id) => {
if (_id === id) {
setError('');
}
});
}, [grapher, id]);
return (
<Wrapper>
<div
id={`f${id}`}
onClick={() => {
toggleFormulaVisibility(id);
}}
style={{
cursor: 'pointer',
color: enabled ? formulaColors[id] : '#808080',
}}
>
f<sub>{id}</sub>(x,t) =
</div>
<div style={{ width: '100%' }}>
<label className={'sr-only'} htmlFor={`f${id}-input`}>
Formula input field for formula {id}
</label>
<FormulaInputField
textareaId={`f${id}-input`}
value={value}
error={error ? 'false' : undefined}
onValueChange={(code) => setFormulaValue(id, code)}
highlight={(code) => highlight(code, languages.js, 'javascript')}
padding={10}
className="userInput"
style={{
fontFamily: '"Fira code", "Fira Mono", monospace',
fontSize: 12,
}}
/>
{error}
</div>
<VisualizerOptions id={id} r={r} g={g} b={b} />
</Wrapper>
);
};
export default FormulaComponent;