@khanacademy/perseus-core 39.2.2 → 40.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.
- package/dist/index.d.ts +1 -1
- package/dist/index.js +20 -253
- package/dist/index.js.map +1 -1
- package/dist/widgets/sorter/sorter-util.d.ts +7 -0
- package/package.json +7 -14
- package/dist/es/index.js +0 -467
- package/dist/es/index.js.map +0 -1
package/dist/es/index.js
DELETED
|
@@ -1,467 +0,0 @@
|
|
|
1
|
-
import _ from 'underscore';
|
|
2
|
-
import invariant from 'tiny-invariant';
|
|
3
|
-
import * as KAS from '@khanacademy/kas';
|
|
4
|
-
import { addLibraryVersionToPerseusDebug } from '@khanacademy/perseus-utils';
|
|
5
|
-
import { UnreachableCaseError, keys } from '@khanacademy/wonder-stuff-core';
|
|
6
|
-
import { parse as parse$1, traverseContent } from '@khanacademy/pure-markdown';
|
|
7
|
-
|
|
8
|
-
const APPROXIMATED_PI_ERROR="APPROXIMATED_PI_ERROR";const CHOOSE_CORRECT_NUM_ERROR="CHOOSE_CORRECT_NUM_ERROR";const EMPTY_RESPONSE_ERROR="EMPTY_RESPONSE_ERROR";const EXTRA_SYMBOLS_ERROR="EXTRA_SYMBOLS_ERROR";const FILL_ALL_CELLS_ERROR="FILL_ALL_CELLS_ERROR";const INVALID_CHOICE_SELECTION="INVALID_CHOICE_SELECTION";const INVALID_SELECTION_ERROR="INVALID_SELECTION_ERROR";const MISSING_PERCENT_ERROR="MISSING_PERCENT_ERROR";const MULTIPLICATION_SIGN_ERROR="MULTIPLICATION_SIGN_ERROR";const NEEDS_TO_BE_SIMPLIFIED_ERROR="NEEDS_TO_BE_SIMPLIFIED_ERROR";const NOT_NONE_ABOVE_ERROR="NOT_NONE_ABOVE_ERROR";const USER_INPUT_EMPTY="USER_INPUT_EMPTY";const USER_INPUT_TOO_LONG="USER_INPUT_TOO_LONG";const WRONG_CASE_ERROR="WRONG_CASE_ERROR";const WRONG_LETTER_ERROR="WRONG_LETTER_ERROR";const ErrorCodes={APPROXIMATED_PI_ERROR,CHOOSE_CORRECT_NUM_ERROR,EMPTY_RESPONSE_ERROR,EXTRA_SYMBOLS_ERROR,FILL_ALL_CELLS_ERROR,INVALID_CHOICE_SELECTION,INVALID_SELECTION_ERROR,MISSING_PERCENT_ERROR,MULTIPLICATION_SIGN_ERROR,NEEDS_TO_BE_SIMPLIFIED_ERROR,NOT_NONE_ABOVE_ERROR,USER_INPUT_EMPTY,USER_INPUT_TOO_LONG,WRONG_CASE_ERROR,WRONG_LETTER_ERROR};
|
|
9
|
-
|
|
10
|
-
function getMatrixSize(matrix){const matrixSize=[1,1];matrix.forEach((matrixRow,row)=>{let rowWidth=0;matrixRow.forEach((matrixCol,col)=>{if(matrixCol!=null&&matrixCol.toString().length){rowWidth=col+1;}});matrixSize[1]=Math.max(matrixSize[1],rowWidth);if(rowWidth>0){matrixSize[0]=Math.max(matrixSize[0],row+1);}});return matrixSize}
|
|
11
|
-
|
|
12
|
-
const getDecimalSeparator=locale=>{switch(locale){case "ka":return ",";default:const parts=new Intl.NumberFormat(locale).formatToParts(1.1);const decimalPart=parts.find(part=>part.type==="decimal");return decimalPart?.value??"."}};
|
|
13
|
-
|
|
14
|
-
const localesThatUseColon=["az","bg","cs","da","de","hu","hy","id","it","ky","lt","lv","nb","nl","pl","pt-pt","ro","sv","uk","vi","ro","ru"];const getDivideSymbol=locale=>{if(localesThatUseColon.includes(locale)){return ":"}return "/"};const getDivideSymbolForTex=locale=>{const divideSymbol=getDivideSymbol(locale);return divideSymbol==="/"?"\\div":divideSymbol};
|
|
15
|
-
|
|
16
|
-
function approximateEqual(x,y){if(typeof x==="number"&&typeof y==="number"){return Math.abs(x-y)<1e-9}return x===y}function approximateDeepEqual(x,y){if(Array.isArray(x)&&Array.isArray(y)){if(x.length!==y.length){return false}for(let i=0;i<x.length;i++){if(!approximateDeepEqual(x[i],y[i])){return false}}return true}if(Array.isArray(x)||Array.isArray(y)){return false}if(typeof x==="function"&&typeof y==="function"){return approximateEqual(x,y)}if(typeof x==="function"||typeof y==="function"){return false}if(typeof x==="object"&&typeof y==="object"&&!!x&&!!y){return x===y||_.all(x,function(v,k){return approximateDeepEqual(y[k],v)})&&_.all(y,function(v,k){return approximateDeepEqual(x[k],v)})}if(typeof x==="object"&&!!x||typeof y==="object"&&!!y){return false}return approximateEqual(x,y)}
|
|
17
|
-
|
|
18
|
-
function addWidget(id){return `[[☃ ${id}]]`}function getWidgetRegex(){return /\[\[☃ ([A-Za-z0-9- ]+)\]\]/g}function getWidgetIdsFromContent(content){const widgets=[];const localWidgetRegex=getWidgetRegex();let match=localWidgetRegex.exec(content);while(match!==null){widgets.push(match[1]);match=localWidgetRegex.exec(content);}return widgets}function getWidgetIdsFromContentByType(type,content,widgetMap){const rv=[];const widgetIdsInContent=getWidgetIdsFromContent(content);widgetIdsInContent.forEach(widgetId=>{const widget=widgetMap[widgetId];if(widget?.type===type){rv.push(widgetId);}});return rv}
|
|
19
|
-
|
|
20
|
-
function deepClone(obj){return JSON.parse(JSON.stringify(obj))}
|
|
21
|
-
|
|
22
|
-
const MOVABLES={PLOT:"PLOT",PARABOLA:"PARABOLA",SINUSOID:"SINUSOID"};function canonicalSineCoefficients(coeffs){let amplitude=coeffs[0];let angularFrequency=coeffs[1];let phase=coeffs[2];const verticalOffset=coeffs[3];if(amplitude<0){amplitude*=-1;angularFrequency*=-1;phase*=-1;}const period=2*Math.PI;if(angularFrequency<0){angularFrequency*=-1;phase*=-1;phase+=period/2;}while(phase>0){phase-=period;}while(phase<0){phase+=period;}return [amplitude,angularFrequency,phase,verticalOffset]}const PlotDefaults={areEqual:function(coeffs1,coeffs2){return approximateDeepEqual(coeffs1,coeffs2)},movable:MOVABLES.PLOT,getPropsForCoeffs:function(coeffs){return {fn:_.partial(this.getFunctionForCoeffs,coeffs)}}};const Linear=_.extend({},PlotDefaults,{url:"https://ka-perseus-graphie.s3.amazonaws.com/67aaf581e6d9ef9038c10558a1f70ac21c11c9f8.png",defaultCoords:[[.25,.75],[.75,.75]],getCoefficients:function(coords){const p1=coords[0];const p2=coords[1];const denom=p2[0]-p1[0];const num=p2[1]-p1[1];if(denom===0){return}const m=num/denom;const b=p2[1]-m*p2[0];return [m,b]},getFunctionForCoeffs:function(coeffs,x){const m=coeffs[0];const b=coeffs[1];return m*x+b},getEquationString:function(coords){const coeffs=this.getCoefficients(coords);const m=coeffs[0];const b=coeffs[1];return "y = "+m.toFixed(3)+"x + "+b.toFixed(3)}});const Quadratic=_.extend({},PlotDefaults,{url:"https://ka-perseus-graphie.s3.amazonaws.com/e23d36e6fc29ee37174e92c9daba2a66677128ab.png",defaultCoords:[[.5,.5],[.75,.75]],movable:MOVABLES.PARABOLA,getCoefficients:function(coords){const p1=coords[0];const p2=coords[1];const h=p1[0];const k=p1[1];const a=(p2[1]-k)/((p2[0]-h)*(p2[0]-h));const b=-2*h*a;const c=a*h*h+k;return [a,b,c]},getFunctionForCoeffs:function(coeffs,x){const a=coeffs[0];const b=coeffs[1];const c=coeffs[2];return (a*x+b)*x+c},getPropsForCoeffs:function(coeffs){return {a:coeffs[0],b:coeffs[1],c:coeffs[2]}},getEquationString:function(coords){const coeffs=this.getCoefficients(coords);const a=coeffs[0];const b=coeffs[1];const c=coeffs[2];return "y = "+a.toFixed(3)+"x^2 + "+b.toFixed(3)+"x + "+c.toFixed(3)}});const Sinusoid=_.extend({},PlotDefaults,{url:"https://ka-perseus-graphie.s3.amazonaws.com/3d68e7718498475f53b206c2ab285626baf8857e.png",defaultCoords:[[.5,.5],[.6,.6]],movable:MOVABLES.SINUSOID,getCoefficients:function(coords){const p1=coords[0];const p2=coords[1];const a=p2[1]-p1[1];const b=Math.PI/(2*(p2[0]-p1[0]));const c=p1[0]*b;const d=p1[1];return [a,b,c,d]},getFunctionForCoeffs:function(coeffs,x){const a=coeffs[0];const b=coeffs[1];const c=coeffs[2];const d=coeffs[3];return a*Math.sin(b*x-c)+d},getPropsForCoeffs:function(coeffs){return {a:coeffs[0],b:coeffs[1],c:coeffs[2],d:coeffs[3]}},getEquationString:function(coords){const coeffs=this.getCoefficients(coords);const a=coeffs[0];const b=coeffs[1];const c=coeffs[2];const d=coeffs[3];return "y = "+a.toFixed(3)+" sin("+b.toFixed(3)+"x - "+c.toFixed(3)+") + "+d.toFixed(3)},areEqual:function(coeffs1,coeffs2){return approximateDeepEqual(canonicalSineCoefficients(coeffs1),canonicalSineCoefficients(coeffs2))}});const Tangent=_.extend({},PlotDefaults,{url:"https://ka-perseus-graphie.s3.amazonaws.com/7db80d23c35214f98659fe1cf0765811c1bbfbba.png",defaultCoords:[[.5,.5],[.75,.75]],getCoefficients:function(coords){const p1=coords[0];const p2=coords[1];const a=p2[1]-p1[1];const b=Math.PI/(4*(p2[0]-p1[0]));const c=p1[0]*b;const d=p1[1];return [a,b,c,d]},getFunctionForCoeffs:function(coeffs,x){const a=coeffs[0];const b=coeffs[1];const c=coeffs[2];const d=coeffs[3];return a*Math.tan(b*x-c)+d},getEquationString:function(coords){const coeffs=this.getCoefficients(coords);const a=coeffs[0];const b=coeffs[1];const c=coeffs[2];const d=coeffs[3];return "y = "+a.toFixed(3)+" tan("+b.toFixed(3)+"x - "+c.toFixed(3)+") + "+d.toFixed(3)}});const Exponential=_.extend({},PlotDefaults,{url:"https://ka-perseus-graphie.s3.amazonaws.com/9cbfad55525e3ce755a31a631b074670a5dad611.png",defaultCoords:[[.5,.55],[.75,.75]],defaultAsymptote:[[0,.5],[1,.5]],extraCoordConstraint:function(newCoord,oldCoord,coords,asymptote,graph){const y=asymptote[0][1];return _.all(coords,coord=>coord[1]!==y)},extraAsymptoteConstraint:function(newCoord,oldCoord,coords,asymptote,graph){const y=newCoord[1];const isValid=_.all(coords,coord=>coord[1]>y)||_.all(coords,coord=>coord[1]<y);if(isValid){return [oldCoord[0],y]}const oldY=oldCoord[1];const wasBelow=_.all(coords,coord=>coord[1]>oldY);if(wasBelow){const bottomMost=_.min(coords.map(coord=>coord[1]));return [oldCoord[0],bottomMost-graph.snapStep[1]]}const topMost=_.max(coords.map(coord=>coord[1]));return [oldCoord[0],topMost+graph.snapStep[1]]},allowReflectOverAsymptote:true,getCoefficients:function(coords,asymptote){const p1=coords[0];const p2=coords[1];const c=asymptote[0][1];const b=Math.log((p1[1]-c)/(p2[1]-c))/(p1[0]-p2[0]);const a=(p1[1]-c)/Math.exp(b*p1[0]);return [a,b,c]},getFunctionForCoeffs:function(coeffs,x){const a=coeffs[0];const b=coeffs[1];const c=coeffs[2];return a*Math.exp(b*x)+c},getEquationString:function(coords,asymptote){if(!asymptote){return null}const coeffs=this.getCoefficients(coords,asymptote);const a=coeffs[0];const b=coeffs[1];const c=coeffs[2];return "y = "+a.toFixed(3)+"e^("+b.toFixed(3)+"x) + "+c.toFixed(3)}});const Logarithm=_.extend({},PlotDefaults,{url:"https://ka-perseus-graphie.s3.amazonaws.com/f6491e99d34af34d924bfe0231728ad912068dc3.png",defaultCoords:[[.55,.5],[.75,.75]],defaultAsymptote:[[.5,0],[.5,1]],extraCoordConstraint:function(newCoord,oldCoord,coords,asymptote,graph){const x=asymptote[0][0];return _.all(coords,coord=>coord[0]!==x)&&coords[0][1]!==coords[1][1]},extraAsymptoteConstraint:function(newCoord,oldCoord,coords,asymptote,graph){const x=newCoord[0];const isValid=_.all(coords,coord=>coord[0]>x)||_.all(coords,coord=>coord[0]<x);if(isValid){return [x,oldCoord[1]]}const oldX=oldCoord[0];const wasLeft=_.all(coords,coord=>coord[0]>oldX);if(wasLeft){const leftMost=_.min(coords.map(coord=>coord[0]));return [leftMost-graph.snapStep[0],oldCoord[1]]}const rightMost=_.max(coords.map(coord=>coord[0]));return [rightMost+graph.snapStep[0],oldCoord[1]]},allowReflectOverAsymptote:true,getCoefficients:function(coords,asymptote){const flip=coord=>[coord[1],coord[0]];const inverseCoeffs=Exponential.getCoefficients(coords.map(flip),asymptote.map(flip));if(inverseCoeffs){const c=-inverseCoeffs[2]/inverseCoeffs[0];const b=1/inverseCoeffs[0];const a=1/inverseCoeffs[1];return [a,b,c]}},getFunctionForCoeffs:function(coeffs,x,asymptote){const a=coeffs[0];const b=coeffs[1];const c=coeffs[2];return a*Math.log(b*x+c)},getEquationString:function(coords,asymptote){if(!asymptote){return null}const coeffs=this.getCoefficients(coords,asymptote);const a=coeffs[0];const b=coeffs[1];const c=coeffs[2];return "y = ln("+a.toFixed(3)+"x + "+b.toFixed(3)+") + "+c.toFixed(3)}});const AbsoluteValue=_.extend({},PlotDefaults,{url:"https://ka-perseus-graphie.s3.amazonaws.com/8256a630175a0cb1d11de223d6de0266daf98721.png",defaultCoords:[[.5,.5],[.75,.75]],getCoefficients:function(coords){const p1=coords[0];const p2=coords[1];const denom=p2[0]-p1[0];const num=p2[1]-p1[1];if(denom===0){return}let m=Math.abs(num/denom);if(p2[1]<p1[1]){m*=-1;}const horizontalOffset=p1[0];const verticalOffset=p1[1];return [m,horizontalOffset,verticalOffset]},getFunctionForCoeffs:function(coeffs,x){const m=coeffs[0];const horizontalOffset=coeffs[1];const verticalOffset=coeffs[2];return m*Math.abs(x-horizontalOffset)+verticalOffset},getEquationString:function(coords){const coeffs=this.getCoefficients(coords);const m=coeffs[0];const horizontalOffset=coeffs[1];const verticalOffset=coeffs[2];return "y = "+m.toFixed(3)+"| x - "+horizontalOffset.toFixed(3)+"| + "+verticalOffset.toFixed(3)}});const functionTypeMapping={linear:Linear,quadratic:Quadratic,sinusoid:Sinusoid,tangent:Tangent,exponential:Exponential,logarithm:Logarithm,absolute_value:AbsoluteValue};const allTypes=Object.keys(functionTypeMapping);function functionForType(type){return functionTypeMapping[type]}
|
|
23
|
-
|
|
24
|
-
var grapherUtil = /*#__PURE__*/Object.freeze({
|
|
25
|
-
__proto__: null,
|
|
26
|
-
MOVABLES: MOVABLES,
|
|
27
|
-
allTypes: allTypes,
|
|
28
|
-
functionForType: functionForType
|
|
29
|
-
});
|
|
30
|
-
|
|
31
|
-
const blankPerseusRenderer={content:"",images:{},widgets:{}};function generateTestPerseusRenderer(customFields={}){return deepClone({...blankPerseusRenderer,...customFields})}const blankPerseusItemData={question:generateTestPerseusRenderer(),answerArea:{calculator:false,calculatorVariant:undefined,periodicTable:false,financialCalculatorMonthlyPayment:false,financialCalculatorTotalAmount:false,financialCalculatorTimeToPayOff:false,periodicTableWithKey:false},hints:[]};function generateTestPerseusItem(customFields={}){return deepClone({...blankPerseusItemData,...customFields})}
|
|
32
|
-
|
|
33
|
-
const itemHasRationales=item=>widgetsHaveRationales(item.question.widgets);const widgetsHaveRationales=widgets=>Object.values(widgets).some(widgetHasRationales);const widgetHasRationales=widget=>{switch(widget.type){case "radio":return radioWidgetHasRationales(widget);case "label-image":return labelImageWidgetHasRationales(widget);case "graded-group":case "group":return widgetsHaveRationales(widget.options.widgets);default:return false}};const radioWidgetHasRationales=widget=>{return widget.options.choices.some(choice=>!!choice.rationale)};const labelImageWidgetHasRationales=widget=>{return widget.options.markers.some(marker=>marker.answers.length>0)};
|
|
34
|
-
|
|
35
|
-
const itemHasHints=item=>{return item.hints.length>0};
|
|
36
|
-
|
|
37
|
-
const makeSafeUrl=(urlString,locale,expectedOrigin)=>{let url;try{url=new URL(urlString);}catch{return null}if(url.origin!==expectedOrigin){return null}url.searchParams.set("locale",locale);return url};
|
|
38
|
-
|
|
39
|
-
function removeOrphanedWidgetsFromPerseusItem(item){return {...item,question:removeOrphanedWidgets(item.question),hints:item.hints.map(removeOrphanedWidgets)}}function removeOrphanedWidgets(renderer){const referencedWidgetIds=getWidgetIdsFromContent(renderer.content);const referencedWidgets={};for(const id of referencedWidgetIds){if(renderer.widgets[id]){referencedWidgets[id]=renderer.widgets[id];}}return {...renderer,widgets:referencedWidgets}}
|
|
40
|
-
|
|
41
|
-
function success(value){return {type:"success",value}}function failure(detail){return {type:"failure",detail}}function isFailure(result){return result.type==="failure"}function isSuccess(result){return result.type==="success"}function all(results,combineFailureDetails=a=>a){const values=[];const failureDetails=[];for(const result of results){if(result.type==="success"){values.push(result.value);}else {failureDetails.push(result.detail);}}if(failureDetails.length>0){return failure(failureDetails.reduce(combineFailureDetails))}return success(values)}
|
|
42
|
-
|
|
43
|
-
class ErrorTrackingParseContext{failure(expected,badValue){return failure([{expected:wrapInArray(expected),badValue,path:this.path}])}forSubtree(key){return new ErrorTrackingParseContext([...this.path,key])}success(value){return success(value)}constructor(path){this.path=path;}}function wrapInArray(a){return Array.isArray(a)?a:[a]}
|
|
44
|
-
|
|
45
|
-
function formatPath(path){return "(root)"+path.map(formatPathSegment).join("")}function formatPathSegment(segment){if(typeof segment==="string"){return validIdentifier.test(segment)?"."+segment:`[${JSON.stringify(segment)}]`}return `[${segment.toString()}]`}const validIdentifier=/^[A-Za-z$_][A-Za-z$_0-9]*$/;
|
|
46
|
-
|
|
47
|
-
function message(failure){const expected=conjoin(failure.expected);const path=formatPath(failure.path);const badValue=JSON.stringify(failure.badValue);return `At ${path} -- expected ${expected}, but got ${badValue}`}function conjoin(items){switch(items.length){case 1:return items[0];case 2:return items.join(" or ");default:{const allButLast=items.slice(0,items.length-1);const last=items[items.length-1];return allButLast.join(", ")+", or "+last}}}
|
|
48
|
-
|
|
49
|
-
function parse(value,parser){const result=parser(value,new ErrorTrackingParseContext([]));if(isFailure(result)){return failure(result.detail.map(message).join("; "))}return result}
|
|
50
|
-
|
|
51
|
-
const any=(rawValue,ctx)=>ctx.success(rawValue);
|
|
52
|
-
|
|
53
|
-
function array(elementParser){return (rawValue,ctx)=>{if(!Array.isArray(rawValue)){return ctx.failure("array",rawValue)}const elementResults=rawValue.map((elem,i)=>elementParser(elem,ctx.forSubtree(i)));return all(elementResults,concat)}}function arrayWithIndex(elementParserFactory){return (rawValue,ctx)=>{if(!Array.isArray(rawValue)){return ctx.failure("array",rawValue)}const elementResults=rawValue.map((elem,index)=>{const elementParser=elementParserFactory(index);return elementParser(elem,ctx.forSubtree(index))});return all(elementResults,concat)}}function concat(a,b){return [...a,...b]}
|
|
54
|
-
|
|
55
|
-
function boolean(rawValue,ctx){if(typeof rawValue==="boolean"){return ctx.success(rawValue)}return ctx.failure("boolean",rawValue)}
|
|
56
|
-
|
|
57
|
-
function constant(acceptedValue){return (rawValue,ctx)=>{if(!Object.is(rawValue,acceptedValue)){return ctx.failure(String(JSON.stringify(acceptedValue)),rawValue)}return ctx.success(acceptedValue)}}
|
|
58
|
-
|
|
59
|
-
function defaulted(parser,fallback){return (rawValue,ctx)=>{if(rawValue==null){return success(fallback(rawValue))}return parser(rawValue,ctx)}}function defaultedNonEmptyString(fallback){return (rawValue,ctx)=>{if(rawValue==null){return ctx.success(fallback())}if(typeof rawValue==="string"){if(rawValue.trim()===""){return ctx.success(fallback())}return ctx.success(rawValue)}return ctx.failure("string",rawValue)}}
|
|
60
|
-
|
|
61
|
-
function enumeration(...acceptedValues){return (rawValue,ctx)=>{if(typeof rawValue==="string"||rawValue==null){const index=acceptedValues.indexOf(rawValue);if(index>-1){return ctx.success(acceptedValues[index])}}const expected=acceptedValues.map(v=>JSON.stringify(v));return ctx.failure(expected,rawValue)}}
|
|
62
|
-
|
|
63
|
-
const objectConstructorString=Object.prototype.constructor.toString();const functionToString=Function.prototype.toString;function isPlainObject(x){if(x==null){return false}const prototype=Object.getPrototypeOf(x);if(prototype==null){return true}return typeof prototype.constructor==="function"&&functionToString.call(prototype.constructor)===objectConstructorString}
|
|
64
|
-
|
|
65
|
-
function nullable(parseValue){return (rawValue,ctx)=>{if(rawValue===null){return ctx.success(rawValue)}return parseValue(rawValue,ctx)}}
|
|
66
|
-
|
|
67
|
-
const number=(rawValue,ctx)=>{if(typeof rawValue==="number"&&Number.isFinite(rawValue)){return ctx.success(rawValue)}return ctx.failure("number",rawValue)};
|
|
68
|
-
|
|
69
|
-
function object(schema){return objectParserWithInitializer(()=>({}),schema)}function looseObject(schema){return objectParserWithInitializer(rawValue=>({...rawValue}),schema)}function objectParserWithInitializer(initializeParsedValue,schema){return (rawValue,ctx)=>{if(!isPlainObject(rawValue)){return ctx.failure("object",rawValue)}const parsed=initializeParsedValue(rawValue);const mismatches=[];for(const[prop,propParser]of Object.entries(schema)){const result=propParser(rawValue[prop],ctx.forSubtree(prop));if(isSuccess(result)){if(result.value!==undefined||prop in rawValue){parsed[prop]=result.value;}}else {mismatches.push(...result.detail);}}if(mismatches.length>0){return failure(mismatches)}return ctx.success(parsed)}}
|
|
70
|
-
|
|
71
|
-
function optional(parseValue){return (rawValue,ctx)=>{if(rawValue===undefined){return ctx.success(rawValue)}return parseValue(rawValue,ctx)}}
|
|
72
|
-
|
|
73
|
-
function pair(parseA,parseB){return (rawValue,ctx)=>{if(!Array.isArray(rawValue)){return ctx.failure("array",rawValue)}if(rawValue.length!==2){return ctx.failure("array of length 2",rawValue)}const[rawA,rawB]=rawValue;const resultA=parseA(rawA,ctx.forSubtree(0));if(isFailure(resultA)){return resultA}const resultB=parseB(rawB,ctx.forSubtree(1));if(isFailure(resultB)){return resultB}return ctx.success([resultA.value,resultB.value])}}
|
|
74
|
-
|
|
75
|
-
function pipeParsers(p){return new ParserPipeline(p)}class ParserPipeline{then(nextParser){return new ParserPipeline(composeParsers(this.parser,nextParser))}constructor(parser){this.parser=parser;}}function composeParsers(parserA,parserB){return (rawValue,ctx)=>{const partialResult=parserA(rawValue,ctx);if(isFailure(partialResult)){return partialResult}return parserB(partialResult.value,ctx)}}
|
|
76
|
-
|
|
77
|
-
function record(parseKey,parseValue){return (rawValue,ctx)=>{if(!isPlainObject(rawValue)){return ctx.failure("object",rawValue)}const result={};const mismatches=[];for(const[key,value]of Object.entries(rawValue)){const entryCtx=ctx.forSubtree(key);const keyResult=parseKey(key,entryCtx);if(isFailure(keyResult)){mismatches.push(...keyResult.detail);}const valueResult=parseValue(value,entryCtx);if(isFailure(valueResult)){mismatches.push(...valueResult.detail);}if(isSuccess(keyResult)&&isSuccess(valueResult)){result[keyResult.value]=valueResult.value;}}if(mismatches.length>0){return failure(mismatches)}return ctx.success(result)}}
|
|
78
|
-
|
|
79
|
-
const string=(rawValue,ctx)=>{if(typeof rawValue==="string"){return ctx.success(rawValue)}return ctx.failure("string",rawValue)};
|
|
80
|
-
|
|
81
|
-
function trio(parseA,parseB,parseC){return (rawValue,ctx)=>{if(!Array.isArray(rawValue)){return ctx.failure("array",rawValue)}if(rawValue.length!==3){return ctx.failure("array of length 3",rawValue)}const resultA=parseA(rawValue[0],ctx.forSubtree(0));if(isFailure(resultA)){return resultA}const resultB=parseB(rawValue[1],ctx.forSubtree(1));if(isFailure(resultB)){return resultB}const resultC=parseC(rawValue[2],ctx.forSubtree(2));if(isFailure(resultC)){return resultC}return ctx.success([resultA.value,resultB.value,resultC.value])}}
|
|
82
|
-
|
|
83
|
-
function union(parseBranch){return new UnionBuilder(parseBranch)}class UnionBuilder{or(newBranch){return new UnionBuilder(either(this.parser,newBranch))}constructor(parser){this.parser=parser;}}function either(parseA,parseB){return (rawValue,ctx)=>{const resultA=parseA(rawValue,ctx);if(isSuccess(resultA)){return resultA}return parseB(rawValue,ctx)}}
|
|
84
|
-
|
|
85
|
-
const parsePerseusImageDetail=object({width:number,height:number});
|
|
86
|
-
|
|
87
|
-
const parseImages=defaulted(record(string,parsePerseusImageDetail),()=>({}));
|
|
88
|
-
|
|
89
|
-
function convert(f){return (rawValue,ctx)=>ctx.success(f(rawValue))}
|
|
90
|
-
|
|
91
|
-
function toValidAlignment(alignment){switch(alignment){case "default":case "block":case "inline-block":case "inline":case "wrap-left":case "wrap-right":case "full-width":case undefined:return alignment;default:return "default"}}const parseAlignment=pipeParsers(optional(string)).then(convert(toValidAlignment)).parser;const forceUndefined=(_rawValue,ctx)=>ctx.success(undefined);function parseWidget(parseType,parseOptions,{supportsStatic=true}={}){return object({type:parseType,static:supportsStatic?optional(boolean):forceUndefined,graded:optional(boolean),alignment:parseAlignment,options:parseOptions,key:optional(nullable(number)),version:optional(object({major:number,minor:number}))})}function parseWidgetWithVersion(parseVersion,parseType,parseOptions,{supportsStatic=true}={}){return object({type:parseType,static:supportsStatic?optional(boolean):forceUndefined,graded:optional(boolean),alignment:parseAlignment,options:parseOptions,key:optional(nullable(number)),version:parseVersion})}
|
|
92
|
-
|
|
93
|
-
const parseBlankWidget=parseWidget(constant("blank"),object({displayType:defaulted(enumeration("normal","superscript","subscript"),()=>"normal"),correctId:string}));
|
|
94
|
-
|
|
95
|
-
const parseCategorizerWidget=parseWidget(constant("categorizer"),object({items:array(string),categories:array(string),randomizeItems:defaulted(boolean,()=>false),values:defaulted(array(defaulted(number,()=>0)),()=>[])}));
|
|
96
|
-
|
|
97
|
-
const parseCSProgramWidget=parseWidget(constant("cs-program"),object({programID:string,programType:any,settings:array(object({name:string,value:string})),showEditor:boolean,showButtons:boolean,height:number}));
|
|
98
|
-
|
|
99
|
-
const parseDefinitionWidget=parseWidget(constant("definition"),object({togglePrompt:string,definition:string}),{supportsStatic:false});
|
|
100
|
-
|
|
101
|
-
const parseDropdownWidget=parseWidget(constant("dropdown"),object({placeholder:defaulted(string,()=>""),ariaLabel:optional(string),visibleLabel:optional(string),choices:array(object({content:string,correct:defaulted(boolean,()=>false)}))}));
|
|
102
|
-
|
|
103
|
-
const parseExplanationWidget=parseWidget(constant("explanation"),object({showPrompt:string,hidePrompt:string,explanation:string,widgets:defaulted((rawVal,ctx)=>parseWidgetsMap(rawVal,ctx),()=>({}))}),{supportsStatic:false});
|
|
104
|
-
|
|
105
|
-
const KeypadKeys=["PLUS","MINUS","NEGATIVE","TIMES","DIVIDE","DECIMAL","PERIOD","PERCENT","CDOT","EQUAL","NEQ","GT","LT","GEQ","LEQ","FRAC_INCLUSIVE","FRAC_EXCLUSIVE","FRAC","EXP","EXP_2","EXP_3","SUB","SQRT","CUBE_ROOT","RADICAL","LEFT_PAREN","RIGHT_PAREN","LN","LOG","LOG_N","SIN","COS","TAN","PI","THETA","UP","RIGHT","DOWN","LEFT","BACKSPACE","DISMISS","JUMP_OUT_PARENTHESES","JUMP_OUT_EXPONENT","JUMP_OUT_BASE","JUMP_INTO_NUMERATOR","JUMP_OUT_NUMERATOR","JUMP_OUT_DENOMINATOR","NUM_0","NUM_1","NUM_2","NUM_3","NUM_4","NUM_5","NUM_6","NUM_7","NUM_8","NUM_9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
|
|
106
|
-
|
|
107
|
-
function deriveExtraKeys(widgetOptions){if(widgetOptions.extraKeys){return widgetOptions.extraKeys}const defaultKeys=["PI"];if(widgetOptions.answerForms==null){return defaultKeys}const uniqueExtraVariables={};const uniqueExtraConstants={};for(const answerForm of widgetOptions.answerForms){const maybeExpr=KAS.parse(answerForm.value,widgetOptions);if(maybeExpr.parsed){const expr=maybeExpr.expr;const isGreek=symbol=>symbol==="pi"||symbol==="theta";const toKey=symbol=>isGreek(symbol)?symbol.toUpperCase():symbol;const isKey=key=>KeypadKeys.includes(key);for(const variable of expr.getVars()){const maybeKey=toKey(variable);if(isKey(maybeKey)){uniqueExtraVariables[maybeKey]=true;}}for(const constant of expr.getConsts()){const maybeKey=toKey(constant);if(isKey(maybeKey)){uniqueExtraConstants[maybeKey]=true;}}}}const extraVariables=Object.keys(uniqueExtraVariables).sort();const extraConstants=Object.keys(uniqueExtraConstants).sort();const extraKeys=[...extraVariables,...extraConstants];if(!extraKeys.length){return defaultKeys}return extraKeys}
|
|
108
|
-
|
|
109
|
-
const keypadKeys=enumeration("PLUS","MINUS","NEGATIVE","TIMES","DIVIDE","DECIMAL","PERIOD","PERCENT","CDOT","EQUAL","NEQ","GT","LT","GEQ","LEQ","FRAC_INCLUSIVE","FRAC_EXCLUSIVE","FRAC","EXP","EXP_2","EXP_3","SUB","SQRT","CUBE_ROOT","RADICAL","LEFT_PAREN","RIGHT_PAREN","LN","LOG","LOG_N","SIN","COS","TAN","PI","THETA","UP","RIGHT","DOWN","LEFT","BACKSPACE","DISMISS","JUMP_OUT_PARENTHESES","JUMP_OUT_EXPONENT","JUMP_OUT_BASE","JUMP_INTO_NUMERATOR","JUMP_OUT_NUMERATOR","JUMP_OUT_DENOMINATOR","NUM_0","NUM_1","NUM_2","NUM_3","NUM_4","NUM_5","NUM_6","NUM_7","NUM_8","NUM_9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
|
|
110
|
-
|
|
111
|
-
const parseLegacyButtonSet=enumeration("basic","basic+div","trig","prealgebra","logarithms","basic relations","advanced relations","scientific");const parseLegacyButtonSets=defaulted(array(parseLegacyButtonSet),()=>["basic","trig","prealgebra","logarithms"]);
|
|
112
|
-
|
|
113
|
-
function versionedWidgetOptions(latestMajorVersion,parseLatest){return new VersionedWidgetOptionsParserBuilder(latestMajorVersion,parseLatest,latest=>latest,(raw,ctx)=>ctx.failure("widget options with a known version number",raw))}class VersionedWidgetOptionsParserBuilder{withMigrationFrom(majorVersion,parseOldVersion,migrateToNextVersion){const parseOtherVersions=this.parser;const migrateToLatest=old=>this.migrateToLatest(migrateToNextVersion(old));return new VersionedWidgetOptionsParserBuilder(majorVersion,parseOldVersion,migrateToLatest,parseOtherVersions)}constructor(majorVersion,parseThisVersion,migrateToLatest,parseOtherVersions){this.migrateToLatest=migrateToLatest;this.parseOtherVersions=parseOtherVersions;const parseThisVersionAndMigrateToLatest=pipeParsers(parseThisVersion).then(convert(this.migrateToLatest)).parser;this.parser=(raw,ctx)=>{if(!isPlainObject(raw)){return ctx.failure("object",raw)}const versionParseResult=parseVersionedObject(raw,ctx);if(isFailure(versionParseResult)){return versionParseResult}if(versionParseResult.value.version.major!==majorVersion){return this.parseOtherVersions(raw,ctx)}return parseThisVersionAndMigrateToLatest(raw,ctx)};}}const parseVersionedObject=object({version:defaulted(object({major:number,minor:number}),()=>({major:0,minor:0}))});
|
|
114
|
-
|
|
115
|
-
const stringOrNumberOrNullOrUndefined=union(string).or(number).or(constant(null)).or(constant(undefined)).parser;function numberOrNullToString(v){return typeof v==="number"||v===null?String(v):v}const parsePossiblyInvalidAnswerForm=object({value:optional(string),form:defaulted(boolean,()=>false),simplify:defaulted(boolean,()=>false),considered:enumeration("correct","wrong","ungraded"),key:pipeParsers(stringOrNumberOrNullOrUndefined).then(convert(numberOrNullToString)).parser});function removeInvalidAnswerForms(possiblyInvalid){return possiblyInvalid.flatMap(answerForm=>{const{value}=answerForm;if(value!=null){return [{...answerForm,value}]}return []})}const parseAnswerForms=pipeParsers(defaulted(array(parsePossiblyInvalidAnswerForm),()=>[])).then(convert(removeInvalidAnswerForms)).parser;const version2$1=object({major:constant(2),minor:number});const parseExpressionWidgetV2=parseWidgetWithVersion(version2$1,constant("expression"),object({answerForms:parseAnswerForms,functions:array(string),times:boolean,visibleLabel:optional(string),ariaLabel:optional(string),buttonSets:parseLegacyButtonSets,buttonsVisible:optional(enumeration("always","never","focused")),extraKeys:optional(array(keypadKeys))}));const version1$2=object({major:constant(1),minor:number});const parseExpressionWidgetV1=parseWidgetWithVersion(version1$2,constant("expression"),object({answerForms:parseAnswerForms,functions:array(string),times:boolean,visibleLabel:optional(string),ariaLabel:optional(string),buttonSets:parseLegacyButtonSets,buttonsVisible:optional(enumeration("always","never","focused"))}));function migrateV1ToV2$1(widget){const{options}=widget;return {...widget,version:{major:2,minor:0},options:{times:options.times,buttonSets:options.buttonSets,functions:options.functions,buttonsVisible:options.buttonsVisible,visibleLabel:options.visibleLabel,ariaLabel:options.ariaLabel,answerForms:options.answerForms,extraKeys:deriveExtraKeys(options)??[]}}}const version0$2=optional(object({major:constant(0),minor:number}));const parseExpressionWidgetV0=parseWidgetWithVersion(version0$2,constant("expression"),object({functions:array(string),times:boolean,visibleLabel:optional(string),ariaLabel:optional(string),form:boolean,simplify:boolean,value:string,buttonSets:parseLegacyButtonSets,buttonsVisible:optional(enumeration("always","never","focused"))}));function migrateV0ToV1$4(widget){const{options}=widget;return {...widget,version:{major:1,minor:0},options:{times:options.times,buttonSets:options.buttonSets,functions:options.functions,buttonsVisible:options.buttonsVisible,visibleLabel:options.visibleLabel,ariaLabel:options.ariaLabel,answerForms:[{considered:"correct",form:options.form,simplify:options.simplify,value:options.value}]}}}const parseExpressionWidget=versionedWidgetOptions(2,parseExpressionWidgetV2).withMigrationFrom(1,parseExpressionWidgetV1,migrateV1ToV2$1).withMigrationFrom(0,parseExpressionWidgetV0,migrateV0ToV1$4).parser;
|
|
116
|
-
|
|
117
|
-
const answerTileSchema={id:string,content:string,label:string,imageHeight:optional(number)};const parseAnswerTile=object(answerTileSchema);
|
|
118
|
-
|
|
119
|
-
const usesPerTile=(rawValue,ctx)=>{if(rawValue==="unlimited"){return ctx.success(rawValue)}if(typeof rawValue==="number"&&Number.isInteger(rawValue)&&rawValue>=1){return ctx.success(rawValue)}return ctx.failure('a positive number, or "unlimited"',rawValue)};const parseFillInTheBlankWidget=parseWidget(constant("fill-in-the-blank"),object({content:string,widgets:(rawVal,ctx)=>parseWidgetsMap(rawVal,ctx),tiles:array(parseAnswerTile),maxUsesPerTile:usesPerTile,randomize:boolean}));
|
|
120
|
-
|
|
121
|
-
const parseFreeResponseWidget=parseWidget(constant("free-response"),object({allowUnlimitedCharacters:boolean,characterLimit:number,placeholder:string,question:string,scoringCriteria:array(object({text:string}))}));
|
|
122
|
-
|
|
123
|
-
const booleanOrFalse=defaulted(boolean,()=>false);const calculatorVariantOrUndefined=pipeParsers(defaulted(nullable(enumeration("scientific","graphing","four_function")),()=>null)).then(convert(v=>v??undefined)).parser;const baseParser=defaulted(object({calculator:booleanOrFalse,calculatorVariant:calculatorVariantOrUndefined,financialCalculatorMonthlyPayment:booleanOrFalse,financialCalculatorTotalAmount:booleanOrFalse,financialCalculatorTimeToPayOff:booleanOrFalse,periodicTable:booleanOrFalse,periodicTableWithKey:booleanOrFalse}),()=>({calculator:false,calculatorVariant:undefined,financialCalculatorMonthlyPayment:false,financialCalculatorTotalAmount:false,financialCalculatorTimeToPayOff:false,periodicTable:false,periodicTableWithKey:false}));const parsePerseusAnswerArea=pipeParsers(baseParser).then(convert(parsed=>{const{calculatorVariant:parsedCalcVariant,...rest}=parsed;const calculatorVariant=parsed.calculator&&parsedCalcVariant===undefined?"scientific":parsedCalcVariant;return calculatorVariant!==undefined?{...rest,calculatorVariant}:rest})).parser;
|
|
124
|
-
|
|
125
|
-
const falseToNull=pipeParsers(constant(false)).then(convert(()=>null)).parser;const parseGradedGroupWidgetOptions=object({title:defaulted(string,()=>""),hint:union(falseToNull).or(constant(null)).or(constant(undefined)).or((rawVal,ctx)=>parsePerseusRenderer(rawVal,ctx)).parser,content:string,widgets:(rawVal,ctx)=>parseWidgetsMap(rawVal,ctx),images:record(string,object({width:number,height:number})),answerArea:optional(parsePerseusAnswerArea)});const parseGradedGroupWidget=parseWidget(constant("graded-group"),parseGradedGroupWidgetOptions);
|
|
126
|
-
|
|
127
|
-
const parseGradedGroupSetWidget=parseWidget(constant("graded-group-set"),object({gradedGroups:array(parseGradedGroupWidgetOptions)}));
|
|
128
|
-
|
|
129
|
-
function discriminatedUnionOn(discriminantKey){const noMoreBranches=(raw,ctx)=>{if(!isPlainObject(raw)){return ctx.failure("object",raw)}return ctx.forSubtree(discriminantKey).failure("a valid value",raw[discriminantKey])};return new DiscriminatedUnionBuilder(discriminantKey,noMoreBranches)}class DiscriminatedUnionBuilder{withBranch(discriminantValue,parseNewVariant){const parseNewBranch=discriminatedUnionBranch(this.discriminantKey,discriminantValue,parseNewVariant,this.parser);return new DiscriminatedUnionBuilder(this.discriminantKey,parseNewBranch)}constructor(discriminantKey,parser){this.discriminantKey=discriminantKey;this.parser=parser;}}function discriminatedUnionBranch(discriminantKey,discriminantValue,parseVariant,parseOtherBranches){return (raw,ctx)=>{if(!isPlainObject(raw)){return ctx.failure("object",raw)}if(raw[discriminantKey]===discriminantValue){return parseVariant(raw,ctx)}return parseOtherBranches(raw,ctx)}}
|
|
130
|
-
|
|
131
|
-
const pairOfNumbers$3=pair(number,number);const pairOfPoints=pair(pairOfNumbers$3,pairOfNumbers$3);const emptyArray=(rawVal,ctx)=>{if(Array.isArray(rawVal)&&rawVal.length===0){return ctx.success([])}return ctx.failure("empty array",rawVal)};const parseCoords=union(nullable(pairOfPoints)).or(pipeParsers(emptyArray).then(convert(()=>null)).parser).parser;const parseCorrect=defaulted(discriminatedUnionOn("type").withBranch("absolute_value",object({type:constant("absolute_value"),coords:parseCoords})).withBranch("exponential",object({type:constant("exponential"),asymptote:pairOfPoints,coords:parseCoords})).withBranch("linear",object({type:constant("linear"),coords:parseCoords})).withBranch("logarithm",object({type:constant("logarithm"),asymptote:pairOfPoints,coords:parseCoords})).withBranch("quadratic",object({type:constant("quadratic"),coords:parseCoords})).withBranch("sinusoid",object({type:constant("sinusoid"),coords:parseCoords})).withBranch("tangent",object({type:constant("tangent"),coords:parseCoords})).parser,()=>({type:"linear",coords:null}));const parseGrapherWidget=parseWidget(constant("grapher"),object({availableTypes:array(enumeration("absolute_value","exponential","linear","logarithm","quadratic","sinusoid","tangent")),correct:optional(parseCorrect),graph:object({backgroundImage:object({bottom:optional(number),height:optional(number),left:optional(number),scale:optional(number),url:optional(nullable(string)),width:optional(number)}),box:optional(pairOfNumbers$3),editableSettings:optional(array(enumeration("graph","snap","image","measure"))),gridStep:optional(pairOfNumbers$3),labels:pair(string,string),markings:enumeration("graph","none","grid","axes"),range:pair(pairOfNumbers$3,pairOfNumbers$3),rulerLabel:constant(""),rulerTicks:number,showProtractor:optional(boolean),showRuler:optional(boolean),showTooltips:optional(boolean),snapStep:optional(pairOfNumbers$3),step:pairOfNumbers$3,valid:optional(union(boolean).or(string).parser)})}));
|
|
132
|
-
|
|
133
|
-
const parseGroupWidget=parseWidget(constant("group"),(rawVal,ctx)=>parsePerseusRenderer(rawVal,ctx));
|
|
134
|
-
|
|
135
|
-
const parseIframeWidget=parseWidget(constant("iframe"),object({url:string,settings:optional(array(object({name:string,value:string}))),width:union(number).or(string).parser,height:union(number).or(string).parser,allowFullScreen:defaulted(boolean,()=>false),allowTopNavigation:optional(boolean)}));
|
|
136
|
-
|
|
137
|
-
const stringToNumber=(rawValue,ctx)=>{if(typeof rawValue==="number"){return ctx.success(rawValue)}const parsedNumber=+rawValue;if(rawValue===""||isNaN(parsedNumber)){return ctx.failure("a number or numeric string",rawValue)}return ctx.success(parsedNumber)};
|
|
138
|
-
|
|
139
|
-
function emptyToZero(x){return x===""?0:x}const imageDimensionToNumber=pipeParsers(union(number).or(string).parser).then(convert(emptyToZero)).then(stringToNumber).parser;const dimensionOrUndefined=defaulted(optional(imageDimensionToNumber),()=>undefined);const parsePerseusImageBackground=object({url:optional(nullable(string)),width:dimensionOrUndefined,height:dimensionOrUndefined,top:dimensionOrUndefined,left:dimensionOrUndefined,bottom:dimensionOrUndefined,scale:dimensionOrUndefined});
|
|
140
|
-
|
|
141
|
-
const pairOfNumbers$2=pair(number,number);const parseImageWidget=parseWidget(constant("image"),object({title:defaulted(string,()=>""),caption:defaulted(string,()=>""),alt:defaulted(string,()=>""),longDescription:defaulted(string,()=>""),decorative:defaulted(boolean,()=>false),backgroundImage:parsePerseusImageBackground,scale:defaulted(number,()=>1),labels:defaulted(array(object({content:string,alignment:string,coordinates:array(number)})),()=>[]),range:defaulted(pair(pairOfNumbers$2,pairOfNumbers$2),()=>[[0,10],[0,10]]),box:defaulted(pairOfNumbers$2,()=>[400,400])}),{supportsStatic:false});
|
|
142
|
-
|
|
143
|
-
const booleanToZero=(rawValue,ctx)=>{if(typeof rawValue==="boolean"){return ctx.success(0)}return ctx.failure("boolean",rawValue)};const parseMathFormat$1=enumeration("integer","mixed","improper","proper","decimal","percent","pi");const parseInputNumberWidgetV1=parseWidgetWithVersion(object({major:constant(1),minor:number}),constant("input-number"),object({size:string,coefficient:boolean,labelText:optional(string),textAlign:enumeration("left","center","right"),answers:array(object({value:optional(nullable(number)),status:string,message:string,answerForms:optional(array(parseMathFormat$1)),strict:boolean,maxError:optional(nullable(number)),simplify:enumeration("required","enforced","optional")}))}));function migrateV0ToV1$3(v0){const v1Options=convertInputNumberOptionsToNumericInput(v0.options);return {...v0,version:{major:1,minor:0},options:v1Options}}const parseInputNumberWidgetV0=parseWidgetWithVersion(defaulted(optional(object({major:constant(0),minor:number})),()=>undefined),constant("input-number"),object({answerType:optional(enumeration("number","decimal","integer","rational","improper","mixed","percent","pi")),inexact:optional(boolean),maxError:optional(union(number).or(string).parser),rightAlign:optional(boolean),simplify:enumeration("required","optional","enforced"),size:enumeration("normal","small"),value:defaulted(union(number).or(string).or(booleanToZero).parser,()=>0)}));function convertInputNumberOptionsToNumericInput(inputNumberOptions){return {coefficient:false,textAlign:inputNumberOptions.rightAlign?"right":"left",size:inputNumberOptions.size,answers:[{status:"correct",value:Number(inputNumberOptions.value),simplify:inputNumberOptions.simplify,message:"",maxError:getMaxError(inputNumberOptions),strict:true,answerForms:getAnswerForms(inputNumberOptions)}]}}function getMaxError(inputNumberOptions){if(!inputNumberOptions.inexact){return 0}if(inputNumberOptions.maxError==null){return undefined}return Number(inputNumberOptions.maxError)}const mathFormatsForAnswerType={number:[],decimal:["decimal"],integer:["integer"],rational:["integer","proper","improper","mixed"],improper:["integer","proper","improper"],mixed:["integer","proper","mixed"],percent:["integer","decimal","proper","improper","mixed","percent"],pi:["pi"]};function getAnswerForms(options){const value=Number(options.value);const{inexact}=options;const precision=1e10;const rounded=Math.round(value*precision)/precision;const answerType=options.answerType??"number";if(answerType==="number"&&!inexact&&!equalFloats(rounded,value)){return ["proper","improper","mixed"]}return mathFormatsForAnswerType[answerType]}function equalFloats(a,b){return Math.abs(a-b)<Math.pow(2,-42)}const parseInputNumberWidget=versionedWidgetOptions(1,parseInputNumberWidgetV1).withMigrationFrom(0,parseInputNumberWidgetV0,migrateV0ToV1$3).parser;
|
|
144
|
-
|
|
145
|
-
const pairOfNumbers$1=pair(number,number);const stringOrEmpty=defaulted(string,()=>"");const parseKey=pipeParsers(optional(string)).then(convert(String)).parser;const parseFunctionElement=object({type:constant("function"),key:parseKey,options:object({value:string,funcName:string,rangeMin:string,rangeMax:string,color:string,strokeDasharray:string,strokeWidth:number})});const parseLabelElement=object({type:constant("label"),key:parseKey,options:object({label:string,color:string,coordX:string,coordY:string})});const parseLineElement=object({type:constant("line"),key:parseKey,options:object({color:string,startX:string,startY:string,endX:string,endY:string,strokeDasharray:string,strokeWidth:number,arrows:string})});const parseMovableLineElement=object({type:constant("movable-line"),key:parseKey,options:object({startX:string,startY:string,startSubscript:number,endX:string,endY:string,endSubscript:number,constraint:string,snap:number,constraintFn:string,constraintXMin:string,constraintXMax:string,constraintYMin:string,constraintYMax:string})});const parseMovablePointElement=object({type:constant("movable-point"),key:parseKey,options:object({startX:string,startY:string,varSubscript:number,constraint:string,snap:number,constraintFn:string,constraintXMin:stringOrEmpty,constraintXMax:stringOrEmpty,constraintYMin:stringOrEmpty,constraintYMax:stringOrEmpty})});const parseParametricElement=object({type:constant("parametric"),key:parseKey,options:object({x:string,y:string,rangeMin:string,rangeMax:string,color:string,strokeDasharray:string,strokeWidth:number})});const parsePointElement=object({type:constant("point"),key:parseKey,options:object({color:string,coordX:string,coordY:string})});const parseRectangleElement=object({type:constant("rectangle"),key:parseKey,options:object({color:string,coordX:string,coordY:string,width:string,height:string})});const parseInteractionWidget=parseWidget(constant("interaction"),object({graph:object({editableSettings:optional(array(enumeration("canvas","graph"))),box:pairOfNumbers$1,labels:array(string),range:pair(pairOfNumbers$1,pairOfNumbers$1),gridStep:pairOfNumbers$1,markings:enumeration("graph","grid","none","axes"),snapStep:optional(pairOfNumbers$1),valid:optional(union(boolean).or(string).parser),backgroundImage:optional(parsePerseusImageBackground),showProtractor:optional(boolean),showRuler:optional(boolean),rulerLabel:optional(string),rulerTicks:optional(number),tickStep:pairOfNumbers$1}),elements:array(discriminatedUnionOn("type").withBranch("function",parseFunctionElement).withBranch("label",parseLabelElement).withBranch("line",parseLineElement).withBranch("movable-line",parseMovableLineElement).withBranch("movable-point",parseMovablePointElement).withBranch("parametric",parseParametricElement).withBranch("point",parsePointElement).withBranch("rectangle",parseRectangleElement).parser)}),{supportsStatic:false});
|
|
146
|
-
|
|
147
|
-
const pairOfNumbers=pair(number,number);const parsePerseusGraphTypeAngle=object({type:constant("angle"),showAngles:optional(boolean),allowReflexAngles:optional(boolean),angleOffsetDeg:optional(nullable(number)),snapDegrees:optional(number),match:optional(constant("congruent")),coords:optional(trio(pairOfNumbers,pairOfNumbers,pairOfNumbers)),startCoords:optional(trio(pairOfNumbers,pairOfNumbers,pairOfNumbers)),pointLabels:optional(trio(string,string,string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeCircle=object({type:constant("circle"),center:optional(pairOfNumbers),radius:optional(number),startCoords:optional(object({center:pairOfNumbers,radius:number})),pointLabels:optional(array(string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeLinear=object({type:constant("linear"),coords:optional(nullable(pair(pairOfNumbers,pairOfNumbers))),startCoords:optional(pair(pairOfNumbers,pairOfNumbers)),pointLabels:optional(pair(string,string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeLinearSystem=object({type:constant("linear-system"),coords:optional(nullable(array(pair(pairOfNumbers,pairOfNumbers)))),startCoords:optional(array(pair(pairOfNumbers,pairOfNumbers))),pointLabels:optional(array(string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeNone=object({type:constant("none")});const parsePerseusGraphTypePoint=object({type:constant("point"),numPoints:optional(union(number).or(constant("unlimited")).parser),coords:optional(nullable(array(pairOfNumbers))),startCoords:optional(array(pairOfNumbers)),coord:optional(pairOfNumbers),pointLabels:optional(array(string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypePolygon=object({type:constant("polygon"),numSides:optional(union(number).or(constant("unlimited")).parser),showAngles:optional(boolean),showSides:optional(boolean),snapTo:optional(enumeration("grid","angles","sides")),match:optional(enumeration("similar","congruent","approx","exact")),startCoords:optional(array(pairOfNumbers)),coords:optional(nullable(array(pairOfNumbers))),pointLabels:optional(array(string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeQuadratic=object({type:constant("quadratic"),coords:optional(nullable(trio(pairOfNumbers,pairOfNumbers,pairOfNumbers))),startCoords:optional(trio(pairOfNumbers,pairOfNumbers,pairOfNumbers)),pointLabels:optional(trio(string,string,string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeRay=object({type:constant("ray"),coords:optional(nullable(pair(pairOfNumbers,pairOfNumbers))),startCoords:optional(pair(pairOfNumbers,pairOfNumbers)),pointLabels:optional(pair(string,string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeSegment=object({type:constant("segment"),numSegments:optional(number),coords:optional(nullable(array(pair(pairOfNumbers,pairOfNumbers)))),startCoords:optional(array(pair(pairOfNumbers,pairOfNumbers))),pointLabels:optional(array(string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeSinusoid=object({type:constant("sinusoid"),coords:optional(nullable(pair(pairOfNumbers,pairOfNumbers))),startCoords:optional(pair(pairOfNumbers,pairOfNumbers)),pointLabels:optional(array(string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeExponential=object({type:constant("exponential"),coords:optional(nullable(pair(pairOfNumbers,pairOfNumbers))),asymptote:optional(nullable(number)),startCoords:optional(object({coords:pair(pairOfNumbers,pairOfNumbers),asymptote:number})),pointLabels:optional(array(string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeAbsoluteValue=object({type:constant("absolute-value"),coords:optional(nullable(pair(pairOfNumbers,pairOfNumbers))),startCoords:optional(pair(pairOfNumbers,pairOfNumbers)),pointLabels:optional(pair(string,string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeTangent=object({type:constant("tangent"),coords:optional(nullable(pair(pairOfNumbers,pairOfNumbers))),startCoords:optional(pair(pairOfNumbers,pairOfNumbers)),pointLabels:optional(array(string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeLogarithm=object({type:constant("logarithm"),coords:optional(nullable(pair(pairOfNumbers,pairOfNumbers))),asymptote:optional(nullable(number)),startCoords:optional(object({coords:pair(pairOfNumbers,pairOfNumbers),asymptote:number})),pointLabels:optional(array(string)),showPointLabels:optional(boolean)});const parsePerseusGraphTypeVector=object({type:constant("vector"),coords:optional(nullable(pair(pairOfNumbers,pairOfNumbers))),startCoords:optional(pair(pairOfNumbers,pairOfNumbers)),match:optional(enumeration("exact","congruent"))});const parsePerseusGraphType=discriminatedUnionOn("type").withBranch("absolute-value",parsePerseusGraphTypeAbsoluteValue).withBranch("angle",parsePerseusGraphTypeAngle).withBranch("circle",parsePerseusGraphTypeCircle).withBranch("exponential",parsePerseusGraphTypeExponential).withBranch("linear",parsePerseusGraphTypeLinear).withBranch("linear-system",parsePerseusGraphTypeLinearSystem).withBranch("none",parsePerseusGraphTypeNone).withBranch("point",parsePerseusGraphTypePoint).withBranch("polygon",parsePerseusGraphTypePolygon).withBranch("quadratic",parsePerseusGraphTypeQuadratic).withBranch("ray",parsePerseusGraphTypeRay).withBranch("segment",parsePerseusGraphTypeSegment).withBranch("sinusoid",parsePerseusGraphTypeSinusoid).withBranch("tangent",parsePerseusGraphTypeTangent).withBranch("logarithm",parsePerseusGraphTypeLogarithm).withBranch("vector",parsePerseusGraphTypeVector).parser;const parseLockedFigureColor=pipeParsers(enumeration("blue","gold","green","grayH","purple","pink","red","orange")).then(convert(color=>color==="orange"?"gold":color)).parser;const parseLockedFigureFillType=enumeration("none","white","translucent","solid");const parseLockedLineStyle=enumeration("solid","dashed");const parseLockedFigureStrokeStyle=enumeration("solid","dashed","none");const parseStrokeWeight=defaulted(enumeration("medium","thin","thick"),()=>"medium");const parseLockedLabelType=object({type:constant("label"),coord:pairOfNumbers,text:defaulted(string,()=>""),color:defaulted(parseLockedFigureColor,()=>"grayH"),size:defaulted(enumeration("small","medium","large"),()=>"medium")});const parseLockedPointType=object({type:constant("point"),coord:pairOfNumbers,color:parseLockedFigureColor,filled:boolean,labels:defaulted(array(parseLockedLabelType),()=>[]),ariaLabel:optional(string)});const parseLockedLineType=object({type:constant("line"),kind:enumeration("line","ray","segment"),points:pair(parseLockedPointType,parseLockedPointType),color:parseLockedFigureColor,lineStyle:parseLockedLineStyle,showPoint1:defaulted(boolean,()=>false),showPoint2:defaulted(boolean,()=>false),weight:parseStrokeWeight,labels:defaulted(array(parseLockedLabelType),()=>[]),ariaLabel:optional(string)});const parseLockedVectorType=object({type:constant("vector"),points:pair(pairOfNumbers,pairOfNumbers),color:parseLockedFigureColor,weight:parseStrokeWeight,labels:defaulted(array(parseLockedLabelType),()=>[]),ariaLabel:optional(string)});const parseLockedEllipseType=object({type:constant("ellipse"),center:pairOfNumbers,radius:pairOfNumbers,angle:number,color:parseLockedFigureColor,fillStyle:parseLockedFigureFillType,strokeStyle:parseLockedFigureStrokeStyle,weight:parseStrokeWeight,labels:defaulted(array(parseLockedLabelType),()=>[]),ariaLabel:optional(string)});const parseLockedPolygonType=object({type:constant("polygon"),points:array(pairOfNumbers),color:parseLockedFigureColor,showVertices:boolean,fillStyle:parseLockedFigureFillType,strokeStyle:parseLockedFigureStrokeStyle,weight:parseStrokeWeight,labels:defaulted(array(parseLockedLabelType),()=>[]),ariaLabel:optional(string)});const numberOrNegativeInfinity=union(number).or(constant(-Infinity)).parser;const numberOrPositiveInfinity=union(number).or(constant(Infinity)).parser;const parseLockedFunctionDomain=defaulted(pair(defaulted(numberOrNegativeInfinity,()=>-Infinity),defaulted(numberOrPositiveInfinity,()=>Infinity)),()=>[-Infinity,Infinity]);const parseLockedFunctionType=object({type:constant("function"),color:parseLockedFigureColor,strokeStyle:parseLockedLineStyle,weight:parseStrokeWeight,equation:string,directionalAxis:enumeration("x","y"),domain:parseLockedFunctionDomain,labels:defaulted(array(parseLockedLabelType),()=>[]),ariaLabel:optional(string)});const parseLockedFigure=discriminatedUnionOn("type").withBranch("point",parseLockedPointType).withBranch("line",parseLockedLineType).withBranch("vector",parseLockedVectorType).withBranch("ellipse",parseLockedEllipseType).withBranch("polygon",parseLockedPolygonType).withBranch("function",parseLockedFunctionType).withBranch("label",parseLockedLabelType).parser;const parseLabelLocation=pipeParsers(enumeration("onAxis","alongEdge","",null,undefined)).then(convert(value=>value||"onAxis")).parser;const parseInteractiveGraphWidget=parseWidget(constant("interactive-graph"),object({step:pairOfNumbers,gridStep:optional(pairOfNumbers),snapStep:optional(pairOfNumbers),backgroundImage:defaulted(parsePerseusImageBackground,()=>({url:null})),markings:enumeration("graph","grid","none","axes"),labels:defaulted(array(string),()=>["$x$","$y$"]),labelLocation:parseLabelLocation,showProtractor:boolean,showRuler:optional(boolean),showTooltips:defaulted(boolean,()=>false),rulerLabel:optional(string),rulerTicks:optional(number),range:pair(pairOfNumbers,pairOfNumbers),showAxisArrows:defaulted(object({xMin:boolean,xMax:boolean,yMin:boolean,yMax:boolean}),()=>({xMin:true,xMax:true,yMin:true,yMax:true})),showAxisTicks:defaulted(object({x:boolean,y:boolean}),()=>({x:true,y:true})),graph:defaulted(parsePerseusGraphType,()=>({type:"linear"})),correct:defaulted(parsePerseusGraphType,()=>({type:"linear"})),lockedFigures:defaulted(array(parseLockedFigure),()=>[]),fullGraphAriaLabel:optional(string),fullGraphAriaDescription:optional(string)}));
|
|
148
|
-
|
|
149
|
-
const parseLabelImageWidget=parseWidget(constant("label-image"),object({choices:array(string),imageUrl:string,imageAlt:string,imageHeight:number,imageWidth:number,markers:array(object({answers:defaulted(array(string),()=>[]),label:string,x:number,y:number})),hideChoicesFromInstructions:boolean,multipleAnswers:boolean}));
|
|
150
|
-
|
|
151
|
-
const matcherOptions=object({labels:array(string),left:array(string),right:array(string),orderMatters:boolean,padding:boolean});function getDefaultOptions$1(){return {left:["$x$","$y$","$z$"],right:["$1$","$2$","$3$"],labels:["test","label"],orderMatters:false,padding:true}}const parseMatcherWidget=parseWidget(constant("matcher"),defaulted(matcherOptions,getDefaultOptions$1));
|
|
152
|
-
|
|
153
|
-
const numberOrStringOrNaN=union(number).or(string).or(constant(NaN)).parser;const numeric=pipeParsers(defaulted(numberOrStringOrNaN,()=>NaN)).then(stringToNumber).parser;const parseMatrixWidget=parseWidget(defaulted(constant("matrix"),()=>"matrix"),object({prefix:defaulted(string,()=>""),suffix:defaulted(string,()=>""),answers:defaulted(array(array(numeric)),()=>[]),matrixBoardSize:array(number)}));
|
|
154
|
-
|
|
155
|
-
const parseMeasurerWidgetV1=parseWidgetWithVersion(object({major:constant(1),minor:number}),constant("measurer"),object({image:defaulted(parsePerseusImageBackground,()=>({url:null,top:0,left:0})),showProtractor:boolean,showRuler:boolean,rulerLabel:string,rulerTicks:number,rulerPixels:number,rulerLength:number,box:pair(number,number)}),{supportsStatic:false});const parseMeasurerWidgetV0=parseWidget(constant("measurer"),object({imageTop:number,imageLeft:number,imageUrl:optional(nullable(string)),showProtractor:boolean,showRuler:boolean,rulerLabel:string,rulerTicks:number,rulerPixels:number,rulerLength:number,box:pair(number,number)}),{supportsStatic:false});function migrateV0ToV1$2(v0){const{imageTop,imageLeft,imageUrl,...v1Options}=v0.options;return {...v0,version:{major:1,minor:0},options:{image:{top:imageTop,left:imageLeft,url:imageUrl},...v1Options}}}const parseMeasurerWidget=versionedWidgetOptions(1,parseMeasurerWidgetV1).withMigrationFrom(0,parseMeasurerWidgetV0,migrateV0ToV1$2).parser;
|
|
156
|
-
|
|
157
|
-
const emptyStringToNull=pipeParsers(constant("")).then(convert(()=>null)).parser;const parseNumberLineWidget=parseWidget(constant("number-line"),object({range:array(number),labelRange:array(nullable(union(number).or(emptyStringToNull).parser)),labelStyle:enumeration("decimal","improper","mixed","non-reduced"),labelTicks:boolean,isTickCtrl:defaulted(boolean,()=>false),isInequality:defaulted(boolean,()=>false),divisionRange:array(number),numDivisions:optional(nullable(number)),snapDivisions:defaulted(number,()=>2),tickStep:optional(nullable(number)),correctRel:defaulted(optional(enumeration("eq","lt","gt","le","ge")),()=>undefined),correctX:defaulted(nullable(number),()=>null),initialX:optional(nullable(number)),showTooltips:optional(boolean)}));
|
|
158
|
-
|
|
159
|
-
const parseMathFormat=enumeration("integer","mixed","improper","proper","decimal","percent","pi");const parseSimplify=pipeParsers(union(constant(null)).or(constant(undefined)).or(boolean).or(constant("true")).or(constant("required")).or(constant("correct")).or(constant("enforced")).or(constant("optional")).or(constant("accepted")).parser).then(convert(deprecatedSimplifyValuesToRequired)).parser;function deprecatedSimplifyValuesToRequired(simplify){switch(simplify){case "enforced":case "required":case "optional":return simplify;default:return "required"}}const parseNumericInputAnswers=array(object({message:defaulted(string,()=>""),value:optional(nullable(number)),status:string,answerForms:defaulted(optional(array(parseMathFormat)),()=>undefined),strict:defaulted(boolean,()=>false),maxError:optional(nullable(number)),simplify:parseSimplify}));const version1$1=object({major:constant(1),minor:number});const parseNumericInputWidgetV1=parseWidgetWithVersion(version1$1,constant("numeric-input"),object({answers:parseNumericInputAnswers,labelText:optional(string),size:string,coefficient:defaulted(boolean,()=>false),textAlign:defaulted(enumeration("left","right","center"),()=>"left")}));const version0$1=optional(object({major:constant(0),minor:number}));const parseNumericInputWidgetV0=parseWidgetWithVersion(version0$1,constant("numeric-input"),object({answers:parseNumericInputAnswers,labelText:optional(string),size:string,coefficient:defaulted(boolean,()=>false),rightAlign:optional(boolean)}));function migrateV0ToV1$1(widget){const{rightAlign,...options}=widget.options;return {...widget,version:{major:1,minor:0},options:{...options,textAlign:rightAlign?"right":"left"}}}const parseNumericInputWidget=versionedWidgetOptions(1,parseNumericInputWidgetV1).withMigrationFrom(0,parseNumericInputWidgetV0,migrateV0ToV1$1).parser;
|
|
160
|
-
|
|
161
|
-
function parseRenderer(rawValue,ctx){return parsePerseusRenderer(rawValue,ctx)}const largeToAuto=(height,ctx)=>{if(height==="large"){return ctx.success("auto")}return ctx.success(height)};const parseOrdererWidget=parseWidget(constant("orderer"),object({options:defaulted(array(parseRenderer),()=>[]),correctOptions:defaulted(array(parseRenderer),()=>[]),otherOptions:defaulted(array(parseRenderer),()=>[]),height:pipeParsers(enumeration("normal","auto","large")).then(largeToAuto).parser,layout:defaulted(enumeration("horizontal","vertical"),()=>"horizontal")}));
|
|
162
|
-
|
|
163
|
-
const parsePhetSimulationWidget=parseWidget(constant("phet-simulation"),object({url:string,description:string}),{supportsStatic:false});
|
|
164
|
-
|
|
165
|
-
const plotterPlotTypes$1=enumeration("bar","line","pic","histogram","dotplot");const parsePlotterWidget=parseWidget(constant("plotter"),object({labels:array(string),categories:array(string),type:plotterPlotTypes$1,maxY:number,scaleY:defaulted(number,()=>1),labelInterval:defaulted(number,()=>1),snapsPerLine:defaulted(number,()=>2),starting:array(number),correct:defaulted(array(number),()=>[1]),picUrl:defaulted(nullable(string),()=>null),picSize:defaulted(number,()=>30),picBoxHeight:defaulted(number,()=>36),plotDimensions:defaulted(array(number),()=>[380,300])}));
|
|
166
|
-
|
|
167
|
-
const parsePythonProgramWidget=parseWidget(constant("python-program"),object({programID:string,height:number}),{supportsStatic:false});
|
|
168
|
-
|
|
169
|
-
function deriveNumCorrect(choices){return choices.filter(c=>c.correct).length}
|
|
170
|
-
|
|
171
|
-
const parseWidgetsMapOrUndefined=defaulted(optional((rawVal,ctx)=>parseWidgetsMap(rawVal,ctx)),()=>undefined);function getDefaultOptions(){return {choices:[{content:"",id:generateChoiceId(0)},{content:"",id:generateChoiceId(1)},{content:"",id:generateChoiceId(2)},{content:"",id:generateChoiceId(3)}]}}const parseOnePerLine=defaulted(optional(boolean),()=>undefined);const parseNoneOfTheAbove=defaulted(optional(constant(false)),()=>undefined);function generateChoiceId(index){return `radio-choice-${index}`}const version3=optional(object({major:constant(3),minor:number}));const parseRadioWidgetV3=parseWidgetWithVersion(version3,constant("radio"),object({numCorrect:optional(number),choices:arrayWithIndex(index=>object({content:defaulted(string,()=>""),rationale:optional(string),correct:optional(boolean),isNoneOfTheAbove:optional(boolean),id:defaultedNonEmptyString(()=>generateChoiceId(index))})),hasNoneOfTheAbove:optional(boolean),countChoices:optional(boolean),randomize:optional(boolean),multipleSelect:optional(boolean),deselectEnabled:optional(boolean)}));const version2=optional(object({major:constant(2),minor:number}));const parseRadioWidgetV2=parseWidgetWithVersion(version2,constant("radio"),defaulted(object({numCorrect:optional(number),choices:array(object({content:defaulted(string,()=>""),clue:optional(string),correct:optional(boolean),isNoneOfTheAbove:optional(boolean),rationale:optional(string),widgets:parseWidgetsMapOrUndefined})),hasNoneOfTheAbove:optional(boolean),countChoices:optional(boolean),randomize:optional(boolean),multipleSelect:optional(boolean),deselectEnabled:optional(boolean),onePerLine:parseOnePerLine,displayCount:optional(any),noneOfTheAbove:parseNoneOfTheAbove}),getDefaultOptions));const version1=optional(object({major:constant(1),minor:number}));const parseRadioWidgetV1=parseWidgetWithVersion(version1,constant("radio"),defaulted(object({choices:array(object({content:defaulted(string,()=>""),clue:optional(string),correct:optional(boolean),isNoneOfTheAbove:optional(boolean),widgets:parseWidgetsMapOrUndefined})),hasNoneOfTheAbove:optional(boolean),countChoices:optional(boolean),randomize:optional(boolean),multipleSelect:optional(boolean),deselectEnabled:optional(boolean),onePerLine:parseOnePerLine,displayCount:optional(any),noneOfTheAbove:parseNoneOfTheAbove}),getDefaultOptions));const version0=optional(object({major:constant(0),minor:number}));const parseRadioWidgetV0=parseWidgetWithVersion(version0,constant("radio"),defaulted(object({choices:array(object({content:defaulted(string,()=>""),clue:optional(string),correct:optional(boolean),isNoneOfTheAbove:optional(boolean),widgets:parseWidgetsMapOrUndefined})),hasNoneOfTheAbove:optional(boolean),countChoices:optional(boolean),randomize:optional(boolean),multipleSelect:optional(boolean),deselectEnabled:optional(boolean),onePerLine:parseOnePerLine,displayCount:optional(any),noneOfTheAbove:parseNoneOfTheAbove}),getDefaultOptions));function migrateV2toV3(widget){const{options}=widget;return {...widget,version:{major:3,minor:0},options:{numCorrect:options.numCorrect,hasNoneOfTheAbove:options.hasNoneOfTheAbove,countChoices:options.countChoices,randomize:options.randomize,multipleSelect:options.multipleSelect,deselectEnabled:options.deselectEnabled,choices:options.choices.map((choice,index)=>({content:choice.content,rationale:choice["rationale"]||choice.clue,correct:choice.correct,isNoneOfTheAbove:choice.isNoneOfTheAbove,id:generateChoiceId(index)}))}}}function migrateV1ToV2(widget){const{options}=widget;return {...widget,version:{major:2,minor:0},options:{...options,numCorrect:deriveNumCorrect(options.choices)}}}function migrateV0ToV1(widget){const{options}=widget;const{noneOfTheAbove,...rest}=options;return {...widget,version:{major:1,minor:0},options:{...rest,hasNoneOfTheAbove:false,noneOfTheAbove:undefined}}}const parseRadioWidget=versionedWidgetOptions(3,parseRadioWidgetV3).withMigrationFrom(2,parseRadioWidgetV2,migrateV2toV3).withMigrationFrom(1,parseRadioWidgetV1,migrateV1ToV2).withMigrationFrom(0,parseRadioWidgetV0,migrateV0ToV1).parser;
|
|
172
|
-
|
|
173
|
-
const parseSorterWidget=parseWidget(constant("sorter"),object({correct:array(string),padding:boolean,layout:enumeration("horizontal","vertical")}));
|
|
174
|
-
|
|
175
|
-
const parseTableWidget=parseWidget(constant("table"),object({headers:array(string),rows:number,columns:number,answers:defaulted(array(array(string)),()=>[])}));
|
|
176
|
-
|
|
177
|
-
const parseVideoWidget=parseWidget(constant("video"),object({location:string}),{supportsStatic:false});
|
|
178
|
-
|
|
179
|
-
const parseStringToNonNegativeInt=(rawValue,ctx)=>{if(typeof rawValue!=="string"||!/^(0|[1-9][0-9]*)$/.test(rawValue)){return ctx.failure("a string representing a non-negative integer",rawValue)}return ctx.success(+rawValue)};const parseWidgetIdComponents=pair(string,parseStringToNonNegativeInt);
|
|
180
|
-
|
|
181
|
-
const parseWidgetsMap=(rawValue,ctx)=>{if(!isPlainObject(rawValue)){return ctx.failure("PerseusWidgetsMap",rawValue)}const widgetsMap={};for(const key of Object.keys(rawValue)){const entryResult=parseWidgetsMapEntry([key,rawValue[key]],widgetsMap,ctx.forSubtree(key));if(isFailure(entryResult)){return entryResult}}return ctx.success(widgetsMap)};const parseWidgetsMapEntry=([id,widget],widgetMap,ctx)=>{const idComponentsResult=parseWidgetIdComponents(id.split(" "),ctx.forSubtree("(widget ID)"));if(isFailure(idComponentsResult)){return idComponentsResult}const[type,n]=idComponentsResult.value;function parseAndAssign(key,parse){const widgetResult=parse(widget,ctx);if(isFailure(widgetResult)){return widgetResult}widgetMap[key]=widgetResult.value;return ctx.success(undefined)}switch(type){case "blank":return parseAndAssign(`blank ${n}`,parseBlankWidget);case "categorizer":return parseAndAssign(`categorizer ${n}`,parseCategorizerWidget);case "cs-program":return parseAndAssign(`cs-program ${n}`,parseCSProgramWidget);case "definition":return parseAndAssign(`definition ${n}`,parseDefinitionWidget);case "dropdown":return parseAndAssign(`dropdown ${n}`,parseDropdownWidget);case "explanation":return parseAndAssign(`explanation ${n}`,parseExplanationWidget);case "expression":return parseAndAssign(`expression ${n}`,parseExpressionWidget);case "fill-in-the-blank":return parseAndAssign(`fill-in-the-blank ${n}`,parseFillInTheBlankWidget);case "free-response":return parseAndAssign(`free-response ${n}`,parseFreeResponseWidget);case "grapher":return parseAndAssign(`grapher ${n}`,parseGrapherWidget);case "group":return parseAndAssign(`group ${n}`,parseGroupWidget);case "graded-group":return parseAndAssign(`graded-group ${n}`,parseGradedGroupWidget);case "graded-group-set":return parseAndAssign(`graded-group-set ${n}`,parseGradedGroupSetWidget);case "iframe":return parseAndAssign(`iframe ${n}`,parseIframeWidget);case "image":return parseAndAssign(`image ${n}`,parseImageWidget);case "input-number":return parseAndAssign(`input-number ${n}`,parseInputNumberWidget);case "interaction":return parseAndAssign(`interaction ${n}`,parseInteractionWidget);case "interactive-graph":return parseAndAssign(`interactive-graph ${n}`,parseInteractiveGraphWidget);case "label-image":return parseAndAssign(`label-image ${n}`,parseLabelImageWidget);case "matcher":return parseAndAssign(`matcher ${n}`,parseMatcherWidget);case "matrix":return parseAndAssign(`matrix ${n}`,parseMatrixWidget);case "measurer":return parseAndAssign(`measurer ${n}`,parseMeasurerWidget);case "molecule-renderer":return parseAndAssign(`molecule-renderer ${n}`,parseDeprecatedWidget);case "number-line":return parseAndAssign(`number-line ${n}`,parseNumberLineWidget);case "numeric-input":return parseAndAssign(`numeric-input ${n}`,parseNumericInputWidget);case "orderer":return parseAndAssign(`orderer ${n}`,parseOrdererWidget);case "phet-simulation":return parseAndAssign(`phet-simulation ${n}`,parsePhetSimulationWidget);case "plotter":return parseAndAssign(`plotter ${n}`,parsePlotterWidget);case "python-program":return parseAndAssign(`python-program ${n}`,parsePythonProgramWidget);case "radio":return parseAndAssign(`radio ${n}`,parseRadioWidget);case "sorter":return parseAndAssign(`sorter ${n}`,parseSorterWidget);case "table":return parseAndAssign(`table ${n}`,parseTableWidget);case "video":return parseAndAssign(`video ${n}`,parseVideoWidget);case "sequence":return parseAndAssign(`sequence ${n}`,parseDeprecatedWidget);case "lights-puzzle":return parseAndAssign(`lights-puzzle ${n}`,parseDeprecatedWidget);case "simulator":return parseAndAssign(`simulator ${n}`,parseDeprecatedWidget);case "transformer":return parseAndAssign(`transformer ${n}`,parseDeprecatedWidget);case "passage":return parseAndAssign(`passage ${n}`,parseDeprecatedWidget);case "passage-ref":return parseAndAssign(`passage-ref ${n}`,parseDeprecatedWidget);case "passage-ref-target":return parseAndAssign(`passage-ref-target ${n}`,parseDeprecatedWidget);default:return parseAndAssign(`${type} ${n}`,parseWidget(constant(type),any))}};const parseDeprecatedWidget=parseWidget((_,ctx)=>ctx.success("deprecated-standin"),looseObject({}));
|
|
182
|
-
|
|
183
|
-
const parsePerseusRenderer=defaulted(object({content:defaulted(string,()=>""),widgets:defaulted((rawVal,ctx)=>parseWidgetsMap(rawVal,ctx),()=>({})),images:parseImages,metadata:any}),()=>({content:"",widgets:{},images:{}}));
|
|
184
|
-
|
|
185
|
-
const parsePerseusArticle=union(parsePerseusRenderer).or(array(parsePerseusRenderer)).parser;
|
|
186
|
-
|
|
187
|
-
const parseHint=object({replace:defaulted(optional(boolean),()=>undefined),placeholder:defaulted(optional(boolean),()=>undefined),content:string,widgets:defaulted(parseWidgetsMap,()=>({})),images:parseImages,metadata:any});
|
|
188
|
-
|
|
189
|
-
const parsePerseusItem=object({question:parsePerseusRenderer,hints:defaulted(array(parseHint),()=>[]),answerArea:parsePerseusAnswerArea});
|
|
190
|
-
|
|
191
|
-
const parseCategorizerUserInput=object({values:array(optional(nullable(number)))});
|
|
192
|
-
|
|
193
|
-
const parseCSProgramUserInput=object({status:enumeration("correct","incorrect","incomplete"),message:nullable(string)});
|
|
194
|
-
|
|
195
|
-
const parseDropdownUserInput=object({value:number});
|
|
196
|
-
|
|
197
|
-
const parseExpressionUserInput=string;
|
|
198
|
-
|
|
199
|
-
const parseFreeResponseUserInput=object({currentValue:string});
|
|
200
|
-
|
|
201
|
-
const coord=pair(number,number);const coordPair=pair(coord,coord);const parseAbsoluteValueBranch=object({type:constant("absolute_value"),coords:nullable(coordPair)});const parseExponentialBranch=object({type:constant("exponential"),asymptote:coordPair,coords:nullable(coordPair)});const parseLinearBranch=object({type:constant("linear"),coords:nullable(coordPair)});const parseLogarithmBranch=object({type:constant("logarithm"),asymptote:coordPair,coords:nullable(coordPair)});const parseQuadraticBranch=object({type:constant("quadratic"),coords:nullable(coordPair)});const parseSinusoidBranch=object({type:constant("sinusoid"),coords:nullable(coordPair)});const parseTangentBranch=object({type:constant("tangent"),coords:nullable(coordPair)});const parseGrapherUserInput=discriminatedUnionOn("type").withBranch("absolute_value",parseAbsoluteValueBranch).withBranch("exponential",parseExponentialBranch).withBranch("linear",parseLinearBranch).withBranch("logarithm",parseLogarithmBranch).withBranch("quadratic",parseQuadraticBranch).withBranch("sinusoid",parseSinusoidBranch).withBranch("tangent",parseTangentBranch).parser;
|
|
202
|
-
|
|
203
|
-
const parseGroupUserInput=(rawVal,ctx)=>parseUserInputMap(rawVal,ctx);
|
|
204
|
-
|
|
205
|
-
const parseIFrameUserInput=object({status:enumeration("correct","incorrect","incomplete"),message:optional(nullable(string))});
|
|
206
|
-
|
|
207
|
-
const parseInputNumberUserInput=object({currentValue:string});
|
|
208
|
-
|
|
209
|
-
const parseInteractiveGraphUserInput=parsePerseusGraphType;
|
|
210
|
-
|
|
211
|
-
const parseLabelImageUserInput=object({markers:array(object({selected:optional(array(string)),label:string}))});
|
|
212
|
-
|
|
213
|
-
const parseMatcherUserInput=object({left:array(string),right:array(string)});
|
|
214
|
-
|
|
215
|
-
const parseMatrixUserInput=object({answers:array(array(string))});
|
|
216
|
-
|
|
217
|
-
const parseNumberLineUserInput=object({numLinePosition:number,rel:enumeration("eq","lt","gt","le","ge"),numDivisions:number});
|
|
218
|
-
|
|
219
|
-
const parseNumericInputUserInput=object({currentValue:string});
|
|
220
|
-
|
|
221
|
-
const parseOrdererUserInput=object({current:array(string)});
|
|
222
|
-
|
|
223
|
-
const parsePlotterUserInput=array(number);
|
|
224
|
-
|
|
225
|
-
const parseRadioUserInput=object({selectedChoiceIds:array(string)});
|
|
226
|
-
|
|
227
|
-
const parseSorterUserInput=object({options:array(string),changed:boolean});
|
|
228
|
-
|
|
229
|
-
const parseTableUserInput=array(array(string));
|
|
230
|
-
|
|
231
|
-
const parseUserInputMap=(rawValue,ctx)=>{if(!isPlainObject(rawValue)){return ctx.failure("UserInputMap",rawValue)}const userInputMap={};for(const key of Object.keys(rawValue)){const entryResult=parseUserInputMapEntry([key,rawValue[key]],userInputMap,ctx.forSubtree(key));if(isFailure(entryResult)){return entryResult}}return ctx.success(userInputMap)};const parseUserInputMapEntry=([id,userInput],userInputMap,ctx)=>{const idComponentsResult=parseWidgetIdComponents(id.split(" "),ctx.forSubtree("(widget ID)"));if(isFailure(idComponentsResult)){return idComponentsResult}const[type,n]=idComponentsResult.value;function parseAndAssign(key,parse){const userInputResult=parse(userInput,ctx);if(isFailure(userInputResult)){return userInputResult}userInputMap[key]=userInputResult.value;return ctx.success(undefined)}switch(type){case "categorizer":return parseAndAssign(`categorizer ${n}`,parseCategorizerUserInput);case "cs-program":return parseAndAssign(`cs-program ${n}`,parseCSProgramUserInput);case "dropdown":return parseAndAssign(`dropdown ${n}`,parseDropdownUserInput);case "expression":return parseAndAssign(`expression ${n}`,parseExpressionUserInput);case "free-response":return parseAndAssign(`free-response ${n}`,parseFreeResponseUserInput);case "grapher":return parseAndAssign(`grapher ${n}`,parseGrapherUserInput);case "group":return parseAndAssign(`group ${n}`,parseGroupUserInput);case "iframe":return parseAndAssign(`iframe ${n}`,parseIFrameUserInput);case "input-number":return parseAndAssign(`input-number ${n}`,parseInputNumberUserInput);case "interactive-graph":return parseAndAssign(`interactive-graph ${n}`,parseInteractiveGraphUserInput);case "label-image":return parseAndAssign(`label-image ${n}`,parseLabelImageUserInput);case "matcher":return parseAndAssign(`matcher ${n}`,parseMatcherUserInput);case "matrix":return parseAndAssign(`matrix ${n}`,parseMatrixUserInput);case "number-line":return parseAndAssign(`number-line ${n}`,parseNumberLineUserInput);case "numeric-input":return parseAndAssign(`numeric-input ${n}`,parseNumericInputUserInput);case "orderer":return parseAndAssign(`orderer ${n}`,parseOrdererUserInput);case "plotter":return parseAndAssign(`plotter ${n}`,parsePlotterUserInput);case "radio":return parseAndAssign(`radio ${n}`,parseRadioUserInput);case "sorter":return parseAndAssign(`sorter ${n}`,parseSorterUserInput);case "table":return parseAndAssign(`table ${n}`,parseTableUserInput);default:return parseAndAssign(`${type} ${n}`,any)}};
|
|
232
|
-
|
|
233
|
-
function parseAndMigratePerseusItem(data){const object=typeof data==="string"?JSON.parse(data):data;const result=parse(object,parsePerseusItem);if(isFailure(result)){return failure({message:result.detail,invalidObject:object})}return result}function parseAndMigratePerseusArticle(data){const object=typeof data==="string"?JSON.parse(data):data;const result=parse(object,parsePerseusArticle);if(isFailure(result)){return failure({message:result.detail,invalidObject:object})}return result}function parseAndMigrateUserInputMap(data){const object=typeof data==="string"?JSON.parse(data):data;const result=parse(object,parseUserInputMap);if(isFailure(result)){return failure({message:result.detail,invalidObject:object})}return result}function parseAndMigratePerseusRenderer(data){const object=typeof data==="string"?JSON.parse(data):data;const result=parse(object,parsePerseusRenderer);if(isFailure(result)){return failure({message:result.detail,invalidObject:object})}return result}
|
|
234
|
-
|
|
235
|
-
const libName="@khanacademy/perseus-core";const libVersion="39.2.2";addLibraryVersionToPerseusDebug(libName,libVersion);
|
|
236
|
-
|
|
237
|
-
const Errors=Object.freeze({Unknown:"Unknown",Internal:"Internal",InvalidInput:"InvalidInput",NotAllowed:"NotAllowed",TransientService:"TransientService",Service:"Service"});
|
|
238
|
-
|
|
239
|
-
class PerseusError extends Error{constructor(message,kind,options){super(message);this.kind=kind;this.metadata=options?.metadata;}}
|
|
240
|
-
|
|
241
|
-
const ItemExtras=["calculator","financialCalculatorMonthlyPayment","financialCalculatorTotalAmount","financialCalculatorTimeToPayOff","periodicTable","periodicTableWithKey"];const PerseusExpressionAnswerFormConsidered=["correct","wrong","ungraded"];const lockedFigureColorNames=["blue","gold","green","grayH","purple","pink","red"];const lockedFigureColors={blue:"var(--wb-semanticColor-learning-math-foreground-blue)",gold:"var(--wb-semanticColor-learning-math-foreground-gold)",grayH:"var(--wb-semanticColor-learning-math-foreground-grayH)",green:"var(--wb-semanticColor-learning-math-foreground-green)",pink:"var(--wb-semanticColor-learning-math-foreground-pink)",purple:"var(--wb-semanticColor-learning-math-foreground-purple)",red:"var(--wb-semanticColor-learning-math-foreground-red)"};const lockedFigureFillStyles={none:0,white:1,translucent:.4,solid:1};const plotterPlotTypes=["bar","line","pic","histogram","dotplot"];
|
|
242
|
-
|
|
243
|
-
const pluck=function(table,subKey){return _.object(_.map(table,function(value,key){return [key,value[subKey]]}))};const mapObject=function(obj,lambda){const result={};Object.keys(obj).forEach(key=>{result[key]=lambda(obj[key],key);});return result};
|
|
244
|
-
|
|
245
|
-
function getBlankPublicWidgetOptions(options){const{correctId,...publicWidgetOptions}=options;return publicWidgetOptions}
|
|
246
|
-
|
|
247
|
-
const blankWidgetLogic={name:"blank",version:{major:0,minor:0},defaultAlignment:"inline-block",getPublicWidgetOptions:getBlankPublicWidgetOptions,accessible:true};
|
|
248
|
-
|
|
249
|
-
function getCategorizerPublicWidgetOptions(options){return {items:options.items,categories:options.categories,randomizeItems:options.randomizeItems}}
|
|
250
|
-
|
|
251
|
-
const defaultWidgetOptions$u={items:[],categories:[],values:[],randomizeItems:false};const categorizerWidgetLogic={name:"categorizer",defaultWidgetOptions: defaultWidgetOptions$u,getPublicWidgetOptions:getCategorizerPublicWidgetOptions,accessible:false};
|
|
252
|
-
|
|
253
|
-
function getCSProgramPublicWidgetOptions(options){return options}
|
|
254
|
-
|
|
255
|
-
const DEFAULT_HEIGHT=400;const defaultWidgetOptions$t={programID:"",programType:null,settings:[{name:"",value:""}],showEditor:false,showButtons:false,height:DEFAULT_HEIGHT};const csProgramWidgetLogic={name:"cs-program",defaultWidgetOptions: defaultWidgetOptions$t,supportedAlignments:["block","full-width"],getPublicWidgetOptions:getCSProgramPublicWidgetOptions,accessible:false};
|
|
256
|
-
|
|
257
|
-
const defaultWidgetOptions$s={togglePrompt:"",definition:""};const definitionWidgetLogic={name:"definition",defaultWidgetOptions: defaultWidgetOptions$s,defaultAlignment:"inline",accessible:true};
|
|
258
|
-
|
|
259
|
-
function getDropdownPublicWidgetOptions(options){return {choices:options.choices.map(choice=>({content:choice.content})),placeholder:options.placeholder,visibleLabel:options.visibleLabel,ariaLabel:options.ariaLabel}}
|
|
260
|
-
|
|
261
|
-
const defaultWidgetOptions$r={placeholder:"",choices:[{content:"",correct:false}]};const dropdownWidgetLogic={name:"dropdown",defaultWidgetOptions: defaultWidgetOptions$r,defaultAlignment:"inline-block",getPublicWidgetOptions:getDropdownPublicWidgetOptions,accessible:true};
|
|
262
|
-
|
|
263
|
-
const defaultWidgetOptions$q={showPrompt:"Explain",hidePrompt:"Hide explanation",explanation:"explanation goes here\n\nmore explanation",widgets:{}};const explanationWidgetLogic={name:"explanation",defaultWidgetOptions: defaultWidgetOptions$q,defaultAlignment:"inline",accessible:true};
|
|
264
|
-
|
|
265
|
-
function getExpressionPublicWidgetOptions(options){return {buttonSets:options.buttonSets,functions:options.functions,times:options.times,visibleLabel:options.visibleLabel,ariaLabel:options.ariaLabel,buttonsVisible:options.buttonsVisible,extraKeys:options.extraKeys}}
|
|
266
|
-
|
|
267
|
-
const currentVersion$1={major:2,minor:0};const defaultWidgetOptions$p={answerForms:[],times:false,buttonSets:["basic"],functions:["f","g","h"]};const expressionWidgetLogic={name:"expression",version:currentVersion$1,defaultWidgetOptions:defaultWidgetOptions$p,defaultAlignment:"inline-block",getPublicWidgetOptions:getExpressionPublicWidgetOptions,accessible:true};
|
|
268
|
-
|
|
269
|
-
class Registry{throwIfUnregistered(){if(!this.anythingRegistered){throw new Error(`${this.name} accessed before initialization!`)}}has(key){this.throwIfUnregistered();return Object.prototype.hasOwnProperty.call(this.contents,key)}get(key){this.throwIfUnregistered();return this.contents[key]}keys(){this.throwIfUnregistered();return Object.keys(this.contents)}entries(){this.throwIfUnregistered();return Object.entries(this.contents)}set(key,value){this.anythingRegistered=true;this.contents[key]=value;}constructor(name="Registry"){this.contents={};this.anythingRegistered=false;this.name=name;}}
|
|
270
|
-
|
|
271
|
-
const deprecatedStandinWidgetLogic={name:"deprecated-standin",accessible:true};
|
|
272
|
-
|
|
273
|
-
const defaultWidgetOptions$o={title:"",content:"",widgets:{},images:{},hint:null};const traverseChildWidgets$3=function(props,traverseRenderer){return {...props,...traverseRenderer(props)}};const gradedGroupWidgetLogic={name:"graded-group",defaultWidgetOptions: defaultWidgetOptions$o,accessible:true,traverseChildWidgets:traverseChildWidgets$3};
|
|
274
|
-
|
|
275
|
-
const defaultWidgetOptions$n={gradedGroups:[]};const traverseChildWidgets$2=function(props,traverseRenderer){return {...props,...traverseRenderer(props)}};const gradedGroupSetWidgetLogic={name:"graded-group-set",defaultWidgetOptions: defaultWidgetOptions$n,accessible:true,traverseChildWidgets:traverseChildWidgets$2};
|
|
276
|
-
|
|
277
|
-
function getGrapherPublicWidgetOptions(options){const{correct,...publicOptions}=options;return publicOptions}
|
|
278
|
-
|
|
279
|
-
const defaultWidgetOptions$m={graph:{labels:["x","y"],range:[[-10,10],[-10,10]],step:[1,1],backgroundImage:{url:null},markings:"graph",rulerLabel:"",rulerTicks:10,valid:true,showTooltips:false},correct:{type:"linear",coords:null},availableTypes:["linear"]};const grapherWidgetLogic={name:"grapher",defaultWidgetOptions: defaultWidgetOptions$m,getPublicWidgetOptions:getGrapherPublicWidgetOptions,accessible:options=>!options.graph.backgroundImage.url&&options.availableTypes.length===1&&options.availableTypes[0]!=="quadratic"};
|
|
280
|
-
|
|
281
|
-
function getGroupPublicWidgetOptions(options){return splitPerseusRenderer(options)}
|
|
282
|
-
|
|
283
|
-
const defaultWidgetOptions$l={content:"",widgets:{},images:{}};const traverseChildWidgets$1=function(props,traverseRenderer){return {...props,...traverseRenderer(props)}};const groupWidgetLogic={name:"group",defaultWidgetOptions: defaultWidgetOptions$l,accessible:false,traverseChildWidgets:traverseChildWidgets$1,getPublicWidgetOptions:getGroupPublicWidgetOptions};
|
|
284
|
-
|
|
285
|
-
function getIFramePublicWidgetOptions(options){return options}
|
|
286
|
-
|
|
287
|
-
const defaultWidgetOptions$k={url:"",settings:[{name:"",value:""}],width:"400",height:"400",allowFullScreen:false,allowTopNavigation:false};const iframeWidgetLogic={name:"iframe",defaultWidgetOptions: defaultWidgetOptions$k,getPublicWidgetOptions:getIFramePublicWidgetOptions,accessible:false};
|
|
288
|
-
|
|
289
|
-
const defaultWidgetOptions$j={title:"",range:[[0,10],[0,10]],box:[400,400],backgroundImage:{url:null,width:0,height:0},scale:1,labels:[],alt:"",caption:"",longDescription:"",decorative:false};const imageWidgetLogic={name:"image",defaultWidgetOptions: defaultWidgetOptions$j,supportedAlignments:["block","wrap-left","wrap-right","full-width"],defaultAlignment:"block",accessible:widgetOptions=>{const bgImage=widgetOptions.backgroundImage;const hasBackgroundImage=bgImage.url!=null;const hasAltText=!!widgetOptions.alt;const isDecorative=widgetOptions.decorative;return hasBackgroundImage&&(hasAltText||isDecorative)}};
|
|
290
|
-
|
|
291
|
-
function getNumericInputAnswerPublicData(answer){return {status:answer.status,answerForms:answer.answerForms,simplify:answer.simplify,value:null,strict:false,message:""}}function getNumericInputPublicWidgetOptions(options){const{answers,...publicWidgetOptions}=options;return {...publicWidgetOptions,answers:answers.map(getNumericInputAnswerPublicData)}}
|
|
292
|
-
|
|
293
|
-
const getInputNumberPublicWidgetOptions=getNumericInputPublicWidgetOptions;
|
|
294
|
-
|
|
295
|
-
const defaultWidgetOptions$i={textAlign:"left",coefficient:false,size:"normal",answers:[{status:"correct",value:0,simplify:"required",maxError:0,answerForms:[],message:"",strict:true}]};const inputNumberWidgetLogic={name:"input-number",version:{major:1,minor:0},defaultWidgetOptions: defaultWidgetOptions$i,defaultAlignment:"inline-block",accessible:true,getPublicWidgetOptions:getInputNumberPublicWidgetOptions};
|
|
296
|
-
|
|
297
|
-
const defaultWidgetOptions$h={graph:{box:[400,400],labels:["x","y"],range:[[-10,10],[-10,10]],tickStep:[1,1],gridStep:[1,1],markings:"graph"},elements:[]};const interactionWidgetLogic={name:"interaction",defaultWidgetOptions: defaultWidgetOptions$h,accessible:false};
|
|
298
|
-
|
|
299
|
-
const svgLabelsRegex=/^web\+graphie:/;const svgLocalLabelsRegex=/^file\+graphie:/;function getRealImageUrl(graphieUrl){if(isLabeledSVG(graphieUrl)){return getSvgUrl(graphieUrl)}return graphieUrl}function isLabeledSVG(graphieUrl){return svgLabelsRegex.test(graphieUrl)||svgLocalLabelsRegex.test(graphieUrl)}function getBaseUrl(graphieUrl){return graphieUrl.replace(svgLabelsRegex,"https:").replace(svgLocalLabelsRegex,"file:")}function getSvgUrl(graphieUrl){return getBaseUrl(graphieUrl)+".svg"}function getDataUrl(graphieUrl){return getBaseUrl(graphieUrl)+"-data.json"}async function getImageSizeModern(url){const image=new Image;return new Promise((resolve,reject)=>{image.onload=()=>{resolve([image.naturalWidth,image.naturalHeight]);};image.onerror=reject;image.src=getRealImageUrl(url);})}
|
|
300
|
-
|
|
301
|
-
function accessible(widgetOptions){if(widgetOptions.showProtractor){return false}if(widgetOptions.backgroundImage?.url&&isLabeledSVG(widgetOptions.backgroundImage?.url)){return false}if(widgetOptions.lockedFigures.length>0&&!widgetOptions.fullGraphAriaDescription){return false}return true}
|
|
302
|
-
|
|
303
|
-
function getInteractiveGraphPublicWidgetOptions(options){const{correct,...publicOptions}=options;return publicOptions}
|
|
304
|
-
|
|
305
|
-
const defaultWidgetOptions$g={labels:["$x$","$y$"],labelLocation:"onAxis",lockedFigures:[],range:[[-10,10],[-10,10]],step:[1,1],backgroundImage:{url:null},markings:"graph",showAxisArrows:{xMin:true,xMax:true,yMin:true,yMax:true},showAxisTicks:{x:true,y:true},showTooltips:false,showProtractor:false,graph:{type:"none"},correct:{type:"none"}};const interactiveGraphWidgetLogic={name:"interactive-graph",defaultWidgetOptions: defaultWidgetOptions$g,getPublicWidgetOptions:getInteractiveGraphPublicWidgetOptions,accessible};
|
|
306
|
-
|
|
307
|
-
function getLabelImagePublicWidgetOptions(options){return {...options,markers:options.markers.map(getLabelImageMarkerPublicData)}}function getLabelImageMarkerPublicData(marker){const{answers,...publicData}=marker;return publicData}function isLabelImageAccessible(options){const labelImageOptions=options;if(labelImageOptions.imageUrl!==""&&labelImageOptions.imageAlt===""){return false}for(const marker of labelImageOptions.markers){if(marker.label===""){return false}}return true}
|
|
308
|
-
|
|
309
|
-
const defaultWidgetOptions$f={choices:[],imageAlt:"",imageUrl:"",imageWidth:0,imageHeight:0,markers:[],multipleAnswers:false,hideChoicesFromInstructions:false};const labelImageWidgetLogic={name:"label-image",defaultWidgetOptions: defaultWidgetOptions$f,getPublicWidgetOptions:getLabelImagePublicWidgetOptions,accessible:isLabelImageAccessible};
|
|
310
|
-
|
|
311
|
-
const seededRNG=function(seed){let randomSeed=seed;return function(){let seed=randomSeed;seed=seed+0x7ed55d16+(seed<<12)&0xffffffff;seed=(seed^0xc761c23c^seed>>>19)&0xffffffff;seed=seed+0x165667b1+(seed<<5)&0xffffffff;seed=(seed+0xd3a2646c^seed<<9)&0xffffffff;seed=seed+0xfd7046c5+(seed<<3)&0xffffffff;seed=(seed^0xb55a4f09^seed>>>16)&0xffffffff;return (randomSeed=seed&0xfffffff)/0x10000000}};function shuffle(array,randomSeed,ensurePermuted=false){let random;if(typeof randomSeed==="function"){random=randomSeed;}else {random=seededRNG(randomSeed);}function isValidShuffle(shuffled){return ensurePermuted?!_.isEqual(array,shuffled):true}return constrainedShuffle(array,random,isValidShuffle)}function constrainedShuffle(array,random,isValidShuffle){const maxIterations=100;const shuffled=[...array];if(shuffled.every(value=>_.isEqual(value,shuffled[0]))){return shuffled}for(let i=0;i<maxIterations;i++){shuffleInPlace(shuffled,random);if(isValidShuffle(shuffled)){return shuffled}}throw new Error(`constrainedShuffle: constraint not met after ${maxIterations} attempts`)}function shuffleInPlace(a,random){for(let i=a.length-1;i>0;i--){const k=randomIntInRange(0,i,random);[a[k],a[i]]=[a[i],a[k]];}}function randomIntInRange(min,max,random){return Math.floor(random()*(max-min+1))+min}const random=seededRNG(new Date().getTime()&0xffffffff);
|
|
312
|
-
|
|
313
|
-
const shuffleMatcher=(options,problemNum)=>{const rng=seededRNG(problemNum);return {left:!options.orderMatters?options.left:shuffleDisplacingFirst$1(options.left,rng),right:shuffleDisplacingFirst$1(options.right,rng)}};function getMatcherPublicWidgetOptions(options){return {...options,left:options.orderMatters?sortAllButFirst$1(options.left):options.left,right:sortAllButFirst$1(options.right)}}function sortAllButFirst$1([first,...rest]){return [first,...rest.sort()]}function shuffleDisplacingFirst$1(array,rng){function isFirstElementDisplaced(shuffled){return shuffled[0]!==array[0]}return constrainedShuffle(array,rng,isFirstElementDisplaced)}
|
|
314
|
-
|
|
315
|
-
const defaultWidgetOptions$e={left:["$x$","$y$","$z$"],right:["$1$","$2$","$3$"],labels:["test","label"],orderMatters:false,padding:true};const matcherWidgetLogic={name:"matcher",defaultWidgetOptions: defaultWidgetOptions$e,getPublicWidgetOptions:getMatcherPublicWidgetOptions,accessible:false};
|
|
316
|
-
|
|
317
|
-
function getMatrixPublicWidgetOptions(options){const{answers,...publicOptions}=options;return publicOptions}
|
|
318
|
-
|
|
319
|
-
const defaultWidgetOptions$d={matrixBoardSize:[3,3],answers:[[]],prefix:"",suffix:""};const matrixWidgetLogic={name:"matrix",defaultWidgetOptions: defaultWidgetOptions$d,getPublicWidgetOptions:getMatrixPublicWidgetOptions,accessible:false};
|
|
320
|
-
|
|
321
|
-
const defaultWidgetOptions$c={box:[480,480],image:{},showProtractor:true,showRuler:false,rulerLabel:"",rulerTicks:10,rulerPixels:40,rulerLength:10};const measurerWidgetLogic={name:"measurer",version:{major:1,minor:0},defaultWidgetOptions:defaultWidgetOptions$c,accessible:false};
|
|
322
|
-
|
|
323
|
-
function getNumberLinePublicWidgetOptions(options){const{correctX,correctRel,...publicOptions}=options;return publicOptions}
|
|
324
|
-
|
|
325
|
-
const defaultWidgetOptions$b={range:[0,10],labelRange:[null,null],labelStyle:"decimal",labelTicks:true,isTickCtrl:false,isInequality:false,divisionRange:[1,12],numDivisions:5,snapDivisions:2,tickStep:null,correctRel:"eq",correctX:null,initialX:null,showTooltips:false};const numberLineWidgetLogic={name:"number-line",defaultWidgetOptions: defaultWidgetOptions$b,getPublicWidgetOptions:getNumberLinePublicWidgetOptions,accessible:false};
|
|
326
|
-
|
|
327
|
-
const defaultWidgetOptions$a={answers:[{value:null,status:"correct",message:"",simplify:"required",answerForms:[],strict:false,maxError:null}],size:"normal",coefficient:false,labelText:"",textAlign:"left"};const numericInputWidgetLogic={name:"numeric-input",version:{major:1,minor:0},defaultWidgetOptions: defaultWidgetOptions$a,defaultAlignment:"inline-block",getPublicWidgetOptions:getNumericInputPublicWidgetOptions,accessible:true};
|
|
328
|
-
|
|
329
|
-
function getOrdererPublicWidgetOptions(fullOptions){const{options,height,layout}=fullOptions;return {options,height,layout}}function toCard(content){return {content,widgets:{},images:{}}}function getCategoryScore(content){if(/\d/.test(content)){return 0}if(/^\$?[a-zA-Z]+\$?$/.test(content)){return 2}return 1}function mergeCards(correctOptions,otherOptions){const allCards=[...correctOptions,...otherOptions];return [...new Set(allCards.map(card=>card.content))].filter(content=>content!=="").sort().sort((a,b)=>getCategoryScore(a)-getCategoryScore(b)).map(toCard)}
|
|
330
|
-
|
|
331
|
-
const defaultCorrectOptions=[toCard("$x$")];const defaultOtherOptions=[toCard("$y$")];const defaultWidgetOptions$9={correctOptions:defaultCorrectOptions,otherOptions:defaultOtherOptions,options:mergeCards(defaultCorrectOptions,defaultOtherOptions),height:"normal",layout:"horizontal"};const ordererWidgetLogic={name:"orderer",defaultWidgetOptions: defaultWidgetOptions$9,getPublicWidgetOptions:getOrdererPublicWidgetOptions,accessible:false};
|
|
332
|
-
|
|
333
|
-
const defaultWidgetOptions$8={url:"",description:""};const phetSimulationWidgetLogic={name:"phet-simulation",defaultWidgetOptions: defaultWidgetOptions$8,accessible:true};
|
|
334
|
-
|
|
335
|
-
function getPlotterPublicWidgetOptions(options){const{correct,...publicOptions}=options;return publicOptions}
|
|
336
|
-
|
|
337
|
-
const defaultWidgetOptions$7={scaleY:1,maxY:10,snapsPerLine:2,correct:[1],starting:[1],type:"bar",labels:["",""],categories:[""],picSize:30,picBoxHeight:36,plotDimensions:[275,200],labelInterval:1,picUrl:null};const plotterWidgetLogic={name:"plotter",defaultWidgetOptions: defaultWidgetOptions$7,getPublicWidgetOptions:getPlotterPublicWidgetOptions,accessible:false};
|
|
338
|
-
|
|
339
|
-
const defaultWidgetOptions$6={programID:"",height:400};const pythonProgramWidgetLogic={name:"python-program",defaultWidgetOptions: defaultWidgetOptions$6,accessible:true};
|
|
340
|
-
|
|
341
|
-
function getRadioChoicePublicData(choice){const{id,content,isNoneOfTheAbove}=choice;return {id,content,isNoneOfTheAbove}}function usesNumCorrect(multipleSelect,countChoices,numCorrect){return multipleSelect&&countChoices&&numCorrect}function getRadioPublicWidgetOptions(options){const{numCorrect,choices,multipleSelect,countChoices}=options;return {...options,numCorrect:usesNumCorrect(multipleSelect,countChoices,numCorrect)?numCorrect:undefined,choices:choices.map(getRadioChoicePublicData)}}
|
|
342
|
-
|
|
343
|
-
const currentVersion={major:3,minor:0};const defaultWidgetOptions$5={choices:[{content:"",id:"radio-choice-0"},{content:"",id:"radio-choice-1"},{content:"",id:"radio-choice-2"},{content:"",id:"radio-choice-3"}],randomize:false,hasNoneOfTheAbove:false,multipleSelect:false,countChoices:false,deselectEnabled:false};const radioWidgetLogic={name:"radio",version:currentVersion,defaultWidgetOptions:defaultWidgetOptions$5,getPublicWidgetOptions:getRadioPublicWidgetOptions,accessible:true};
|
|
344
|
-
|
|
345
|
-
const SORTER_MAX_CARDS=10;function getSorterPublicWidgetOptions(options){return {...options,correct:sortAllButFirst(options.correct)}}function shuffleSorter(options,problemNum){const{correct}=options;const rng=seededRNG(problemNum??0);return shuffleDisplacingFirst(correct,rng)}function sortAllButFirst(cards){if(cards.length===0){return []}const[first,...rest]=cards;return [first,...rest.sort()]}function shuffleDisplacingFirst(array,rng){function isFirstElementDisplaced(shuffled){return shuffled[0]!==array[0]}return constrainedShuffle(array,rng,isFirstElementDisplaced)}
|
|
346
|
-
|
|
347
|
-
const defaultWidgetOptions$4={correct:["$x$","$y$","$z$"],layout:"horizontal",padding:true};const sorterWidgetLogic={name:"sorter",defaultWidgetOptions: defaultWidgetOptions$4,getPublicWidgetOptions:getSorterPublicWidgetOptions,accessible:false};
|
|
348
|
-
|
|
349
|
-
function getTablePublicWidgetOptions(options){const{answers,...publicOptions}=options;return publicOptions}
|
|
350
|
-
|
|
351
|
-
const defaultRows=4;const defaultColumns=1;const answers=new Array(defaultRows).fill(0).map(()=>new Array(defaultColumns).fill(""));const defaultWidgetOptions$3={headers:[""],rows:defaultRows,columns:defaultColumns,answers:answers};const tableWidgetLogic={name:"table",defaultWidgetOptions: defaultWidgetOptions$3,getPublicWidgetOptions:getTablePublicWidgetOptions,accessible:true};
|
|
352
|
-
|
|
353
|
-
const defaultWidgetOptions$2={location:""};const videoWidgetLogic={name:"video",defaultWidgetOptions: defaultWidgetOptions$2,supportedAlignments:["block","full-width"],defaultAlignment:"block",accessible:true};
|
|
354
|
-
|
|
355
|
-
const widgets=new Registry("Core widget registry");function registerWidget(type,logic){widgets.set(type,logic);}function isWidgetRegistered(type){const widgetLogic=widgets.get(type);return Boolean(widgetLogic)}function getCurrentVersion(type){const widgetLogic=widgets.get(type);return widgetLogic?.version||{major:0,minor:0}}const getPublicWidgetOptionsFunction=type=>{return widgets.get(type)?.getPublicWidgetOptions??(i=>i)};function getDefaultWidgetOptions(type){const widgetLogic=widgets.get(type);return widgetLogic?.defaultWidgetOptions||{}}function isAccessible(type,widgetOptions){const accessible=widgets.get(type)?.accessible;return typeof accessible==="function"?accessible(widgetOptions):!!accessible}const traverseChildWidgets=(widgetInfo,traverseRenderer)=>{if(!traverseRenderer){throw new PerseusError("traverseRenderer must be provided, but was not",Errors.Internal)}if(!widgetInfo||!widgetInfo.type||!widgets.get(widgetInfo.type)){return widgetInfo}const widgetExports=widgets.get(widgetInfo.type);const props=widgetInfo.options;if(widgetExports?.traverseChildWidgets!=null&&props!=null){const newProps=widgetExports.traverseChildWidgets(props,traverseRenderer);return {...widgetInfo,options:newProps}}return widgetInfo};const getSupportedAlignments=type=>{const widgetLogic=widgets.get(type);if(!widgetLogic?.supportedAlignments?.[0]){return ["default"]}return widgetLogic?.supportedAlignments};const getDefaultAlignment=type=>{const widgetLogic=widgets.get(type);if(!widgetLogic?.defaultAlignment){return "block"}return widgetLogic.defaultAlignment};const getAlignmentClassName=(type,alignment)=>{switch(alignment){case "block":return " widget-block";case "inline-block":return " widget-inline-block";case "inline":return " widget-inline";case "wrap-left":return " widget-wrap-left";case "wrap-right":return " widget-wrap-right";case "full-width":return " widget-full-width";case "default":return getDefaultAlignment(type);default:return ""}};function registerCoreWidgets(){const widgets=[blankWidgetLogic,categorizerWidgetLogic,csProgramWidgetLogic,definitionWidgetLogic,deprecatedStandinWidgetLogic,dropdownWidgetLogic,explanationWidgetLogic,expressionWidgetLogic,fillInTheBlankWidgetLogic,gradedGroupWidgetLogic,gradedGroupSetWidgetLogic,grapherWidgetLogic,groupWidgetLogic,iframeWidgetLogic,imageWidgetLogic,inputNumberWidgetLogic,interactionWidgetLogic,interactiveGraphWidgetLogic,labelImageWidgetLogic,matcherWidgetLogic,matrixWidgetLogic,measurerWidgetLogic,numberLineWidgetLogic,numericInputWidgetLogic,ordererWidgetLogic,phetSimulationWidgetLogic,plotterWidgetLogic,pythonProgramWidgetLogic,radioWidgetLogic,sorterWidgetLogic,tableWidgetLogic,videoWidgetLogic];widgets.forEach(w=>{registerWidget(w.name,w);});}
|
|
356
|
-
|
|
357
|
-
var coreWidgetRegistry = /*#__PURE__*/Object.freeze({
|
|
358
|
-
__proto__: null,
|
|
359
|
-
getAlignmentClassName: getAlignmentClassName,
|
|
360
|
-
getCurrentVersion: getCurrentVersion,
|
|
361
|
-
getDefaultAlignment: getDefaultAlignment,
|
|
362
|
-
getDefaultWidgetOptions: getDefaultWidgetOptions,
|
|
363
|
-
getPublicWidgetOptionsFunction: getPublicWidgetOptionsFunction,
|
|
364
|
-
getSupportedAlignments: getSupportedAlignments,
|
|
365
|
-
isAccessible: isAccessible,
|
|
366
|
-
isWidgetRegistered: isWidgetRegistered,
|
|
367
|
-
registerCoreWidgets: registerCoreWidgets,
|
|
368
|
-
registerWidget: registerWidget,
|
|
369
|
-
traverseChildWidgets: traverseChildWidgets
|
|
370
|
-
});
|
|
371
|
-
|
|
372
|
-
const applyDefaultsToWidget=oldWidgetInfo=>{const type=oldWidgetInfo.type;const latestVersion=getCurrentVersion(type);const version=oldWidgetInfo.version??latestVersion;const defaultOptions=getDefaultWidgetOptions(type);const options={...defaultOptions,...oldWidgetInfo.options};let alignment=oldWidgetInfo.alignment;if(alignment==null||alignment==="default"){alignment=getSupportedAlignments(type)?.[0];if(!alignment){throw new PerseusError("applyDefaultsToWidget: No default alignment found",Errors.Internal,{metadata:{widgetType:type}})}}return {...oldWidgetInfo,version,graded:oldWidgetInfo.graded??true,alignment,static:oldWidgetInfo.static??false,options}};function applyDefaultsToWidgets(oldWidgetOptions){return mapObject(oldWidgetOptions,applyDefaultsToWidget)}
|
|
373
|
-
|
|
374
|
-
function splitPerseusRenderer(original){return {...original,widgets:splitWidgetsMap(original.widgets)}}function splitWidgetsMap(widgets){const upgradedWidgets=applyDefaultsToWidgets(deepClone(widgets??{}));const splitWidgets={};for(const[id,widget]of Object.entries(upgradedWidgets)){if(widget.static){splitWidgets[id]=widget;}else {const publicWidgetOptionsFun=getPublicWidgetOptionsFunction(widget.type);splitWidgets[id]={...widget,options:publicWidgetOptionsFun(widget.options)};}}return splitWidgets}
|
|
375
|
-
|
|
376
|
-
function getFillInTheBlankPublicWidgetOptions(options){return {...options,widgets:splitWidgetsMap(options.widgets)}}
|
|
377
|
-
|
|
378
|
-
const defaultWidgetOptions$1={content:"",widgets:{},tiles:[],maxUsesPerTile:1,randomize:false};const fillInTheBlankWidgetLogic={name:"fill-in-the-blank",version:{major:0,minor:0},defaultAlignment:"block",defaultWidgetOptions: defaultWidgetOptions$1,accessible:true,getPublicWidgetOptions:getFillInTheBlankPublicWidgetOptions,traverseChildWidgets:(props,traverseRenderer)=>({...props,...traverseRenderer(props)})};
|
|
379
|
-
|
|
380
|
-
function getFreeResponsePublicWidgetOptions(options){return {allowUnlimitedCharacters:options.allowUnlimitedCharacters,characterLimit:options.characterLimit,placeholder:options.placeholder,question:options.question}}
|
|
381
|
-
|
|
382
|
-
const defaultWidgetOptions={allowUnlimitedCharacters:false,characterLimit:500,placeholder:"Please provide response here",question:"",scoringCriteria:[{text:""}]};const freeResponseWidgetLogic={name:"free-response",defaultWidgetOptions,getPublicWidgetOptions:getFreeResponsePublicWidgetOptions};
|
|
383
|
-
|
|
384
|
-
function convertGrapherOptionsToInteractiveGraph(grapherOptions){if(grapherOptions.availableTypes.length!==1){return null}const[type]=grapherOptions.availableTypes;if(type==="quadratic"){return null}const graph={type:grapherFunctionTypeToInteractiveGraphType(type)};return {step:grapherOptions.graph.step,gridStep:grapherOptions.graph.gridStep,snapStep:grapherOptions.graph.snapStep,backgroundImage:grapherOptions.graph.backgroundImage,markings:grapherOptions.graph.markings,labels:grapherOptions.graph.labels.map(wrapTexInDelimitersForMarkdown),labelLocation:"onAxis",showAxisArrows:{xMin:true,xMax:true,yMin:true,yMax:true},showAxisTicks:{x:true,y:true},showProtractor:grapherOptions.graph.showProtractor??false,showTooltips:grapherOptions.graph.showTooltips??false,range:grapherOptions.graph.range,graph,correct:grapherOptions.correct?grapherAnswerTypesToPerseusGraphType(grapherOptions.correct):graph,lockedFigures:[]}}function convertGrapherUserInputToInteractiveGraph(grapherUserInput){return grapherAnswerTypesToPerseusGraphType(grapherUserInput)}function convertInteractiveGraphUserInputToGrapher(interactiveGraphUserInput){switch(interactiveGraphUserInput.type){case "absolute-value":return {type:"absolute_value",coords:interactiveGraphUserInput.coords??null};case "exponential":{invariant(interactiveGraphUserInput.asymptote!=null,"exponential graph asymptote must not be nullish in user input");const asymptoteY=interactiveGraphUserInput.asymptote;return {type:"exponential",coords:interactiveGraphUserInput.coords??null,asymptote:[[0,asymptoteY],[1,asymptoteY]]}}case "linear":return {type:"linear",coords:interactiveGraphUserInput.coords??null};case "logarithm":{invariant(interactiveGraphUserInput.asymptote!=null,"logarithm graph asymptote must not be nullish in user input");const asymptoteX=interactiveGraphUserInput.asymptote;return {type:"logarithm",coords:interactiveGraphUserInput.coords??null,asymptote:[[asymptoteX,0],[asymptoteX,1]]}}case "sinusoid":return {type:"sinusoid",coords:interactiveGraphUserInput.coords??null};case "tangent":return {type:"tangent",coords:interactiveGraphUserInput.coords??null};case "angle":case "circle":case "linear-system":case "none":case "point":case "polygon":case "quadratic":case "ray":case "segment":case "vector":throw Error("Can't convert interactive-graph user input to grapher user input. Type: "+interactiveGraphUserInput.type);default:throw new UnreachableCaseError(interactiveGraphUserInput)}}function grapherAnswerTypesToPerseusGraphType(grapherAnswerTypes){switch(grapherAnswerTypes.type){case "absolute_value":return {type:"absolute-value",coords:grapherAnswerTypes.coords};case "exponential":return {type:"exponential",coords:grapherAnswerTypes.coords,asymptote:grapherAnswerTypes.asymptote[0][1]};case "linear":return {type:"linear",coords:grapherAnswerTypes.coords};case "logarithm":return {type:"logarithm",coords:grapherAnswerTypes.coords,asymptote:grapherAnswerTypes.asymptote[0][0]};case "quadratic":throw Error("Can't convert GrapherAnswerTypes to interactive graph. Type: quadratic");case "sinusoid":return {type:"sinusoid",coords:grapherAnswerTypes.coords};case "tangent":return {type:"tangent",coords:grapherAnswerTypes.coords};default:throw new UnreachableCaseError(grapherAnswerTypes)}}function grapherFunctionTypeToInteractiveGraphType(type){return type==="absolute_value"?"absolute-value":type}function wrapTexInDelimitersForMarkdown(tex){return `$${tex}$`}
|
|
385
|
-
|
|
386
|
-
function getDefaultAnswerArea(){return {...ItemExtras.reduce((acc,curr)=>({...acc,[curr]:false}),{}),calculatorVariant:undefined}}
|
|
387
|
-
|
|
388
|
-
const DEFAULT_COLOR="grayH";function getDefaultFigureForType(type){switch(type){case "point":return {type:"point",coord:[0,0],color:DEFAULT_COLOR,filled:true,labels:[]};case "line":return {type:"line",kind:"line",points:[getDefaultFigureForType("point"),{...getDefaultFigureForType("point"),coord:[2,2]}],color:DEFAULT_COLOR,lineStyle:"solid",showPoint1:false,showPoint2:false,weight:"medium",labels:[]};case "vector":return {type:"vector",points:[[0,0],[2,2]],color:DEFAULT_COLOR,weight:"medium",labels:[]};case "ellipse":return {type:"ellipse",center:[0,0],radius:[1,1],angle:0,color:DEFAULT_COLOR,fillStyle:"none",strokeStyle:"solid",weight:"medium",labels:[]};case "polygon":return {type:"polygon",points:[[0,2],[-1,0],[1,0]],color:DEFAULT_COLOR,showVertices:false,fillStyle:"none",strokeStyle:"solid",weight:"medium",labels:[]};case "function":return {type:"function",color:DEFAULT_COLOR,strokeStyle:"solid",weight:"medium",equation:"x^2",domain:[-Infinity,Infinity],directionalAxis:"x",labels:[]};case "label":return {type:"label",coord:[0,0],text:"label",color:DEFAULT_COLOR,size:"medium"};default:throw new UnreachableCaseError(type)}}
|
|
389
|
-
|
|
390
|
-
function splitPerseusItem(original){const item=deepClone(original);return {...item,question:splitPerseusRenderer(item.question),hints:original.hints.map(()=>({content:"",widgets:{},images:{},placeholder:true}))}}function splitPerseusItemJSON(data){const parseResult=parseAndMigratePerseusItem(data);if(isFailure(parseResult)){throw new SyntaxError(parseResult.detail.message)}const item=parseResult.value;return JSON.stringify(splitPerseusItem(item))}
|
|
391
|
-
|
|
392
|
-
const PerseusFeatureFlags=["perseus-renderer-upgrade","desmos-calculator","article-extras","dnd-widget-fitb"];function isFeatureOn(props,flag){return props.apiOptions?.flags?.[flag]??false}
|
|
393
|
-
|
|
394
|
-
const noop=function(){};const deepCallbackFor=function(contentCallback,widgetCallback,optionsCallback){const deepCallback=function(widgetInfo,widgetId){const newWidgetInfo=traverseChildWidgets(widgetInfo,rendererOptions=>{return traverseRenderer(rendererOptions,contentCallback,deepCallback,optionsCallback)});const userWidgetInfo=widgetCallback(newWidgetInfo,widgetId);if(userWidgetInfo!==undefined){return userWidgetInfo}return newWidgetInfo};return deepCallback};const traverseRenderer=function(rendererOptions,contentCallback,deepWidgetCallback,optionsCallback){let newContent=rendererOptions.content;if(rendererOptions.content!=null){const modifiedContent=contentCallback(rendererOptions.content);if(modifiedContent!==undefined){newContent=modifiedContent;}}const newWidgets=mapObject(rendererOptions.widgets||{},function(widgetInfo,widgetId){if(widgetInfo==null||widgetInfo.type==null){return widgetInfo}return deepWidgetCallback(widgetInfo,widgetId)});const newOptions=_.extend({},rendererOptions,{content:newContent,widgets:newWidgets});const userOptions=optionsCallback(newOptions);if(userOptions!==undefined){return userOptions}return newOptions};const traverse=function(rendererOptions,contentCallback,widgetCallback,optionsCallback){contentCallback=contentCallback||noop;widgetCallback=widgetCallback||noop;optionsCallback=optionsCallback||noop;return traverseRenderer(rendererOptions,contentCallback,deepCallbackFor(contentCallback,widgetCallback,optionsCallback),optionsCallback)};
|
|
395
|
-
|
|
396
|
-
function isItemAccessible(itemData){const ast=parse$1(itemData.question.content);const widgetIdsInUse=getWidgetIdsFromContent(itemData.question.content);let hasInaccessibleImage=false;traverseContent(ast,node=>{if(node.type==="image"&&(node.alt==null||node.alt==="")){hasInaccessibleImage=true;}});if(hasInaccessibleImage){return false}const itemDataWithOnlyActiveWidgets={...itemData,question:{...itemData.question,widgets:Object.fromEntries(Object.entries(itemData.question.widgets).filter(([id])=>widgetIdsInUse.includes(id)))},hints:itemData.hints.map(hint=>{const hintWidgetIdsInUse=getWidgetIdsFromContent(hint.content);return {...hint,widgets:Object.fromEntries(Object.entries(hint.widgets).filter(([id])=>hintWidgetIdsInUse.includes(id)))}})};let hasInaccessibleWidget=false;const checkAccessibility=info=>{if(info.type&&!isAccessible(info.type,info.options)){hasInaccessibleWidget=true;}};traverse(itemDataWithOnlyActiveWidgets.question,null,checkAccessibility);for(const hint of itemDataWithOnlyActiveWidgets.hints){traverse(hint,null,checkAccessibility);}return !hasInaccessibleWidget}
|
|
397
|
-
|
|
398
|
-
function generateBlankOptions(options){const defaultBlankOptions={displayType:"normal",correctId:"answer-tile-1"};return {...defaultBlankOptions,...options}}function generateBlankWidget(blankWidgetProperties){return {type:"blank",graded:true,version:{major:0,minor:0},static:false,alignment:"default",...blankWidgetProperties,options:generateBlankOptions({...blankWidgetProperties?.options})}}
|
|
399
|
-
|
|
400
|
-
function generateDefinitionOptions(options){return {...definitionWidgetLogic.defaultWidgetOptions,...options}}function generateDefinitionWidget(definitionWidgetProperties){return {type:"definition",graded:false,version:{major:0,minor:0},static:false,alignment:"default",options:generateDefinitionOptions(),...definitionWidgetProperties}}
|
|
401
|
-
|
|
402
|
-
function generateDropdownOptions(options){return {...dropdownWidgetLogic.defaultWidgetOptions,...options}}function generateDropdownWidget(dropdownWidgetProperties){return {type:"dropdown",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateDropdownOptions(),...dropdownWidgetProperties}}
|
|
403
|
-
|
|
404
|
-
function generateExplanationOptions(options){return {...explanationWidgetLogic.defaultWidgetOptions,...options}}function generateExplanationWidget(explanationWidgetProperties){return {type:"explanation",graded:false,version:{major:0,minor:0},static:false,alignment:"default",options:generateExplanationOptions(),...explanationWidgetProperties}}
|
|
405
|
-
|
|
406
|
-
function generateExpressionOptions(options){return {...expressionWidgetLogic.defaultWidgetOptions,...options}}function generateExpressionAnswerForm(answerFormOptions){return {value:"",form:false,simplify:false,considered:"wrong",...answerFormOptions}}function generateExpressionWidget(expressionWidgetProperties){return {type:"expression",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateExpressionOptions(),...expressionWidgetProperties}}
|
|
407
|
-
|
|
408
|
-
function generateAnswerTile(tile){const defaultAnswerTile={id:"answer-tile-1",content:"answer",label:"answer"};return {...defaultAnswerTile,...tile}}function generateFillInTheBlankOptions(options){return {...fillInTheBlankWidgetLogic.defaultWidgetOptions,...options}}function generateFillInTheBlankWidget(fillInTheBlankWidgetProperties){return {type:"fill-in-the-blank",graded:true,version:{major:0,minor:0},static:false,alignment:"default",...fillInTheBlankWidgetProperties,options:generateFillInTheBlankOptions(fillInTheBlankWidgetProperties?.options)}}
|
|
409
|
-
|
|
410
|
-
function generateFreeResponseOptions(options){return {...freeResponseWidgetLogic.defaultWidgetOptions,...options}}function generateFreeResponseWidget(freeResponseWidgetProperties){return {type:"free-response",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateFreeResponseOptions(),...freeResponseWidgetProperties}}
|
|
411
|
-
|
|
412
|
-
function generateGradedGroupOptions(options){return {...gradedGroupWidgetLogic.defaultWidgetOptions,...options}}function generateGradedGroupWidget(gradedGroupWidgetProperties){return {type:"graded-group",graded:false,version:{major:0,minor:0},static:false,alignment:"default",options:generateGradedGroupOptions(),...gradedGroupWidgetProperties}}
|
|
413
|
-
|
|
414
|
-
function generateGradedGroupSetWidget(gradedGroupSetWidgetProperties){return {type:"graded-group-set",graded:false,version:{major:0,minor:0},static:false,alignment:"default",options:{gradedGroups:[]},...gradedGroupSetWidgetProperties}}
|
|
415
|
-
|
|
416
|
-
function generateGroupOptions(options){return {...groupWidgetLogic.defaultWidgetOptions,...options}}function generateGroupWidget(groupWidgetProperties){return {type:"group",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateGroupOptions(),...groupWidgetProperties}}
|
|
417
|
-
|
|
418
|
-
function generateImageOptions(options){const defaultImageOptions={title:"",caption:"",alt:"",longDescription:"",decorative:false,backgroundImage:{},scale:1,box:[400,400],labels:[],range:[[0,10],[0,10]]};return {...defaultImageOptions,...options}}function generateImageWidget(imageWidgetProperties){return {type:"image",graded:false,version:{major:0,minor:0},static:false,alignment:"default",options:generateImageOptions({}),...imageWidgetProperties}}
|
|
419
|
-
|
|
420
|
-
function generateInputNumberWidget(inputNumberWidgetProperties){return {type:"input-number",graded:true,static:false,version:{major:1,minor:0},options:generateInputNumberOptions(),...inputNumberWidgetProperties}}function generateInputNumberOptions(options){return {...inputNumberWidgetLogic.defaultWidgetOptions,...options}}function generateInputNumberAnswer(params){return {...inputNumberWidgetLogic.defaultWidgetOptions.answers[0],...params}}
|
|
421
|
-
|
|
422
|
-
function generateLabelImageOptions(options){return {...labelImageWidgetLogic.defaultWidgetOptions,...options}}function generateLabelImageWidget(labelImageWidgetProperties){return {type:"label-image",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateLabelImageOptions(),...labelImageWidgetProperties}}
|
|
423
|
-
|
|
424
|
-
function generateMatcherOptions(options){return {...matcherWidgetLogic.defaultWidgetOptions,...options}}function generateMatcherWidget(matcherWidgetProperties){return {type:"matcher",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateMatcherOptions(),...matcherWidgetProperties}}
|
|
425
|
-
|
|
426
|
-
function generateMeasurerOptions(options){return {...measurerWidgetLogic.defaultWidgetOptions,...options}}function generateMeasurerWidget(measurerWidgetProperties){return {type:"measurer",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateMeasurerOptions(),...measurerWidgetProperties}}
|
|
427
|
-
|
|
428
|
-
function generateCategorizerOptions(options){return {...categorizerWidgetLogic.defaultWidgetOptions,...options}}function generateCategorizerWidget(categorizerWidgetProperties){return {type:"categorizer",graded:true,version:{major:0,minor:0},static:false,alignment:"default",...categorizerWidgetProperties,options:generateCategorizerOptions(categorizerWidgetProperties?.options)}}
|
|
429
|
-
|
|
430
|
-
function generateInteractiveGraphWidget(interactiveGraphWidgetProperties){return {type:"interactive-graph",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateInteractiveGraphOptions(),...interactiveGraphWidgetProperties}}function generateInteractiveGraphOptions(options){return {...interactiveGraphWidgetLogic.defaultWidgetOptions,...options}}function generateIGAngleGraph(options){return {type:"angle",...options}}function generateIGCircleGraph(options){return {type:"circle",...options}}function generateIGLinearGraph(options){return {type:"linear",...options}}function generateIGLinearSystemGraph(options){return {type:"linear-system",...options}}function generateIGLogarithmGraph(options){return {type:"logarithm",...options}}function generateIGNoneGraph(){return {type:"none"}}function generateIGPointGraph(options){return {type:"point",...options}}function generateIGPolygonGraph(options){return {type:"polygon",...options}}function generateIGQuadraticGraph(options){return {type:"quadratic",...options}}function generateIGRayGraph(options){return {type:"ray",...options}}function generateIGSegmentGraph(options){return {type:"segment",...options}}function generateIGSinusoidGraph(options){return {type:"sinusoid",...options}}function generateIGTangentGraph(options){return {type:"tangent",...options}}function generateIGVectorGraph(options){return {type:"vector",...options}}function generateIGLockedPoint(options){return {...getDefaultFigureForType("point"),...options}}function generateIGLockedLine(options){return {...getDefaultFigureForType("line"),...options}}function generateIGLockedVector(options){return {...getDefaultFigureForType("vector"),...options}}function generateIGLockedEllipse(options){return {...getDefaultFigureForType("ellipse"),...options}}function generateIGLockedPolygon(options){return {...getDefaultFigureForType("polygon"),...options}}function generateIGLockedFunction(options){return {...getDefaultFigureForType("function"),...options}}function generateIGLockedLabel(options){return {...getDefaultFigureForType("label"),...options}}function generateIGExponentialGraph(options){return {type:"exponential",...options}}function generateIGAbsoluteValueGraph(options){return {type:"absolute-value",...options}}function generateInteractiveGraphQuestion(options){const{content="[[☃ interactive-graph 1]]",isStatic=false,graded=true,...widgetOptions}=options??{};if(widgetOptions.correct&&!widgetOptions.graph){const{coords,coord,center,radius,asymptote,match,...graphConfig}=widgetOptions.correct;widgetOptions.graph=graphConfig;}const optionsWithDefaults={gridStep:[1,1],snapStep:[.5,.5],...widgetOptions};return generateTestPerseusRenderer({content:content,widgets:{"interactive-graph 1":generateInteractiveGraphWidget({static:isStatic,graded,options:generateInteractiveGraphOptions(optionsWithDefaults)})}})}
|
|
431
|
-
|
|
432
|
-
function generateMatrixOptions(options){return {...matrixWidgetLogic.defaultWidgetOptions,...options}}function generateMatrixWidget(matrixWidgetProperties){return {type:"matrix",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateMatrixOptions(),...matrixWidgetProperties}}
|
|
433
|
-
|
|
434
|
-
function generateOrdererOption(content){return {content,widgets:{},images:{}}}function generateOrdererOptions(options){const merged={...ordererWidgetLogic.defaultWidgetOptions,...options};return {...merged,options:options?.options??[...merged.correctOptions,...merged.otherOptions]}}function generateOrdererWidget(ordererWidgetProperties){return {type:"orderer",graded:true,version:{major:0,minor:0},static:false,alignment:"default",...ordererWidgetProperties,options:generateOrdererOptions(ordererWidgetProperties?.options)}}
|
|
435
|
-
|
|
436
|
-
function generatePlotterOptions(options){return {...plotterWidgetLogic.defaultWidgetOptions,...options}}function generatePlotterWidget(plotterWidgetProperties){return {type:"plotter",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generatePlotterOptions(),...plotterWidgetProperties}}
|
|
437
|
-
|
|
438
|
-
function generatePhetSimulationOptions(options){return {...phetSimulationWidgetLogic.defaultWidgetOptions,...options}}function generatePhetSimulationWidget(phetSimulationWidgetProperties){return {type:"phet-simulation",graded:false,version:{major:0,minor:0},static:false,alignment:"default",...phetSimulationWidgetProperties,options:generatePhetSimulationOptions(phetSimulationWidgetProperties?.options)}}
|
|
439
|
-
|
|
440
|
-
function generateNumberLineOptions(options){const defaultNumberLineOptions={range:[-4,4],labelRange:[null,null],labelStyle:"decimal",labelTicks:true,isInequality:false,isTickCtrl:false,divisionRange:[1,10],numDivisions:null,snapDivisions:2,tickStep:1,correctRel:"eq",correctX:null,initialX:null,showTooltips:false};return {...defaultNumberLineOptions,...options}}function generateNumberLineWidget(numberLineWidgetProperties){return {type:"number-line",graded:true,version:{major:0,minor:0},static:false,alignment:"default",...numberLineWidgetProperties,options:generateNumberLineOptions(numberLineWidgetProperties?.options)}}
|
|
441
|
-
|
|
442
|
-
function generateNumericInputOptions(options){return {...numericInputWidgetLogic.defaultWidgetOptions,static:false,...options}}function generateNumericInputAnswer(answerOptions){return {...numericInputWidgetLogic.defaultWidgetOptions.answers[0],...answerOptions}}function generateNumericInputWidget(numericInputWidgetProperties){return {type:"numeric-input",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateNumericInputOptions(),...numericInputWidgetProperties}}
|
|
443
|
-
|
|
444
|
-
function generateRadioOptions(options){return {...radioWidgetLogic.defaultWidgetOptions,...options}}function generateRadioWidget(radioWidgetProperties){return {type:"radio",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateRadioOptions(),...radioWidgetProperties}}function generateRadioChoice(text,options){return {content:text,id:`radio-choice-${Math.random()}`,correct:false,...options}}function generateSimpleRadioQuestion(options){return generateTestPerseusRenderer({content:"[[☃ radio 1]]",widgets:{"radio 1":generateRadioWidget({options:generateRadioOptions(options)})}})}function generateSimpleRadioItem(options){return generateTestPerseusItem({question:generateSimpleRadioQuestion(options)})}
|
|
445
|
-
|
|
446
|
-
function generateVideoWidget(videoWidgetProperties){return {type:"video",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:{location:""},...videoWidgetProperties}}
|
|
447
|
-
|
|
448
|
-
function generateSorterOptions(options){return {...sorterWidgetLogic.defaultWidgetOptions,...options}}function generateSorterWidget(sorterWidgetProperties){return {type:"sorter",graded:true,version:{major:0,minor:0},static:false,alignment:"default",options:generateSorterOptions(),...sorterWidgetProperties}}
|
|
449
|
-
|
|
450
|
-
function generateTableOptions(options){const merged={...tableWidgetLogic.defaultWidgetOptions,...options};const columns=options?.columns??merged.answers[0]?.length??tableWidgetLogic.defaultWidgetOptions.columns;return {...merged,rows:options?.rows??merged.answers.length,columns,headers:options?.headers??new Array(columns).fill("")}}
|
|
451
|
-
|
|
452
|
-
function generateGrapherWidgetOptions(options={}){return {...grapherWidgetLogic.defaultWidgetOptions,...options}}
|
|
453
|
-
|
|
454
|
-
const joinOptionContents=options=>options.map(({content})=>content).join("\n");const toOptionLetter=index=>String.fromCharCode("A".charCodeAt(0)+index);function getAnswersFromWidgets(widgets){const answers=[];keys(widgets).forEach(widgetID=>{const widget=widgets[widgetID];if(!widget.options){return}switch(widget.type){case "radio":const radio=widget;const options=radio.options;if(options?.choices?.length){for(const choice of options.choices){if(choice?.correct){answers.push(choice.content);}}}break;case "categorizer":const categorizer=widget;if(categorizer.options?.categories&&categorizer.options?.items&&categorizer.options?.values){const categories=categorizer.options?.categories;const items=categorizer.options?.items;const values=categorizer.options?.values;answers.push(...values.map((value,index)=>`${items[index]}: ${categories[value]}`));}break;case "dropdown":const dropdown=widget;if(dropdown.options?.choices){for(const choice of dropdown.options.choices){if(choice.correct){answers.push(choice.content);}}}break;case "input-number":case "numeric-input":const numericInput=widget;if(numericInput.options?.answers){for(const ans of numericInput.options.answers){if(ans.status==="correct"&&ans.value!=null){answers.push(ans.value.toString());}}}break;case "expression":const expression=widget;if(expression.options?.answerForms){answers.push(...expression.options.answerForms.map(answer=>answer.value));}break;case "group":case "graded-group":const gradedGroup=widget;if(gradedGroup.options?.widgets){answers.push(...getAnswersFromWidgets(gradedGroup.options.widgets));}break;case "plotter":const plotter=widget;if(plotter.options?.categories&&plotter.options?.correct&&plotter.options.categories.length===plotter.options.correct.length){const{categories,correct}=plotter.options;answers.push(`{${categories.map((category,index)=>`${category}: ${correct[index]}`).join(", ")}}`);}break;case "interactive-graph":case "grapher":const grapher=widget;if(grapher.options?.correct?.coords){answers.push(`There should be point(s) on [${grapher.options.correct?.coords.join("], [")}]`);}break;case "orderer":const orderer=widget;if(orderer.options?.correctOptions){answers.push(joinOptionContents(orderer.options.correctOptions));}break;case "sorter":const sorter=widget;if(sorter.options?.correct){answers.push(sorter.options.correct.join(", "));}break;case "label-image":const labelImage=widget;if(labelImage.options?.markers){answers.push(...labelImage.options.markers.map(m=>`{label: "${m.label}", position: {${m.x},${m.y}}, answer: "${m.answers.join(", ")}"}`));}break;case "number-line":const numberLine=widget;if(numberLine.options?.correctX!=null){answers.push(numberLine.options.correctX.toString());}break;case "matrix":const matrix=widget;if(matrix.options?.answers){answers.push(`[${matrix.options.answers.join("], [")}]`);}break;case "matcher":const matcher=widget;if(matcher.options?.left&&matcher.options?.right){const{left,right}=matcher.options;const[leftHeader,rightHeader]=matcher.options.labels;const tableHeader=`| ${leftHeader} | ${rightHeader} |
|
|
455
|
-
| --- | --- |`;const tableRows=left.map((leftItem,index)=>{return `| ${leftItem} | ${right[index]} |`});const table=[tableHeader,...tableRows].join("\n");answers.push(table);}break}});return answers}function injectWidgets(content,widgets,widgetProps){if(!content){return ""}if(!widgets){return content}let context=content;keys(widgets).forEach(widgetID=>{const widget=widgets[widgetID];if(!widget.options){return}switch(widget.type){case "radio":const radio=widget;const radioProps=widgetProps?.[widgetID];if(radio.options?.choices?.length){let radioContext=joinOptionContents(radioProps?radioProps.choices.map(({content},i)=>({content:`Option ${toOptionLetter(i)}: ${content}`})):radio.options.choices);if(!radioProps&&radio.options?.randomize){radioContext+="\nThose options are displayed in a different order to the user. If the user says the letter, number, or ordinal number, always ask them clarify which option they are referring to.\n";}context=context.replace(`[[☃ ${widgetID}]]`,radioContext);}break;case "image":const image=widget;if(image.options?.alt){context=context.replace(`[[☃ ${widgetID}]]`,`<img id="${widgetID}" alt="${image.options.alt}">`);}break;case "label-image":const labelImage=widget;if(labelImage.options?.imageAlt){context=context.replace(`[[☃ ${widgetID}]]`,`[An image with dots that user needs to label. Label choices: [${labelImage.options.choices.join(", ")}]. Image alt text: ${labelImage.options?.imageAlt??""}]`);}break;case "explanation":const explanation=widget;if(explanation.options?.explanation){context=context.replace(`[[☃ ${widgetID}]]`,injectWidgets(explanation.options.explanation,explanation.options.widgets));}break;case "group":case "graded-group":const group=widget;if(group.options?.widgets&&group.options.content){context=context.replace(`[[☃ ${widgetID}]]`,injectWidgets(group.options.content,group.options.widgets));}break;case "graded-group-set":const gradedGroup=widget;if(gradedGroup.options?.gradedGroups){const gradedGroups=gradedGroup.options.gradedGroups;const gradedGroupsContent=gradedGroups.reduce((acc,group)=>{if(group.widgets&&group.content){acc+=injectWidgets(group.content,group.widgets)+"\n";}return acc},"");context=context.replace(`[[☃ ${widgetID}]]`,gradedGroupsContent);}break;case "categorizer":const categorizer=widget;if(categorizer.options?.categories&&categorizer.options.items){const categories=categorizer.options.categories;const items=categorizer.options.items;context=context.replace(`[[☃ ${widgetID}]]`,`For each item, select the correct category. Categories: ${categories.join(", ")}.
|
|
456
|
-
Items:
|
|
457
|
-
${items.join("\n")}
|
|
458
|
-
`);}break;case "dropdown":const dropdown=widget;if(dropdown.options?.choices){const choices=dropdown.options.choices.map(choice=>choice.content);context=context.replace(`[[☃ ${widgetID}]]`,`[${choices.join(" | ")}]`);}break;case "definition":const definition=widget;if(definition.options?.togglePrompt){context=context.replace(`[[☃ ${widgetID}]]`,definition.options.togglePrompt);}break;case "orderer":const orderer=widget;if(orderer.options?.options){context=context.replace(`[[☃ ${widgetID}]]`,joinOptionContents(orderer.options.options));}break;case "sorter":const sorter=widget;if(sorter.options?.correct){const choices=sorter.options.correct;context=context.replace(`[[☃ ${widgetID}]]`,`[${choices.join(" | ")}]`);}break;case "interactive-graph":const interactiveGraph=widget;if(interactiveGraph.options?.range.length===2){const[x,y]=interactiveGraph.options.range;context=context.replace(`[[☃ ${widgetID}]]`,`[Graph with an x range of ${x[0]} to ${x[1]} and y range of ${y[0]} to ${y[1]}]`);}break;case "number-line":const numberLine=widget;if(numberLine.options?.range.length===2&&numberLine.options?.tickStep&&numberLine.options?.initialX){const[min,max]=numberLine.options.range;const step=numberLine.options.tickStep;const initialPosition=numberLine.options.initialX;context=context.replace(`[[☃ ${widgetID}]]`,`[Number line with a range of ${min} to ${max}, a step of ${step}, and an initial position of ${initialPosition}]`);}break;case "matrix":const matrix=widget;if(matrix.options?.matrixBoardSize.length===2){const[rows,columns]=matrix.options.matrixBoardSize;context=context.replace(`[[☃ ${widgetID}]]`,`[Matrix with ${rows} rows and ${columns} columns. The user can click on each cell to enter a value]`);}break;case "matcher":const matcher=widget;if(matcher.options?.left&&matcher.options?.right){const{left,right}=matcher.options;const[leftHeader,rightHeader]=matcher.options.labels;const tableHeader=`| ${leftHeader} | ${rightHeader} |
|
|
459
|
-
| --- | --- |`;const tableRows=left.map((leftItem,index)=>{return `| ${leftItem} | ${right[index]} |`});const table=[tableHeader,...tableRows].join("\n");const matcherWidgetExplanation="The user needs to move items in the right column to match the correct option on the left. The order of items on the right side will be different from what the user sees.";context=context.replace(`[[☃ ${widgetID}]]`,`${matcherWidgetExplanation}
|
|
460
|
-
${table}`);}break;case "numeric-input":case "input-number":case "expression":context=context.replace(`[[☃ ${widgetID}]]`,"?");break;default:context=context.replace(`[[☃ ${widgetID}]]`,`[[Unsupported ${widget.type} widget: Explain to the user that you are unable to understand the content in this widget and ask them to describe it.]]`);}});return context}function getPerseusAIData(perseusItem){const answers=getAnswersFromWidgets(perseusItem.question.widgets);const hints=perseusItem.hints.map(hint=>injectWidgets(hint.content,hint.widgets));return {answers,hints}}
|
|
461
|
-
|
|
462
|
-
const denylist=["key","ref","containerSizeClass","widgetId","onChange","problemNum","apiOptions","widgetIsOpen","findWidgets","onRemove","id","onBlur","onFocus","trackInteraction","keypadElement","linterContext","handleUserInput","analytics","showSolutions","reviewMode","widgetIndex","graded"];function excludeDenylistKeys(obj){if(obj==null){return obj}const rv={};for(const k of Object.keys(obj)){if(!denylist.includes(k)){rv[k]=obj[k];}}return rv}
|
|
463
|
-
|
|
464
|
-
registerCoreWidgets();
|
|
465
|
-
|
|
466
|
-
export { coreWidgetRegistry as CoreWidgetRegistry, ErrorCodes, Errors, grapherUtil as GrapherUtil, ItemExtras, PerseusError, PerseusExpressionAnswerFormConsidered, PerseusFeatureFlags, Registry, SORTER_MAX_CARDS, addWidget, applyDefaultsToWidget, applyDefaultsToWidgets, approximateDeepEqual, approximateEqual, blankWidgetLogic as blankLogic, categorizerWidgetLogic as categorizerLogic, convertGrapherOptionsToInteractiveGraph, convertGrapherUserInputToInteractiveGraph, convertInteractiveGraphUserInputToGrapher, csProgramWidgetLogic as csProgramLogic, deepClone, definitionWidgetLogic as definitionLogic, deriveExtraKeys, deriveNumCorrect, dropdownWidgetLogic as dropdownLogic, excludeDenylistKeys, explanationWidgetLogic as explanationLogic, expressionWidgetLogic as expressionLogic, fillInTheBlankWidgetLogic as fillInTheBlankLogic, freeResponseWidgetLogic as freeResponseLogic, generateAnswerTile, generateBlankOptions, generateBlankWidget, generateCategorizerOptions, generateCategorizerWidget, generateDefinitionOptions, generateDefinitionWidget, generateDropdownOptions, generateDropdownWidget, generateExplanationOptions, generateExplanationWidget, generateExpressionAnswerForm, generateExpressionOptions, generateExpressionWidget, generateFillInTheBlankOptions, generateFillInTheBlankWidget, generateFreeResponseOptions, generateFreeResponseWidget, generateGradedGroupOptions, generateGradedGroupSetWidget, generateGradedGroupWidget, generateGrapherWidgetOptions, generateGroupOptions, generateGroupWidget, generateIGAbsoluteValueGraph, generateIGAngleGraph, generateIGCircleGraph, generateIGExponentialGraph, generateIGLinearGraph, generateIGLinearSystemGraph, generateIGLockedEllipse, generateIGLockedFunction, generateIGLockedLabel, generateIGLockedLine, generateIGLockedPoint, generateIGLockedPolygon, generateIGLockedVector, generateIGLogarithmGraph, generateIGNoneGraph, generateIGPointGraph, generateIGPolygonGraph, generateIGQuadraticGraph, generateIGRayGraph, generateIGSegmentGraph, generateIGSinusoidGraph, generateIGTangentGraph, generateIGVectorGraph, generateImageOptions, generateImageWidget, generateInputNumberAnswer, generateInputNumberOptions, generateInputNumberWidget, generateInteractiveGraphOptions, generateInteractiveGraphQuestion, generateInteractiveGraphWidget, generateLabelImageOptions, generateLabelImageWidget, generateMatcherOptions, generateMatcherWidget, generateMatrixOptions, generateMatrixWidget, generateMeasurerOptions, generateMeasurerWidget, generateNumberLineOptions, generateNumberLineWidget, generateNumericInputAnswer, generateNumericInputOptions, generateNumericInputWidget, generateOrdererOption, generateOrdererOptions, generateOrdererWidget, generatePhetSimulationOptions, generatePhetSimulationWidget, generatePlotterOptions, generatePlotterWidget, generateRadioChoice, generateRadioOptions, generateRadioWidget, generateSimpleRadioItem, generateSimpleRadioQuestion, generateSorterOptions, generateSorterWidget, generateTableOptions, generateTestPerseusItem, generateTestPerseusRenderer, generateVideoWidget, getAnswersFromWidgets, getBaseUrl, getCSProgramPublicWidgetOptions, getCategorizerPublicWidgetOptions, getDataUrl, getDecimalSeparator, getDefaultAnswerArea, getDefaultFigureForType, getDivideSymbol, getDivideSymbolForTex, getDropdownPublicWidgetOptions, getExpressionPublicWidgetOptions, getFreeResponsePublicWidgetOptions, getGrapherPublicWidgetOptions, getGroupPublicWidgetOptions, getIFramePublicWidgetOptions, getImageSizeModern, getInteractiveGraphPublicWidgetOptions, getLabelImagePublicWidgetOptions, getMatcherPublicWidgetOptions, getMatrixPublicWidgetOptions, getMatrixSize, getNumberLinePublicWidgetOptions, getNumericInputPublicWidgetOptions, getOrdererPublicWidgetOptions, getPerseusAIData, getPlotterPublicWidgetOptions, getRadioPublicWidgetOptions, getRealImageUrl, getSorterPublicWidgetOptions, getSvgUrl, getTablePublicWidgetOptions, getWidgetIdsFromContent, getWidgetIdsFromContentByType, gradedGroupWidgetLogic as gradedGroupLogic, gradedGroupSetWidgetLogic as gradedGroupSetLogic, grapherWidgetLogic as grapherLogic, groupWidgetLogic as groupLogic, iframeWidgetLogic as iframeLogic, imageWidgetLogic as imageLogic, injectWidgets, inputNumberWidgetLogic as inputNumberLogic, interactionWidgetLogic as interactionLogic, interactiveGraphWidgetLogic as interactiveGraphLogic, isFailure, isFeatureOn, isItemAccessible, isLabeledSVG, isSuccess, itemHasHints, itemHasRationales, labelImageWidgetLogic as labelImageLogic, libVersion, lockedFigureColorNames, lockedFigureColors, lockedFigureFillStyles, makeSafeUrl, mapObject, matcherWidgetLogic as matcherLogic, matrixWidgetLogic as matrixLogic, measurerWidgetLogic as measurerLogic, mergeCards, numberLineWidgetLogic as numberLineLogic, numericInputWidgetLogic as numericInputLogic, ordererWidgetLogic as ordererLogic, parseAndMigratePerseusArticle, parseAndMigratePerseusItem, parseAndMigratePerseusRenderer, parseAndMigrateUserInputMap, phetSimulationWidgetLogic as phetSimulationLogic, plotterWidgetLogic as plotterLogic, plotterPlotTypes, pluck, pythonProgramWidgetLogic as pythonProgramLogic, radioWidgetLogic as radioLogic, random, removeOrphanedWidgetsFromPerseusItem, seededRNG, shuffle, shuffleMatcher, shuffleSorter, sorterWidgetLogic as sorterLogic, splitPerseusItem, splitPerseusItemJSON, tableWidgetLogic as tableLogic, toCard, traverse, usesNumCorrect, videoWidgetLogic as videoLogic };
|
|
467
|
-
//# sourceMappingURL=index.js.map
|