-
Notifications
You must be signed in to change notification settings - Fork 4
/
Equality.tsx
321 lines (295 loc) · 15.7 KB
/
Equality.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import React, {ChangeEvent, lazy, useEffect, useLayoutEffect, useRef, useState} from "react";
import {withRouter} from "react-router-dom";
import {Button, Col, Container, Input, InputGroup, Label, Row, UncontrolledTooltip} from "reactstrap";
import queryString from "query-string";
import {ifKeyIsEnter, isDefined, isStaff, siteSpecific, sanitiseInequalityState} from "../../services";
import katex from "katex";
import {TitleAndBreadcrumb} from "../elements/TitleAndBreadcrumb";
import {RouteComponentProps} from "react-router";
import {Inequality, makeInequality} from 'inequality';
import {parseBooleanExpression, parseMathsExpression, ParsingError} from 'inequality-grammar';
import {selectors, useAppSelector, useGetSegueEnvironmentQuery} from "../../state";
import {EditorMode, LogicSyntax} from "../elements/modals/inequality/constants";
import QuestionInputValidation from "../elements/inputs/QuestionInputValidation";
const InequalityModal = lazy(() => import("../elements/modals/inequality/InequalityModal"));
function isError(p: ParsingError | any[]): p is ParsingError {
return p.hasOwnProperty("error");
}
const equalityValidator = (input: string, editorMode: string) => {
const openBracketsCount = input.split('(').length - 1;
const closeBracketsCount = input.split(')').length - 1;
let regexStr = '';
const errors = [];
let parsedExpression: ParsingError | any[];
if (editorMode === 'maths') {
regexStr = "[^ 0-9A-Za-z()*+,-./<=>^_±²³¼½¾×÷=]+";
parsedExpression = parseMathsExpression(input);
} else {
regexStr = "[^ A-Za-z&|01()~¬∧∨⊻+.!=]+";
parsedExpression = parseBooleanExpression(input);
}
const badCharacters = new RegExp(regexStr);
if (isError(parsedExpression) && parsedExpression.error) {
errors.push(`Syntax error: unexpected token "${parsedExpression.error.token.value || ''}"`);
}
if (/\\[a-zA-Z()]|[{}]/.test(input)) {
errors.push('LaTeX syntax is not supported.');
}
if (/\|.+?\|/.test(input)) {
errors.push('Vertical bar syntax for absolute value is not supported; use abs() instead.');
}
if (badCharacters.test(input)) {
const usedBadChars: string[] = [];
for(let i = 0; i < input.length; i++) {
const char = input.charAt(i);
if (badCharacters.test(char)) {
if (!usedBadChars.includes(char)) {
usedBadChars.push(char);
}
}
}
errors.push('Some of the characters you are using are not allowed: ' + usedBadChars.join(" "));
}
if (openBracketsCount !== closeBracketsCount) {
errors.push('You are missing some ' + (closeBracketsCount > openBracketsCount ? 'opening' : 'closing') + ' brackets.');
}
if (/\.[0-9]/.test(input)) {
errors.push('Please convert decimal numbers to fractions.');
}
return errors;
}
const Equality = withRouter(({location}: RouteComponentProps<{}, {}, {board?: string; mode?: string; symbols?: string}>) => {
const queryParams = queryString.parse(location.search);
const [modalVisible, setModalVisible] = useState(false);
const initialEditorSymbols = useRef<string[]>([]);
const [currentAttempt, setCurrentAttempt] = useState<any>({type: 'formula', value: {}, pythonExpression: ''});
const [editorSyntax, setEditorSyntax] = useState<LogicSyntax>('logic');
const [textInput, setTextInput] = useState('');
const user = useAppSelector(selectors.user.orNull);
// Does this really need to be a state variable if it is immutable?
const [editorMode, setEditorMode] = useState<EditorMode>((queryParams.mode as EditorMode) || siteSpecific('maths', 'logic'));
const {data: segueEnvironment} = useGetSegueEnvironmentQuery();
/*** Text based input stuff */
const hiddenEditorRef = useRef<HTMLDivElement | null>(null);
const sketchRef = useRef<Inequality | null | undefined>();
const [inputState, setInputState] = useState(() => ({pythonExpression: '', userInput: '', valid: true}));
interface ChildrenMap {
children: {[key: string]: ChildrenMap};
}
function countChildren(root: ChildrenMap) {
let q = [root];
let count = 1;
while (q.length > 0) {
let e = q.shift();
if (!e) continue;
let c = Object.keys(e.children).length;
if (c > 0) {
count = count + c;
q = q.concat(Object.values(e.children));
}
}
return count;
}
function updateState(state: any) {
const newState = sanitiseInequalityState(state);
const pythonExpression = newState?.result?.python || "";
const previousPythonExpression = currentAttempt.value?.result?.python || "";
if (!previousPythonExpression || previousPythonExpression !== pythonExpression) {
setCurrentAttempt({type: 'formula', value: JSON.stringify(newState), pythonExpression});
}
initialEditorSymbols.current = state.symbols;
}
const updateEquation = (e: ChangeEvent<HTMLInputElement>) => {
_updateEquation(e.target.value);
}
const _updateEquation = (input: string) => {
// const pycode = e.target.value;
setTextInput(input);
setInputState({...inputState, pythonExpression: input, userInput: textInput});
let parsedExpression: any[] | ParsingError | undefined;
if (editorMode === 'maths') {
parsedExpression = parseMathsExpression(input);
} else if (editorMode === 'logic') {
parsedExpression = parseBooleanExpression(input);
}
if (!isDefined(parsedExpression) || !(isError(parsedExpression) || (parsedExpression.length === 0 && input !== ''))) {
if (input === '') {
const state = {result: {tex: "", python: "", mathml: ""}};
setCurrentAttempt({ type: 'formula', value: JSON.stringify(sanitiseInequalityState(state)), pythonExpression: ""});
initialEditorSymbols.current = [];
} else if (isDefined(parsedExpression) && parsedExpression.length === 1) {
// This and the next one are using pycode instead of textInput because React will update the state whenever it sees fit
// so textInput will almost certainly be out of sync with pycode which is the current content of the text box.
if (sketchRef.current) {
sketchRef.current.parseSubtreeObject(parsedExpression[0], true, true, input);
}
} else if (isDefined(parsedExpression)) {
if (sketchRef.current) {
const sizes = parsedExpression.map(countChildren);
const i = sizes.indexOf(Math.max.apply(null, sizes));
sketchRef.current.parseSubtreeObject(parsedExpression[i], true, true, input);
}
}
}
};
useEffect(() => {
if (sketchRef.current) {
sketchRef.current.logicSyntax = editorSyntax;
}
}, [editorSyntax]);
useLayoutEffect(() => {
const {sketch, p} = makeInequality(
hiddenEditorRef.current,
100,
0,
[],
{
textEntry: true,
fontItalicPath: '/assets/common/fonts/STIXGeneral-Italic.ttf',
fontRegularPath: '/assets/common/fonts/STIXGeneral-Regular.ttf',
}
);
if (!isDefined(sketch)) throw new Error("Unable to initialize Inequality.");
sketch.log = { initialState: [], actions: [] };
sketch.onNewEditorState = updateState;
sketch.onCloseMenus = () => undefined;
sketch.isUserPrivileged = () => true;
sketch.onNotifySymbolDrag = () => undefined;
sketch.isTrashActive = () => false;
sketchRef.current = sketch;
return () => {
if (sketchRef.current) {
sketchRef.current.onNewEditorState = () => null;
sketchRef.current.onCloseMenus = () => null;
sketchRef.current.isTrashActive = () => false;
sketchRef.current = null;
}
p.remove();
};
}, [hiddenEditorRef.current]);
/*** End of text based input stuff */
const availableSymbols = queryParams.symbols && (queryParams.symbols as string).split(',').map(s => s.trim());
let currentAttemptValue: any | undefined;
if (currentAttempt && currentAttempt.value) {
try {
currentAttemptValue = JSON.parse(currentAttempt.value);
} catch(e) {
currentAttemptValue = { result: { tex: '' } };
}
}
const closeModal = () => {
document.body.style.overflow = "auto";
setModalVisible(false);
};
const previewText = currentAttemptValue && currentAttemptValue.result && currentAttemptValue.result.tex;
return <div>
<Container>
<Row>
<Col>
<TitleAndBreadcrumb currentPageTitle="Equation editor demo page" />
</Col>
</Row>
<Row>
<Col md={{size: 2}} className="py-4 syntax-picker mode-picker">
<div>
<Label for="inequality-mode-select">Editor mode:</Label>
<Input type="select" name="mode" id="inequality-mode-select" value={editorMode as string} onChange={(e: React.ChangeEvent<HTMLInputElement>) => setEditorMode(e.target.value as EditorMode)}>
<option value="maths">Maths</option>
<option value="chemistry">Chemistry</option>
<option value="logic">Boolean Logic</option>
</Input>
</div>
{(editorMode === 'logic') && <div className="mt-4">
<Label for="inequality-syntax-select">Boolean Logic Syntax</Label>
<Input type="select" name="syntax" id="inequality-syntax-select" value={editorSyntax} onChange={(e: React.ChangeEvent<HTMLInputElement>) => { setEditorSyntax(e.target.value as LogicSyntax); _updateEquation(textInput); } }>
<option value="logic">Boolean Logic</option>
<option value="binary">Digital Electronics</option>
</Input>
</div>}
</Col>
<Col md={{size: 8}} className="py-4 question-panel">
{(editorMode === 'maths' || (isStaff(user) && editorMode === 'logic')) && <div className="eqn-editor-input mt-4">
<div ref={hiddenEditorRef} className="equation-editor-text-entry" style={{height: 0, overflow: "hidden", visibility: "hidden"}} />
<InputGroup className="my-2">
<Input className="py-4" type="text" onChange={updateEquation} value={textInput}
placeholder="Type your expression here"/>
<>
{siteSpecific(
<Button type="button" className="eqn-editor-help pt-2" id="inequality-help" size="sm" tag="a" href="/solving_problems#symbolic_text">?</Button>,
<span id={"inequality-help"} className="icon-help-q my-auto"/>
)}
{editorMode === 'maths' && <UncontrolledTooltip placement="top" autohide={false} target='inequality-help'>
Here are some examples of expressions you can type:<br />
<br />
a*x^2 + b x + c<br />
(-b ± sqrt(b**2 - 4ac)) / (2a)<br />
1/2 mv**2<br />
log(x_a, 2) == log(x_a) / log(2)<br />
<br />
As you type, the box below will preview the result.
</UncontrolledTooltip>}
{editorMode === 'logic' && <UncontrolledTooltip placement="top" autohide={false} target='inequality-help'>
Here are some examples of expressions you can type:<br />
<br />
A AND (B XOR NOT C)<br />
A & (B ^ !C)<br />
T & ~(F + A)<br />
1 . ~(0 + A)<br />
As you type, the box below will preview the result.
</UncontrolledTooltip>}
</>
</InputGroup>
<QuestionInputValidation userInput={textInput} validator={(i: string) => equalityValidator(i, editorMode)} />
</div>}
<div className="equality-page">
<div
role="button" className={`eqn-editor-preview rounded ${!previewText ? 'empty' : ''} ${editorMode !== 'maths' ? 'mt-4' : ''}`} tabIndex={0}
onClick={() => setModalVisible(true)} onKeyDown={ifKeyIsEnter(() => setModalVisible(true))}
dangerouslySetInnerHTML={{ __html: previewText ? katex.renderToString(previewText) : `<small>${editorMode === 'maths' ? 'or c' : 'C'}lick here to enter a formula</small>` }}
/>
{modalVisible && <InequalityModal
close={closeModal}
onEditorStateChange={(state: any) => {
setCurrentAttempt({
type: 'logicFormula',
value: JSON.stringify(state),
pythonExpression: (state && state.result && state.result.python)||"",
symbols: [],
})
setTextInput(state?.result?.python || '');
initialEditorSymbols.current = state.symbols;
}}
availableSymbols={availableSymbols || []}
initialEditorSymbols={initialEditorSymbols.current}
editorMode={editorMode}
logicSyntax={editorSyntax}
/>}
</div>
</Col>
</Row>
{currentAttemptValue && currentAttemptValue.result && currentAttemptValue.result.tex && <Row>
<Col md={{size: 8, offset: 2}} className="py-4 inequality-results">
<h4>LaTeX</h4>
<pre>${currentAttemptValue?.result?.tex}$</pre>
{editorMode === 'chemistry' && <>
<h4>MhChem</h4>
<pre>{currentAttemptValue?.result?.mhchem}</pre>
</>}
{editorMode !== 'chemistry' && <>
<h4>Python</h4>
<pre>{currentAttemptValue?.result?.python}</pre>
<h4>MathML</h4>
<pre>{currentAttemptValue?.result?.mathml}</pre>
</>}
<h4>Available symbols</h4>
<pre>{currentAttemptValue?.result?.uniqueSymbols}</pre>
{(segueEnvironment === "DEV" || isStaff(user)) && <>
<h4>Inequality seed</h4>
<pre>{currentAttemptValue && currentAttemptValue.symbols && JSON.stringify(currentAttemptValue.symbols)}</pre>
</>}
</Col>
</Row>}
</Container>
</div>;
});
export default Equality;