@khanacademy/perseus 20.6.0 → 20.7.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.
package/dist/index.js CHANGED
@@ -18894,7 +18894,7 @@ const isAccessible = widgetInfo => {
18894
18894
  }
18895
18895
  return !!accessible;
18896
18896
  };
18897
- const getAllWidgetTypes = () => {
18897
+ const getAllWidgetTypes$1 = () => {
18898
18898
  return ___default["default"].keys(widgets);
18899
18899
  };
18900
18900
  const upgradeWidgetInfoToLatestVersion = oldWidgetInfo => {
@@ -19166,7 +19166,7 @@ var widgets$1 = /*#__PURE__*/Object.freeze({
19166
19166
  getVersionVector: getVersionVector,
19167
19167
  getPublicWidgets: getPublicWidgets,
19168
19168
  isAccessible: isAccessible,
19169
- getAllWidgetTypes: getAllWidgetTypes,
19169
+ getAllWidgetTypes: getAllWidgetTypes$1,
19170
19170
  upgradeWidgetInfoToLatestVersion: upgradeWidgetInfoToLatestVersion,
19171
19171
  getRendererPropsForWidgetInfo: getRendererPropsForWidgetInfo,
19172
19172
  traverseChildWidgets: traverseChildWidgets$3,
@@ -28320,22 +28320,55 @@ const GraphLockedLayer = props => {
28320
28320
  };
28321
28321
 
28322
28322
  const MOVE_CONTROL_POINT = "move-control-point";
28323
- function moveControlPoint(objectIndex, pointIndex, destination) {
28323
+ function moveControlPoint(pointIndex, destination, itemIndex) {
28324
28324
  return {
28325
28325
  type: MOVE_CONTROL_POINT,
28326
- objectIndex,
28326
+ itemIndex,
28327
28327
  pointIndex,
28328
28328
  destination
28329
28329
  };
28330
28330
  }
28331
+ const MOVE_ALL = "move-all";
28331
28332
  const MOVE_LINE = "move-line";
28332
- function moveSegment(lineIndex, delta) {
28333
+ /** This action assumes the state.coords holds an array of collinear tuples that define lines */
28334
+ function moveLine(itemIndex, delta) {
28333
28335
  return {
28334
28336
  type: MOVE_LINE,
28335
- lineIndex,
28337
+ itemIndex,
28336
28338
  delta
28337
28339
  };
28338
28340
  }
28341
+ /** This action assumes a flat array of vectors */
28342
+ const moveAll = delta => ({
28343
+ type: MOVE_ALL,
28344
+ delta
28345
+ });
28346
+
28347
+ /**
28348
+ * 44 is touch best practice and AAA compliant for WCAG
28349
+ * https://www.w3.org/WAI/WCAG21/Understanding/target-size.html
28350
+ */
28351
+ const TARGET_SIZE = 44;
28352
+
28353
+ // same as pointsFromNormalized in interactive-graph.tsx
28354
+ const normalizePoints = (range, step, coordsList, noSnap) => coordsList.map(coords =>
28355
+ // maps over [x, y]
28356
+ coords.map((coord, i) => {
28357
+ const axisRange = range[i];
28358
+ if (noSnap) {
28359
+ return axisRange[0] + (axisRange[1] - axisRange[0]) * coord;
28360
+ }
28361
+ const axisStep = step[i];
28362
+ const nSteps = Math.floor((axisRange[1] - axisRange[0]) / axisStep);
28363
+ const tick = Math.round(coord * nSteps);
28364
+ return axisRange[0] + axisStep * tick;
28365
+ }));
28366
+
28367
+ // same as normalizeCoords in interactive-graph.tsx
28368
+ const normalizeCoords = (coordsList, ranges) => coordsList.map(coords => coords.map((coord, i) => {
28369
+ const extent = ranges[i][1] - ranges[i][0];
28370
+ return (coord + ranges[i][1]) / extent;
28371
+ }));
28339
28372
 
28340
28373
  const defaultStroke = "var(--movable-line-stroke-color)";
28341
28374
  const MovableLine = props => {
@@ -28383,7 +28416,7 @@ const MovableLine = props => {
28383
28416
  end: endPtPx,
28384
28417
  style: {
28385
28418
  stroke: "transparent",
28386
- strokeWidth: 44
28419
+ strokeWidth: TARGET_SIZE
28387
28420
  }
28388
28421
  }), /*#__PURE__*/React__namespace.createElement(SVGLine, {
28389
28422
  start: startPtPx,
@@ -28416,7 +28449,7 @@ function SVGLine(props) {
28416
28449
  x2: end[0],
28417
28450
  y2: end[1],
28418
28451
  style: style,
28419
- className: dragging ? "movable-line-dragging" : undefined
28452
+ className: dragging ? "movable-dragging" : undefined
28420
28453
  });
28421
28454
  }
28422
28455
 
@@ -28491,7 +28524,7 @@ const StyledMovablePoint = props => {
28491
28524
  }
28492
28525
  }, /*#__PURE__*/React__namespace.createElement("circle", {
28493
28526
  className: "movable-point-hitbox",
28494
- r: 22,
28527
+ r: TARGET_SIZE / 2,
28495
28528
  cx: x,
28496
28529
  cy: y
28497
28530
  }), /*#__PURE__*/React__namespace.createElement("circle", {
@@ -28527,9 +28560,9 @@ const SegmentGraph = props => {
28527
28560
  snaps: snapStep,
28528
28561
  range: range,
28529
28562
  onMoveLine: delta => {
28530
- dispatch(moveSegment(i, delta));
28563
+ dispatch(moveLine(i, delta));
28531
28564
  },
28532
- onMovePoint: (endpointIndex, destination) => dispatch(moveControlPoint(i, endpointIndex, destination)),
28565
+ onMovePoint: (endpointIndex, destination) => dispatch(moveControlPoint(endpointIndex, destination, i)),
28533
28566
  "data-testid": "segment" + i
28534
28567
  })));
28535
28568
  };
@@ -28572,9 +28605,9 @@ const LinearGraph = props => {
28572
28605
  snaps: snapStep,
28573
28606
  range: range,
28574
28607
  onMoveLine: delta => {
28575
- dispatch(moveSegment(i, delta));
28608
+ dispatch(moveLine(i, delta));
28576
28609
  },
28577
- onMovePoint: (endpointIndex, destination) => dispatch(moveControlPoint(i, endpointIndex, destination))
28610
+ onMovePoint: (endpointIndex, destination) => dispatch(moveControlPoint(endpointIndex, destination, i))
28578
28611
  // "linear" or "linear-system" + index
28579
28612
  ,
28580
28613
  "data-testid": type + i,
@@ -28625,8 +28658,8 @@ const RayGraph = props => {
28625
28658
 
28626
28659
  // a ray only has one line
28627
28660
  const [start, end] = lines[0];
28628
- const handleMoveLine = delta => dispatch(moveSegment(0, delta));
28629
- const handleMovePoint = (newPoint, pointIndex) => dispatch(moveControlPoint(0, pointIndex, newPoint));
28661
+ const handleMoveLine = delta => dispatch(moveLine(0, delta));
28662
+ const handleMovePoint = (newPoint, pointIndex) => dispatch(moveControlPoint(pointIndex, newPoint, 0));
28630
28663
  return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(MovableLine, {
28631
28664
  start: start,
28632
28665
  end: end,
@@ -28645,6 +28678,62 @@ const RayGraph = props => {
28645
28678
  }));
28646
28679
  };
28647
28680
 
28681
+ const PolygonGraph = props => {
28682
+ const [focused, setFocused] = React__namespace.useState(false);
28683
+ const [hovered, setHovered] = React__namespace.useState(false);
28684
+ const {
28685
+ dispatch
28686
+ } = props;
28687
+ const {
28688
+ coords,
28689
+ type
28690
+ } = props.graphState;
28691
+ const points = coords ?? [[0, 0]];
28692
+ const pointsSum = points.reduce((acc, point) => mafs.vec.add(acc, point), [0, 0]);
28693
+ const midpoint = pointsSum && mafs.vec.scale(pointsSum, 1 / (points.length ?? 1));
28694
+ const ref = React__namespace.useRef(null);
28695
+ const {
28696
+ dragging
28697
+ } = mafs.useMovable({
28698
+ gestureTarget: ref,
28699
+ point: midpoint,
28700
+ onMove: newPoint => {
28701
+ const delta = mafs.vec.sub(newPoint, midpoint);
28702
+ dispatch(moveAll(delta));
28703
+ },
28704
+ constrain: p => p
28705
+ });
28706
+ const active = hovered || focused || dragging;
28707
+ return /*#__PURE__*/React__namespace.createElement(React__namespace.Fragment, null, /*#__PURE__*/React__namespace.createElement(mafs.Polygon, {
28708
+ points: [...points],
28709
+ color: "var(--movable-line-stroke-color)",
28710
+ svgPolygonProps: {
28711
+ strokeWidth: active ? "var(--movable-line-stroke-weight-active)" : "var(--movable-line-stroke-weight)"
28712
+ }
28713
+ }), /*#__PURE__*/React__namespace.createElement(mafs.Polygon, {
28714
+ points: [...points],
28715
+ color: "transparent",
28716
+ svgPolygonProps: {
28717
+ ref,
28718
+ tabIndex: 0,
28719
+ strokeWidth: TARGET_SIZE,
28720
+ style: {
28721
+ cursor: dragging ? "grabbing" : "grab"
28722
+ },
28723
+ onFocus: () => setFocused(true),
28724
+ onBlur: () => setFocused(false),
28725
+ onMouseEnter: () => setHovered(true),
28726
+ onMouseLeave: () => setHovered(false),
28727
+ className: "movable-polygon"
28728
+ }
28729
+ }), points.map((point, i) => /*#__PURE__*/React__namespace.createElement(StyledMovablePoint, {
28730
+ key: i,
28731
+ point: point,
28732
+ onMove: destination => dispatch(moveControlPoint(i, destination)),
28733
+ "data-testid": type + i
28734
+ })));
28735
+ };
28736
+
28648
28737
  const renderLineLabel = (n, _ref) => {
28649
28738
  let [min, max] = _ref;
28650
28739
  return n !== -1 && n !== min && n !== max;
@@ -28660,234 +28749,6 @@ const Grid = props => props.markings === "none" ? null : /*#__PURE__*/React__nam
28660
28749
  yAxis: axisOptions(props, 1)
28661
28750
  });
28662
28751
 
28663
- function interactiveGraphReducer(state, action) {
28664
- switch (action.type) {
28665
- case MOVE_CONTROL_POINT:
28666
- {
28667
- const newCoords = updateAtIndex({
28668
- array: state.coords,
28669
- index: action.objectIndex,
28670
- update: tuple => setAtIndex({
28671
- array: tuple,
28672
- index: action.pointIndex,
28673
- newValue: snap(state, bound$1(state, action.destination))
28674
- })
28675
- });
28676
- if (!validSegments(newCoords)) {
28677
- return state;
28678
- }
28679
- return {
28680
- ...state,
28681
- hasBeenInteractedWith: true,
28682
- coords: newCoords
28683
- };
28684
- }
28685
- case MOVE_LINE:
28686
- {
28687
- const currentLine = state.coords?.[action.lineIndex];
28688
- if (!currentLine) {
28689
- throw new Error("No line to move");
28690
- }
28691
- const maxMoves = currentLine.map(point => maxMove(state, point));
28692
- const minMoves = currentLine.map(point => minMove(state, point));
28693
- const maxXMove = Math.min(...maxMoves.map(move => move[0]));
28694
- const maxYMove = Math.min(...maxMoves.map(move => move[1]));
28695
- const minXMove = Math.max(...minMoves.map(move => move[0]));
28696
- const minYMove = Math.max(...minMoves.map(move => move[1]));
28697
- const dx = clamp(action.delta[0], minXMove, maxXMove);
28698
- const dy = clamp(action.delta[1], minYMove, maxYMove);
28699
- const newValue = [snap(state, mafs.vec.add(currentLine[0], [dx, dy])), snap(state, mafs.vec.add(currentLine[1], [dx, dy]))];
28700
- const newLine = setAtIndex({
28701
- array: state.coords,
28702
- index: action.lineIndex,
28703
- newValue
28704
- });
28705
- return {
28706
- ...state,
28707
- hasBeenInteractedWith: true,
28708
- coords: newLine
28709
- };
28710
- }
28711
- default:
28712
- throw new wonderStuffCore.UnreachableCaseError(action);
28713
- }
28714
- }
28715
- function snap(state, point) {
28716
- const [requestedX, requestedY] = point;
28717
- const [snapX, snapY] = state.snapStep;
28718
- return [Math.round(requestedX / snapX) * snapX, Math.round(requestedY / snapY) * snapY];
28719
- }
28720
-
28721
- // Returns the closest point to the given `point` that is within the graph
28722
- // bounds given in `state`.
28723
- function bound$1(state, point) {
28724
- const [requestedX, requestedY] = point;
28725
- const [snapX, snapY] = state.snapStep;
28726
- const [[minX, maxX], [minY, maxY]] = state.range;
28727
- return [clamp(requestedX, minX + snapX, maxX - snapX), clamp(requestedY, minY + snapY, maxY - snapY)];
28728
- }
28729
-
28730
- // Returns the vector from the given point to the top-right corner of the graph
28731
- function maxMove(state, point) {
28732
- const topRight = bound$1(state, [Infinity, Infinity]);
28733
- return mafs.vec.sub(topRight, point);
28734
- }
28735
-
28736
- // Returns the vector from the given point to the bottom-left corner of the
28737
- // graph
28738
- function minMove(state, point) {
28739
- const bottomLeft = bound$1(state, [-Infinity, -Infinity]);
28740
- return mafs.vec.sub(bottomLeft, point);
28741
- }
28742
- function clamp(value, min, max) {
28743
- if (value < min) {
28744
- return min;
28745
- }
28746
- if (value > max) {
28747
- return max;
28748
- }
28749
- return value;
28750
- }
28751
- function validSegments(segments) {
28752
- return segments.every(_ref => {
28753
- let [start, end] = _ref;
28754
- return !kmath.vector.equal(start, end);
28755
- });
28756
- }
28757
- function updateAtIndex(args) {
28758
- const {
28759
- array = [],
28760
- index,
28761
- update
28762
- } = args;
28763
- const newValue = update(array[index]);
28764
- return setAtIndex({
28765
- array,
28766
- index,
28767
- newValue
28768
- });
28769
- }
28770
- function setAtIndex(args) {
28771
- const {
28772
- array = [],
28773
- index,
28774
- newValue
28775
- } = args;
28776
- const copy = [...array];
28777
- copy[index] = newValue;
28778
- // restoring readonly to array
28779
- return copy;
28780
- }
28781
-
28782
- // same as pointsFromNormalized in interactive-graph.tsx
28783
- const normalizePoints = (range, step, coordsList, noSnap) => coordsList.map(coords =>
28784
- // maps over [x, y]
28785
- coords.map((coord, i) => {
28786
- const axisRange = range[i];
28787
- if (noSnap) {
28788
- return axisRange[0] + (axisRange[1] - axisRange[0]) * coord;
28789
- }
28790
- const axisStep = step[i];
28791
- const nSteps = Math.floor((axisRange[1] - axisRange[0]) / axisStep);
28792
- const tick = Math.round(coord * nSteps);
28793
- return axisRange[0] + axisStep * tick;
28794
- }));
28795
-
28796
- // same as normalizeCoords in interactive-graph.tsx
28797
- const normalizeCoords = (coordsList, ranges) => coordsList.map(coords => coords.map((coord, i) => {
28798
- const extent = ranges[i][1] - ranges[i][0];
28799
- return (coord + ranges[i][1]) / extent;
28800
- }));
28801
-
28802
- function initializeGraphState(params) {
28803
- const {
28804
- graph,
28805
- step,
28806
- snapStep,
28807
- range
28808
- } = params;
28809
- switch (graph.type) {
28810
- case "segment":
28811
- return {
28812
- type: "segment",
28813
- hasBeenInteractedWith: false,
28814
- range,
28815
- snapStep,
28816
- coords: getDefaultSegments({
28817
- graph,
28818
- step,
28819
- range
28820
- })
28821
- };
28822
- case "linear":
28823
- case "linear-system":
28824
- case "ray":
28825
- return {
28826
- type: graph.type,
28827
- hasBeenInteractedWith: false,
28828
- range,
28829
- snapStep,
28830
- // Linear and ray graphs have a single tuple of points, while a
28831
- // linear system has two tuples of points.
28832
- coords: getLineCoords(graph, range, step)
28833
- };
28834
- }
28835
- throw new Error("Mafs not yet implemented for graph type: " + graph.type);
28836
- }
28837
- const getDefaultSegments = props => {
28838
- const ys = n => {
28839
- switch (n) {
28840
- case 2:
28841
- return [5, -5];
28842
- case 3:
28843
- return [5, 0, -5];
28844
- case 4:
28845
- return [6, 2, -2, -6];
28846
- case 5:
28847
- return [6, 3, 0, -3, -6];
28848
- case 6:
28849
- return [5, 3, 1, -1, -3, -5];
28850
- default:
28851
- return [5];
28852
- }
28853
- };
28854
- return ys(props.graph.numSegments).map(y => {
28855
- let endpoints = [[-5, y], [5, y]];
28856
- endpoints = normalizeCoords(endpoints, props.range);
28857
- endpoints = normalizePoints(props.range, props.step, endpoints);
28858
- return endpoints;
28859
- });
28860
- };
28861
-
28862
- // TS v4 doesn't narrow return types, while v5 does.
28863
- // Instead of updating to v5, using generic type to relate input and output types.
28864
- function getGradableGraph(state, initialGraph) {
28865
- if (!state.hasBeenInteractedWith) {
28866
- return initialGraph;
28867
- }
28868
- switch (true) {
28869
- // coords: Array of CollinearTuple
28870
- case state.type === "linear-system" && initialGraph.type === "linear-system":
28871
- case state.type === "segment" && initialGraph.type === "segment":
28872
- return {
28873
- ...initialGraph,
28874
- coords: state.coords
28875
- };
28876
- // coords: CollinearTuple
28877
- case state.type === "linear" && initialGraph.type === "linear":
28878
- case state.type === "ray" && initialGraph.type === "ray":
28879
- return {
28880
- ...initialGraph,
28881
- coords: state.coords?.[0]
28882
- };
28883
- }
28884
- throw new Error("Mafs is not yet implemented for graph type: " + initialGraph.type);
28885
- }
28886
- const defaultLinearCoords = [[[0.25, 0.75], [0.75, 0.75]], [[0.25, 0.25], [0.75, 0.25]]];
28887
- const getLineCoords = (graph, range, step) =>
28888
- // Return two lines for a linear system, one for a ray or linear
28889
- graph.coords ?? graph.type === "linear-system" ? defaultLinearCoords.map(collinear => normalizePoints(range, step, collinear)) : [normalizePoints(range, step, defaultLinearCoords[0])];
28890
-
28891
28752
  // Displays a stylized open eye: lint warnings are visible
28892
28753
  const VisibleIcon = () => /*#__PURE__*/React__namespace.createElement("svg", {
28893
28754
  width: "24",
@@ -29423,161 +29284,540 @@ class NumberInput extends React__namespace.Component {
29423
29284
  };
29424
29285
  }
29425
29286
 
29426
- /* eslint-disable @babel/no-invalid-this */
29427
-
29428
- /* A checkbox that syncs its value to props using the
29429
- * renderer's onChange method, and gets the prop name
29430
- * dynamically from its props list
29431
- */
29432
- const PropCheckBox = createReactClass__default["default"]({
29433
- displayName: "PropCheckBox",
29434
- propTypes: {
29435
- labelAlignment: PropTypes__default["default"].oneOf(["left", "right"])
29436
- },
29437
- DEFAULT_PROPS: {
29438
- label: null,
29439
- onChange: null,
29440
- labelAlignment: "left"
29441
- },
29442
- getDefaultProps: function () {
29443
- return this.DEFAULT_PROPS;
29444
- },
29445
- propName: function () {
29446
- const propName = ___default["default"].find(___default["default"].keys(this.props), function (localPropName) {
29447
- // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
29448
- return !___default["default"].has(this.DEFAULT_PROPS, localPropName);
29449
- }, this);
29450
- if (!propName) {
29451
- throw new PerseusError("Attempted to create a PropCheckBox with no prop!", Errors.InvalidInput);
29452
- }
29453
- return propName;
29454
- },
29455
- _labelAlignLeft: function () {
29456
- return this.props.labelAlignment === "left";
29457
- },
29458
- render: function () {
29459
- const propName = this.propName();
29460
- return /*#__PURE__*/React__namespace.createElement("label", {
29461
- className: aphrodite.css(styles$h.labeledCheckbox)
29462
- }, this._labelAlignLeft() && /*#__PURE__*/React__namespace.createElement(wonderBlocksTypography.LabelSmall, null, this.props.label), /*#__PURE__*/React__namespace.createElement(wonderBlocksForm.Checkbox, {
29463
- checked: this.props[propName],
29464
- onChange: this.toggle
29465
- }), !this._labelAlignLeft() && /*#__PURE__*/React__namespace.createElement(wonderBlocksTypography.LabelSmall, null, this.props.label));
29466
- },
29467
- toggle: function () {
29468
- const propName = this.propName();
29469
- const changes = {};
29470
- changes[propName] = !this.props[propName];
29471
- this.props.onChange(changes);
29472
- }
29473
- });
29474
- const styles$h = aphrodite.StyleSheet.create({
29475
- labeledCheckbox: {
29476
- display: "flex",
29477
- flexDirection: "row",
29478
- alignItems: "center"
29287
+ /* eslint-disable @babel/no-invalid-this */
29288
+
29289
+ /* A checkbox that syncs its value to props using the
29290
+ * renderer's onChange method, and gets the prop name
29291
+ * dynamically from its props list
29292
+ */
29293
+ const PropCheckBox = createReactClass__default["default"]({
29294
+ displayName: "PropCheckBox",
29295
+ propTypes: {
29296
+ labelAlignment: PropTypes__default["default"].oneOf(["left", "right"])
29297
+ },
29298
+ DEFAULT_PROPS: {
29299
+ label: null,
29300
+ onChange: null,
29301
+ labelAlignment: "left"
29302
+ },
29303
+ getDefaultProps: function () {
29304
+ return this.DEFAULT_PROPS;
29305
+ },
29306
+ propName: function () {
29307
+ const propName = ___default["default"].find(___default["default"].keys(this.props), function (localPropName) {
29308
+ // @ts-expect-error - TS2683 - 'this' implicitly has type 'any' because it does not have a type annotation.
29309
+ return !___default["default"].has(this.DEFAULT_PROPS, localPropName);
29310
+ }, this);
29311
+ if (!propName) {
29312
+ throw new PerseusError("Attempted to create a PropCheckBox with no prop!", Errors.InvalidInput);
29313
+ }
29314
+ return propName;
29315
+ },
29316
+ _labelAlignLeft: function () {
29317
+ return this.props.labelAlignment === "left";
29318
+ },
29319
+ render: function () {
29320
+ const propName = this.propName();
29321
+ return /*#__PURE__*/React__namespace.createElement("label", {
29322
+ className: aphrodite.css(styles$h.labeledCheckbox)
29323
+ }, this._labelAlignLeft() && /*#__PURE__*/React__namespace.createElement(wonderBlocksTypography.LabelSmall, null, this.props.label), /*#__PURE__*/React__namespace.createElement(wonderBlocksForm.Checkbox, {
29324
+ checked: this.props[propName],
29325
+ onChange: this.toggle
29326
+ }), !this._labelAlignLeft() && /*#__PURE__*/React__namespace.createElement(wonderBlocksTypography.LabelSmall, null, this.props.label));
29327
+ },
29328
+ toggle: function () {
29329
+ const propName = this.propName();
29330
+ const changes = {};
29331
+ changes[propName] = !this.props[propName];
29332
+ this.props.onChange(changes);
29333
+ }
29334
+ });
29335
+ const styles$h = aphrodite.StyleSheet.create({
29336
+ labeledCheckbox: {
29337
+ display: "flex",
29338
+ flexDirection: "row",
29339
+ alignItems: "center"
29340
+ }
29341
+ });
29342
+
29343
+ const truth = () => true;
29344
+
29345
+ /* A minor abstraction on top of NumberInput for ranges
29346
+ *
29347
+ */
29348
+ class RangeInput extends React__namespace.Component {
29349
+ static propTypes = {
29350
+ value: PropTypes__default["default"].array.isRequired,
29351
+ onChange: PropTypes__default["default"].func.isRequired,
29352
+ placeholder: PropTypes__default["default"].array,
29353
+ checkValidity: PropTypes__default["default"].func
29354
+ };
29355
+ static defaultProps = {
29356
+ placeholder: [null, null]
29357
+ };
29358
+ render() {
29359
+ const value = this.props.value;
29360
+ const checkValidity = this.props.checkValidity || truth;
29361
+ return /*#__PURE__*/React__namespace.createElement("div", {
29362
+ className: "range-input"
29363
+ }, /*#__PURE__*/React__namespace.createElement(NumberInput, _extends({}, this.props, {
29364
+ value: value[0],
29365
+ checkValidity: val => checkValidity([val, value[1]])
29366
+ // eslint-disable-next-line react/jsx-no-bind
29367
+ ,
29368
+ onChange: this.onChange.bind(this, 0),
29369
+ placeholder: this.props.placeholder[0]
29370
+ })), /*#__PURE__*/React__namespace.createElement(NumberInput, _extends({}, this.props, {
29371
+ value: value[1],
29372
+ checkValidity: val => checkValidity([value[0], val])
29373
+ // eslint-disable-next-line react/jsx-no-bind
29374
+ ,
29375
+ onChange: this.onChange.bind(this, 1),
29376
+ placeholder: this.props.placeholder[1]
29377
+ })));
29378
+ }
29379
+ onChange = (i, newVal) => {
29380
+ const value = this.props.value;
29381
+ if (i === 0) {
29382
+ this.props.onChange([newVal, value[1]]);
29383
+ } else {
29384
+ this.props.onChange([value[0], newVal]);
29385
+ }
29386
+ };
29387
+ }
29388
+
29389
+ var components = /*#__PURE__*/Object.freeze({
29390
+ __proto__: null,
29391
+ ButtonGroup: ButtonGroup,
29392
+ Graph: Graph,
29393
+ Graphie: Graphie,
29394
+ HUD: HUD,
29395
+ Icon: Icon,
29396
+ InfoTip: InfoTip,
29397
+ InlineIcon: InlineIcon,
29398
+ MathInput: MathInput,
29399
+ MultiButtonGroup: MultiButtonGroup,
29400
+ NumberInput: NumberInput,
29401
+ PropCheckBox: PropCheckBox,
29402
+ RangeInput: RangeInput,
29403
+ SvgImage: SvgImage,
29404
+ TextInput: TextInput,
29405
+ TextListEditor: TextListEditor
29406
+ });
29407
+
29408
+ /**
29409
+ * If a graphie URL is provided in `backgroundImage`, will return the rendered graphie background.
29410
+ * Otherwise, returns `null`.
29411
+ */
29412
+ const getLegacyGrid = (box, backgroundImage) => {
29413
+ const {
29414
+ url,
29415
+ width,
29416
+ height
29417
+ } = backgroundImage ?? {};
29418
+ if (url && typeof url === "string") {
29419
+ const scale = box[0] / interactiveSizes$1.defaultBoxSize;
29420
+ return /*#__PURE__*/React__namespace.createElement(wonderBlocksCore.View, {
29421
+ style: {
29422
+ position: "absolute",
29423
+ bottom: 0,
29424
+ left: 0
29425
+ }
29426
+ }, /*#__PURE__*/React__namespace.createElement(context$1.Consumer, null, _ref => {
29427
+ let {
29428
+ setAssetStatus
29429
+ } = _ref;
29430
+ return /*#__PURE__*/React__namespace.createElement(SvgImage, {
29431
+ src: url,
29432
+ width: width,
29433
+ height: height,
29434
+ scale: scale,
29435
+ responsive: false,
29436
+ setAssetStatus: setAssetStatus,
29437
+ alt: ""
29438
+ });
29439
+ }));
29440
+ }
29441
+ return null;
29442
+ };
29443
+
29444
+ /** Determine if coords is type CollinearTuple[] */
29445
+ const isCollinearTuples = coords => Array.isArray(coords[0][0]);
29446
+
29447
+ // Generic type makes returned state match input state
29448
+ function interactiveGraphReducer(state, action) {
29449
+ const {
29450
+ snapStep,
29451
+ range
29452
+ } = state;
29453
+ if (!state.coords) {
29454
+ throw new Error("Graph state must have been initialized with coords");
29455
+ }
29456
+ switch (action.type) {
29457
+ case MOVE_CONTROL_POINT:
29458
+ {
29459
+ const newCoords = action.itemIndex !== undefined && state.coords && isCollinearTuples(state.coords) ? updateAtIndex({
29460
+ array: state.coords,
29461
+ index: action.itemIndex,
29462
+ update: tuple => setAtIndex({
29463
+ array: tuple,
29464
+ index: action.pointIndex,
29465
+ newValue: snap({
29466
+ snapStep,
29467
+ point: bound$1({
29468
+ snapStep,
29469
+ range,
29470
+ point: action.destination
29471
+ })
29472
+ })
29473
+ })
29474
+ }) : setAtIndex({
29475
+ array: state.coords,
29476
+ index: action.pointIndex,
29477
+ newValue: snap({
29478
+ snapStep,
29479
+ point: bound$1({
29480
+ snapStep,
29481
+ range,
29482
+ point: action.destination
29483
+ })
29484
+ })
29485
+ });
29486
+
29487
+ // Cannot type narrow both conditions within function parameters,
29488
+ // so this may seem redundant, but it's necessary for type safety.
29489
+ const coordsToCheck = isCollinearTuples(newCoords) && action.itemIndex !== undefined ? newCoords[action.itemIndex] : newCoords;
29490
+ if (!isCollinearTuples(coordsToCheck) && coordsOverlap(coordsToCheck)) {
29491
+ return state;
29492
+ }
29493
+ return {
29494
+ ...state,
29495
+ hasBeenInteractedWith: true,
29496
+ coords: newCoords
29497
+ };
29498
+ }
29499
+ case MOVE_LINE:
29500
+ {
29501
+ if (!isCollinearTuples(state.coords)) {
29502
+ throw new Error("Cannot call this action unless coords is array of CollinearTuple.");
29503
+ }
29504
+ if (action.itemIndex === undefined) {
29505
+ throw new Error("Please provide index of line to move");
29506
+ }
29507
+ const currentLine = state.coords?.[action.itemIndex];
29508
+ if (!currentLine) {
29509
+ throw new Error("No line to move");
29510
+ }
29511
+ const change = getChange(currentLine, action.delta, {
29512
+ snapStep,
29513
+ range
29514
+ });
29515
+ const newLine = [snap({
29516
+ snapStep,
29517
+ point: mafs.vec.add(currentLine[0], change)
29518
+ }), snap({
29519
+ snapStep,
29520
+ point: mafs.vec.add(currentLine[1], change)
29521
+ })];
29522
+ const newCoords = setAtIndex({
29523
+ array: state.coords,
29524
+ index: action.itemIndex,
29525
+ newValue: newLine
29526
+ });
29527
+ return {
29528
+ ...state,
29529
+ hasBeenInteractedWith: true,
29530
+ coords: newCoords
29531
+ };
29532
+ }
29533
+ case MOVE_ALL:
29534
+ {
29535
+ if (isCollinearTuples(state.coords)) {
29536
+ throw new Error("Cannot call this action unless coords is array of vectors.");
29537
+ }
29538
+ const change = getChange(state.coords, action.delta, {
29539
+ snapStep,
29540
+ range
29541
+ });
29542
+ const newCoords = state.coords.map(point => snap({
29543
+ snapStep,
29544
+ point: mafs.vec.add(point, change)
29545
+ }));
29546
+ return {
29547
+ ...state,
29548
+ hasBeenInteractedWith: true,
29549
+ coords: newCoords
29550
+ };
29551
+ }
29552
+ default:
29553
+ throw new wonderStuffCore.UnreachableCaseError(action);
29554
+ }
29555
+ }
29556
+ const getChange = (coords, delta, constraintOpts) => {
29557
+ const [deltaX, deltaY] = delta;
29558
+ const maxMoves = coords.map(point => maxMove({
29559
+ ...constraintOpts,
29560
+ point
29561
+ }));
29562
+ const minMoves = coords.map(point => minMove({
29563
+ ...constraintOpts,
29564
+ point
29565
+ }));
29566
+ const maxXMove = Math.min(...maxMoves.map(move => move[0]));
29567
+ const maxYMove = Math.min(...maxMoves.map(move => move[1]));
29568
+ const minXMove = Math.max(...minMoves.map(move => move[0]));
29569
+ const minYMove = Math.max(...minMoves.map(move => move[1]));
29570
+ const dx = clamp(deltaX, minXMove, maxXMove);
29571
+ const dy = clamp(deltaY, minYMove, maxYMove);
29572
+ return [dx, dy];
29573
+ };
29574
+ function snap(_ref) {
29575
+ let {
29576
+ snapStep,
29577
+ point
29578
+ } = _ref;
29579
+ const [requestedX, requestedY] = point;
29580
+ const [snapX, snapY] = snapStep;
29581
+ return [Math.round(requestedX / snapX) * snapX, Math.round(requestedY / snapY) * snapY];
29582
+ }
29583
+
29584
+ // Returns the closest point to the given `point` that is within the graph
29585
+ // bounds given in `state`.
29586
+ function bound$1(_ref2) {
29587
+ let {
29588
+ snapStep,
29589
+ range,
29590
+ point
29591
+ } = _ref2;
29592
+ const [requestedX, requestedY] = point;
29593
+ const [snapX, snapY] = snapStep;
29594
+ const [[minX, maxX], [minY, maxY]] = range;
29595
+ return [clamp(requestedX, minX + snapX, maxX - snapX), clamp(requestedY, minY + snapY, maxY - snapY)];
29596
+ }
29597
+
29598
+ // Returns the vector from the given point to the top-right corner of the graph
29599
+ function maxMove(_ref3) {
29600
+ let {
29601
+ snapStep,
29602
+ range,
29603
+ point
29604
+ } = _ref3;
29605
+ const topRight = bound$1({
29606
+ snapStep,
29607
+ range,
29608
+ point: [Infinity, Infinity]
29609
+ });
29610
+ return mafs.vec.sub(topRight, point);
29611
+ }
29612
+
29613
+ // Returns the vector from the given point to the bottom-left corner of the
29614
+ // graph
29615
+ function minMove(_ref4) {
29616
+ let {
29617
+ snapStep,
29618
+ range,
29619
+ point
29620
+ } = _ref4;
29621
+ const bottomLeft = bound$1({
29622
+ snapStep,
29623
+ range,
29624
+ point: [-Infinity, -Infinity]
29625
+ });
29626
+ return mafs.vec.sub(bottomLeft, point);
29627
+ }
29628
+ function clamp(value, min, max) {
29629
+ if (value < min) {
29630
+ return min;
29631
+ }
29632
+ if (value > max) {
29633
+ return max;
29634
+ }
29635
+ return value;
29636
+ }
29637
+ const coordsOverlap = coords => coords.some((coord, i) => coords.some((c, j) => i !== j && kmath.vector.equal(coord, c)));
29638
+ function updateAtIndex(args) {
29639
+ const {
29640
+ array = [],
29641
+ index,
29642
+ update
29643
+ } = args;
29644
+ const newValue = update(array[index]);
29645
+ return setAtIndex({
29646
+ array,
29647
+ index,
29648
+ newValue
29649
+ });
29650
+ }
29651
+ function setAtIndex(args) {
29652
+ const {
29653
+ array = [],
29654
+ index,
29655
+ newValue
29656
+ } = args;
29657
+ const copy = [...array];
29658
+ copy[index] = newValue;
29659
+ // restoring readonly to array
29660
+ return copy;
29661
+ }
29662
+
29663
+ function initializeGraphState(params) {
29664
+ const {
29665
+ graph,
29666
+ step,
29667
+ snapStep,
29668
+ range
29669
+ } = params;
29670
+ switch (graph.type) {
29671
+ case "segment":
29672
+ return {
29673
+ type: "segment",
29674
+ hasBeenInteractedWith: false,
29675
+ range,
29676
+ snapStep,
29677
+ coords: getDefaultSegments({
29678
+ graph,
29679
+ step,
29680
+ range
29681
+ })
29682
+ };
29683
+ case "linear":
29684
+ case "linear-system":
29685
+ case "ray":
29686
+ return {
29687
+ type: graph.type,
29688
+ hasBeenInteractedWith: false,
29689
+ range,
29690
+ snapStep,
29691
+ // Linear and ray graphs have a single tuple of points, while a
29692
+ // linear system has two tuples of points.
29693
+ coords: getLineCoords({
29694
+ graph,
29695
+ range,
29696
+ step
29697
+ })
29698
+ };
29699
+ case "polygon":
29700
+ return {
29701
+ type: "polygon",
29702
+ hasBeenInteractedWith: false,
29703
+ range,
29704
+ snapStep,
29705
+ coords: getPolygonCoords({
29706
+ graph,
29707
+ range,
29708
+ step
29709
+ })
29710
+ };
29711
+ case "angle":
29712
+ case "point":
29713
+ case "circle":
29714
+ case "sinusoid":
29715
+ case "quadratic":
29716
+ throw new Error("Mafs not yet implemented for graph type: " + graph.type);
29717
+ default:
29718
+ throw new wonderStuffCore.UnreachableCaseError(graph);
29719
+ }
29720
+ }
29721
+
29722
+ // TS v4 doesn't narrow return types, while v5 does.
29723
+ // Instead of updating to v5, using generic type to relate input and output types.
29724
+ function getGradableGraph(state, initialGraph) {
29725
+ if (!state.hasBeenInteractedWith) {
29726
+ return initialGraph;
29479
29727
  }
29480
- });
29481
-
29482
- const truth = () => true;
29483
-
29484
- /* A minor abstraction on top of NumberInput for ranges
29485
- *
29486
- */
29487
- class RangeInput extends React__namespace.Component {
29488
- static propTypes = {
29489
- value: PropTypes__default["default"].array.isRequired,
29490
- onChange: PropTypes__default["default"].func.isRequired,
29491
- placeholder: PropTypes__default["default"].array,
29492
- checkValidity: PropTypes__default["default"].func
29493
- };
29494
- static defaultProps = {
29495
- placeholder: [null, null]
29496
- };
29497
- render() {
29498
- const value = this.props.value;
29499
- const checkValidity = this.props.checkValidity || truth;
29500
- return /*#__PURE__*/React__namespace.createElement("div", {
29501
- className: "range-input"
29502
- }, /*#__PURE__*/React__namespace.createElement(NumberInput, _extends({}, this.props, {
29503
- value: value[0],
29504
- checkValidity: val => checkValidity([val, value[1]])
29505
- // eslint-disable-next-line react/jsx-no-bind
29506
- ,
29507
- onChange: this.onChange.bind(this, 0),
29508
- placeholder: this.props.placeholder[0]
29509
- })), /*#__PURE__*/React__namespace.createElement(NumberInput, _extends({}, this.props, {
29510
- value: value[1],
29511
- checkValidity: val => checkValidity([value[0], val])
29512
- // eslint-disable-next-line react/jsx-no-bind
29513
- ,
29514
- onChange: this.onChange.bind(this, 1),
29515
- placeholder: this.props.placeholder[1]
29516
- })));
29728
+ switch (true) {
29729
+ // coords: Array of CollinearTuple
29730
+ case state.type === "linear-system" && initialGraph.type === "linear-system":
29731
+ case state.type === "segment" && initialGraph.type === "segment":
29732
+ return {
29733
+ ...initialGraph,
29734
+ coords: state.coords
29735
+ };
29736
+ // coords: CollinearTuple
29737
+ case state.type === "linear" && initialGraph.type === "linear":
29738
+ case state.type === "ray" && initialGraph.type === "ray":
29739
+ return {
29740
+ ...initialGraph,
29741
+ coords: state.coords?.[0]
29742
+ };
29743
+ case state.type === "polygon" && initialGraph.type === "polygon":
29744
+ return {
29745
+ ...initialGraph,
29746
+ coords: state.coords
29747
+ };
29748
+ default:
29749
+ throw new Error("Mafs is not yet implemented for graph type: " + initialGraph.type);
29517
29750
  }
29518
- onChange = (i, newVal) => {
29519
- const value = this.props.value;
29520
- if (i === 0) {
29521
- this.props.onChange([newVal, value[1]]);
29522
- } else {
29523
- this.props.onChange([value[0], newVal]);
29751
+ }
29752
+ const getDefaultSegments = _ref => {
29753
+ let {
29754
+ graph,
29755
+ range,
29756
+ step
29757
+ } = _ref;
29758
+ const ys = n => {
29759
+ switch (n) {
29760
+ case 2:
29761
+ return [5, -5];
29762
+ case 3:
29763
+ return [5, 0, -5];
29764
+ case 4:
29765
+ return [6, 2, -2, -6];
29766
+ case 5:
29767
+ return [6, 3, 0, -3, -6];
29768
+ case 6:
29769
+ return [5, 3, 1, -1, -3, -5];
29770
+ default:
29771
+ return [5];
29524
29772
  }
29525
29773
  };
29526
- }
29774
+ return ys(graph.numSegments).map(y => {
29775
+ let endpoints = [[-5, y], [5, y]];
29776
+ endpoints = normalizeCoords(endpoints, range);
29777
+ endpoints = normalizePoints(range, step, endpoints);
29778
+ return endpoints;
29779
+ });
29780
+ };
29781
+ const defaultLinearCoords = [[[0.25, 0.75], [0.75, 0.75]], [[0.25, 0.25], [0.75, 0.25]]];
29782
+ const getLineCoords = _ref2 => {
29783
+ let {
29784
+ graph,
29785
+ range,
29786
+ step
29787
+ } = _ref2;
29788
+ return (
29789
+ // Return two lines for a linear system, one for a ray or linear
29790
+ graph.coords ?? graph.type === "linear-system" ? defaultLinearCoords.map(collinear => normalizePoints(range, step, collinear)) : [normalizePoints(range, step, defaultLinearCoords[0])]
29791
+ );
29792
+ };
29793
+ const getPolygonCoords = _ref3 => {
29794
+ let {
29795
+ graph,
29796
+ range,
29797
+ step
29798
+ } = _ref3;
29799
+ let coords = graph.coords;
29800
+ if (coords) {
29801
+ return coords;
29802
+ }
29803
+ const n = graph.numSides || 3;
29804
+ if (n === "unlimited") {
29805
+ coords = [];
29806
+ } else {
29807
+ const angle = 2 * Math.PI / n;
29808
+ const offset = (1 / n - 1 / 2) * Math.PI;
29527
29809
 
29528
- var components = /*#__PURE__*/Object.freeze({
29529
- __proto__: null,
29530
- ButtonGroup: ButtonGroup,
29531
- Graph: Graph,
29532
- Graphie: Graphie,
29533
- HUD: HUD,
29534
- Icon: Icon,
29535
- InfoTip: InfoTip,
29536
- InlineIcon: InlineIcon,
29537
- MathInput: MathInput,
29538
- MultiButtonGroup: MultiButtonGroup,
29539
- NumberInput: NumberInput,
29540
- PropCheckBox: PropCheckBox,
29541
- RangeInput: RangeInput,
29542
- SvgImage: SvgImage,
29543
- TextInput: TextInput,
29544
- TextListEditor: TextListEditor
29545
- });
29810
+ // TODO(alex): Generalize this to more than just triangles so that
29811
+ // all polygons have whole number side lengths if snapping to sides
29812
+ const radius = graph.snapTo === "sides" ? Math.sqrt(3) / 3 * 7 : 4;
29546
29813
 
29547
- /**
29548
- * If a graphie URL is provided in `backgroundImage`, will return the rendered graphie background.
29549
- * Otherwise, returns `null`.
29550
- */
29551
- const getLegacyGrid = (box, backgroundImage) => {
29552
- const {
29553
- url,
29554
- width,
29555
- height
29556
- } = backgroundImage ?? {};
29557
- if (url && typeof url === "string") {
29558
- const scale = box[0] / interactiveSizes$1.defaultBoxSize;
29559
- return /*#__PURE__*/React__namespace.createElement(wonderBlocksCore.View, {
29560
- style: {
29561
- position: "absolute",
29562
- bottom: 0,
29563
- left: 0
29564
- }
29565
- }, /*#__PURE__*/React__namespace.createElement(context$1.Consumer, null, _ref => {
29566
- let {
29567
- setAssetStatus
29568
- } = _ref;
29569
- return /*#__PURE__*/React__namespace.createElement(SvgImage, {
29570
- src: url,
29571
- width: width,
29572
- height: height,
29573
- scale: scale,
29574
- responsive: false,
29575
- setAssetStatus: setAssetStatus,
29576
- alt: ""
29577
- });
29578
- }));
29814
+ // Generate coords of a regular polygon with n sides
29815
+ coords = [...Array(n).keys()].map(i => [radius * Math.cos(i * angle + offset), radius * Math.sin(i * angle + offset)]);
29579
29816
  }
29580
- return null;
29817
+ coords = normalizeCoords(coords, [[-10, 10], [-10, 10]]);
29818
+ const snapToGrid = !["angles", "sides"].includes(graph.snapTo || "");
29819
+ coords = normalizePoints(range, step, coords, /* noSnap */!snapToGrid);
29820
+ return coords;
29581
29821
  };
29582
29822
 
29583
29823
  const renderGraph = props => {
@@ -29605,6 +29845,11 @@ const renderGraph = props => {
29605
29845
  graphState: state,
29606
29846
  dispatch: dispatch
29607
29847
  });
29848
+ case "polygon":
29849
+ return /*#__PURE__*/React__namespace.createElement(PolygonGraph, {
29850
+ graphState: state,
29851
+ dispatch: dispatch
29852
+ });
29608
29853
  default:
29609
29854
  return new wonderStuffCore.UnreachableCaseError(type);
29610
29855
  }
@@ -29618,8 +29863,8 @@ const MafsGraph = /*#__PURE__*/React__namespace.forwardRef((props, ref) => {
29618
29863
  }));
29619
29864
  return /*#__PURE__*/React__namespace.createElement(wonderBlocksCore.View, {
29620
29865
  style: {
29621
- width: props.backgroundImage?.width ?? width,
29622
- height: props.backgroundImage?.height ?? height,
29866
+ width,
29867
+ height,
29623
29868
  position: "relative"
29624
29869
  }
29625
29870
  }, legacyGrid, /*#__PURE__*/React__namespace.createElement(wonderBlocksCore.View, {
@@ -41649,7 +41894,7 @@ const init = function (options) {
41649
41894
 
41650
41895
  // This file is processed by a Rollup plugin (replace) to inject the production
41651
41896
  const libName = "@khanacademy/perseus";
41652
- const libVersion = "20.6.0";
41897
+ const libVersion = "20.7.0";
41653
41898
  perseusCore.addLibraryVersionToPerseusDebug(libName, libVersion);
41654
41899
 
41655
41900
  const apiVersion = {
@@ -44417,6 +44662,153 @@ function getWidgetTypeFromWidgetId(widgetId) {
44417
44662
  return widgetType;
44418
44663
  }
44419
44664
 
44665
+ let WidgetType = /*#__PURE__*/function (WidgetType) {
44666
+ WidgetType["Categorizer"] = "categorizer";
44667
+ WidgetType["CSProgram"] = "cs-program";
44668
+ WidgetType["Definition"] = "definition";
44669
+ WidgetType["Dropdown"] = "dropdown";
44670
+ WidgetType["Explanation"] = "explanation";
44671
+ WidgetType["Expression"] = "expression";
44672
+ WidgetType["GradedGroup"] = "graded-group";
44673
+ WidgetType["GradedGroupAnswerBar"] = "graded-group-answer-bar";
44674
+ WidgetType["GradedGroupSet"] = "graded-group-set";
44675
+ WidgetType["Grapher"] = "grapher";
44676
+ WidgetType["Group"] = "group";
44677
+ WidgetType["Iframe"] = "iframe";
44678
+ WidgetType["Image"] = "image";
44679
+ WidgetType["InputNumber"] = "input-number";
44680
+ WidgetType["Interaction"] = "interaction";
44681
+ WidgetType["InteractiveGraph"] = "interactive-graph";
44682
+ WidgetType["InteractiveNumberLine"] = "interactive-number-line";
44683
+ WidgetType["LabelImage"] = "label-image";
44684
+ WidgetType["Matcher"] = "matcher";
44685
+ WidgetType["Matrix"] = "matrix";
44686
+ WidgetType["Measurer"] = "measurer";
44687
+ WidgetType["Molecule"] = "molecule";
44688
+ WidgetType["NumberLine"] = "number-line";
44689
+ WidgetType["NumericInput"] = "numeric-input";
44690
+ WidgetType["Orderer"] = "orderer";
44691
+ WidgetType["Passage"] = "passage";
44692
+ WidgetType["PassageRef"] = "passage-ref";
44693
+ WidgetType["PassageRefTarget"] = "passage-ref-target";
44694
+ WidgetType["Plotter"] = "plotter";
44695
+ WidgetType["Protractor"] = "protractor";
44696
+ WidgetType["PythonProgram"] = "python-program";
44697
+ WidgetType["Radio"] = "radio";
44698
+ WidgetType["Sorter"] = "sorter";
44699
+ WidgetType["Table"] = "table";
44700
+ WidgetType["Unit"] = "unit";
44701
+ WidgetType["Video"] = "video";
44702
+ WidgetType["VideoTranscriptLink"] = "video-transcript-link";
44703
+ return WidgetType;
44704
+ }({});
44705
+ // These are all the current widgets that require user-input and are supported for automatic scoring
44706
+ const QUESTION_WIDGETS = ["numeric-input", "input-number", "radio", "interactive-graph", "interactive-number-line", "categorizer", "plotter", "orderer", "protractor", "matcher", "sorter"];
44707
+
44708
+ /**
44709
+ * Regex for widget placeholders in a string.
44710
+ *
44711
+ * First capture group is the widget ID (ex. 'radio 1')
44712
+ * Second capture group is the widget type (ex. "radio)
44713
+ * exec return will look like: ['[[☃ radio 1]]', 'radio 1', 'radio']
44714
+ */
44715
+ function getWidgetRegex() {
44716
+ return /\[\[☃ (([a-z-]+) \d+)\]\]/g;
44717
+ }
44718
+
44719
+ /**
44720
+ * Add a widget placeholder using the provided widget type and instance number.
44721
+ * ex. addWidget(WidgetType.Radio, 1) => "[[☃ radio 1]]"
44722
+ *
44723
+ * @param {WidgetType} widgetType
44724
+ * @param {number} instance
44725
+ * @returns {string}
44726
+ */
44727
+ function addWidget(widgetType, instance) {
44728
+ return `[[☃ ${widgetType} ${String(instance)}]]`;
44729
+ }
44730
+
44731
+ /**
44732
+ * Extract all widget IDs, which includes the widget type and instance number.
44733
+ * example output: ['radio 1', 'categorizer 1', 'categorizor 2']
44734
+ *
44735
+ * Content should contain Perseus widget placeholders,
44736
+ * which look like: '[[☃ radio 1]]'.
44737
+ *
44738
+ * @param {string} content
44739
+ * @returns {Array<WidgetId>} widgets
44740
+ */
44741
+ function getAllWidgetIds(content) {
44742
+ const widgets = [];
44743
+ const localWidgetRegex = getWidgetRegex();
44744
+ let match = localWidgetRegex.exec(content);
44745
+ while (match !== null) {
44746
+ widgets.push(match[1]);
44747
+ match = localWidgetRegex.exec(content);
44748
+ }
44749
+ return widgets;
44750
+ }
44751
+
44752
+ /**
44753
+ * Check if a specific widget is an actual widget type using its name.
44754
+ * The widget name should include a widget type, without an instance number,
44755
+ * as a string. ex. 'radio'
44756
+ *
44757
+ * @param {string} widgetName
44758
+ * @returns {boolean}
44759
+ */
44760
+ function isWidgetType(widgetName) {
44761
+ return Object.values(WidgetType).includes(widgetName);
44762
+ }
44763
+
44764
+ /**
44765
+ * Extract all widget types from a Perseus JSON content string.
44766
+ * This does not include the instance number and prevents duplicates.
44767
+ * example output: ['radio', 'categorizer']
44768
+ *
44769
+ * @param {string} content
44770
+ * @returns {Array<WidgetId>}
44771
+ */
44772
+ function getAllWidgetTypes(content) {
44773
+ const widgetTypes = [];
44774
+ const localWidgetRegex = getWidgetRegex();
44775
+ let match = localWidgetRegex.exec(content);
44776
+ while (match !== null) {
44777
+ const matchType = match[2];
44778
+ if (!widgetTypes.includes(matchType) && isWidgetType(matchType)) {
44779
+ widgetTypes.push(matchType);
44780
+ }
44781
+ match = localWidgetRegex.exec(content);
44782
+ }
44783
+ return widgetTypes;
44784
+ }
44785
+
44786
+ /**
44787
+ * Check if a specific widget is a question widget type using its ID.
44788
+ * The widget ID includes the widget type and the instance number.
44789
+ *
44790
+ * @param {WidgetId} widgetId
44791
+ * @returns {boolean}
44792
+ */
44793
+ function isQuestionWidgetType(widgetId) {
44794
+ return QUESTION_WIDGETS.includes(widgetId.split(" ")[0]);
44795
+ }
44796
+
44797
+ /**
44798
+ * Extract the widget IDs of all widgets considered question widgets. Widget IDs
44799
+ * include widget type and instance number.
44800
+ * example output: ['radio 1', 'categorizer 1']
44801
+ *
44802
+ * Content should contain Perseus widget placeholders,
44803
+ * which look like: '[[☃ radio 1]]'.
44804
+ *
44805
+ * @param {string} content
44806
+ * @returns Array<WidgetId>
44807
+ */
44808
+ function getQuestionWidgetIds(content) {
44809
+ return getAllWidgetIds(content).filter(isQuestionWidgetType);
44810
+ }
44811
+
44420
44812
  const EditorJsonify = {
44421
44813
  serialize: function () {
44422
44814
  // Omit props that get passed to all widgets
@@ -44458,6 +44850,7 @@ exports.PerseusError = PerseusError;
44458
44850
  exports.PerseusExpressionAnswerFormConsidered = PerseusExpressionAnswerFormConsidered;
44459
44851
  exports.PerseusMarkdown = PerseusMarkdown;
44460
44852
  exports.PlotterWidget = Plotter$1;
44853
+ exports.QUESTION_WIDGETS = QUESTION_WIDGETS;
44461
44854
  exports.Radio = Radio;
44462
44855
  exports.Renderer = Renderer;
44463
44856
  exports.ServerItemRenderer = ref;
@@ -44466,7 +44859,9 @@ exports.TableWidget = Table$1;
44466
44859
  exports.Util = Util;
44467
44860
  exports.WIDGET_PROP_DENYLIST = denylist;
44468
44861
  exports.WidgetJsonifyDeprecated = WidgetJsonifyDeprecated;
44862
+ exports.WidgetType = WidgetType;
44469
44863
  exports.Widgets = widgets$1;
44864
+ exports.addWidget = addWidget;
44470
44865
  exports.apiVersion = apiVersion;
44471
44866
  exports.buildEmptyItemTreeForShape = buildEmptyItemTreeForShape;
44472
44867
  exports.buildMapper = buildMapper;
@@ -44476,7 +44871,10 @@ exports.convertWidgetNameToEnum = convertWidgetNameToEnum;
44476
44871
  exports.displaySigFigs = displaySigFigs;
44477
44872
  exports.generateTestPerseusItem = generateTestPerseusItem;
44478
44873
  exports.genericPerseusItemData = genericPerseusItemData;
44874
+ exports.getAllWidgetIds = getAllWidgetIds;
44875
+ exports.getAllWidgetTypes = getAllWidgetTypes;
44479
44876
  exports.getAnswersFromWidgets = getAnswersFromWidgets;
44877
+ exports.getQuestionWidgetIds = getQuestionWidgetIds;
44480
44878
  exports.getWidgetTypeFromWidgetId = getWidgetTypeFromWidgetId;
44481
44879
  exports.globalConstants = globalConstants;
44482
44880
  exports.globalStyles = globalStyles;