@khanacademy/perseus 18.0.1 → 19.0.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.
@@ -1,2936 +0,0 @@
1
- /* eslint-disable @khanacademy/ts-no-error-suppressions */
2
- /* eslint-disable @babel/no-invalid-this */
3
- /* eslint-disable camelcase */
4
- /* eslint-disable react/no-did-update-set-state */
5
- /* eslint-disable react/sort-comp */
6
- /*
7
- NOTE(Pereus stabilize project): This widget is no-longer-used as of January
8
- 2022. It's not present in US content but is still present in some
9
- international content so it can't be removed quite yet. As soon as it's
10
- verified to have been removed from international content this all needs
11
- to get deleted. In the meantime- do not maintain this code.
12
-
13
- ref: https://khanacademy.slack.com/archives/CJDRXTGQ7/p1641857400011600
14
- ref: https://khanacademy.slack.com/archives/C2RFQGYKU/p1596160975061500?thread_ts=1596129758.040000&cid=C2RFQGYKU
15
- */
16
- import {
17
- number as knumber,
18
- vector as kvector,
19
- point as kpoint,
20
- ray as kray,
21
- line as kline,
22
- } from "@khanacademy/kmath";
23
- import * as i18n from "@khanacademy/wonder-blocks-i18n";
24
- import createReactClass from "create-react-class";
25
- import $ from "jquery";
26
- import * as React from "react";
27
- import ReactDOM from "react-dom";
28
- import _ from "underscore";
29
-
30
- import Graph from "../components/graph";
31
- import InlineIcon from "../components/inline-icon";
32
- import NumberInput from "../components/number-input";
33
- import SimpleKeypadInput from "../components/simple-keypad-input";
34
- import {getDependencies} from "../dependencies";
35
- import {iconPlus, iconUndo} from "../icon-paths";
36
- import InteractiveUtil from "../interactive2/interactive-util";
37
- import {Errors} from "../logging/log";
38
- import {ApiOptions} from "../perseus-api";
39
- import {PerseusError} from "../perseus-error";
40
- import Util from "../util";
41
- import KhanColors from "../util/colors";
42
- import KhanMath from "../util/math";
43
-
44
- import type {Coord} from "../interactive2/types";
45
- import type {
46
- PerseusTransformerWidgetOptions,
47
- PerseusTransformerTransformation as TransformerTransformation,
48
- DilationTransformation,
49
- ReflectionTransformation,
50
- RotationTransformation,
51
- TranslationTransformation,
52
- } from "../perseus-types";
53
- import type {Path, PerseusScore, WidgetExports, WidgetProps} from "../types";
54
-
55
- const {deepEq, getGridStep, captureScratchpadTouchStart} = Util;
56
- const {assert} = InteractiveUtil;
57
-
58
- const ROTATE_SNAP_DEGREES = 15;
59
-
60
- const DEGREE_SIGN = "\u00B0";
61
- const RENDER_TRANSFORM_DELAY_IN_MS = 300;
62
- const ROTATE_HANDLE_DIST = 1.5;
63
- const REFLECT_ROTATE_HANDLE_DIST = 2;
64
- const REFLECT_BUTTON_SIZE = 1;
65
- const defaultBoxSize = 400;
66
- const defaultBackgroundImage = {
67
- url: null,
68
- } as const;
69
-
70
- /* Does a pluck on keys inside objects in an object
71
- *
72
- * Ex:
73
- * tools = {
74
- * translation: {
75
- * enabled: true
76
- * },
77
- * rotation: {
78
- * enabled: false
79
- * }
80
- * };
81
- * pluckObject(tools, "enabled") returns {
82
- * translation: true
83
- * rotation: false
84
- * }
85
- */
86
- function pluckObject(object, subKey: string) {
87
- return _.object(
88
- _.map(object, function (value, key) {
89
- return [key, value[subKey]];
90
- }),
91
- );
92
- }
93
-
94
- const defaultGraphProps = function (setProps, boxSize) {
95
- setProps = setProps || {};
96
- const labels = setProps.labels || ["x", "y"];
97
- const range = setProps.range || [
98
- [-10, 10],
99
- [-10, 10],
100
- ];
101
- const step = setProps.step || [1, 1];
102
- const gridStep = setProps.gridStep || getGridStep(range, step, boxSize);
103
- return {
104
- box: [boxSize, boxSize],
105
- labels: labels,
106
- range: range,
107
- step: step,
108
- gridStep: gridStep,
109
- valid: true,
110
- backgroundImage: defaultBackgroundImage,
111
- markings: "grid",
112
- showProtractor: false,
113
- };
114
- };
115
-
116
- const defaultTransformerProps = {
117
- apiOptions: ApiOptions.defaults,
118
- gradeEmpty: false,
119
- graphMode: "interactive",
120
- listMode: "dynamic",
121
- graph: {},
122
- tools: {
123
- translation: {
124
- enabled: true,
125
- required: false,
126
- constraints: {},
127
- },
128
- rotation: {
129
- enabled: true,
130
- required: false,
131
- constraints: {
132
- fixed: false,
133
- },
134
- coord: [1, 6],
135
- },
136
- reflection: {
137
- enabled: true,
138
- required: false,
139
- constraints: {
140
- fixed: false,
141
- },
142
- coords: [
143
- [2, -4],
144
- [2, 2],
145
- ],
146
- },
147
- dilation: {
148
- enabled: true,
149
- required: false,
150
- constraints: {
151
- fixed: false,
152
- },
153
- coord: [6, 6],
154
- },
155
- },
156
- drawSolutionShape: true,
157
- starting: {
158
- shape: {
159
- type: "polygon-3",
160
- coords: [
161
- [2, 2],
162
- [2, 6],
163
- [7, 2],
164
- ],
165
- },
166
- transformations: [],
167
- },
168
- correct: {
169
- shape: {
170
- type: "polygon-3",
171
- coords: [
172
- [2, 2],
173
- [2, 6],
174
- [7, 2],
175
- ],
176
- },
177
- transformations: [],
178
- },
179
- } as const;
180
-
181
- function colorForTool(tool) {
182
- return tool.constraints.fixed ? KhanColors.DYNAMIC : KhanColors.INTERACTIVE;
183
- }
184
-
185
- /* Scales a distance from the default range of
186
- * [-10, 10] to a given props.range pair
187
- *
188
- * Used for sizing various transformation tools
189
- * (rotation handle, dilation circle)
190
- */
191
- function scaleToRange(dist: number, range) {
192
- const spreadX = range[0][1] - range[0][0];
193
- const spreadY = range[1][1] - range[1][0];
194
-
195
- return (dist * Math.max(spreadX, spreadY)) / 20;
196
- }
197
-
198
- function dilatePointFromCenter(
199
- point: any,
200
- dilationCenter: Coord,
201
- scale: number,
202
- ) {
203
- const pv = kvector.subtract(point, dilationCenter);
204
- const pvScaled = kvector.scale(pv, scale);
205
- const transformedPoint = kvector.add(dilationCenter, pvScaled);
206
- return transformedPoint;
207
- }
208
-
209
- // TODO(jack): i18nize this
210
- function stringFromDecimal(number) {
211
- return String(KhanMath.roundTo(9, number));
212
- }
213
-
214
- function stringFromFraction(number) {
215
- const frac = KhanMath.toFraction(number, knumber.DEFAULT_TOLERANCE);
216
- if (frac[1] === 1) {
217
- return stringFromDecimal(number);
218
- }
219
- return stringFromDecimal(frac[0]) + "/" + stringFromDecimal(frac[1]);
220
- }
221
-
222
- function texFromPoint(point: Coord) {
223
- const {TeX} = getDependencies();
224
-
225
- return [
226
- <TeX key="(">(</TeX>,
227
- stringFromDecimal(point[0]),
228
- <TeX key=",">{", {}"}</TeX>,
229
- stringFromDecimal(point[1]),
230
- <TeX key=")">)</TeX>,
231
- ];
232
- }
233
-
234
- function texFromVector(vector) {
235
- const {TeX} = getDependencies();
236
-
237
- return [
238
- <TeX key="<">{i18n.doNotTranslate("\\langle")}</TeX>,
239
- stringFromDecimal(vector[0]),
240
- <TeX key=",">{", {}"}</TeX>,
241
- stringFromDecimal(vector[1]),
242
- <TeX key=">">{i18n.doNotTranslate("\\rangle")}</TeX>,
243
- ];
244
- }
245
-
246
- function texFromAngleDeg(angleDeg: number) {
247
- return stringFromDecimal(angleDeg) + DEGREE_SIGN;
248
- }
249
-
250
- function orderInsensitiveCoordsEqual(coords1, coords2: any) {
251
- coords1 = _.clone(coords1).sort(kpoint.compare);
252
- coords2 = _.clone(coords2).sort(kpoint.compare);
253
- return _.all(
254
- _.map(coords1, function (coord1, i) {
255
- const coord2 = coords2[i];
256
- return kpoint.equal(coord1, coord2);
257
- }),
258
- );
259
- }
260
-
261
- const inputComponentForApiOptions = (apiOptions) => {
262
- if (apiOptions.customKeypad) {
263
- return SimpleKeypadInput;
264
- }
265
- return NumberInput;
266
- };
267
-
268
- /* Perform operations on raw transform objects */
269
- const TransformOps = {
270
- apply: function (transform: TransformerTransformation) {
271
- // Any transformation with empty text boxes is a no-op until
272
- // filled out (these show up as nulls in transform.vector/line/etc).
273
- // TODO (jack): Merge this just into reflections now that other
274
- // transforms are always valid (after merging transformation
275
- // collapsing, which may use isValid)
276
- // @ts-expect-error - TS2345 - Argument of type 'PerseusTransformerTransformation' is not assignable to parameter of type 'never'.
277
- if (!Transformations[transform.type].isValid(transform)) {
278
- return _.identity; // do not transform the coord
279
- }
280
- // @ts-expect-error - TS2345 - Argument of type 'PerseusTransformerTransformation' is not assignable to parameter of type 'never'.
281
- return Transformations[transform.type].apply(transform);
282
- },
283
-
284
- append: function (transformList, newTransform) {
285
- // Append newTransform to transformList, and collapse the last
286
- // two transforms if they are collapsable
287
- const results = TransformOps._appendAndCollapseLastTwo(
288
- transformList,
289
- newTransform,
290
- );
291
- // Collapse any no-ops at the end of the transformation list
292
- return TransformOps._collapseFinalNoOps(results);
293
- },
294
-
295
- _collapseFinalNoOps: function (transforms) {
296
- // Collapse no-op transformations at the end of the list
297
- if (transforms.length && TransformOps.isNoOp(_.last(transforms))) {
298
- return _.initial(transforms);
299
- }
300
- return transforms;
301
- },
302
-
303
- _appendAndCollapseLastTwo: function (transformList, newTransform) {
304
- if (!transformList.length) {
305
- return [newTransform];
306
- }
307
- const collapsed = TransformOps.collapse(
308
- _.last(transformList),
309
- newTransform,
310
- );
311
- return _.initial(transformList).concat(collapsed);
312
- },
313
-
314
- isNoOp: function (transform) {
315
- return Transformations[transform.type].isNoOp(transform);
316
- },
317
-
318
- collapse: function (transform1, transform2) {
319
- // We can only collapse transforms that have the same type
320
- if (transform1.type !== transform2.type) {
321
- return [transform1, transform2];
322
- }
323
-
324
- // Clicking the button again removes empty transformations
325
- if (
326
- TransformOps.isEmpty(transform1) &&
327
- TransformOps.isEmpty(transform2)
328
- ) {
329
- return [];
330
- }
331
-
332
- // Don't collapse invalid transformations otherwise
333
- if (
334
- !TransformOps.isValid(transform1) ||
335
- !TransformOps.isValid(transform2)
336
- ) {
337
- return [transform1, transform2];
338
- }
339
-
340
- return TransformOps._collapseValidMonotypedTransforms(
341
- transform1,
342
- transform2,
343
- );
344
- },
345
-
346
- isValid: function (transform: TransformerTransformation): boolean {
347
- // @ts-expect-error - TS2345 - Argument of type 'PerseusTransformerTransformation' is not assignable to parameter of type 'never'.
348
- return Transformations[transform.type].isValid(transform);
349
- },
350
-
351
- isEmpty: function (transform: TransformerTransformation): boolean {
352
- // @ts-expect-error - TS2345 - Argument of type 'PerseusTransformerTransformation' is not assignable to parameter of type 'never'.
353
- return Transformations[transform.type].isEmpty(transform);
354
- },
355
-
356
- _collapseValidMonotypedTransforms: function (transform1, transform2) {
357
- let collapsed = Transformations[transform1.type].collapse(
358
- transform1,
359
- transform2,
360
- );
361
- if (collapsed) {
362
- // Force all answers into an array
363
- if (!_.isArray(collapsed)) {
364
- collapsed = [collapsed];
365
- }
366
- // Add types to all transforms in the answer
367
- _.each(collapsed, function (transform) {
368
- transform.type = transform1.type;
369
- });
370
- return collapsed;
371
- }
372
- // These transforms can't be collapsed together
373
- return [transform1, transform2];
374
- },
375
-
376
- toTeX: function (transform) {
377
- return Transformations[transform.type].toTeX(transform);
378
- },
379
-
380
- /* A react representation of this transform object */
381
- ListItem: createReactClass({
382
- displayName: "ListItem",
383
-
384
- render: function () {
385
- if (this.props.mode === "dynamic") {
386
- return <div>{TransformOps.toTeX(this.props.transform)}</div>;
387
- }
388
- if (this.props.mode === "interactive") {
389
- const TransformClass =
390
- Transformations[this.props.transform.type].Input;
391
- return (
392
- <TransformClass
393
- // eslint-disable-next-line react/no-string-refs
394
- ref="transform"
395
- onChange={this.handleChange}
396
- onFocus={this.props.onFocus}
397
- onBlur={this.props.onBlur}
398
- keypadElement={this.props.keypadElement}
399
- apiOptions={this.props.apiOptions}
400
- {...this.props.transform}
401
- />
402
- );
403
- }
404
- throw new PerseusError(
405
- "Invalid mode: " + this.props.mode,
406
- Errors.InvalidInput,
407
- );
408
- },
409
-
410
- value: function () {
411
- if (this.props.mode === "interactive") {
412
- return _.extend(
413
- {
414
- type: this.props.transform.type,
415
- },
416
- // eslint-disable-next-line react/no-string-refs
417
- this.refs.transform.value(),
418
- );
419
- }
420
- return this.props.transform;
421
- },
422
-
423
- handleChange: _.debounce(function (callback) {
424
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation. | TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
425
- this.props.onChange(this.value(), callback);
426
- }, RENDER_TRANSFORM_DELAY_IN_MS),
427
-
428
- /* InputPath API: depending on the API call, this could involve simply
429
- * navigating to the right ref and calling the function on that
430
- * component, or threading the call down and returning the result. */
431
- _getComponentAtPath: function (path) {
432
- // eslint-disable-next-line react/no-string-refs
433
- const transform = this.refs.transform;
434
- const ref = _.head(path);
435
- return transform.refs[ref];
436
- },
437
-
438
- focus: function () {
439
- // eslint-disable-next-line react/no-string-refs
440
- const transform = this.refs.transform;
441
- const path = _.head(transform.getInputPaths());
442
- if (path) {
443
- this.focusInputPath(path);
444
- }
445
- },
446
-
447
- focusInputPath: function (path) {
448
- this._getComponentAtPath(path).focus();
449
- },
450
-
451
- blurInputPath: function (path) {
452
- this._getComponentAtPath(path).blur();
453
- },
454
-
455
- getDOMNodeForPath: function (path) {
456
- return ReactDOM.findDOMNode(this._getComponentAtPath(path));
457
- },
458
-
459
- getGrammarTypeForPath: function (path) {
460
- return "number";
461
- },
462
-
463
- setInputValue: function (path, value: string | number, cb) {
464
- // `value` comes in as a string on mobile, but we need a number
465
- // We let through the empty string so that "Clear" works -- in
466
- // that case, the transformer widget will just act as if there is
467
- // no input, which is what we want.
468
- // @ts-expect-error - TS2339 - Property 'length' does not exist on type 'string | number'.
469
- if (value.length) {
470
- // @ts-expect-error - TS2345 - Argument of type 'string | number' is not assignable to parameter of type 'string'.
471
- value = parseFloat(value);
472
- if (isNaN(value)) {
473
- return;
474
- }
475
- }
476
- // eslint-disable-next-line react/no-string-refs
477
- this.refs.transform.setInputValue(path, value, cb);
478
- },
479
-
480
- getInputPaths: function () {
481
- // If we're in dynamic mode, then the list items are made up of
482
- // static text.
483
- if (this.props.mode === "dynamic") {
484
- return [];
485
- }
486
- // eslint-disable-next-line react/no-string-refs
487
- return this.refs.transform.getInputPaths();
488
- },
489
- }),
490
- } as const;
491
-
492
- const Transformations = {
493
- translation: {
494
- // I18N: As in the command, "Translate the polygon"
495
- verbName: i18n._("Translate"),
496
- nounName: i18n._("Translation"),
497
- lowerNounName: i18n._("translation"),
498
- apply: function (transform: TranslationTransformation) {
499
- return function (coord) {
500
- return kvector.add(coord, transform.vector);
501
- };
502
- },
503
- isValid: function (transform: TranslationTransformation) {
504
- return (
505
- _.isFinite(transform.vector[0]) &&
506
- _.isFinite(transform.vector[1])
507
- );
508
- },
509
- isEmpty: function (transform: TranslationTransformation) {
510
- return transform.vector[0] === null && transform.vector[1] === null;
511
- },
512
- isNoOp: function (transform) {
513
- return kvector.equal(transform.vector, [0, 0]);
514
- },
515
- collapse: function (
516
- transform1: TranslationTransformation,
517
- transform2: TranslationTransformation,
518
- ) {
519
- return {
520
- vector: kvector.add(transform1.vector, transform2.vector),
521
- };
522
- },
523
- toTeX: function (transform: TranslationTransformation) {
524
- // I18N: As in the command, "Translation by <3, 1>"
525
- return i18n.$_("Translation by %(vector)s", {
526
- vector: texFromVector(transform.vector),
527
- });
528
- },
529
- Input: class extends React.Component<any, any> {
530
- state = {
531
- vector: this.props.vector || [null, null],
532
- };
533
-
534
- componentDidUpdate(prevProps: any) {
535
- if (!deepEq(this.props, prevProps)) {
536
- this.setState({vector: this.props.vector});
537
- }
538
- }
539
-
540
- render(): React.ReactNode {
541
- const InputComponent = inputComponentForApiOptions(
542
- this.props.apiOptions,
543
- );
544
- const {TeX} = getDependencies();
545
-
546
- const vector = [
547
- <TeX key="<">{i18n.doNotTranslate("\\langle")}</TeX>,
548
- <InputComponent
549
- key="vec_x"
550
- // eslint-disable-next-line react/no-string-refs
551
- ref="x"
552
- placeholder={0}
553
- value={this.state.vector[0]}
554
- useArrowKeys={true}
555
- onChange={(val0) => {
556
- const val1 = this.state.vector[1];
557
- this.setState({vector: [val0, val1]}, () => {
558
- this.props.onChange();
559
- });
560
- }}
561
- onFocus={_.partial(this.props.onFocus, "x")}
562
- onBlur={_.partial(this.props.onBlur, "x")}
563
- keypadElement={this.props.keypadElement}
564
- />,
565
- <TeX key=",">{", {}"}</TeX>,
566
- <InputComponent
567
- key="vec_y"
568
- // eslint-disable-next-line react/no-string-refs
569
- ref="y"
570
- placeholder={0}
571
- value={this.state.vector[1]}
572
- useArrowKeys={true}
573
- onChange={(val1) => {
574
- const val0 = this.state.vector[0];
575
- this.setState({vector: [val0, val1]}, () => {
576
- this.props.onChange();
577
- });
578
- }}
579
- onFocus={_.partial(this.props.onFocus, "y")}
580
- onBlur={_.partial(this.props.onBlur, "y")}
581
- keypadElement={this.props.keypadElement}
582
- />,
583
- <TeX key=">">{i18n.doNotTranslate("\\rangle")}</TeX>,
584
- ];
585
- return (
586
- <div>
587
- {i18n.$_("Translation by %(vector)s", {vector: vector})}
588
- </div>
589
- );
590
- }
591
-
592
- value = () => {
593
- // eslint-disable-next-line react/no-string-refs
594
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
595
- const x = this.refs.x.getValue();
596
- // eslint-disable-next-line react/no-string-refs
597
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
598
- const y = this.refs.y.getValue();
599
- return {
600
- vector: [x, y],
601
- };
602
- };
603
-
604
- /* InputPath API */
605
- setInputValue = (path, value, cb) => {
606
- const id = _.first(path);
607
- const vector = _.clone(this.state.vector);
608
- if (id === "x") {
609
- vector[0] = value;
610
- } else if (id === "y") {
611
- vector[1] = value;
612
- }
613
- this.setState({vector: vector}, () => {
614
- this.props.onChange(cb);
615
- });
616
- };
617
-
618
- getInputPaths = () => {
619
- return [["x"], ["y"]];
620
- };
621
- },
622
- },
623
-
624
- rotation: {
625
- // I18N: As in the command, "Rotate the polygon"
626
- verbName: i18n._("Rotate"),
627
- nounName: i18n._("Rotation"),
628
- lowerNounName: i18n._("rotation"),
629
- apply: function (transform: RotationTransformation) {
630
- return function (coord: any) {
631
- return kpoint.rotateDeg(
632
- coord,
633
- transform.angleDeg,
634
- transform.center,
635
- );
636
- };
637
- },
638
- isValid: function (transform: RotationTransformation) {
639
- return (
640
- _.isFinite(transform.angleDeg) &&
641
- _.isFinite(transform.center[0]) &&
642
- _.isFinite(transform.center[1])
643
- );
644
- },
645
- isEmpty: function (transform: RotationTransformation) {
646
- return (
647
- transform.angleDeg === null &&
648
- transform.center[0] === null &&
649
- transform.center[1] === null
650
- );
651
- },
652
- isNoOp: function (transform: RotationTransformation) {
653
- return knumber.equal(transform.angleDeg, 0);
654
- },
655
- collapse: function (
656
- transform1: RotationTransformation,
657
- transform2: RotationTransformation,
658
- ) {
659
- if (!kpoint.equal(transform1.center, transform2.center)) {
660
- return false;
661
- }
662
- return {
663
- center: transform1.center,
664
- angleDeg: transform1.angleDeg + transform2.angleDeg,
665
- };
666
- },
667
- toTeX: function (transform: RotationTransformation) {
668
- return i18n.$_("Rotation by %(degrees)s about %(point)s", {
669
- degrees: texFromAngleDeg(transform.angleDeg),
670
- point: texFromPoint(transform.center),
671
- });
672
- },
673
- Input: class extends React.Component<any, any> {
674
- state = {
675
- center: this.props.center || [null, null],
676
- angleDeg: this.props.angleDeg || null,
677
- };
678
-
679
- componentDidUpdate(prevProps: any) {
680
- if (!deepEq(this.props, prevProps)) {
681
- this.setState({
682
- center: this.props.center,
683
- angleDeg: this.props.angleDeg,
684
- });
685
- }
686
- }
687
-
688
- render(): React.ReactNode {
689
- const InputComponent = inputComponentForApiOptions(
690
- this.props.apiOptions,
691
- );
692
- const {TeX} = getDependencies();
693
-
694
- const point = [
695
- <TeX key="(">(</TeX>,
696
- <InputComponent
697
- key="X"
698
- // eslint-disable-next-line react/no-string-refs
699
- ref="centerX"
700
- placeholder={0}
701
- value={this.state.center[0]}
702
- useArrowKeys={true}
703
- onChange={(val0) => {
704
- const val1 = this.state.center[1];
705
- this.setState({center: [val0, val1]}, () => {
706
- this.props.onChange();
707
- });
708
- }}
709
- onFocus={_.partial(this.props.onFocus, "centerX")}
710
- onBlur={_.partial(this.props.onBlur, "centerX")}
711
- keypadElement={this.props.keypadElement}
712
- />,
713
- <TeX key=",">{", {}"}</TeX>,
714
- <InputComponent
715
- key="Y"
716
- // eslint-disable-next-line react/no-string-refs
717
- ref="centerY"
718
- placeholder={0}
719
- value={this.state.center[1]}
720
- useArrowKeys={true}
721
- onChange={(val1) => {
722
- const val0 = this.state.center[0];
723
- this.setState({center: [val0, val1]}, () => {
724
- this.props.onChange();
725
- });
726
- }}
727
- onFocus={_.partial(this.props.onFocus, "centerY")}
728
- onBlur={_.partial(this.props.onBlur, "centerY")}
729
- keypadElement={this.props.keypadElement}
730
- />,
731
- <TeX key=")">)</TeX>,
732
- ];
733
- const degrees = [
734
- <InputComponent
735
- key="deg"
736
- // eslint-disable-next-line react/no-string-refs
737
- ref="angleDeg"
738
- placeholder={0}
739
- value={this.state.angleDeg}
740
- useArrowKeys={true}
741
- onChange={(val) => {
742
- this.setState({angleDeg: val}, () => {
743
- this.props.onChange();
744
- });
745
- }}
746
- onFocus={_.partial(this.props.onFocus, "angleDeg")}
747
- onBlur={_.partial(this.props.onBlur, "angleDeg")}
748
- keypadElement={this.props.keypadElement}
749
- />,
750
- DEGREE_SIGN,
751
- ];
752
- // I18N: %(point)s must come before %(degrees)s in this phrase
753
- const text = i18n.$_(
754
- "Rotation about %(point)s by %(degrees)s",
755
- {
756
- point,
757
- degrees,
758
- },
759
- );
760
-
761
- return <div>{text}</div>;
762
- }
763
-
764
- value = () => {
765
- // eslint-disable-next-line react/no-string-refs
766
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
767
- const angleDeg = this.refs.angleDeg.getValue();
768
- // eslint-disable-next-line react/no-string-refs
769
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
770
- const centerX = this.refs.centerX.getValue();
771
- // eslint-disable-next-line react/no-string-refs
772
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
773
- const centerY = this.refs.centerY.getValue();
774
- return {
775
- angleDeg: angleDeg,
776
- center: [centerX, centerY],
777
- };
778
- };
779
-
780
- /* InputPath API */
781
- setInputValue = (path, value, cb) => {
782
- const id = _.first(path);
783
- let angleDeg = _.clone(this.state.angleDeg);
784
- const center = _.clone(this.state.center);
785
- if (id === "angleDeg") {
786
- angleDeg = value;
787
- } else if (id === "centerX") {
788
- center[0] = value;
789
- } else if (id === "centerY") {
790
- center[1] = value;
791
- }
792
- this.setState({angleDeg: angleDeg, center: center}, () => {
793
- this.props.onChange(cb);
794
- });
795
- };
796
-
797
- getInputPaths = () => {
798
- return [["centerX"], ["centerY"], ["angleDeg"]];
799
- };
800
- },
801
- },
802
-
803
- reflection: {
804
- // I18N: As in the command, "Reflect the polygon"
805
- verbName: i18n._("Reflect"),
806
- nounName: i18n._("Reflection"),
807
- lowerNounName: i18n._("reflection"),
808
- apply: function (transform: ReflectionTransformation) {
809
- return function (coord: any) {
810
- return kpoint.reflectOverLine(coord, transform.line);
811
- };
812
- },
813
- isValid: function (transform: ReflectionTransformation) {
814
- // A bit hacky, but we'll also define reflecting over a
815
- // single point as a no-op, to avoid NaN fun.
816
- return (
817
- _.all(_.flatten(transform.line), _.isFinite) &&
818
- !kpoint.equal(transform.line[0], transform.line[1])
819
- );
820
- },
821
- isEmpty: function (transform: ReflectionTransformation) {
822
- return _.all(_.flatten(transform.line), _.isNull);
823
- },
824
- isNoOp: function (transform: ReflectionTransformation) {
825
- // Invalid transforms are implicitly no-ops, so we don't
826
- // have to catch that case here.
827
- return false;
828
- },
829
- collapse: function (
830
- transform1: ReflectionTransformation,
831
- transform2: ReflectionTransformation,
832
- ) {
833
- if (!kline.equal(transform1.line, transform2.line)) {
834
- return false;
835
- }
836
- return [];
837
- },
838
- toTeX: function (transform) {
839
- const point1 = transform.line[0];
840
- const point2 = transform.line[1];
841
- return i18n.$_(
842
- "Reflection over the line from %(point1)s to %(point2)s",
843
- {
844
- point1: texFromPoint(point1),
845
- point2: texFromPoint(point2),
846
- },
847
- );
848
- },
849
- Input: class extends React.Component<any, any> {
850
- state = {
851
- line: this.props.line || [
852
- [null, null],
853
- [null, null],
854
- ],
855
- };
856
-
857
- componentDidUpdate(prevProps) {
858
- if (!deepEq(this.props, prevProps)) {
859
- this.setState({line: this.props.line});
860
- }
861
- }
862
-
863
- render(): React.ReactNode {
864
- const InputComponent = inputComponentForApiOptions(
865
- this.props.apiOptions,
866
- );
867
- const {TeX} = getDependencies();
868
-
869
- const point1 = [
870
- <TeX key="(">(</TeX>,
871
- <InputComponent
872
- key="x1"
873
- // eslint-disable-next-line react/no-string-refs
874
- ref="x1"
875
- value={this.state.line[0][0]}
876
- useArrowKeys={true}
877
- // eslint-disable-next-line react/jsx-no-bind
878
- onChange={this.changePoint.bind(this, 0, 0)}
879
- onFocus={_.partial(this.props.onFocus, "x1")}
880
- onBlur={_.partial(this.props.onBlur, "x1")}
881
- keypadElement={this.props.keypadElement}
882
- />,
883
- <TeX key=",">{", {}"}</TeX>,
884
- <InputComponent
885
- key="y1"
886
- // eslint-disable-next-line react/no-string-refs
887
- ref="y1"
888
- value={this.state.line[0][1]}
889
- useArrowKeys={true}
890
- // eslint-disable-next-line react/jsx-no-bind
891
- onChange={this.changePoint.bind(this, 0, 1)}
892
- onFocus={_.partial(this.props.onFocus, "y1")}
893
- onBlur={_.partial(this.props.onBlur, "y1")}
894
- keypadElement={this.props.keypadElement}
895
- />,
896
- <TeX key=")">)</TeX>,
897
- ];
898
- const point2 = [
899
- <TeX key="(">(</TeX>,
900
- <InputComponent
901
- key="x2"
902
- // eslint-disable-next-line react/no-string-refs
903
- ref="x2"
904
- value={this.state.line[1][0]}
905
- useArrowKeys={true}
906
- // eslint-disable-next-line react/jsx-no-bind
907
- onChange={this.changePoint.bind(this, 1, 0)}
908
- onFocus={_.partial(this.props.onFocus, "x2")}
909
- onBlur={_.partial(this.props.onBlur, "x2")}
910
- keypadElement={this.props.keypadElement}
911
- />,
912
- <TeX key=",">{", {}"}</TeX>,
913
- <InputComponent
914
- key="y2"
915
- // eslint-disable-next-line react/no-string-refs
916
- ref="y2"
917
- value={this.state.line[1][1]}
918
- useArrowKeys={true}
919
- // eslint-disable-next-line react/jsx-no-bind
920
- onChange={this.changePoint.bind(this, 1, 1)}
921
- onFocus={_.partial(this.props.onFocus, "y2")}
922
- onBlur={_.partial(this.props.onBlur, "y2")}
923
- keypadElement={this.props.keypadElement}
924
- />,
925
- <TeX key=")">)</TeX>,
926
- ];
927
- return (
928
- <div>
929
- {i18n.$_(
930
- "Reflection over the line from " +
931
- "%(point1)s to %(point2)s",
932
- {point1, point2},
933
- )}
934
- </div>
935
- );
936
- }
937
-
938
- changePoint = (
939
- i: undefined | number,
940
- j: undefined | number,
941
- val: any,
942
- cb,
943
- ) => {
944
- const line = _.map(this.state.line, _.clone);
945
- // @ts-expect-error - TS2538 - Type 'undefined' cannot be used as an index type.
946
- line[i][j] = val;
947
- this.setState({line: line}, () => {
948
- this.props.onChange(cb);
949
- });
950
- };
951
-
952
- value = () => {
953
- // eslint-disable-next-line react/no-string-refs
954
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
955
- const x1 = this.refs.x1.getValue();
956
- // eslint-disable-next-line react/no-string-refs
957
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
958
- const y1 = this.refs.y1.getValue();
959
- // eslint-disable-next-line react/no-string-refs
960
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
961
- const x2 = this.refs.x2.getValue();
962
- // eslint-disable-next-line react/no-string-refs
963
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
964
- const y2 = this.refs.y2.getValue();
965
- return {
966
- line: [
967
- [x1, y1],
968
- [x2, y2],
969
- ],
970
- };
971
- };
972
-
973
- /* InputPath API */
974
- setInputValue = (path: any, value: any, cb: any) => {
975
- const id = _.first(path);
976
- let j;
977
- if (id[0] === "x") {
978
- j = 0;
979
- } else if (id[0] === "y") {
980
- j = 1;
981
- }
982
- let i;
983
- if (id[1] === "1") {
984
- i = 0;
985
- } else if (id[1] === "2") {
986
- i = 1;
987
- }
988
- this.changePoint(i, j, value, cb);
989
- };
990
-
991
- getInputPaths = () => {
992
- return [["x1"], ["y1"], ["x2"], ["y2"]];
993
- };
994
- },
995
- },
996
-
997
- dilation: {
998
- // I18N: As in the command, "Dilate the polygon"
999
- verbName: i18n._("Dilate"),
1000
- nounName: i18n._("Dilation"),
1001
- lowerNounName: i18n._("dilation"),
1002
- apply: function (transform: DilationTransformation) {
1003
- return function (coord: any) {
1004
- return dilatePointFromCenter(
1005
- coord,
1006
- transform.center,
1007
- transform.scale,
1008
- );
1009
- };
1010
- },
1011
- isValid: function (transform: DilationTransformation) {
1012
- return (
1013
- _.isFinite(transform.scale) &&
1014
- _.isFinite(transform.center[0]) &&
1015
- _.isFinite(transform.center[1])
1016
- );
1017
- },
1018
- isEmpty: function (transform: DilationTransformation) {
1019
- return (
1020
- transform.scale === null &&
1021
- transform.center[0] === null &&
1022
- transform.center[1] === null
1023
- );
1024
- },
1025
- isNoOp: function (transform: DilationTransformation) {
1026
- return knumber.equal(transform.scale, 1);
1027
- },
1028
- collapse: function (
1029
- transform1: DilationTransformation,
1030
- transform2: DilationTransformation,
1031
- ) {
1032
- if (!kpoint.equal(transform1.center, transform2.center)) {
1033
- return false;
1034
- }
1035
- return {
1036
- center: transform1.center,
1037
- scale: transform1.scale * transform2.scale,
1038
- };
1039
- },
1040
- toTeX: function (transform: DilationTransformation) {
1041
- const scaleString = stringFromFraction(transform.scale);
1042
- return i18n.$_("Dilation of scale %(scale)s about %(point)s", {
1043
- scale: scaleString,
1044
- point: texFromPoint(transform.center),
1045
- });
1046
- },
1047
- Input: class extends React.Component<any, any> {
1048
- state = {
1049
- center: this.props.center || [null, null],
1050
- scale: this.props.scale || null,
1051
- };
1052
-
1053
- componentDidUpdate(prevProps: any) {
1054
- if (!deepEq(this.props, prevProps)) {
1055
- this.setState({
1056
- center: this.props.center,
1057
- scale: this.props.scale,
1058
- });
1059
- }
1060
- }
1061
-
1062
- render(): React.ReactNode {
1063
- const InputComponent = inputComponentForApiOptions(
1064
- this.props.apiOptions,
1065
- );
1066
- const {TeX} = getDependencies();
1067
-
1068
- const point = [
1069
- <TeX key="(">(</TeX>,
1070
- <InputComponent
1071
- key="point_x"
1072
- // eslint-disable-next-line react/no-string-refs
1073
- ref="x"
1074
- placeholder={0}
1075
- value={this.state.center[0]}
1076
- useArrowKeys={true}
1077
- onChange={(val0) => {
1078
- const val1 = this.state.center[1];
1079
- this.setState({center: [val0, val1]}, () => {
1080
- this.props.onChange();
1081
- });
1082
- }}
1083
- onFocus={_.partial(this.props.onFocus, "x")}
1084
- onBlur={_.partial(this.props.onBlur, "x")}
1085
- keypadElement={this.props.keypadElement}
1086
- />,
1087
- <TeX key=",">{", {}"}</TeX>,
1088
- <InputComponent
1089
- key="point_y"
1090
- // eslint-disable-next-line react/no-string-refs
1091
- ref="y"
1092
- placeholder={0}
1093
- value={this.state.center[1]}
1094
- useArrowKeys={true}
1095
- onChange={(val1) => {
1096
- const val0 = this.state.center[0];
1097
- this.setState({center: [val0, val1]}, () => {
1098
- this.props.onChange();
1099
- });
1100
- }}
1101
- onFocus={_.partial(this.props.onFocus, "y")}
1102
- onBlur={_.partial(this.props.onBlur, "y")}
1103
- keypadElement={this.props.keypadElement}
1104
- />,
1105
- <TeX key=")">)</TeX>,
1106
- ];
1107
- const scale = (
1108
- <InputComponent
1109
- // eslint-disable-next-line react/no-string-refs
1110
- ref="scale"
1111
- placeholder={1}
1112
- value={this.state.scale}
1113
- useArrowKeys={true}
1114
- onChange={(val) => {
1115
- this.setState({scale: val}, () => {
1116
- this.props.onChange();
1117
- });
1118
- }}
1119
- onFocus={_.partial(this.props.onFocus, "scale")}
1120
- onBlur={_.partial(this.props.onBlur, "scale")}
1121
- keypadElement={this.props.keypadElement}
1122
- />
1123
- );
1124
- return (
1125
- <div>
1126
- {i18n.$_("Dilation about %(point)s by %(scale)s", {
1127
- point,
1128
- scale,
1129
- })}
1130
- </div>
1131
- );
1132
- }
1133
-
1134
- value = () => {
1135
- // eslint-disable-next-line react/no-string-refs
1136
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
1137
- const scale = this.refs.scale.getValue();
1138
- // eslint-disable-next-line react/no-string-refs
1139
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
1140
- const x = this.refs.x.getValue();
1141
- // eslint-disable-next-line react/no-string-refs
1142
- // @ts-expect-error - TS2339 - Property 'getValue' does not exist on type 'ReactInstance'.
1143
- const y = this.refs.y.getValue();
1144
- return {
1145
- scale: scale,
1146
- center: [x, y],
1147
- };
1148
- };
1149
-
1150
- /* InputPath API */
1151
- setInputValue = (path: any, value, cb: any) => {
1152
- const id = _.first(path);
1153
- let scale = this.state.scale;
1154
- const center = _.clone(this.state.center);
1155
- if (id === "x") {
1156
- center[0] = value;
1157
- } else if (id === "y") {
1158
- center[1] = value;
1159
- } else if (id === "scale") {
1160
- scale = value;
1161
- }
1162
- this.setState({scale: scale, center: center}, () => {
1163
- this.props.onChange(cb);
1164
- });
1165
- };
1166
-
1167
- getInputPaths = () => {
1168
- return [["x"], ["y"], ["scale"]];
1169
- };
1170
- },
1171
- },
1172
- } as const;
1173
-
1174
- /* Various functions to deal with different shape types */
1175
- const ShapeTypes = {
1176
- getPointCountForType: function (type) {
1177
- const splitType = type.split("-");
1178
- if (splitType[0] === "polygon") {
1179
- return splitType[1] || 3;
1180
- }
1181
- if (splitType[0] === "line" || splitType[0] === "lineSegment") {
1182
- return 2;
1183
- }
1184
- if (splitType[0] === "angle") {
1185
- return 3;
1186
- }
1187
- if (splitType[0] === "circle") {
1188
- return 2;
1189
- }
1190
- if (splitType[0] === "point") {
1191
- return 1;
1192
- }
1193
- },
1194
-
1195
- addMovableShape: function (graphie, options) {
1196
- if (options.editable && options.translatable) {
1197
- throw new PerseusError(
1198
- "It doesn't make sense to have a movable shape " +
1199
- "where you can stretch the points and translate them " +
1200
- "simultaneously. options: " +
1201
- JSON.stringify(options),
1202
- Errors.InvalidInput,
1203
- );
1204
- }
1205
-
1206
- const points = _.map(options.shape.coords, function (coord) {
1207
- let isMoving = false;
1208
- let previousCoord = coord;
1209
-
1210
- const onMove = function (x, y: any) {
1211
- if (!isMoving) {
1212
- previousCoord = currentPoint.coord;
1213
- isMoving = true;
1214
- }
1215
-
1216
- let moveVector = kvector.subtract([x, y], currentPoint.coord);
1217
-
1218
- // Translate from (x, y) semantics to (dX, dY) semantics
1219
- // This is more useful for translations on multiple points,
1220
- // where we care about how the points moved, not where any
1221
- // individual point ended up
1222
- if (options.onMove) {
1223
- moveVector = options.onMove(moveVector[0], moveVector[1]);
1224
- }
1225
-
1226
- // Perform a translation on all points in this shape when
1227
- // any point moves
1228
- if (options.translatable) {
1229
- _.each(points, function (point) {
1230
- // The point itself will be updated by the
1231
- // movablePoint class, so only translate the other
1232
- // points
1233
- if (point !== currentPoint) {
1234
- point.setCoord(
1235
- kvector.add(point.coord, moveVector),
1236
- );
1237
- }
1238
- });
1239
- }
1240
-
1241
- // Update our shape and our currentPoint
1242
- // Without this, some shapes (circles, angles) appear
1243
- // "bouncy" as they are updated with currentPoint at the
1244
- // current mouse coordinate (oldCoord), rather than newCoord
1245
- const oldCoord = currentPoint.coord;
1246
- const newCoord = kvector.add(currentPoint.coord, moveVector);
1247
- // Temporarily change our coordinate so that
1248
- // shape.update() sees the new coordinate
1249
- currentPoint.coord = newCoord;
1250
- shape.update();
1251
- // ...But don't break onMove, which assumes it
1252
- // is the only thing changing our coord
1253
- currentPoint.coord = oldCoord;
1254
- return newCoord;
1255
- };
1256
-
1257
- const onMoveEnd = function () {
1258
- // onMove isn't guaranteed to be called before onMoveEnd, so
1259
- // we have to take into account that we may not have moved and
1260
- // set previousCoord.
1261
- if (options.onMoveEnd && isMoving) {
1262
- isMoving = false;
1263
- // We don't use the supplied x and y parameters here
1264
- // because MovablePoint's onMoveEnd semantics suck.
1265
- // It returns the mouseX, mouseY without processing them
1266
- // through onMove, leaving us with weird fractional moves
1267
- const change = kvector.subtract(
1268
- currentPoint.coord,
1269
- previousCoord,
1270
- );
1271
- options.onMoveEnd(change[0], change[1]);
1272
- }
1273
- shape.update();
1274
- };
1275
-
1276
- const currentPoint = graphie.addMovablePoint({
1277
- coord: coord,
1278
- normalStyle: options.normalPointStyle,
1279
- highlightStyle: options.highlightPointStyle,
1280
- constraints: {
1281
- fixed: !options.translatable && !options.editable,
1282
- },
1283
- visible: options.showPoints,
1284
- snapX: (options.snap && options.snap[0]) || 0,
1285
- snapY: (options.snap && options.snap[1]) || 0,
1286
- bounded: false, // Don't bound it when placing it on the graph
1287
- onMove: onMove,
1288
- onMoveEnd: onMoveEnd,
1289
- });
1290
-
1291
- // Bound it when moving
1292
- // We can't set this earlier, because doing so would mean any
1293
- // points outside of the graph would be moved into a moved into
1294
- // a position that doesn't preserve the shape
1295
- currentPoint.bounded = true;
1296
-
1297
- return currentPoint;
1298
- });
1299
-
1300
- const shape = ShapeTypes.addShape(graphie, options, points);
1301
- const removeShapeWithoutPoints = shape.remove;
1302
- shape.remove = function () {
1303
- removeShapeWithoutPoints.apply(shape);
1304
- _.invoke(points, "remove");
1305
- };
1306
- return shape;
1307
- },
1308
-
1309
- addShape: function (graphie, options, points) {
1310
- points = points || options.shape.coords;
1311
-
1312
- const types = ShapeTypes._typesOf(options.shape);
1313
- const typeOptions =
1314
- options.shape.options || ShapeTypes.defaultOptions(types);
1315
-
1316
- // @ts-expect-error - TS2554 - Expected 4 arguments, but got 3.
1317
- const shapes = ShapeTypes._mapTypes(
1318
- types,
1319
- points,
1320
- function (type, points, i) {
1321
- const shapeOptions = _.extend({}, options, typeOptions[i]);
1322
- return ShapeTypes._addType(graphie, type, points, shapeOptions);
1323
- },
1324
- );
1325
-
1326
- const updateFuncs = _.filter(_.pluck(shapes, "update"), _.identity);
1327
- const update = function () {
1328
- _.invoke(updateFuncs, "call");
1329
- };
1330
-
1331
- const removeFuncs = _.filter(_.pluck(shapes, "remove"), _.identity);
1332
- const remove = function () {
1333
- _.invoke(removeFuncs, "call");
1334
- };
1335
-
1336
- const getOptions = function () {
1337
- return _.map(shapes, function (shape) {
1338
- if (shape.getOptions) {
1339
- return shape.getOptions();
1340
- }
1341
- return {};
1342
- });
1343
- };
1344
-
1345
- const toJSON = function () {
1346
- const coords = _.map(points, function (pt) {
1347
- if (_.isArray(pt)) {
1348
- return pt;
1349
- }
1350
- return pt.coord;
1351
- });
1352
- return {
1353
- type: types,
1354
- coords: coords,
1355
- options: getOptions(),
1356
- };
1357
- };
1358
-
1359
- return {
1360
- type: types,
1361
- points: points,
1362
- update: update,
1363
- remove: remove,
1364
- toJSON: toJSON,
1365
- getOptions: getOptions,
1366
- };
1367
- },
1368
-
1369
- equal: function (shape1, shape2) {
1370
- const types1 = ShapeTypes._typesOf(shape1);
1371
- const types2 = ShapeTypes._typesOf(shape2);
1372
- if (types1.length !== types2.length) {
1373
- return false;
1374
- }
1375
- // @ts-expect-error - TS2554 - Expected 4 arguments, but got 3.
1376
- const shapes1 = ShapeTypes._mapTypes(
1377
- types1,
1378
- shape1.coords,
1379
- ShapeTypes._combine,
1380
- );
1381
- // @ts-expect-error - TS2554 - Expected 4 arguments, but got 3.
1382
- const shapes2 = ShapeTypes._mapTypes(
1383
- types2,
1384
- shape2.coords,
1385
- ShapeTypes._combine,
1386
- );
1387
- return _.all(
1388
- _.map(shapes1, function (partialShape1, i) {
1389
- const partialShape2 = shapes2[i];
1390
- if (partialShape1.type !== partialShape2.type) {
1391
- return false;
1392
- }
1393
- return ShapeTypes._forType(partialShape1.type).equal(
1394
- partialShape1.coords,
1395
- partialShape2.coords,
1396
- );
1397
- }),
1398
- );
1399
- },
1400
-
1401
- _typesOf: function (shape) {
1402
- let types = shape.type;
1403
- if (!_.isArray(types)) {
1404
- types = [types];
1405
- }
1406
- return _.map(types, function (type) {
1407
- if (type === "polygon") {
1408
- return "polygon-3";
1409
- }
1410
- return type;
1411
- });
1412
- },
1413
-
1414
- defaultOptions: function (types) {
1415
- return _.map(types, function (type) {
1416
- const typeDefaultOptions = ShapeTypes._forType(type).defaultOptions;
1417
- return _.extend({}, typeDefaultOptions);
1418
- });
1419
- },
1420
-
1421
- _forType: function (type) {
1422
- const baseType = type.split("-")[0];
1423
- return ShapeTypes[baseType];
1424
- },
1425
-
1426
- _mapTypes: function (types, points, func, context) {
1427
- return _.map(types, function (type, i) {
1428
- const pointCount = ShapeTypes.getPointCountForType(type);
1429
- const currentPoints = _.first(points, pointCount);
1430
- points = _.rest(points, pointCount);
1431
- return func.call(context, type, currentPoints, i);
1432
- });
1433
- },
1434
-
1435
- _addType: function (graphie, type, points, options) {
1436
- const lineCoords = _.isArray(points[0])
1437
- ? {
1438
- coordA: points[0],
1439
- coordZ: points[1],
1440
- }
1441
- : {
1442
- pointA: points[0],
1443
- pointZ: points[1],
1444
- };
1445
-
1446
- type = type.split("-")[0];
1447
- if (type === "polygon") {
1448
- const polygon = graphie.addMovablePolygon(
1449
- _.extend({}, options, {
1450
- fixed: !options.editable,
1451
- snapX: (options.snap && options.snap[0]) || 0,
1452
- snapY: (options.snap && options.snap[1]) || 0,
1453
- points: points,
1454
- constrainToGraph: false,
1455
- }),
1456
- );
1457
- return {
1458
- update: polygon.transform.bind(polygon),
1459
- remove: polygon.remove.bind(polygon),
1460
- };
1461
- }
1462
- if (type === "line" || type === "lineSegment") {
1463
- const line = graphie.addMovableLineSegment(
1464
- _.extend({}, options, lineCoords, {
1465
- movePointsWithLine: true,
1466
- fixed: true,
1467
- constraints: {
1468
- fixed: true,
1469
- },
1470
- extendLine: type === "line",
1471
- }),
1472
- );
1473
-
1474
- // TODO(jack): Hide points on uneditable lines when translation
1475
- // is a vector.
1476
- // We can't just remove the points yet, because they are the
1477
- // translation handle for the line.
1478
- return {
1479
- update: line.transform.bind(line, true),
1480
- remove: line.remove.bind(line),
1481
- };
1482
- }
1483
- if (type === "angle") {
1484
- // If this angle is editable, we want to be able to make angles
1485
- // both larger and smaller than 180 degrees.
1486
- // If this angle is not editable, it should always maintain
1487
- // it's angle measure, even if it is reflected (causing the
1488
- // clockwise-ness of the points to change)
1489
- const shouldChangeReflexivity = options.editable ? null : false;
1490
-
1491
- const angle = graphie.addMovableAngle({
1492
- angleLabel: "$deg0",
1493
- fixed: true,
1494
- points: points,
1495
- normalStyle: options.normalStyle,
1496
- reflex: options.reflex,
1497
- });
1498
-
1499
- // Hide non-vertex points on uneditable angles
1500
- if (!_.isArray(points[0]) && !options.editable) {
1501
- points[0].remove();
1502
- points[2].remove();
1503
- }
1504
- return {
1505
- update: angle.update.bind(angle, shouldChangeReflexivity),
1506
- remove: angle.remove.bind(angle),
1507
- getOptions: function () {
1508
- return {
1509
- reflex: angle.isReflex(),
1510
- };
1511
- },
1512
- };
1513
- }
1514
- if (type === "circle") {
1515
- let perimeter = {
1516
- // temporary object for the first removal
1517
- remove: _.identity,
1518
- };
1519
- const redrawPerim = function () {
1520
- const coord0 = points[0].coord || points[0];
1521
- const coord1 = points[1].coord || points[1];
1522
- const radius = kpoint.distanceToPoint(coord0, coord1);
1523
- // @ts-expect-error - TS2554 - Expected 1 arguments, but got 0.
1524
- perimeter.remove();
1525
- perimeter = graphie.circle(
1526
- coord0,
1527
- radius,
1528
- _.extend(
1529
- {
1530
- stroke: KhanColors.DYNAMIC,
1531
- "stroke-width": 2,
1532
- },
1533
- options.normalStyle,
1534
- ),
1535
- );
1536
- };
1537
-
1538
- redrawPerim();
1539
- if (points[1].remove && !options.editable) {
1540
- points[1].remove();
1541
- }
1542
-
1543
- return {
1544
- update: redrawPerim,
1545
- remove: function () {
1546
- // Not _.bind because the remove function changes
1547
- // when the perimeter is redrawn
1548
- // @ts-expect-error - TS2554 - Expected 1 arguments, but got 0.
1549
- perimeter.remove();
1550
- },
1551
- };
1552
- }
1553
- if (type === "point") {
1554
- // do nothing
1555
- return {
1556
- update: null,
1557
- remove: null,
1558
- };
1559
- }
1560
- throw new PerseusError(
1561
- "Invalid shape type " + type,
1562
- Errors.InvalidInput,
1563
- );
1564
- },
1565
-
1566
- _combine: function (type, coords) {
1567
- return {
1568
- type: type,
1569
- coords: coords,
1570
- };
1571
- },
1572
-
1573
- polygon: {
1574
- equal: orderInsensitiveCoordsEqual,
1575
- },
1576
-
1577
- line: {
1578
- equal: kline.equal,
1579
- },
1580
-
1581
- lineSegment: {
1582
- equal: orderInsensitiveCoordsEqual,
1583
- },
1584
-
1585
- angle: {
1586
- equal: function (points1, points2) {
1587
- if (!kpoint.equal(points1[1], points2[1])) {
1588
- return false;
1589
- }
1590
-
1591
- const line1_0 = [points1[1], points1[0]];
1592
- const line1_2 = [points1[1], points1[2]];
1593
- const line2_0 = [points2[1], points2[0]];
1594
- const line2_2 = [points2[1], points2[2]];
1595
-
1596
- const equalUnflipped =
1597
- // @ts-expect-error - TS2345 - Argument of type 'any[]' is not assignable to parameter of type 'Ray'. | TS2345 - Argument of type 'any[]' is not assignable to parameter of type 'Ray'.
1598
- kray.equal(line1_0, line2_0) && kray.equal(line1_2, line2_2);
1599
- const equalFlipped =
1600
- // @ts-expect-error - TS2345 - Argument of type 'any[]' is not assignable to parameter of type 'Ray'. | TS2345 - Argument of type 'any[]' is not assignable to parameter of type 'Ray'.
1601
- kray.equal(line1_0, line2_2) && kray.equal(line1_2, line2_0);
1602
-
1603
- return equalUnflipped || equalFlipped;
1604
- },
1605
-
1606
- defaultOptions: {
1607
- reflex: false,
1608
- },
1609
- },
1610
-
1611
- circle: {
1612
- equal: function (points1, points2) {
1613
- const radius1 = kpoint.distanceToPoint(points1[0], points1[1]);
1614
- const radius2 = kpoint.distanceToPoint(points2[0], points2[1]);
1615
- return (
1616
- kpoint.equal(points1[0], points2[0]) &&
1617
- knumber.equal(radius1, radius2)
1618
- );
1619
- },
1620
- },
1621
-
1622
- point: {
1623
- equal: kpoint.equal,
1624
- },
1625
- } as const;
1626
-
1627
- const TransformationListItem = TransformOps.ListItem;
1628
-
1629
- class TransformationList extends React.Component<any, any> {
1630
- render(): React.ReactNode {
1631
- if (this.props.mode === "static") {
1632
- return <span />; // don't render anything
1633
- }
1634
-
1635
- const transformationList = _.map(
1636
- this.props.transformations,
1637
- function (transform, i) {
1638
- return (
1639
- <TransformationListItem
1640
- ref={"transformation" + i}
1641
- key={"transformation" + i}
1642
- transform={transform}
1643
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1644
- mode={this.props.mode}
1645
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1646
- onChange={this.handleChange}
1647
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1648
- onFocus={_.partial(this.props.onFocus, "" + i)}
1649
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1650
- onBlur={_.partial(this.props.onBlur, "" + i)}
1651
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1652
- keypadElement={this.props.keypadElement}
1653
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1654
- apiOptions={this.props.apiOptions}
1655
- />
1656
- );
1657
- },
1658
- this,
1659
- );
1660
-
1661
- return (
1662
- <div className="perseus-transformation-list">
1663
- {transformationList}
1664
- </div>
1665
- );
1666
- }
1667
-
1668
- _transformationRefs = () => {
1669
- return _.times(this.props.transformations.length, (i) => {
1670
- // eslint-disable-next-line react/no-string-refs
1671
- return this.refs["transformation" + i];
1672
- });
1673
- };
1674
-
1675
- value = () => {
1676
- return _.invoke(this._transformationRefs(), "value");
1677
- };
1678
-
1679
- handleChange = (changed: any, callback: any) => {
1680
- this.props.onChange(this.value(), callback);
1681
- };
1682
-
1683
- focusLast = () => {
1684
- const transformationRefs = this._transformationRefs();
1685
- if (transformationRefs.length !== 0) {
1686
- // @ts-expect-error - TS2532 - Object is possibly 'undefined'. | TS2339 - Property 'focus' does not exist on type 'ReactInstance'.
1687
- _.last(transformationRefs).focus();
1688
- }
1689
- };
1690
- }
1691
-
1692
- class ToolButton extends React.Component<any, any> {
1693
- render(): React.ReactNode {
1694
- const classes = this.props.toggled
1695
- ? "simple-button exercise-orange toggled highlighted-tool-button"
1696
- : "simple-button";
1697
-
1698
- return (
1699
- <button
1700
- type="button"
1701
- className={classes}
1702
- disabled={this.props.disabled}
1703
- onClick={this.props.onClick}
1704
- // @ts-expect-error - TS2322 - Type '(e: TouchEvent) => void' is not assignable to type 'TouchEventHandler<HTMLButtonElement>'.
1705
- onTouchStart={captureScratchpadTouchStart}
1706
- >
1707
- {this.props.children}
1708
- </button>
1709
- );
1710
- }
1711
- }
1712
-
1713
- class ToolsBar extends React.Component<any, any> {
1714
- state = {
1715
- selected: null,
1716
- };
1717
-
1718
- render(): React.ReactNode {
1719
- const tools = _.map(
1720
- Transformations,
1721
- function (tool, type) {
1722
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1723
- if (this.props.enabled[type]) {
1724
- return (
1725
- <ToolButton
1726
- key={type}
1727
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1728
- disabled={this.props.apiOptions.readOnly}
1729
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1730
- toggled={this.state.selected === type}
1731
- // eslint-disable-next-line react/jsx-no-bind
1732
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation. | TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1733
- onClick={this.changeSelected.bind(this, type)}
1734
- >
1735
- {tool.verbName}
1736
- </ToolButton>
1737
- );
1738
- }
1739
- },
1740
- this,
1741
- );
1742
-
1743
- return (
1744
- <div className="transformer-tools-bar">
1745
- <span className="simple-button-group">{tools}</span>
1746
- <button
1747
- className="transformer-undo-button simple-button"
1748
- type="button"
1749
- disabled={this.props.apiOptions.readOnly}
1750
- onClick={this.props.onUndoClick}
1751
- // @ts-expect-error - TS2322 - Type '(e: TouchEvent) => void' is not assignable to type 'TouchEventHandler<HTMLButtonElement>'.
1752
- onTouchStart={captureScratchpadTouchStart}
1753
- >
1754
- <InlineIcon {...iconUndo} />
1755
- {" " + i18n._("Undo")}
1756
- </button>
1757
- <div className="clear" />
1758
- </div>
1759
- );
1760
- }
1761
-
1762
- changeSelected = (tool) => {
1763
- this.props.removeTool(this.state.selected);
1764
-
1765
- if (!tool || tool === this.state.selected) {
1766
- this.setState({
1767
- selected: null,
1768
- });
1769
- } else {
1770
- this.props.addTool(tool);
1771
- this.setState({
1772
- selected: tool,
1773
- });
1774
- }
1775
- };
1776
- }
1777
-
1778
- class AddTransformBar extends React.Component<any, any> {
1779
- render(): React.ReactNode {
1780
- const tools = _.map(
1781
- Transformations,
1782
- function (tool, type) {
1783
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1784
- if (this.props.enabled[type]) {
1785
- return (
1786
- <ToolButton
1787
- key={type}
1788
- toggled={false}
1789
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1790
- disabled={this.props.apiOptions.readOnly}
1791
- // eslint-disable-next-line react/jsx-no-bind
1792
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation. | TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
1793
- onClick={this.changeSelected.bind(this, type)}
1794
- >
1795
- <InlineIcon {...iconPlus} /> {tool.nounName}
1796
- </ToolButton>
1797
- );
1798
- }
1799
- },
1800
- this,
1801
- );
1802
-
1803
- return (
1804
- <div className="transformer-tools-bar">
1805
- {tools}
1806
- <button
1807
- className="transformer-undo-button simple-button"
1808
- type="button"
1809
- onClick={this.props.onUndoClick}
1810
- disabled={this.props.apiOptions.readOnly}
1811
- // @ts-expect-error - TS2322 - Type '(e: TouchEvent) => void' is not assignable to type 'TouchEventHandler<HTMLButtonElement>'.
1812
- onTouchStart={captureScratchpadTouchStart}
1813
- >
1814
- <InlineIcon {...iconUndo} />
1815
- {" " + i18n._("Undo")}
1816
- </button>
1817
- <div className="clear" />
1818
- </div>
1819
- );
1820
- }
1821
-
1822
- changeSelected = (tool: any) => {
1823
- if (tool) {
1824
- this.props.addTool(tool);
1825
- }
1826
- };
1827
- }
1828
-
1829
- type Graphie = any;
1830
- type Tool = any;
1831
- type ToolCleanup = any;
1832
-
1833
- type Rubric = PerseusTransformerWidgetOptions;
1834
- type RenderProps = PerseusTransformerWidgetOptions; // there's no transform in the exports
1835
- type UserInput = any;
1836
- type Props = WidgetProps<RenderProps, Rubric> & {
1837
- transformations: ReadonlyArray<TransformerTransformation>;
1838
- keypadElement: any;
1839
- };
1840
-
1841
- class Transformer extends React.Component<Props> {
1842
- // @ts-expect-error - TS2564 - Property 'tools' has no initializer and is not definitely assigned in the constructor.
1843
- tools: {
1844
- [key: string]: Tool;
1845
- };
1846
- currentTool: Tool | null | undefined;
1847
- // @ts-expect-error - TS2564 - Property 'transformations' has no initializer and is not definitely assigned in the constructor.
1848
- transformations: ReadonlyArray<TransformerTransformation>;
1849
- shape: any | null | undefined; // This is not the same as TransformerShape
1850
- dilationCircle: any | null | undefined;
1851
- rotatePoint: any | null | undefined;
1852
- rotateHandle: any | null | undefined;
1853
-
1854
- static defaultProps: any = _.defaults(
1855
- {
1856
- transformations: [],
1857
- },
1858
- defaultTransformerProps,
1859
- );
1860
-
1861
- render(): React.ReactNode {
1862
- // Fill in any missing value in this.props.graph
1863
- // this can happen because the graph json doesn't include
1864
- // box, for example
1865
- const graph = _.extend(
1866
- defaultGraphProps(this.props.graph, defaultBoxSize),
1867
- this.props.graph,
1868
- );
1869
-
1870
- const interactiveToolsMode = this.props.graphMode === "interactive";
1871
-
1872
- const ToolsBarClass = interactiveToolsMode ? ToolsBar : AddTransformBar;
1873
-
1874
- // This style is applied inline because it is dependent on the
1875
- // size of the graph as set by the graph.box prop, and this also
1876
- // lets us specify it in the same place the graph's width is
1877
- // specified.
1878
- const toolsBar = (
1879
- <div style={{width: graph.box[0]}}>
1880
- <ToolsBarClass
1881
- // eslint-disable-next-line react/no-string-refs
1882
- ref="toolsBar"
1883
- enabled={pluckObject(this.props.tools, "enabled")}
1884
- apiOptions={this.props.apiOptions}
1885
- addTool={this.addTool}
1886
- removeTool={this.removeTool}
1887
- onUndoClick={this.handleUndoClick}
1888
- />
1889
- </div>
1890
- );
1891
-
1892
- return (
1893
- <div className={"perseus-widget " + "perseus-widget-transformer"}>
1894
- <Graph
1895
- // eslint-disable-next-line react/no-string-refs
1896
- ref="graph"
1897
- box={graph.box}
1898
- range={graph.range}
1899
- labels={graph.labels}
1900
- step={graph.step}
1901
- gridStep={graph.gridStep}
1902
- markings={graph.markings}
1903
- backgroundImage={graph.backgroundImage}
1904
- showProtractor={graph.showProtractor}
1905
- onGraphieUpdated={this.setupGraphie}
1906
- setDrawingAreaAvailable={
1907
- this.props.apiOptions.setDrawingAreaAvailable
1908
- }
1909
- />
1910
-
1911
- {!interactiveToolsMode && i18n._("Add transformations below:")}
1912
-
1913
- {this.props.graphMode === "static" && [
1914
- <br key="static-br" />,
1915
- <em key="static-nomove">
1916
- {" "}
1917
- {i18n._(
1918
- "Note: For this question, the shape will not move.",
1919
- )}{" "}
1920
- </em>,
1921
- ]}
1922
-
1923
- {interactiveToolsMode && toolsBar}
1924
-
1925
- <TransformationList
1926
- // eslint-disable-next-line react/no-string-refs
1927
- ref="transformationList"
1928
- mode={this.props.listMode}
1929
- transformations={this.props.transformations}
1930
- onChange={this.setTransformationProps}
1931
- onFocus={this._handleFocus}
1932
- onBlur={this._handleBlur}
1933
- keypadElement={this.props.keypadElement}
1934
- apiOptions={this.props.apiOptions}
1935
- />
1936
-
1937
- {!interactiveToolsMode && toolsBar}
1938
- </div>
1939
- );
1940
- }
1941
-
1942
- componentDidMount() {
1943
- this.setupGraphie(this.graphie());
1944
- }
1945
-
1946
- componentDidUpdate(prevProps: Props) {
1947
- if (this.shouldSetupGraphie(this.props, prevProps)) {
1948
- // eslint-disable-next-line react/no-string-refs
1949
- // @ts-expect-error - TS2339 - Property 'reset' does not exist on type 'ReactInstance'.
1950
- this.refs.graph.reset();
1951
- } else if (!deepEq(this.props.transformations, this.transformations)) {
1952
- this.setTransformations(this.props.transformations);
1953
- }
1954
- }
1955
-
1956
- shouldSetupGraphie: (arg1: Props, arg2: Props) => boolean = (
1957
- nextProps,
1958
- prevProps,
1959
- ) => {
1960
- if (!deepEq(prevProps.starting, nextProps.starting)) {
1961
- return true;
1962
- }
1963
- if (prevProps.graphMode !== nextProps.graphMode) {
1964
- return true;
1965
- }
1966
- if (prevProps.listMode !== nextProps.listMode) {
1967
- return true;
1968
- }
1969
- if (prevProps.drawSolutionShape !== nextProps.drawSolutionShape) {
1970
- return true;
1971
- }
1972
- if (
1973
- nextProps.drawSolutionShape &&
1974
- !deepEq(prevProps.correct.shape, nextProps.correct.shape)
1975
- ) {
1976
- return true;
1977
- }
1978
- if (!deepEq(this.tools, nextProps.tools)) {
1979
- return true;
1980
- }
1981
- return false;
1982
- };
1983
-
1984
- graphie: () => Graphie = () => {
1985
- // eslint-disable-next-line react/no-string-refs
1986
- // @ts-expect-error - TS2339 - Property 'graphie' does not exist on type 'ReactInstance'.
1987
- return this.refs.graph.graphie();
1988
- };
1989
-
1990
- setupGraphie: (arg1: Graphie) => void = (graphie) => {
1991
- // A background image of our solution:
1992
- if (
1993
- this.props.drawSolutionShape &&
1994
- this.props.correct.shape &&
1995
- this.props.correct.shape.coords
1996
- ) {
1997
- // @ts-expect-error - TS2554 - Expected 3 arguments, but got 2.
1998
- ShapeTypes.addShape(graphie, {
1999
- fixed: true,
2000
- shape: this.props.correct.shape,
2001
- normalStyle: {
2002
- stroke: KhanColors.GRAY,
2003
- "stroke-dasharray": "",
2004
- "stroke-width": 2,
2005
- },
2006
- });
2007
- }
2008
-
2009
- this.currentTool = null;
2010
- // eslint-disable-next-line react/no-string-refs
2011
- // @ts-expect-error - TS2339 - Property 'changeSelected' does not exist on type 'ReactInstance'.
2012
- this.refs.toolsBar.changeSelected(null);
2013
- this.addTransformerShape(
2014
- this.props.starting.shape,
2015
- /* translatable */ false,
2016
- );
2017
- this.setTransformations(this.props.transformations);
2018
-
2019
- // Save a copy of our tools so that we can check future
2020
- // this.props.tools changes against them
2021
- // This seems weird, but gives us an easy way to tell whether
2022
- // props changes were self-inflicted (for which a graphie reset
2023
- // is not required, and is in fact a bad idea right now because
2024
- // of resetting the size of the dilation tool).
2025
- // TODO (jack): A deepClone method would be nice here
2026
- this.tools = {
2027
- translation: _.clone(this.props.tools.translation),
2028
- rotation: _.clone(this.props.tools.rotation),
2029
- reflection: _.clone(this.props.tools.reflection),
2030
- dilation: _.clone(this.props.tools.dilation),
2031
- };
2032
- };
2033
-
2034
- /* Applies all transformations in `transformations`
2035
- * to the starting shape, and updates this.transformations
2036
- * to reflect this
2037
- *
2038
- * Usually called with this.props.transformations
2039
- */
2040
- setTransformations: (
2041
- arg1: ReadonlyArray<TransformerTransformation>,
2042
- ) => void = (transformations) => {
2043
- this.resetCoords();
2044
- this.transformations = _.clone(transformations);
2045
- _.each(this.transformations, this.applyTransform);
2046
- };
2047
-
2048
- // the polygon that we transform
2049
- addTransformerShape: (arg1: any, arg2: boolean) => void = (
2050
- shape,
2051
- translatable,
2052
- ) => {
2053
- const self = this;
2054
- const graphie = this.graphie();
2055
-
2056
- this.shape = ShapeTypes.addMovableShape(graphie, {
2057
- shape: shape,
2058
- editable: false,
2059
- showPoints: this.props.graphMode !== "static",
2060
- translatable: translatable,
2061
- onMove: function (dX, dY) {
2062
- dX = KhanMath.roundToNearest(graphie.snap[0], dX);
2063
- dY = KhanMath.roundToNearest(graphie.snap[1], dY);
2064
- // NOTE(kevinb): object is missing .constraints property
2065
- // @ts-expect-error - TS2345 - Argument of type '{ type: "translation"; vector: [any, any]; }' is not assignable to parameter of type 'PerseusTransformerTransformation'.
2066
- self.addTransform({
2067
- type: "translation",
2068
- vector: [dX, dY],
2069
- });
2070
- return [dX, dY];
2071
- },
2072
- normalPointStyle: {
2073
- fill: translatable
2074
- ? KhanColors.INTERACTIVE
2075
- : KhanColors.DYNAMIC,
2076
- stroke: translatable
2077
- ? KhanColors.INTERACTIVE
2078
- : KhanColors.DYNAMIC,
2079
- },
2080
- highlightPointStyle: {
2081
- fill: KhanColors.INTERACTING,
2082
- stroke: KhanColors.INTERACTING,
2083
- },
2084
- });
2085
- };
2086
-
2087
- addTool: (arg1: TransformerTransformation["type"]) => void = (toolId) => {
2088
- const self = this;
2089
-
2090
- if (this.props.graphMode === "interactive") {
2091
- if (toolId === "translation") {
2092
- this.currentTool = this.addTranslationTool();
2093
- } else if (toolId === "rotation") {
2094
- this.currentTool = this.addRotationTool();
2095
- } else if (toolId === "reflection") {
2096
- this.currentTool = this.addReflectionTool();
2097
- } else if (toolId === "dilation") {
2098
- this.currentTool = this.addDilationTool();
2099
- } else {
2100
- throw new PerseusError(
2101
- "Invalid tool id: " + toolId,
2102
- Errors.InvalidInput,
2103
- );
2104
- }
2105
- } else {
2106
- let transform: TransformerTransformation;
2107
- if (toolId === "translation") {
2108
- // NOTE(kevinb): object is missing .constraints property
2109
- transform = {
2110
- type: "translation",
2111
- // NOTE(kevib): these should be numbers
2112
- // @ts-expect-error - TS2322 - Type 'null' is not assignable to type 'number'. | TS2322 - Type 'null' is not assignable to type 'number'.
2113
- vector: [null, null],
2114
- };
2115
- } else if (toolId === "rotation") {
2116
- // NOTE(kevinb): object is missing .constraints property
2117
- transform = {
2118
- type: "rotation",
2119
- // NOTE(kevib): these should be numbers
2120
- // @ts-expect-error - TS2322 - Type 'null' is not assignable to type 'number'. | TS2322 - Type 'null' is not assignable to type 'number'.
2121
- center: [null, null],
2122
- // NOTE(kevib): this should be a number
2123
- // @ts-expect-error - TS2322 - Type 'null' is not assignable to type 'number'.
2124
- angleDeg: null,
2125
- };
2126
- } else if (toolId === "reflection") {
2127
- // Reflections with nulls in them won't be applied until
2128
- // fills in the blanks
2129
- transform = {
2130
- type: "reflection",
2131
- line: [
2132
- // NOTE(kevib): these should be numbers
2133
- // @ts-expect-error - TS2322 - Type 'null' is not assignable to type 'number'. | TS2322 - Type 'null' is not assignable to type 'number'.
2134
- [null, null],
2135
- // NOTE(kevib): these should be numbers
2136
- // @ts-expect-error - TS2322 - Type 'null' is not assignable to type 'number'. | TS2322 - Type 'null' is not assignable to type 'number'.
2137
- [null, null],
2138
- ],
2139
- };
2140
- } else if (toolId === "dilation") {
2141
- // NOTE(kevinb): object is missing .constraints property
2142
- transform = {
2143
- type: "dilation",
2144
- // NOTE(kevib): these should be numbers
2145
- // @ts-expect-error - TS2322 - Type 'null' is not assignable to type 'number'. | TS2322 - Type 'null' is not assignable to type 'number'.
2146
- center: [null, null],
2147
- // NOTE(kevib): this should be a number
2148
- // @ts-expect-error - TS2322 - Type 'null' is not assignable to type 'number'.
2149
- scale: null,
2150
- };
2151
- } else {
2152
- throw new PerseusError(
2153
- "Invalid tool id: " + toolId,
2154
- Errors.InvalidInput,
2155
- );
2156
- }
2157
-
2158
- this.doTransform(transform, function () {
2159
- // @ts-expect-error - TS2339 - Property 'focusLast' does not exist on type 'ReactInstance'.
2160
- self.refs.transformationList.focusLast();
2161
- });
2162
- }
2163
- };
2164
-
2165
- removeTool: (arg1: string) => void = (toolId) => {
2166
- if (this.currentTool) {
2167
- this.currentTool.remove();
2168
- }
2169
- this.currentTool = null;
2170
- };
2171
-
2172
- addTranslationTool: () => any = () => {
2173
- const self = this;
2174
- this.shape?.remove();
2175
- this.addTransformerShape(this.shape?.toJSON(), /* translatable */ true);
2176
-
2177
- return {
2178
- remove: function () {
2179
- self.shape?.remove();
2180
- self.addTransformerShape(
2181
- self.shape?.toJSON(),
2182
- /* translatable */ false,
2183
- );
2184
- },
2185
- };
2186
- };
2187
-
2188
- // Snaps a coord to this.graphie()'s snap
2189
- // @ts-expect-error - TS2322 - Type '(coord: Coord) => number[]' is not assignable to type '(arg1: Coord) => Coord'.
2190
- snapCoord: (arg1: Coord) => Coord = (coord) => {
2191
- const graphie = this.graphie();
2192
- return _.map(coord, function (val, dim) {
2193
- return KhanMath.roundToNearest(graphie.snap[dim], val);
2194
- });
2195
- };
2196
-
2197
- // Normalize the coords into something that fits the new 45 degree
2198
- // reflection line.
2199
- // @ts-expect-error - TS2322 - Type '(messyCoords: [Coord, Coord]) => any[]' is not assignable to type '(arg1: [Coord, Coord]) => [Coord, Coord]'.
2200
- normalizeReflectionCoords: (arg1: [Coord, Coord]) => [Coord, Coord] = (
2201
- messyCoords,
2202
- ) => {
2203
- // @ts-expect-error - TS2345 - Argument of type 'Point' is not assignable to parameter of type 'Coord'.
2204
- const midpoint = this.snapCoord(kline.midpoint(messyCoords));
2205
- const origDirectionPolar = kvector.polarDegFromCart(
2206
- kvector.subtract(messyCoords[0], messyCoords[1]),
2207
- );
2208
-
2209
- const direction = kvector.cartFromPolarDeg(
2210
- 1,
2211
- KhanMath.roundToNearest(45, origDirectionPolar[1]),
2212
- );
2213
- const coords = _.map(
2214
- [-1, 1],
2215
- function (directionCoefficient) {
2216
- const coord = kvector.add(
2217
- midpoint,
2218
- kvector.scale(
2219
- direction,
2220
- directionCoefficient *
2221
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
2222
- this.scaleToCurrentRange(
2223
- REFLECT_ROTATE_HANDLE_DIST,
2224
- ),
2225
- ),
2226
- );
2227
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
2228
- return this.snapCoord(coord);
2229
- },
2230
- this,
2231
- );
2232
- return coords;
2233
- };
2234
-
2235
- addReflectionTool: () => ToolCleanup = () => {
2236
- const options = this.props.tools.reflection;
2237
- if (!options.enabled) {
2238
- return;
2239
- }
2240
- const self = this;
2241
- // eslint-disable-next-line react/no-string-refs
2242
- // @ts-expect-error - TS2339 - Property 'graphie' does not exist on type 'ReactInstance'.
2243
- const graphie = this.refs.graph.graphie();
2244
-
2245
- const updateReflectionTool = function () {
2246
- self.changeTool("reflection", {
2247
- coords: _.pluck(reflectPoints, "coord"),
2248
- });
2249
- };
2250
-
2251
- const coords = this.normalizeReflectionCoords(options.coords);
2252
-
2253
- // The points defining the line of reflection; hidden from the
2254
- // user.
2255
- const reflectPoints = _.map(
2256
- coords,
2257
- function (coord) {
2258
- return graphie.addMovablePoint({
2259
- coord: coord,
2260
- visible: false,
2261
- });
2262
- },
2263
- this,
2264
- );
2265
-
2266
- // the line of reflection
2267
- // TODO(jack): graphie.style here is a hack to prevent the dashed
2268
- // style from leaking into the rest of the shapes. Remove when
2269
- // graphie.addMovableLineSegment doesn't leak styles anymore.
2270
- let reflectLine;
2271
- const normalColor = colorForTool(options);
2272
- graphie.style({}, function () {
2273
- reflectLine = graphie.addMovableLineSegment({
2274
- fixed: options.constraints.fixed,
2275
- constraints: options.constraints,
2276
- pointA: reflectPoints[0],
2277
- pointZ: reflectPoints[1],
2278
- snapX: graphie.snap[0],
2279
- snapY: graphie.snap[1],
2280
- extendLine: true,
2281
- normalStyle: {
2282
- stroke: normalColor,
2283
- "stroke-width": 2,
2284
- "stroke-dasharray": "- ",
2285
- },
2286
- highlightStyle: {
2287
- stroke: KhanColors.INTERACTING,
2288
- "stroke-width": 2,
2289
- "stroke-dasharray": "- ", // TODO(jack) solid doesn't
2290
- // work here, but would be
2291
- // nicer
2292
- },
2293
- movePointsWithLine: true,
2294
- onMoveEnd: updateReflectionTool,
2295
- });
2296
- });
2297
-
2298
- // the "button" point in the center of the line of reflection
2299
- const reflectButton = graphie.addReflectButton({
2300
- fixed: options.constraints.fixed,
2301
- line: reflectLine,
2302
- size: this.scaleToCurrentRange(REFLECT_BUTTON_SIZE),
2303
- onClick: function () {
2304
- self.doTransform({
2305
- type: "reflection",
2306
- // @ts-expect-error - TS2322 - Type 'any[]' is not assignable to type '[Coord, Coord]'.
2307
- line: _.pluck(reflectPoints, "coord"),
2308
- });
2309
- if (reflectRotateHandle) {
2310
- // flip the rotation handle
2311
- // @ts-expect-error - TS2339 - Property 'setCoord' does not exist on type 'never'.
2312
- reflectRotateHandle.setCoord(
2313
- kvector.add(
2314
- reflectButton.coord,
2315
- kvector.subtract(
2316
- reflectButton.coord,
2317
- // @ts-expect-error - TS2339 - Property 'coord' does not exist on type 'never'.
2318
- reflectRotateHandle.coord,
2319
- ),
2320
- ),
2321
- );
2322
- // @ts-expect-error - TS2339 - Property 'update' does not exist on type 'never'.
2323
- reflectRotateHandle.update();
2324
- }
2325
- },
2326
- normalStyle: {
2327
- stroke: normalColor,
2328
- "stroke-width": 2,
2329
- fill: normalColor,
2330
- },
2331
- highlightStyle: {
2332
- stroke: KhanColors.INTERACTING,
2333
- "stroke-width": 3,
2334
- fill: KhanColors.INTERACTING,
2335
- },
2336
- onMoveEnd: updateReflectionTool,
2337
- });
2338
-
2339
- let reflectRotateHandle = null;
2340
- if (!options.constraints.fixed) {
2341
- // The rotation handle for rotating the line of reflection
2342
- const initRotateHandleAngle =
2343
- kvector.polarDegFromCart(
2344
- kvector.subtract(
2345
- reflectPoints[1].coord,
2346
- reflectPoints[0].coord,
2347
- ),
2348
- )[1] + 90; // 90 degrees off of the line
2349
- reflectRotateHandle = graphie.addRotateHandle({
2350
- center: reflectButton,
2351
- radius: this.scaleToCurrentRange(REFLECT_ROTATE_HANDLE_DIST),
2352
- angleDeg: initRotateHandleAngle,
2353
- width: this.scaleToCurrentRange(0.24),
2354
- hoverWidth: this.scaleToCurrentRange(0.4),
2355
- lengthAngle: 17,
2356
- onMove: function (newAngle) {
2357
- return KhanMath.roundToNearest(45, newAngle);
2358
- },
2359
- onMoveEnd: updateReflectionTool,
2360
- });
2361
- }
2362
-
2363
- // Move the reflectButton and reflectRotateHandle with the line
2364
- $(reflectLine).on("move", function () {
2365
- reflectButton.update();
2366
- $(reflectButton).trigger("move"); // update the rotation handle,
2367
- // which watches for this in util/interactive.js.
2368
- });
2369
-
2370
- // Update the line and reflect button when the reflectRotateHandle is
2371
- // rotated
2372
- if (reflectRotateHandle) {
2373
- $(reflectRotateHandle).on("move", function () {
2374
- const rotateHandleApprox = self.snapCoord(
2375
- // @ts-expect-error - TS2531 - Object is possibly 'null'.
2376
- reflectRotateHandle.coord,
2377
- );
2378
-
2379
- const rotateVector = kvector.subtract(
2380
- rotateHandleApprox,
2381
- reflectButton.coord,
2382
- );
2383
-
2384
- const flipped = reflectButton.isFlipped() ? 1 : 0;
2385
- reflectPoints[flipped].setCoord(
2386
- kvector.add(
2387
- reflectButton.coord,
2388
- kvector.rotateDeg(rotateVector, 90),
2389
- ),
2390
- );
2391
- reflectPoints[1 - flipped].setCoord(
2392
- kvector.add(
2393
- reflectButton.coord,
2394
- kvector.rotateDeg(rotateVector, -90),
2395
- ),
2396
- );
2397
-
2398
- reflectLine.transform(true);
2399
- reflectButton.update();
2400
- });
2401
- }
2402
-
2403
- return {
2404
- remove: function () {
2405
- reflectButton.remove();
2406
- if (reflectRotateHandle) {
2407
- // @ts-expect-error - TS2339 - Property 'remove' does not exist on type 'never'.
2408
- reflectRotateHandle.remove();
2409
- }
2410
- reflectLine.remove();
2411
- reflectPoints[0].remove();
2412
- reflectPoints[1].remove();
2413
- },
2414
- };
2415
- };
2416
-
2417
- /* Scales a distance from the default range of
2418
- * [-10, 10] to the current this.props.graph.range
2419
- *
2420
- * Used for sizing various transformation tools
2421
- * (rotation handle, dilation circle)
2422
- */
2423
- scaleToCurrentRange: (arg1: number) => number = (dist) => {
2424
- // eslint-disable-next-line react/no-string-refs
2425
- // @ts-expect-error - TS2339 - Property 'props' does not exist on type 'ReactInstance'.
2426
- return scaleToRange(dist, this.refs.graph.props.range);
2427
- };
2428
-
2429
- addRotationTool: () => ToolCleanup = () => {
2430
- const options = this.props.tools.rotation;
2431
- if (!options.enabled) {
2432
- return;
2433
- }
2434
- const self = this;
2435
- // eslint-disable-next-line react/no-string-refs
2436
- // @ts-expect-error - TS2339 - Property 'graphie' does not exist on type 'ReactInstance'.
2437
- const graphie = this.refs.graph.graphie();
2438
-
2439
- const pointColor = colorForTool(options);
2440
- // The center of our rotation, which can be moved to change the
2441
- // center of rotation
2442
- this.rotatePoint = graphie.addMovablePoint({
2443
- constraints: options.constraints,
2444
- coord: options.coord,
2445
- snapX: graphie.snap[0],
2446
- snapY: graphie.snap[1],
2447
- normalStyle: {
2448
- // ugh, this seems to be a global and
2449
- "stroke-dasharray": "", // is set to dash above
2450
- stroke: pointColor,
2451
- fill: pointColor,
2452
- },
2453
- highlightStyle: {
2454
- "stroke-dasharray": "",
2455
- stroke: KhanColors.INTERACTING,
2456
- fill: KhanColors.INTERACTING,
2457
- },
2458
- });
2459
-
2460
- // The point that we move around the center of rotation to actually
2461
- // cause rotations
2462
- this.rotateHandle = graphie.addRotateHandle({
2463
- center: this.rotatePoint,
2464
- radius: this.scaleToCurrentRange(ROTATE_HANDLE_DIST),
2465
- width: this.scaleToCurrentRange(0.24),
2466
- hoverWidth: this.scaleToCurrentRange(0.4),
2467
- onMove: function (newAngle, oldAngle) {
2468
- const transform = self.getRotationTransformFromAngle(
2469
- self.rotatePoint.coord,
2470
- newAngle - oldAngle,
2471
- );
2472
-
2473
- // Rotate polygon with rotateHandle
2474
- self.doTransform(transform);
2475
-
2476
- // @ts-expect-error - TS2339 - Property 'angleDeg' does not exist on type 'PerseusTransformerTransformation'.
2477
- return oldAngle + transform.angleDeg;
2478
- },
2479
- });
2480
-
2481
- // Update tools.rotation.coord
2482
- this.rotatePoint.onMoveEnd = (x: any, y: any) => {
2483
- self.changeTool("rotation", {
2484
- coord: [x, y],
2485
- });
2486
- };
2487
-
2488
- return {
2489
- remove: function () {
2490
- self.rotateHandle?.remove();
2491
- self.rotatePoint?.remove();
2492
- },
2493
- };
2494
- };
2495
-
2496
- addDilationTool: () => ToolCleanup = () => {
2497
- const options = this.props.tools.dilation;
2498
- if (!options.enabled) {
2499
- return;
2500
- }
2501
- const self = this;
2502
- // eslint-disable-next-line react/no-string-refs
2503
- // @ts-expect-error - TS2339 - Property 'graphie' does not exist on type 'ReactInstance'.
2504
- const graphie = this.refs.graph.graphie();
2505
-
2506
- const pointColor = colorForTool(options);
2507
- // the circle for causing dilation transforms
2508
- self.dilationCircle = graphie.addCircleGraph({
2509
- centerConstraints: options.constraints,
2510
- center: options.coord,
2511
- radius: self.scaleToCurrentRange(2),
2512
- snapX: graphie.snap[0],
2513
- snapY: graphie.snap[1],
2514
- minRadius: self.scaleToCurrentRange(1),
2515
- snapRadius: self.scaleToCurrentRange(0.5),
2516
- onResize: function (newRadius, oldRadius) {
2517
- // NOTE(kevinb): object is missing .constraints property
2518
- // @ts-expect-error - TS2345 - Argument of type '{ type: "dilation"; center: any; scale: number; }' is not assignable to parameter of type 'PerseusTransformerTransformation'.
2519
- self.doTransform({
2520
- type: "dilation",
2521
- center: self.dilationCircle.centerPoint.coord,
2522
- scale: newRadius / oldRadius,
2523
- });
2524
- },
2525
- circleNormalStyle: {
2526
- stroke: pointColor,
2527
- "stroke-width": 2,
2528
- "stroke-dasharray": "- ",
2529
- "fill-opacity": 0,
2530
- },
2531
- circleHighlightStyle: {
2532
- stroke: KhanColors.INTERACTING,
2533
- "stroke-width": 2,
2534
- "stroke-dasharray": "",
2535
- fill: KhanColors.INTERACTING,
2536
- "fill-opacity": 0.05,
2537
- },
2538
- centerNormalStyle: {
2539
- stroke: pointColor,
2540
- fill: pointColor,
2541
- "stroke-width": 2,
2542
- "stroke-dasharray": "",
2543
- },
2544
- centerHighlightStyle: {
2545
- stroke: pointColor,
2546
- fill: pointColor,
2547
- "stroke-width": 2,
2548
- "stroke-dasharray": "",
2549
- },
2550
- });
2551
-
2552
- const origOnMoveEnd = this.dilationCircle.centerPoint.onMoveEnd;
2553
- this.dilationCircle.centerPoint.onMoveEnd = (...args) => {
2554
- if (origOnMoveEnd) {
2555
- origOnMoveEnd(args);
2556
- }
2557
- self.changeTool("dilation", {
2558
- coord: self.dilationCircle.centerPoint.coord,
2559
- });
2560
- };
2561
-
2562
- return {
2563
- remove: function () {
2564
- self.dilationCircle?.remove();
2565
- },
2566
- };
2567
- };
2568
-
2569
- // returns a transformation object representing a rotation
2570
- // rounds the angle to the nearest 15 degrees
2571
- // @ts-expect-error - TS2322 - Type '(center: Coord, angleChanged: number) => { type: "rotation"; center: Coord; angleDeg: number; }' is not assignable to type '(arg1: Coord, arg2: number) => PerseusTransformerTransformation'.
2572
- getRotationTransformFromAngle: (
2573
- arg1: Coord,
2574
- arg2: number,
2575
- ) => TransformerTransformation = (center, angleChanged) => {
2576
- angleChanged = (angleChanged + 360) % 360;
2577
- if (angleChanged > 180) {
2578
- angleChanged -= 360;
2579
- }
2580
- const roundedAngle =
2581
- Math.round(angleChanged / ROTATE_SNAP_DEGREES) *
2582
- ROTATE_SNAP_DEGREES;
2583
-
2584
- // NOTE(kevinb): return object is missing .constraints property
2585
- return {
2586
- type: "rotation",
2587
- center: center,
2588
- angleDeg: roundedAngle,
2589
- };
2590
- };
2591
-
2592
- // apply and save a transform
2593
- doTransform: (
2594
- arg1: TransformerTransformation,
2595
- arg2?: (arg1: any) => unknown | null | undefined,
2596
- ) => void = (transform, callback) => {
2597
- this.applyTransform(transform);
2598
- this.addTransform(transform, callback);
2599
- };
2600
-
2601
- // apply a transform to our polygon (without modifying our transformation
2602
- // list)
2603
- applyTransform: (arg1: TransformerTransformation) => void = (transform) => {
2604
- if (this.props.graphMode !== "static") {
2605
- const transformFunc = TransformOps.apply(transform);
2606
- // @ts-expect-error - TS2345 - Argument of type '(coord: any) => any' is not assignable to parameter of type 'PerseusTransformerTransformation'.
2607
- this.applyCoordTransformation(transformFunc);
2608
- }
2609
- };
2610
-
2611
- // transform our polygon by transforming each point using a given function
2612
- applyCoordTransformation: (arg1: TransformerTransformation) => void = (
2613
- pointTransform,
2614
- ) => {
2615
- _.each(this.shape.points, function (point) {
2616
- // @ts-expect-error - TS2349 - This expression is not callable.
2617
- const newCoord = pointTransform(point.coord);
2618
- point.setCoord(newCoord);
2619
- });
2620
- this.shape?.update();
2621
- };
2622
-
2623
- resetCoords: () => void = () => {
2624
- const startCoords = this.props.starting.shape.coords;
2625
- _.each(this.shape.points, function (point, i) {
2626
- point.setCoord(startCoords[i]);
2627
- });
2628
- this.shape?.update();
2629
- };
2630
-
2631
- // Remove the last transformation
2632
- handleUndoClick: () => void = () => {
2633
- // eslint-disable-next-line react/no-string-refs
2634
- // @ts-expect-error - TS2339 - Property 'changeSelected' does not exist on type 'ReactInstance'.
2635
- this.refs.toolsBar.changeSelected(null);
2636
- if (this.props.transformations.length) {
2637
- this.props.onChange({
2638
- transformations: _.initial(this.props.transformations),
2639
- });
2640
- }
2641
- };
2642
-
2643
- setTransformationProps: (
2644
- arg1: ReadonlyArray<TransformerTransformation>,
2645
- arg2: (arg1: any) => unknown,
2646
- ) => void = (newTransfomationList, callback) => {
2647
- this.props.onChange(
2648
- {
2649
- transformations: newTransfomationList,
2650
- },
2651
- // @ts-expect-error - TS2345 - Argument of type '(arg1: any) => unknown' is not assignable to parameter of type '() => unknown'.
2652
- callback,
2653
- );
2654
- };
2655
-
2656
- // add a transformation to our props list of transformation
2657
- addTransform: (
2658
- arg1: TransformerTransformation,
2659
- arg2?: (arg1: any) => unknown | null | undefined,
2660
- ) => void = (transform, callback) => {
2661
- this.transformations = TransformOps.append(
2662
- this.transformations,
2663
- transform,
2664
- );
2665
- this.props.onChange(
2666
- {
2667
- transformations: _.clone(this.transformations),
2668
- },
2669
- // @ts-expect-error - TS2345 - Argument of type '((arg1: any) => unknown) | undefined' is not assignable to parameter of type '(() => unknown) | undefined'.
2670
- callback,
2671
- );
2672
- };
2673
-
2674
- changeTool: (arg1: Tool, arg2: any) => void = (tool, changes) => {
2675
- const newTools = _.clone(this.props.tools);
2676
- newTools[tool] = _.extend({}, this.props.tools[tool], changes);
2677
- this.tools[tool] = _.clone(newTools[tool]);
2678
- this.props.onChange({
2679
- // @ts-expect-error - TS2740 - Type '{ dilation: DilationTool; reflection: ReflectionTool; rotation: RotationTool; translation: TranslationTool; }' is missing the following properties from type 'readonly any[]': length, concat, join, slice, and 18 more.
2680
- tools: newTools,
2681
- });
2682
- this.props.trackInteraction();
2683
- };
2684
-
2685
- simpleValidate: (arg1: Rubric) => PerseusScore = (rubric) => {
2686
- return Transformer.validate(this.getUserInput(), rubric);
2687
- };
2688
-
2689
- /**
2690
- * Calculate where the coordinates would be if they were
2691
- * moved, even if we're in formal mode with no movement
2692
- * (and thus the actual movablepoints may not have moved
2693
- */
2694
- // @ts-expect-error - TS2322 - Type '() => [Coord, Coord] | readonly Coord[] | [Coord, Coord, Coord]' is not assignable to type '() => Coord'.
2695
- getCoords: () => Coord = () => {
2696
- const startCoords = this.props.starting.shape.coords;
2697
- const transforms = this.props.transformations;
2698
- return _.reduce(
2699
- transforms,
2700
- function (coords, transform) {
2701
- return _.map(coords, TransformOps.apply(transform));
2702
- },
2703
- startCoords,
2704
- );
2705
- };
2706
-
2707
- getEditorJSON: () => any = () => {
2708
- const json = _.pick(
2709
- this.props,
2710
- "grading",
2711
- "starting",
2712
- "graphMode",
2713
- "listMode",
2714
- "tools",
2715
- "drawSolutionShape",
2716
- "gradeEmpty",
2717
- );
2718
- // eslint-disable-next-line react/no-string-refs
2719
- // @ts-expect-error - TS2339 - Property 'graph' does not exist on type 'Pick<Readonly<Props> & Readonly<{ children?: ReactNode; }>, "tools" | "starting" | "drawSolutionShape" | "gradeEmpty" | "graphMode" | "listMode">'. | TS2339 - Property 'toJSON' does not exist on type 'ReactInstance'.
2720
- json.graph = this.refs.graph.toJSON();
2721
- // @ts-expect-error - TS2339 - Property 'version' does not exist on type 'Pick<Readonly<Props> & Readonly<{ children?: ReactNode; }>, "tools" | "starting" | "drawSolutionShape" | "gradeEmpty" | "graphMode" | "listMode">'.
2722
- json.version = 1.2; // Give us some safety to change the format
2723
- // when we realize that I wrote
2724
- // a horrible json spec for this widget
2725
-
2726
- // @ts-expect-error - TS2339 - Property 'answer' does not exist on type 'Pick<Readonly<Props> & Readonly<{ children?: ReactNode; }>, "tools" | "starting" | "drawSolutionShape" | "gradeEmpty" | "graphMode" | "listMode">'.
2727
- json.answer = this.getUserInput();
2728
- return json;
2729
- };
2730
-
2731
- getUserInput: UserInput = () => {
2732
- return {
2733
- transformations: this.props.transformations,
2734
- // This doesn't call this.shape.toJSON() because that doesn't
2735
- // handle coordinates in formal mode without movement, since
2736
- // the movablepoints never move
2737
- shape: {
2738
- type: this.shape.type,
2739
- coords: this.getCoords(),
2740
- options: this.shape?.getOptions(),
2741
- },
2742
- };
2743
- };
2744
-
2745
- /* InputPath API */
2746
-
2747
- _handleFocus: (...rest: ReadonlyArray<string>) => void = (...path) => {
2748
- this.props.onFocus(path);
2749
- };
2750
-
2751
- _handleBlur: (...rest: ReadonlyArray<string>) => void = (...path) => {
2752
- this.props.onBlur(path);
2753
- };
2754
-
2755
- _getTransformationForID: (arg1: string) => any = (transformationID) => {
2756
- // Returns the 'transformation' component corresponding to a given ID
2757
- const refPath = [
2758
- "transformationList",
2759
- "transformation" + transformationID,
2760
- ];
2761
-
2762
- // Follow the path of references
2763
- let component = this;
2764
- _.each(refPath, (ref) => {
2765
- // @ts-expect-error - TS2322 - Type 'ReactInstance' is not assignable to type 'this'.
2766
- component = component.refs[ref];
2767
- });
2768
- return component;
2769
- };
2770
-
2771
- getInputPaths: () => ReadonlyArray<Path> = () => {
2772
- // If we're in static mode, then there is no transformation list, and,
2773
- // as a result, no input paths.
2774
- if (this.props.listMode === "static") {
2775
- return [];
2776
- }
2777
-
2778
- let inputPaths: Array<never> | Array<any> = [];
2779
- _.each(this.props.transformations, (transformation, i) => {
2780
- // @ts-expect-error - TS2345 - Argument of type 'number' is not assignable to parameter of type 'string'.
2781
- transformation = this._getTransformationForID(i);
2782
- // @ts-expect-error - TS2339 - Property 'getInputPaths' does not exist on type 'PerseusTransformerTransformation'.
2783
- const innerPaths = transformation.getInputPaths();
2784
- const fullPaths = _.map(innerPaths, (innerPath) => {
2785
- return ["" + i].concat(innerPath);
2786
- });
2787
- // @ts-expect-error - TS2345 - Argument of type 'string[][]' is not assignable to parameter of type 'ConcatArray<never>'.
2788
- inputPaths = inputPaths.concat(fullPaths);
2789
- });
2790
- return inputPaths;
2791
- };
2792
-
2793
- _passToInner: (
2794
- arg1: string,
2795
- arg2: ReadonlyArray<string>,
2796
- arg3?: any | null | undefined,
2797
- arg4?: (arg1: any) => unknown | null | undefined,
2798
- ) => any = function (functionName, path, ...args) {
2799
- if (!path || !path.length) {
2800
- return;
2801
- }
2802
-
2803
- // First argument tells us which transformation will receive the call;
2804
- // remaining arguments are used within that transformation to identify
2805
- // a specific input.
2806
- const innerPath = _.rest(path);
2807
-
2808
- // Pass arguments down to appropriate 'transformation' component
2809
- const transformationID = _.head(path);
2810
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
2811
- const caller = this._getTransformationForID(transformationID);
2812
- return caller[functionName](innerPath, ...args);
2813
- };
2814
-
2815
- focus: () => boolean = () => {
2816
- // Just focus the first showing input
2817
- const inputs = this.getInputPaths();
2818
- if (inputs.length > 0) {
2819
- this.focusInputPath(inputs[0]);
2820
- return true;
2821
- }
2822
- return false;
2823
- };
2824
-
2825
- focusInputPath: (arg1: Path) => boolean = (path) => {
2826
- // Since the transformer exposes the input API, it needs to be robust
2827
- // to empty paths. We don't expect this to happen, as entire-widget
2828
- // focusing is typically done through the focus() method, which already
2829
- // handles the empty path case properly, but it's better to be safe
2830
- // here.
2831
- if (path.length === 0) {
2832
- return false;
2833
- }
2834
-
2835
- assert(path.length >= 2);
2836
- return this._passToInner("focusInputPath", path);
2837
- };
2838
-
2839
- blurInputPath: (arg1: Path) => boolean = (path) => {
2840
- // Since the transformer exposes the input API, it needs to be robust
2841
- // to empty paths (which indicate a blurring of the entire widget,
2842
- // e.g., when switching from interacting with the transformer to
2843
- // interacting with some other widget).
2844
- if (path.length === 0) {
2845
- return false;
2846
- }
2847
-
2848
- assert(path.length >= 2);
2849
- return this._passToInner("blurInputPath", path);
2850
- };
2851
-
2852
- setInputValue: (
2853
- arg1: Path,
2854
- arg2: any,
2855
- arg3: (arg1: any) => unknown,
2856
- ) => any = (path, value, cb) => {
2857
- assert(path.length >= 2);
2858
- return this._passToInner("setInputValue", path, value, cb);
2859
- };
2860
-
2861
- getDOMNodeForPath: (arg1: Path) => any = (path) => {
2862
- assert(path.length >= 2);
2863
- return this._passToInner("getDOMNodeForPath", path);
2864
- };
2865
-
2866
- getGrammarTypeForPath: (arg1: Path) => any = (path) => {
2867
- assert(path.length >= 2);
2868
- return this._passToInner("getGrammarTypeForPath", path);
2869
- };
2870
-
2871
- static validate(guess: UserInput, rubric: Rubric): PerseusScore {
2872
- // Check for any required transformations
2873
- for (const type in Transformations) {
2874
- if (rubric.tools[type].required) {
2875
- const isUsed = _.any(
2876
- _.map(guess.transformations, function (transform) {
2877
- // Required transformations must appear in the
2878
- // transformation list, and must not be no-ops
2879
- return (
2880
- transform.type === type &&
2881
- !TransformOps.isEmpty(transform) &&
2882
- !TransformOps.isNoOp(transform)
2883
- );
2884
- }),
2885
- );
2886
-
2887
- if (!isUsed) {
2888
- return {
2889
- type: "invalid",
2890
- message: i18n._(
2891
- "Your transformation must use a " + "%(type)s.",
2892
- {
2893
- type: Transformations[type].lowerNounName,
2894
- },
2895
- ),
2896
- };
2897
- }
2898
- }
2899
- }
2900
-
2901
- // Compare shapes
2902
- if (ShapeTypes.equal(guess.shape, rubric.correct.shape)) {
2903
- return {
2904
- type: "points",
2905
- earned: 1,
2906
- total: 1,
2907
- message: null,
2908
- };
2909
- }
2910
- if (
2911
- !rubric.gradeEmpty &&
2912
- deepEq(guess.shape.coords, rubric.starting.shape.coords)
2913
- ) {
2914
- return {
2915
- type: "invalid",
2916
- message: i18n._(
2917
- "Use the interactive graph to define a " +
2918
- "correct transformation.",
2919
- ),
2920
- };
2921
- }
2922
- return {
2923
- type: "points",
2924
- earned: 0,
2925
- total: 1,
2926
- message: null,
2927
- };
2928
- }
2929
- }
2930
-
2931
- export default {
2932
- name: "transformer",
2933
- displayName: "Transformer (deprecated)",
2934
- hidden: true,
2935
- widget: Transformer,
2936
- } as WidgetExports<typeof Transformer>;