@khanacademy/math-input 0.3.2 → 0.5.0

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