@khanacademy/math-input 17.0.4 → 17.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/dist/es/index.js +1 -1
  2. package/dist/index.js +1 -1
  3. package/package.json +5 -2
  4. package/.eslintrc.js +0 -18
  5. package/CHANGELOG.md +0 -660
  6. package/less/main.less +0 -2
  7. package/less/overrides.less +0 -122
  8. package/src/components/__tests__/integration.test.tsx +0 -300
  9. package/src/components/aphrodite-css-transition-group/index.tsx +0 -78
  10. package/src/components/aphrodite-css-transition-group/transition-child.tsx +0 -192
  11. package/src/components/aphrodite-css-transition-group/types.ts +0 -20
  12. package/src/components/aphrodite-css-transition-group/util.ts +0 -97
  13. package/src/components/input/__tests__/context-tracking.test.ts +0 -176
  14. package/src/components/input/__tests__/mathquill-helpers.test.ts +0 -105
  15. package/src/components/input/__tests__/mathquill.test.ts +0 -747
  16. package/src/components/input/__tests__/test-math-wrapper.ts +0 -29
  17. package/src/components/input/cursor-contexts.ts +0 -37
  18. package/src/components/input/cursor-handle.tsx +0 -137
  19. package/src/components/input/cursor-styles.ts +0 -10
  20. package/src/components/input/drag-listener.ts +0 -79
  21. package/src/components/input/math-input.tsx +0 -1036
  22. package/src/components/input/math-wrapper.ts +0 -189
  23. package/src/components/input/mathquill-helpers.ts +0 -262
  24. package/src/components/input/mathquill-instance.ts +0 -106
  25. package/src/components/input/mathquill-types.ts +0 -32
  26. package/src/components/input/scroll-into-view.ts +0 -65
  27. package/src/components/key-handlers/__tests__/handle-jump-out.test.ts +0 -94
  28. package/src/components/key-handlers/handle-arrow.ts +0 -70
  29. package/src/components/key-handlers/handle-backspace.ts +0 -277
  30. package/src/components/key-handlers/handle-exponent.ts +0 -53
  31. package/src/components/key-handlers/handle-jump-out.ts +0 -107
  32. package/src/components/key-handlers/key-translator.ts +0 -222
  33. package/src/components/keypad/__tests__/__snapshots__/keypad.test.tsx.snap +0 -1913
  34. package/src/components/keypad/__tests__/__snapshots__/mobile-keypad.test.tsx.snap +0 -600
  35. package/src/components/keypad/__tests__/keypad-button.test.tsx +0 -84
  36. package/src/components/keypad/__tests__/keypad-v2-mathquill.test.tsx +0 -304
  37. package/src/components/keypad/__tests__/keypad-v2.cypress.ts +0 -16
  38. package/src/components/keypad/__tests__/keypad.test.tsx +0 -321
  39. package/src/components/keypad/__tests__/mobile-keypad.test.tsx +0 -115
  40. package/src/components/keypad/__tests__/test-data-tabs.ts +0 -21
  41. package/src/components/keypad/button-assets.tsx +0 -1880
  42. package/src/components/keypad/index.tsx +0 -2
  43. package/src/components/keypad/keypad-button.stories.tsx +0 -81
  44. package/src/components/keypad/keypad-button.tsx +0 -124
  45. package/src/components/keypad/keypad-mathquill.stories.tsx +0 -109
  46. package/src/components/keypad/keypad-pages/extras-page.tsx +0 -35
  47. package/src/components/keypad/keypad-pages/fractions-page.tsx +0 -125
  48. package/src/components/keypad/keypad-pages/geometry-page.tsx +0 -34
  49. package/src/components/keypad/keypad-pages/keypad-pages.stories.tsx +0 -37
  50. package/src/components/keypad/keypad-pages/numbers-page.tsx +0 -94
  51. package/src/components/keypad/keypad-pages/operators-page.tsx +0 -117
  52. package/src/components/keypad/keypad.tsx +0 -233
  53. package/src/components/keypad/mobile-keypad-internals.tsx +0 -240
  54. package/src/components/keypad/mobile-keypad.tsx +0 -24
  55. package/src/components/keypad/navigation-button.tsx +0 -127
  56. package/src/components/keypad/navigation-pad.stories.tsx +0 -26
  57. package/src/components/keypad/navigation-pad.tsx +0 -67
  58. package/src/components/keypad/shared-keys.tsx +0 -109
  59. package/src/components/keypad/utils.ts +0 -34
  60. package/src/components/keypad-context.tsx +0 -70
  61. package/src/components/prop-types.ts +0 -16
  62. package/src/components/tabbar/__tests__/tabbar.test.tsx +0 -105
  63. package/src/components/tabbar/icons.tsx +0 -122
  64. package/src/components/tabbar/index.ts +0 -1
  65. package/src/components/tabbar/item.tsx +0 -146
  66. package/src/components/tabbar/tabbar.stories.tsx +0 -83
  67. package/src/components/tabbar/tabbar.tsx +0 -65
  68. package/src/data/key-configs.ts +0 -770
  69. package/src/data/keys.ts +0 -123
  70. package/src/enums.ts +0 -27
  71. package/src/fake-react-native-web/index.ts +0 -11
  72. package/src/fake-react-native-web/text.tsx +0 -55
  73. package/src/fake-react-native-web/view.tsx +0 -91
  74. package/src/full-keypad.stories.tsx +0 -142
  75. package/src/full-mobile-input.stories.tsx +0 -115
  76. package/src/index.ts +0 -52
  77. package/src/types.ts +0 -70
  78. package/src/utils.test.ts +0 -33
  79. package/src/utils.ts +0 -61
  80. package/src/version.ts +0 -10
  81. package/tsconfig-build.json +0 -11
  82. package/tsconfig-build.tsbuildinfo +0 -1
@@ -1,1036 +0,0 @@
1
- /* eslint-disable @khanacademy/ts-no-error-suppressions */
2
- import Color from "@khanacademy/wonder-blocks-color";
3
- import * as i18n from "@khanacademy/wonder-blocks-i18n";
4
- import {entries} from "@khanacademy/wonder-stuff-core";
5
- import {StyleSheet} from "aphrodite";
6
- import * as React from "react";
7
- import ReactDOM from "react-dom";
8
-
9
- import {View} from "../../fake-react-native-web/index";
10
- import {KeypadContext} from "../keypad-context";
11
-
12
- import CursorHandle from "./cursor-handle";
13
- import {
14
- cursorHandleRadiusPx,
15
- cursorHandleDistanceMultiplier,
16
- } from "./cursor-styles";
17
- import DragListener from "./drag-listener";
18
- import MathWrapper from "./math-wrapper";
19
- import {scrollIntoView} from "./scroll-into-view";
20
-
21
- import type {Cursor, KeypadAPI} from "../../types";
22
-
23
- const constrainingFrictionFactor = 0.8;
24
-
25
- type Props = {
26
- keypadElement?: KeypadAPI;
27
- onBlur: () => void;
28
- onChange: (value: string, callback: any) => void;
29
- onFocus: () => void;
30
- style: any;
31
- value: string;
32
- };
33
-
34
- type DefaultProps = {
35
- style: Props["style"];
36
- value: Props["value"];
37
- };
38
-
39
- type HandleState = {
40
- animateIntoPosition?: boolean;
41
- visible: boolean;
42
- x?: number;
43
- y?: number;
44
- };
45
-
46
- type State = {
47
- focused: boolean;
48
- handle: HandleState;
49
- };
50
-
51
- // eslint-disable-next-line react/no-unsafe
52
- class MathInput extends React.Component<Props, State> {
53
- didTouchOutside: boolean | null | undefined;
54
- didScroll: boolean | null | undefined;
55
- mathField: any;
56
- // @ts-expect-error - TS2564 - Property 'recordTouchStartOutside' has no initializer and is not definitely assigned in the constructor.
57
- recordTouchStartOutside: (arg1: any) => void;
58
- // @ts-expect-error - TS2564 - Property 'blurOnTouchEndOutside' has no initializer and is not definitely assigned in the constructor.
59
- blurOnTouchEndOutside: (arg1: any) => void;
60
- // @ts-expect-error - TS2564 - Property 'blurOnClickOutside' has no initializer and is not definitely assigned in the constructor.
61
- blurOnClickOutside: (arg1: any) => void;
62
- dragListener: any;
63
- inputRef: HTMLDivElement | null | undefined;
64
- _isMounted: boolean | null | undefined;
65
- _mathContainer: any;
66
- // @ts-expect-error - TS2564 - Property '_container' has no initializer and is not definitely assigned in the constructor.
67
- _container: HTMLDivElement;
68
- _root: any;
69
- // @ts-expect-error - TS2564 - Property '_containerBounds' has no initializer and is not definitely assigned in the constructor.
70
- _containerBounds: ClientRect;
71
-
72
- static defaultProps: DefaultProps = {
73
- style: {},
74
- value: "",
75
- };
76
-
77
- state: State = {
78
- focused: false,
79
- handle: {
80
- animateIntoPosition: false,
81
- visible: false,
82
- x: 0,
83
- y: 0,
84
- },
85
- };
86
-
87
- componentDidMount() {
88
- this._isMounted = true;
89
-
90
- this.mathField = new MathWrapper(this._mathContainer, {
91
- onCursorMove: (cursor: Cursor) => {
92
- // TODO(charlie): It's not great that there is so much coupling
93
- // between this keypad and the input behavior. We should wrap
94
- // this `MathInput` component in an intermediary component
95
- // that translates accesses on the keypad into vanilla props,
96
- // to make this input keypad-agnostic.
97
- this.props.keypadElement &&
98
- this.props.keypadElement.setCursor(cursor);
99
- },
100
- });
101
-
102
- this.mathField.setContent(this.props.value);
103
-
104
- this._updateInputPadding();
105
-
106
- this._container = ReactDOM.findDOMNode(this) as HTMLDivElement;
107
- this._root = this._container.querySelector(".mq-root-block");
108
- this._root.addEventListener("scroll", this._handleScroll);
109
-
110
- const isWithinKeypadBounds = (x: number, y: number): boolean => {
111
- const bounds = this._getKeypadBounds();
112
-
113
- // If there are no bounds, then the keypad is not mounted, so we
114
- // assume that the event is not within the keypad bounds.
115
- if (!bounds) {
116
- return false;
117
- }
118
-
119
- return (
120
- (bounds.left <= x &&
121
- bounds.right >= x &&
122
- bounds.top <= y &&
123
- bounds.bottom >= y) ||
124
- bounds.bottom < y
125
- );
126
- };
127
-
128
- // Record the initial scroll displacement on touch start. This allows
129
- // us to detect whether a touch event was a scroll and only blur the
130
- // input on non-scrolls--blurring the input on scroll makes for a
131
- // frustrating user experience.
132
- this.recordTouchStartOutside = (evt: any) => {
133
- if (this.state.focused) {
134
- // Only blur if the touch is both outside of the input, and
135
- // above or to the left or right of the keypad (if it has been
136
- // provided). The reasoning for not blurring when touches occur
137
- // below the keypad is that the keypad may be anchored above
138
- // the 'Check answer' bottom bar, in which case, we don't want
139
- // to dismiss the keypad on check.
140
- // TODO(charlie): Inject this logic.
141
- if (!this._container.contains(evt.target)) {
142
- let touchDidStartInOrBelowKeypad = false;
143
- if (
144
- this.props.keypadElement &&
145
- this.props.keypadElement.getDOMNode()
146
- ) {
147
- for (let i = 0; i < evt.changedTouches.length; i++) {
148
- const [x, y] = [
149
- evt.changedTouches[i].clientX,
150
- evt.changedTouches[i].clientY,
151
- ];
152
- if (isWithinKeypadBounds(x, y)) {
153
- touchDidStartInOrBelowKeypad = true;
154
- break;
155
- }
156
- }
157
- }
158
-
159
- if (!touchDidStartInOrBelowKeypad) {
160
- this.didTouchOutside = true;
161
-
162
- if (this.dragListener) {
163
- this.dragListener.detach();
164
- }
165
-
166
- this.dragListener = new DragListener(() => {
167
- this.didScroll = true;
168
- this.dragListener.detach();
169
- }, evt);
170
- this.dragListener.attach();
171
- }
172
- }
173
- }
174
- };
175
-
176
- this.blurOnTouchEndOutside = (evt) => {
177
- // If the user didn't scroll, blur the input.
178
- // TODO(charlie): Verify that the touch that ended actually started
179
- // outside the keypad. Right now, you can touch down on the keypad,
180
- // touch elsewhere, release the finger on the keypad, and trigger a
181
- // dismissal. This code needs to be generalized to handle
182
- // multi-touch.
183
- if (this.state.focused && this.didTouchOutside && !this.didScroll) {
184
- this.blur();
185
- }
186
-
187
- this.didTouchOutside = false;
188
- this.didScroll = false;
189
-
190
- if (this.dragListener) {
191
- this.dragListener.detach();
192
- }
193
- };
194
-
195
- // We want to allow the user to blur the input by clicking outside of it
196
- // when using ChromeOS third-party browsers that use mobile user agents,
197
- // but don't actually simulate touch events.
198
- this.blurOnClickOutside = (evt: any) => {
199
- if (this.state.focused) {
200
- if (!this._container.contains(evt.target)) {
201
- if (
202
- this.props.keypadElement &&
203
- this.props.keypadElement.getDOMNode()
204
- ) {
205
- const [x, y] = [evt.clientX, evt.clientY];
206
-
207
- // We only want to blur if the click is above the keypad,
208
- // to the left of the keypad, or to the right of the keypad.
209
- // The reasoning for not blurring for any clicks below the keypad is
210
- // that the keypad may be anchored above the 'Check answer' bottom bar,
211
- // in which case we don't want to dismiss the keypad on check.
212
- if (!isWithinKeypadBounds(x, y)) {
213
- this.blur();
214
- }
215
- }
216
- }
217
- }
218
- };
219
-
220
- window.addEventListener("touchstart", this.recordTouchStartOutside);
221
- window.addEventListener("touchend", this.blurOnTouchEndOutside);
222
- window.addEventListener("touchcancel", this.blurOnTouchEndOutside);
223
- window.addEventListener("click", this.blurOnClickOutside);
224
- }
225
-
226
- componentDidUpdate(prevProps: Props, prevState: State) {
227
- if (this.mathField.getContent() !== this.props.value) {
228
- this.mathField.setContent(this.props.value);
229
- }
230
-
231
- if (prevState.focused !== this.state.focused) {
232
- this._updateInputPadding();
233
- }
234
- }
235
-
236
- componentWillUnmount() {
237
- this._isMounted = false;
238
-
239
- window.removeEventListener("touchstart", this.recordTouchStartOutside);
240
- window.removeEventListener("touchend", this.blurOnTouchEndOutside);
241
- window.removeEventListener("touchcancel", this.blurOnTouchEndOutside);
242
- window.removeEventListener("click", this.blurOnClickOutside);
243
- }
244
-
245
- _updateInputPadding: () => void = () => {
246
- this._container = ReactDOM.findDOMNode(this) as HTMLDivElement;
247
- this._root = this._container.querySelector(".mq-root-block");
248
-
249
- const padding = this.getInputInnerPadding();
250
- // NOTE(diedra): This overrides the default 2px padding from Mathquil.
251
- this._root.style.padding =
252
- `${padding.paddingTop}px ${padding.paddingRight}px` +
253
- ` ${padding.paddingBottom}px ${padding.paddingLeft}px`;
254
- this._root.style.fontSize = `${fontSizePt}pt`;
255
- };
256
-
257
- /** Returns the current bounds of the keypadElement */
258
- _getKeypadBounds(): DOMRect | null {
259
- const keypadNode = this.props.keypadElement?.getDOMNode();
260
-
261
- // If the keypad is mounted, return its bounds. Otherwise, return null.
262
- if (keypadNode instanceof Element) {
263
- return keypadNode.getBoundingClientRect();
264
- }
265
-
266
- return null;
267
- }
268
-
269
- _updateCursorHandle: (arg1?: boolean) => void = (animateIntoPosition) => {
270
- const containerBounds = this._container.getBoundingClientRect();
271
- const cursor: any = this._container.querySelector(".mq-cursor");
272
- const cursorBounds = cursor.getBoundingClientRect();
273
-
274
- const cursorWidth = cursorBounds.width;
275
- const gapBelowCursor = 2;
276
-
277
- const inputInnerPadding = this.getInputInnerPadding();
278
-
279
- // The cursor should never be further right or left than the edge of the
280
- // container's values.
281
- const furthestRightCursorBound =
282
- containerBounds.right -
283
- cursorWidth -
284
- inputInnerPadding.paddingRight;
285
- const furthestLeftCursorBound =
286
- containerBounds.left + cursorWidth + inputInnerPadding.paddingLeft;
287
-
288
- let cursorBoundsLeft = cursorBounds.left;
289
- if (cursorBounds.left > furthestRightCursorBound) {
290
- cursorBoundsLeft = furthestRightCursorBound;
291
- } else if (cursorBounds.left < furthestLeftCursorBound) {
292
- cursorBoundsLeft = furthestLeftCursorBound;
293
- }
294
-
295
- this.setState({
296
- handle: {
297
- visible: true,
298
- animateIntoPosition,
299
- // We subtract containerBounds' left/top to correct for the
300
- // position of the container within the page.
301
- x: cursorBoundsLeft + cursorWidth / 2 - containerBounds.left,
302
- y: cursorBounds.bottom + gapBelowCursor - containerBounds.top,
303
- },
304
- });
305
- };
306
-
307
- _hideCursorHandle: () => void = () => {
308
- this.setState({
309
- handle: {
310
- visible: false,
311
- x: 0,
312
- y: 0,
313
- },
314
- });
315
- };
316
-
317
- _handleScroll: () => void = () => {
318
- // If animateIntoPosition is false, the user is currently manually positioning
319
- // the cursor. This is important because the user can scroll the input field
320
- // with the curor handle, and we don't want to override that ability.
321
- // But we do want to hide the handle is the user is just scrolling the input field
322
- // normally, because the handle will not move with the scroll.
323
- if (this.state.handle.animateIntoPosition !== false) {
324
- this._hideCursorHandle();
325
- }
326
- };
327
-
328
- blur: () => void = () => {
329
- this.mathField.blur();
330
- this.props.onBlur && this.props.onBlur();
331
- this.setState({focused: false, handle: {visible: false}});
332
- };
333
-
334
- focus: () => void = () => {
335
- // Pass this component's handleKey method to the keypad so it can call
336
- // it whenever it needs to trigger a keypress action.
337
- this.props.keypadElement?.setKeyHandler((key) => {
338
- const cursor = this.mathField.pressKey(key);
339
-
340
- // Trigger an `onChange` if the value in the input changed, and hide
341
- // the cursor handle whenever the user types a key. If the value
342
- // changed as a result of a keypress, we need to be careful not to
343
- // call `setState` until after `onChange` has resolved.
344
- const hideCursor = () => {
345
- this.setState({
346
- handle: {
347
- visible: false,
348
- },
349
- });
350
- };
351
- const value = this.mathField.getContent();
352
- if (this.props.value !== value) {
353
- this.props.onChange(value, hideCursor);
354
- } else {
355
- hideCursor();
356
- }
357
-
358
- return cursor;
359
- });
360
-
361
- this.mathField.focus();
362
- this.props?.onFocus();
363
- this.setState({focused: true}, () => {
364
- // NOTE(charlie): We use `setTimeout` to allow for a layout pass to
365
- // occur. Otherwise, the keypad is measured incorrectly. Ideally,
366
- // we'd use requestAnimationFrame here, but it's unsupported on
367
- // Android Browser 4.3.
368
- setTimeout(() => {
369
- if (this._isMounted) {
370
- // TODO(benkomalo): the keypad is animating at this point,
371
- // so we can't call _cacheKeypadBounds(), even though
372
- // it'd be nice to do so. It should probably be the case
373
- // that the higher level controller tells us when the
374
- // keypad is settled (then scrollIntoView wouldn't have
375
- // to make assumptions about that either).
376
- const maybeKeypadNode =
377
- this.props.keypadElement?.getDOMNode();
378
- scrollIntoView(this._container, maybeKeypadNode);
379
- }
380
- });
381
- });
382
- };
383
-
384
- /**
385
- * Tries to determine which DOM node to place the cursor next to based on
386
- * where the user drags the cursor handle. If it finds a node it will
387
- * place the cursor next to it, update the handle to be under the cursor,
388
- * and return true. If it doesn't find a node, it returns false.
389
- *
390
- * It searches for nodes by doing it tests at the following points:
391
- *
392
- * (x - dx, y), (x, y), (x + dx, y)
393
- *
394
- * If it doesn't find any nodes from the rendered math it will update y
395
- * by adding dy.
396
- *
397
- * The algorithm ends its search when y goes outside the bounds of
398
- * containerBounds.
399
- *
400
- * @param {DOMRect} containerBounds - bounds of the container node
401
- * @param {number} x - the initial x coordinate in the viewport
402
- * @param {number} y - the initial y coordinate in the viewport
403
- * @param {number} dx - horizontal spacing between elementFromPoint calls
404
- * @param {number} dy - vertical spacing between elementFromPoint calls,
405
- * sign determines direction.
406
- * @returns {boolean} - true if a node was hit, false otherwise.
407
- */
408
- _findHitNode: (
409
- arg1: ClientRect,
410
- arg2: number,
411
- arg3: number,
412
- arg4: number,
413
- arg5: number,
414
- ) => boolean = (containerBounds, x, y, dx, dy) => {
415
- while (y >= containerBounds.top && y <= containerBounds.bottom) {
416
- y += dy;
417
-
418
- const points = [
419
- [x - dx, y],
420
- [x, y],
421
- [x + dx, y],
422
- ];
423
-
424
- const elements = points
425
- // @ts-expect-error - TS2556 - A spread argument must either have a tuple type or be passed to a rest parameter.
426
- .map((point) => document.elementFromPoint(...point))
427
- // We exclude the root container itself and any nodes marked
428
- // as non-leaf which are fractions, parens, and roots. The
429
- // children of those nodes are included in the list because
430
- // those are the items we care about placing the cursor next
431
- // to.
432
- //
433
- // MathQuill's mq-non-leaf is not applied to all non-leaf nodes
434
- // so the naming is a bit confusing. Although fractions are
435
- // included, neither mq-numerator nor mq-denominator nodes are
436
- // and neither are subscripts or superscripts.
437
- .filter(
438
- (element) =>
439
- element &&
440
- this._root.contains(element) &&
441
- ((!element.classList.contains("mq-root-block") &&
442
- !element.classList.contains("mq-non-leaf")) ||
443
- element.classList.contains("mq-empty") ||
444
- element.classList.contains("mq-hasCursor")),
445
- );
446
-
447
- let hitNode = null;
448
-
449
- // Contains only DOMNodes without child elements. These should
450
- // contain some amount of text though.
451
- const leafElements: ReadonlyArray<null | HTMLElement> = [];
452
-
453
- // Contains only DOMNodes with child elements.
454
- const nonLeafElements: ReadonlyArray<null | HTMLElement> = [];
455
-
456
- let max = 0;
457
- const counts: {
458
- [key: string]: number;
459
- } = {};
460
- const elementsById: Record<string, any> = {};
461
-
462
- for (const element of elements) {
463
- // @ts-expect-error - TS2531 - Object is possibly 'null'.
464
- const id = element.getAttribute("mathquill-command-id");
465
- if (id != null) {
466
- // @ts-expect-error - TS2345 - Argument of type 'Element | null' is not assignable to parameter of type 'HTMLElement | null'.
467
- leafElements.push(element);
468
-
469
- counts[id] = (counts[id] || 0) + 1;
470
- elementsById[id] = element;
471
- } else {
472
- // @ts-expect-error - TS2345 - Argument of type 'Element | null' is not assignable to parameter of type 'HTMLElement | null'.
473
- nonLeafElements.push(element);
474
- }
475
- }
476
-
477
- // When determining which DOMNode to place the cursor beside, we
478
- // prefer leaf nodes. Hitting a leaf node is a good sign that the
479
- // cursor is really close to some piece of math that has been
480
- // rendered because leaf nodes contain text. Non-leaf nodes may
481
- // contain a lot of whitespace so the cursor may be further away
482
- // from actual text within the expression.
483
- //
484
- // Since we're doing three hit tests per loop it's possible that
485
- // we hit multiple leaf nodes at the same time. In this case we
486
- // we prefer the DOMNode with the most hits.
487
- // TODO(kevinb) consider preferring nodes hit by [x, y].
488
- for (const [id, count] of entries(counts)) {
489
- if (count > max) {
490
- max = count;
491
- hitNode = elementsById[id];
492
- }
493
- }
494
-
495
- // It's possible that two non-leaf nodes are right beside each
496
- // other. We don't bother counting the number of hits for each,
497
- // b/c this seems like an unlikely situation. Also, ignoring the
498
- // hit count in the situation should not have serious effects on
499
- // the overall accuracy of the algorithm.
500
- if (hitNode == null && nonLeafElements.length > 0) {
501
- // @ts-expect-error - TS2322 - Type 'HTMLElement | null' is not assignable to type 'null'.
502
- hitNode = nonLeafElements[0];
503
- }
504
-
505
- if (hitNode !== null) {
506
- this.mathField.setCursorPosition(x, y, hitNode);
507
- return true;
508
- }
509
- }
510
-
511
- return false;
512
- };
513
-
514
- /**
515
- * Inserts the cursor at the DOM node closest to the given coordinates,
516
- * based on hit-tests conducted using #_findHitNode.
517
- *
518
- * @param {number} x - the x coordinate in the viewport
519
- * @param {number} y - the y coordinate in the viewport
520
- */
521
- _insertCursorAtClosestNode: (arg1: number, arg2: number) => void = (
522
- x,
523
- y,
524
- ) => {
525
- const cursor = this.mathField.getCursor();
526
-
527
- // Pre-emptively check if the input has any child nodes; if not, the
528
- // input is empty, so we throw the cursor at the start.
529
- if (!this._root.hasChildNodes()) {
530
- cursor.insAtLeftEnd(this.mathField.mathField.controller().root);
531
- return;
532
- }
533
-
534
- // NOTE(diedra): The adding and subtracting of 10 or 15 pixels here accounts
535
- // for the padding that surrounds the input values.
536
- if (y > this._containerBounds.bottom) {
537
- y = this._containerBounds.bottom - 10;
538
- } else if (y < this._containerBounds.top) {
539
- y = this._containerBounds.top + 10;
540
- }
541
- if (x > this._containerBounds.right) {
542
- x = this._containerBounds.right - 15;
543
- } else if (x < this._containerBounds.left) {
544
- x = this._containerBounds.left + 15;
545
- }
546
-
547
- let dy;
548
-
549
- // Vertical spacing between hit tests
550
- // dy is negative because we're moving upwards.
551
- dy = -8;
552
-
553
- // Horizontal spacing between hit tests
554
- // Note: This value depends on the font size. If the gap is too small
555
- // we end up placing the cursor at the end of the expression when we
556
- // shouldn't.
557
- const dx = 5;
558
-
559
- if (this._findHitNode(this._containerBounds, x, y, dx, dy)) {
560
- return;
561
- }
562
-
563
- // If we haven't found anything start from the top.
564
- y = this._containerBounds.top;
565
-
566
- // dy is positive b/c we're going downwards.
567
- dy = 8;
568
-
569
- if (this._findHitNode(this._containerBounds, x, y, dx, dy)) {
570
- return;
571
- }
572
-
573
- const firstChildBounds = this._root.firstChild.getBoundingClientRect();
574
- const lastChildBounds = this._root.lastChild.getBoundingClientRect();
575
-
576
- const left = firstChildBounds.left;
577
- const right = lastChildBounds.right;
578
-
579
- // We've exhausted all of the options. We're likely either to the right
580
- // or left of all of the math, so we place the cursor at the end to
581
- // which it's closest.
582
- if (Math.abs(x - right) < Math.abs(x - left)) {
583
- cursor.insAtRightEnd(this.mathField.mathField.controller().root);
584
- } else {
585
- cursor.insAtLeftEnd(this.mathField.mathField.controller().root);
586
- }
587
- // In that event, we need to update the cursor context ourselves.
588
- this.props.keypadElement &&
589
- this.props.keypadElement.setCursor({
590
- context: this.mathField.contextForCursor(),
591
- });
592
- };
593
-
594
- handleTouchStart = (
595
- e: React.TouchEvent<HTMLDivElement>,
596
- keypadActive: boolean,
597
- setKeypadActive: (keypadActive: boolean) => void,
598
- ): void => {
599
- e.stopPropagation();
600
-
601
- // Hide the cursor handle on touch start, if the handle itself isn't
602
- // handling the touch event.
603
- this._hideCursorHandle();
604
-
605
- // Cache the container bounds, so as to avoid re-computing. If we don't
606
- // have any content, then it's not necessary, since the cursor can't be
607
- // moved anyway.
608
- if (this.mathField.getContent() !== "") {
609
- this._containerBounds = this._container.getBoundingClientRect();
610
-
611
- // Make the cursor visible and set the handle-less cursor's
612
- // location.
613
- const touch = e.changedTouches[0];
614
- this._insertCursorAtClosestNode(touch.clientX, touch.clientY);
615
- }
616
-
617
- // If we're already focused, but the keypad isn't active, activate it.
618
- if (this.state.focused && !keypadActive) {
619
- setKeypadActive(true);
620
- }
621
-
622
- // Trigger a focus event, if we're not already focused.
623
- if (!this.state.focused) {
624
- this.focus();
625
- }
626
- };
627
-
628
- // We want to allow the user to be able to focus the input via click
629
- // when using ChromeOS third-party browsers that use mobile user agents,
630
- // but don't actually simulate touch events.
631
- handleClick = (
632
- e: React.MouseEvent<HTMLDivElement>,
633
- keypadActive: boolean,
634
- setKeypadActive: (keypadActive: boolean) => void,
635
- ): void => {
636
- e.stopPropagation();
637
-
638
- // Hide the cursor handle on click
639
- this._hideCursorHandle();
640
-
641
- // Cache the container bounds, so as to avoid re-computing. If we don't
642
- // have any content, then it's not necessary, since the cursor can't be
643
- // moved anyway.
644
- if (this.mathField.getContent() !== "") {
645
- this._containerBounds = this._container.getBoundingClientRect();
646
-
647
- // Make the cursor visible and set the handle-less cursor's
648
- // location.
649
- this._insertCursorAtClosestNode(e.clientX, e.clientY);
650
- }
651
-
652
- // If we're already focused, but the keypad isn't active, activate it.
653
- if (this.state.focused && !keypadActive) {
654
- setKeypadActive(true);
655
- }
656
-
657
- // Trigger a focus event, if we're not already focused.
658
- if (!this.state.focused) {
659
- this.focus();
660
- }
661
- };
662
-
663
- handleTouchMove: (arg1: React.TouchEvent<HTMLDivElement>) => void = (e) => {
664
- e.stopPropagation();
665
-
666
- // Update the handle-less cursor's location on move, if there's any
667
- // content in the box. Note that if the user touched outside the keypad
668
- // (e.g., with a different finger) during this touch interaction, we
669
- // may have blurred, in which case we should ignore the touch (since
670
- // the cursor is no longer visible and the input is no longer
671
- // highlighted).
672
- if (this.mathField.getContent() !== "" && this.state.focused) {
673
- const touch = e.changedTouches[0];
674
- this._insertCursorAtClosestNode(touch.clientX, touch.clientY);
675
- }
676
- };
677
-
678
- handleTouchEnd: (arg1: React.TouchEvent<HTMLDivElement>) => void = (e) => {
679
- e.stopPropagation();
680
-
681
- // And on touch-end, reveal the cursor, unless the input is empty. Note
682
- // that if the user touched outside the keypad (e.g., with a different
683
- // finger) during this touch interaction, we may have blurred, in which
684
- // case we should ignore the touch (since the cursor is no longer
685
- // visible and the input is no longer highlighted).
686
- if (this.mathField.getContent() !== "" && this.state.focused) {
687
- this._updateCursorHandle();
688
- }
689
- };
690
-
691
- /**
692
- * When a touch starts in the cursor handle, we track it so as to avoid
693
- * handling any touch events ourself.
694
- *
695
- * @param {TouchEvent} e - the raw touch event from the browser
696
- */
697
- onCursorHandleTouchStart: (
698
- arg1: React.TouchEvent<HTMLSpanElement>,
699
- ) => void = (e) => {
700
- // NOTE(charlie): The cursor handle is a child of this view, so whenever
701
- // it receives a touch event, that event would also typically be bubbled
702
- // up to our own handlers. However, we want the cursor to handle its own
703
- // touch events, and for this view to only handle touch events that
704
- // don't affect the cursor. As such, we `stopPropagation` on any touch
705
- // events that are being handled by the cursor, so as to avoid handling
706
- // them in our own touch handlers.
707
- e.stopPropagation();
708
-
709
- e.preventDefault();
710
-
711
- // Cache the container bounds, so as to avoid re-computing.
712
- this._containerBounds = this._container.getBoundingClientRect();
713
- };
714
-
715
- _constrainToBound: (
716
- arg1: number,
717
- arg2: number,
718
- arg3: number,
719
- arg4: number,
720
- ) => number = (value, min, max, friction) => {
721
- if (value < min) {
722
- return min + (value - min) * friction;
723
- } else if (value > max) {
724
- return max + (value - max) * friction;
725
- } else {
726
- return value;
727
- }
728
- };
729
-
730
- /**
731
- * When the user moves the cursor handle update the position of the cursor
732
- * and the handle.
733
- *
734
- * @param {TouchEvent} e - the raw touch event from the browser
735
- */
736
- onCursorHandleTouchMove: (arg1: React.TouchEvent<HTMLSpanElement>) => void =
737
- (e) => {
738
- e.stopPropagation();
739
-
740
- const x = e.changedTouches[0].clientX;
741
- const y = e.changedTouches[0].clientY;
742
-
743
- const relativeX = x - this._containerBounds.left;
744
- const relativeY =
745
- y -
746
- 2 * cursorHandleRadiusPx * cursorHandleDistanceMultiplier -
747
- this._containerBounds.top;
748
-
749
- // We subtract the containerBounds left/top to correct for the
750
- // MathInput's position on the page. On top of that, we subtract an
751
- // additional 2 x {height of the cursor} so that the bottom of the
752
- // cursor tracks the user's finger, to make it visible under their
753
- // touch.
754
- this.setState({
755
- handle: {
756
- animateIntoPosition: false,
757
- visible: true,
758
- // TODO(charlie): Use clientX and clientY to avoid the need for
759
- // scroll offsets. This likely also means that the cursor
760
- // detection doesn't work when scrolled, since we're not
761
- // offsetting those values.
762
- x: this._constrainToBound(
763
- relativeX,
764
- 0,
765
- this._containerBounds.width,
766
- constrainingFrictionFactor,
767
- ),
768
- y: this._constrainToBound(
769
- relativeY,
770
- 0,
771
- this._containerBounds.height,
772
- constrainingFrictionFactor,
773
- ),
774
- },
775
- });
776
-
777
- // Use a y-coordinate that's just above where the user is actually
778
- // touching because they're dragging the handle which is a little
779
- // below where the cursor actually is.
780
- const distanceAboveFingerToTrySelecting = 22;
781
- const adjustedY = y - distanceAboveFingerToTrySelecting;
782
-
783
- this._insertCursorAtClosestNode(x, adjustedY);
784
- };
785
-
786
- /**
787
- * When the user releases the cursor handle, animate it back into place.
788
- *
789
- * @param {TouchEvent} e - the raw touch event from the browser
790
- */
791
- onCursorHandleTouchEnd: (arg1: React.TouchEvent<HTMLSpanElement>) => void =
792
- (e) => {
793
- e.stopPropagation();
794
-
795
- this._updateCursorHandle(true);
796
- };
797
-
798
- /**
799
- * If the gesture is cancelled mid-drag, simply hide it.
800
- *
801
- * @param {TouchEvent} e - the raw touch event from the browser
802
- */
803
- onCursorHandleTouchCancel: (
804
- arg1: React.TouchEvent<HTMLSpanElement>,
805
- ) => void = (e) => {
806
- e.stopPropagation();
807
-
808
- this._updateCursorHandle(true);
809
- };
810
-
811
- domKeyToMathQuillKey: (arg1: string) => string | null | undefined = (
812
- key,
813
- ) => {
814
- const keyMap = {
815
- "+": "PLUS",
816
- "-": "MINUS",
817
- "*": "TIMES",
818
- "/": "DIVIDE",
819
- ".": "DECIMAL",
820
- "%": "PERCENT",
821
- "=": "EQUAL",
822
- ">": "GT",
823
- "<": "LT",
824
- "^": "EXP",
825
- } as const;
826
-
827
- // Numbers
828
- if (["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"].includes(key)) {
829
- return `NUM_${key}`;
830
- }
831
-
832
- // Movement keys
833
- else if (key === "Backspace") {
834
- return "BACKSPACE";
835
- }
836
-
837
- // Operators
838
- else if (key in keyMap) {
839
- return keyMap[key];
840
- }
841
-
842
- // The key pressed doesn't map to any of the math input operators
843
- return null;
844
- };
845
-
846
- handleKeyUp: (arg1: React.KeyboardEvent<HTMLDivElement>) => void = (
847
- event,
848
- ) => {
849
- const mathQuillKey = this.domKeyToMathQuillKey(event.key);
850
-
851
- if (mathQuillKey) {
852
- this.mathField.pressKey(mathQuillKey);
853
-
854
- // TODO(diedra): If the new value being added is off-screen to the right
855
- // due to the max-width of the text box, scroll the box to show the newest
856
- // value
857
- const value = this.mathField.getContent();
858
- if (this.props.value !== value) {
859
- this.mathField.setContent(this.props.value);
860
- this.props.onChange(value, false);
861
- this._hideCursorHandle();
862
- }
863
- }
864
- };
865
-
866
- getBorderWidthPx: () => number = () => {
867
- // TODO(diedra): Move these to the common style package.
868
- const normalBorderWidthPx = 1;
869
- const focusedBorderWidthPx = 2;
870
-
871
- return this.state.focused ? focusedBorderWidthPx : normalBorderWidthPx;
872
- };
873
-
874
- // Calculate the appropriate padding based on the border width (which is
875
- // considered 'padding', since we're using 'border-box') and the fact
876
- // that MathQuill automatically applies 2px of padding to the inner
877
- // input.
878
- getInputInnerPadding: () => {
879
- paddingTop: number;
880
- paddingRight: number;
881
- paddingBottom: number;
882
- paddingLeft: number;
883
- } = () => {
884
- const paddingInset = totalDesiredPadding - this.getBorderWidthPx();
885
-
886
- // Now, translate that to the appropriate padding for each direction.
887
- // The complication here is that we want numerals to be centered within
888
- // the input. However, Symbola (MathQuill's font of choice) renders
889
- // numerals with approximately 3px of padding below and 1px of padding
890
- // above (to make room for ascenders and descenders). So we ignore those
891
- // padding values for the vertical directions.
892
- const symbolaPaddingBottom = 3;
893
- const symbolaPaddingTop = 1;
894
- const padding = {
895
- paddingTop: paddingInset - symbolaPaddingTop,
896
- paddingRight: paddingInset,
897
- paddingBottom: paddingInset - symbolaPaddingBottom,
898
- paddingLeft: paddingInset,
899
- } as const;
900
-
901
- return padding;
902
- };
903
-
904
- render(): React.ReactNode {
905
- const {focused, handle} = this.state;
906
- const {style} = this.props;
907
-
908
- const innerStyle = {
909
- ...inlineStyles.innerContainer,
910
- borderWidth: this.getBorderWidthPx(),
911
- ...(focused
912
- ? {
913
- borderColor: Color.blue,
914
- }
915
- : {}),
916
- ...style,
917
- } as const;
918
-
919
- // NOTE(diedra): This label explicitly refers to tapping because this field
920
- // is currently only seen if the user is using a mobile device.
921
- // We added the tapping instructions because there is currently a bug where
922
- // Android users need to use two fingers to tap the input field to make the
923
- // keyboard appear. It should only require one finger, which is how iOS works.
924
- // TODO(diedra): Fix the bug that is causing Android to require a two finger tap
925
- // to the open the keyboard, and then remove the second half of this label.
926
- const ariaLabel =
927
- i18n._("Math input box") +
928
- " " +
929
- i18n._("Tap with one or two fingers to open keyboard");
930
-
931
- return (
932
- <KeypadContext.Consumer>
933
- {({keypadActive, setKeypadActive}) => (
934
- <View
935
- style={styles.input}
936
- onTouchStart={(e: React.TouchEvent<HTMLDivElement>) => {
937
- this.handleTouchStart(
938
- e,
939
- keypadActive,
940
- setKeypadActive,
941
- );
942
- }}
943
- onTouchMove={this.handleTouchMove}
944
- onTouchEnd={this.handleTouchEnd}
945
- onClick={(e: React.MouseEvent<HTMLDivElement>) => {
946
- this.handleClick(e, keypadActive, setKeypadActive);
947
- }}
948
- role={"textbox"}
949
- ariaLabel={ariaLabel}
950
- >
951
- {/* NOTE(charlie): This is used purely to namespace the styles in
952
- overrides.css. */}
953
- <div
954
- className="keypad-input"
955
- // @ts-expect-error - TS2322 - Type 'string' is not assignable to type 'number | undefined'.
956
- tabIndex={"0"}
957
- ref={(node) => {
958
- this.inputRef = node;
959
- }}
960
- onKeyUp={this.handleKeyUp}
961
- >
962
- {/* NOTE(charlie): This element must be styled with inline
963
- styles rather than with Aphrodite classes, as MathQuill
964
- modifies the class names on the DOM node. */}
965
- <div
966
- ref={(node) => {
967
- this._mathContainer =
968
- ReactDOM.findDOMNode(node);
969
- }}
970
- style={innerStyle}
971
- />
972
- </div>
973
- {focused && handle.visible && (
974
- <CursorHandle
975
- {...handle}
976
- onTouchStart={this.onCursorHandleTouchStart}
977
- onTouchMove={this.onCursorHandleTouchMove}
978
- onTouchEnd={this.onCursorHandleTouchEnd}
979
- onTouchCancel={this.onCursorHandleTouchCancel}
980
- />
981
- )}
982
- </View>
983
- )}
984
- </KeypadContext.Consumer>
985
- );
986
- }
987
- }
988
-
989
- const fontSizePt = 18;
990
- const inputMaxWidth = 128;
991
-
992
- // The height of numerals in Symbola (rendered at 18pt) is about 20px (though
993
- // they render at 24px due to padding for ascenders and descenders). We want our
994
- // box to be laid out such that there's 12px of padding between a numeral and the
995
- // edge of the input, so we use this 20px number as our 'base height' and
996
- // account for the ascender and descender padding when computing the additional
997
- // padding in our `render` method.
998
- const numeralHeightPx = 20;
999
- const totalDesiredPadding = 12;
1000
- const minHeightPx = numeralHeightPx + totalDesiredPadding * 2;
1001
- const minWidthPx = 64;
1002
-
1003
- const styles = StyleSheet.create({
1004
- input: {
1005
- position: "relative",
1006
- display: "inline-block",
1007
- verticalAlign: "middle",
1008
- maxWidth: inputMaxWidth,
1009
- },
1010
- });
1011
-
1012
- const inlineStyles = {
1013
- // Styles for the inner, MathQuill-ified input element. It's important that
1014
- // these are done with regular inline styles rather than Aphrodite classes
1015
- // as MathQuill adds CSS class names to the element outside of the typical
1016
- // React flow; assigning a class to the element can thus disrupt MathQuill
1017
- // behavior. For example, if the client provided new styles to be applied
1018
- // on focus and the styles here were applied with Aphrodite, then Aphrodite
1019
- // would merge the provided styles with the base styles here, producing a
1020
- // new CSS class name that we would apply to the element, clobbering any CSS
1021
- // class names that MathQuill had applied itself.
1022
- innerContainer: {
1023
- backgroundColor: "white",
1024
- minHeight: minHeightPx,
1025
- minWidth: minWidthPx,
1026
- maxWidth: inputMaxWidth,
1027
- boxSizing: "border-box",
1028
- position: "relative",
1029
- borderStyle: "solid",
1030
- borderColor: Color.offBlack50,
1031
- borderRadius: 4,
1032
- color: Color.offBlack,
1033
- },
1034
- } as const;
1035
-
1036
- export default MathInput;