@khanacademy/perseus 60.0.2 → 61.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/dist/es/index.css +1 -3184
  2. package/dist/es/index.js +58 -30
  3. package/dist/es/index.js.map +1 -1
  4. package/dist/index.css +1 -3184
  5. package/dist/index.d.ts +2 -2
  6. package/dist/index.js +58 -33
  7. package/dist/index.js.map +1 -1
  8. package/dist/perseus-version.d.ts +0 -4
  9. package/dist/types.d.ts +0 -1
  10. package/dist/util/test-utils.d.ts +1 -12
  11. package/dist/util.d.ts +6 -1
  12. package/dist/widget-ai-utils/radio/radio-ai-utils.d.ts +2 -2
  13. package/dist/widgets/expression/expression.d.ts +3 -3
  14. package/dist/widgets/graded-group/graded-group.d.ts +2 -2
  15. package/dist/widgets/graded-group-set/graded-group-set.d.ts +2 -2
  16. package/dist/widgets/grapher/grapher.d.ts +2 -2
  17. package/dist/widgets/group/group.d.ts +2 -2
  18. package/dist/widgets/input-number/input-number.d.ts +3 -3
  19. package/dist/widgets/interactive-graph.d.ts +13 -13
  20. package/dist/widgets/interactive-graphs/types.d.ts +1 -1
  21. package/dist/widgets/matcher/matcher.d.ts +2 -2
  22. package/dist/widgets/matrix/matrix.d.ts +2 -2
  23. package/dist/widgets/measurer/measurer.d.ts +1 -1
  24. package/dist/widgets/mock-widgets/mock-widget.d.ts +2 -2
  25. package/dist/widgets/number-line/number-line.d.ts +2 -2
  26. package/dist/widgets/numeric-input/numeric-input.class.d.ts +1 -1
  27. package/dist/widgets/numeric-input/numeric-input.d.ts +1 -1
  28. package/dist/widgets/orderer/orderer.d.ts +2 -2
  29. package/dist/widgets/phet-simulation/phet-simulation.d.ts +1 -1
  30. package/dist/widgets/plotter/plotter.d.ts +3 -3
  31. package/dist/widgets/radio/base-radio.new.d.ts +49 -0
  32. package/dist/widgets/radio/choice-a11y-text.new.d.ts +14 -0
  33. package/dist/widgets/radio/choice-icon/choice-icon.new.d.ts +23 -0
  34. package/dist/widgets/radio/choice-none-above.new.d.ts +6 -0
  35. package/dist/widgets/radio/choice.new.d.ts +23 -0
  36. package/dist/widgets/radio/focus-ring.new.d.ts +19 -0
  37. package/dist/widgets/radio/option-status.new.d.ts +24 -0
  38. package/dist/widgets/radio/radio-component.d.ts +4 -4
  39. package/dist/widgets/radio/radio-component.new.d.ts +63 -0
  40. package/dist/widgets/radio/radio.d.ts +1 -1
  41. package/dist/widgets/radio/radio.ff.d.ts +24 -0
  42. package/dist/widgets/sorter/sorter.d.ts +2 -2
  43. package/dist/widgets/table/table.d.ts +23 -17
  44. package/dist/widgets/table/test-util.d.ts +2 -0
  45. package/package.json +11 -11
package/dist/es/index.js CHANGED
@@ -26,8 +26,6 @@ import { TextField } from '@khanacademy/wonder-blocks-form';
26
26
  import { entries, UnreachableCaseError, keys } from '@khanacademy/wonder-stuff-core';
27
27
  import { CircularSpinner } from '@khanacademy/wonder-blocks-progress-spinner';
28
28
  import { point, KhanMath, number, vector as vector$3, geometry, line, angles, coefficients } from '@khanacademy/kmath';
29
- import { _ as _$1 } from '@swc/helpers/_/_class_private_field_loose_base';
30
- import { _ as _$2 } from '@swc/helpers/_/_class_private_field_loose_key';
31
29
  import SimpleMarkdown from '@khanacademy/simple-markdown';
32
30
  import { pureMarkdownRules } from '@khanacademy/pure-markdown';
33
31
  import Button from '@khanacademy/wonder-blocks-button';
@@ -1419,7 +1417,7 @@ var a11y = StyleSheet.create({srOnly:{border:0,clip:"rect(0,0,0,0)",height:1,mar
1419
1417
 
1420
1418
  const debounce=(func,delay)=>{let timer=null;return (...args)=>{if(timer){clearTimeout(timer);}timer=window.setTimeout(()=>{func(...args);},delay);}};
1421
1419
 
1422
- class InnerMathInput extends React.Component{componentDidMount(){this.mathField()?.latex(this.props.value);}openKeypad(){if(this.props.buttonsVisible==="never"){return}this.setState({keypadOpen:true});}closeKeypad(){this.setState({keypadOpen:false});}render(){let className=classNames$1({"perseus-math-input":true,"mq-editable-field":true,"mq-math-mode":true});const popoverContentUniqueId=v4().slice(0,8);if(this.props.className){className=className+" "+this.props.className;}return jsxRuntimeExports.jsx(View,{style:[styles$D.outerWrapper,this.state.focused&&styles$D.wrapperFocused,this.props.hasError&&styles$D.wrapperError],children:jsxRuntimeExports.jsxs("div",{style:{display:"flex",padding:1},onClick:e=>{e.stopPropagation();const mathField=this.mathField();if(!mathField){return}this.setState({cursorContext:getCursorContext(mathField)});},children:[jsxRuntimeExports.jsx("span",{className:className,ref:ref=>this.__mathFieldWrapperRef=ref,onFocus:()=>this.focus(),onBlur:()=>this.blur()}),jsxRuntimeExports.jsx(Popover,{opened:this.state.keypadOpen,dismissEnabled:true,rootBoundary:"document","aria-label":this.context.strings.mathInputTitle,"aria-describedby":`popover-content-${popoverContentUniqueId}`,content:()=>jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(HeadingMedium,{id:`popover-content-${popoverContentUniqueId}`,style:a11y.srOnly,children:this.context.strings.mathInputDescription}),jsxRuntimeExports.jsx(PopoverContentCore,{style:styles$D.popoverContent,children:jsxRuntimeExports.jsx(DesktopKeypad,{onAnalyticsEvent:this.props.onAnalyticsEvent,extraKeys:this.props.extraKeys,onClickKey:this.handleKeypadPress,cursorContext:this.state.cursorContext,convertDotToTimes:this.props.convertDotToTimes,...this.props.keypadButtonSets??mapButtonSets(this.props?.buttonSets),showDismiss:true})})]}),children:this.props.buttonsVisible==="never"?jsxRuntimeExports.jsx(MathInputIcon,{hovered:false,focused:false,active:false}):jsxRuntimeExports.jsx(Clickable,{"aria-label":this.state.keypadOpen?this.context.strings.closeKeypad:this.context.strings.openKeypad,role:"button",onClick:()=>this.state.keypadOpen?this.closeKeypad():this.openKeypad(),children:props=>jsxRuntimeExports.jsx(MathInputIcon,{active:this.state.keypadOpen,...props})})})]})})}constructor(...args){super(...args),this.__mathFieldWrapperRef=null,this.__mathField=null,this.state={focused:false,keypadOpen:this.props.buttonsVisible==="always"?true:false,cursorContext:CursorContext.NONE},this.insert=value=>{const input=this.mathField();const{locale}=this.context;const customKeyTranslator={...getKeyTranslator(locale,this.context.strings),FRAC:mathQuill=>{const contents=mathQuill.latex();mathQuill.typedText("/");if(mathQuill.latex()===contents){mathQuill.cmd("\\frac");}}};const inputModifier=customKeyTranslator[value];if(inputModifier){inputModifier(input,value);input?.focus();return}if(_(value).isFunction()){value(input);}else if(value[0]==="\\"){input?.cmd(value).focus();}else {input?.write(value).focus();}input?.focus();},this.mathField=()=>{if(!this.__mathField&&this.__mathFieldWrapperRef){const{locale}=this.context;this.__mathField=createMathField(this.__mathFieldWrapperRef,locale,this.props.mathInputStrings,baseConfig=>({...baseConfig,handlers:{edit:debounce(mathField=>{let value=mathField.latex();value=value.replace(/<>/g,"\\ne");if(convertDotToTimesByLocale(locale,this.props.convertDotToTimes)){value=value.replace(/\\cdot/g,"\\times");const left=mathField.cursor()[mathQuillInstance.L];if(left&&left.ctrlSeq==="\\cdot "){mathField.controller().backspace();mathField.cmd("\\times");}}else {value=value.replace(/\\times/g,"\\cdot");}if(this.props.value!==value){this.props.onChange(value);}this.setState({cursorContext:getCursorContext(mathField)});},100),enter:()=>{if(this.__mathFieldWrapperRef){$(this.__mathFieldWrapperRef).submit();}},upOutOf:mathField=>{mathField.typedText("^");}}}));}this.__mathField?.setAriaLabel(this.props.ariaLabel);return this.__mathField},this.focus=()=>{this.mathField()?.focus();this.setState({focused:true});},this.blur=()=>this.setState({focused:false}),this.handleKeypadPress=(key,e)=>{const{locale}=this.context;const translator=getKeyTranslator(locale,this.context.strings)[key];const mathField=this.mathField();if(mathField){if(translator){translator(mathField,key);}this.setState({cursorContext:getCursorContext(mathField)});}if(e?.type==="click"){this.focus();}if(key==="DISMISS"){this.closeKeypad();}};}}InnerMathInput.contextType=PerseusI18nContext;InnerMathInput.defaultProps={value:"",convertDotToTimes:false};class MathInput extends React.Component{blur(){this.inputRef.current?.blur();}focus(){this.inputRef.current?.focus();}insert(value){this.inputRef.current?.insert(value);}render(){return jsxRuntimeExports.jsx(InnerMathInput,{...this.props,ref:this.inputRef,mathInputStrings:this.context.strings})}constructor(...args){super(...args),this.inputRef=React.createRef();}}MathInput.contextType=MathInputI18nContext;MathInput.defaultProps={ariaLabel:"Math input"};const MathInputIcon=({hovered,focused,active})=>{let fillColor;switch(true){case focused||active:fillColor=color.white;break;case hovered:fillColor=color.blue;break;default:fillColor=color.offBlack;break}const dynamicClass=active||focused?styles$D.iconActive:styles$D.iconInactive;return jsxRuntimeExports.jsx(View,{style:[styles$D.iconContainer,dynamicClass],children:jsxRuntimeExports.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:fillColor,viewBox:"0 0 256 256",children:jsxRuntimeExports.jsx("path",{d:"M112,72a8,8,0,0,1-8,8H40a8,8,0,0,1,0-16h64A8,8,0,0,1,112,72Zm-8,104H80V152a8,8,0,0,0-16,0v24H40a8,8,0,0,0,0,16H64v24a8,8,0,0,0,16,0V192h24a8,8,0,0,0,0-16Zm48,0h64a8,8,0,0,0,0-16H152a8,8,0,0,0,0,16Zm64,16H152a8,8,0,0,0,0,16h64a8,8,0,0,0,0-16Zm-61.66-90.34a8,8,0,0,0,11.32,0L184,83.31l18.34,18.35a8,8,0,0,0,11.32-11.32L195.31,72l18.35-18.34a8,8,0,0,0-11.32-11.32L184,60.69,165.66,42.34a8,8,0,0,0-11.32,11.32L172.69,72,154.34,90.34A8,8,0,0,0,154.34,101.66Z"})})})};const mapButtonSets=buttonSets=>{const keypadButtonSets={};if(!buttonSets){return keypadButtonSets}buttonSets.forEach(buttonSet=>{switch(buttonSet){case "advanced relations":keypadButtonSets.advancedRelations=true;break;case "basic relations":keypadButtonSets.basicRelations=true;break;case "basic+div":keypadButtonSets.divisionKey=true;break;case "logarithms":keypadButtonSets.logarithms=true;break;case "prealgebra":keypadButtonSets.preAlgebra=true;break;case "trig":keypadButtonSets.trigonometry=true;break;case "scientific":keypadButtonSets.scientific=true;break;}});return keypadButtonSets};const inputFocused={borderWidth:2,borderColor:color.blue,margin:-1};const styles$D=StyleSheet.create({iconContainer:{display:"flex",justifyContent:"center",height:"100%",padding:spacing.xxxSmall_4,borderRadius:1},iconInactive:{border:"2px solid transparent",backgroundColor:color.offBlack8},iconActive:{border:`2px solid ${color.white}`,backgroundColor:color.offBlack64},outerWrapper:{display:"inline-block",borderStyle:"solid",borderWidth:1,borderColor:color.offBlack50,borderRadius:3,background:color.white,":hover":inputFocused},wrapperFocused:inputFocused,wrapperError:{borderColor:color.red,background:color.fadedRed8,":hover":{borderColor:color.red}},popoverContent:{padding:0,paddingBottom:spacing.xxSmall_6,maxWidth:"initial"}});
1420
+ class InnerMathInput extends React.Component{componentDidMount(){this.mathField()?.latex(this.props.value);}openKeypad(){if(this.props.buttonsVisible==="never"){return}this.setState({keypadOpen:true});}closeKeypad(){this.setState({keypadOpen:false});}render(){let className=classNames$1({"perseus-math-input":true,"mq-editable-field":true,"mq-math-mode":true});const popoverContentUniqueId=v4().slice(0,8);if(this.props.className){className=className+" "+this.props.className;}return jsxRuntimeExports.jsx(View,{style:[styles$H.outerWrapper,this.state.focused&&styles$H.wrapperFocused,this.props.hasError&&styles$H.wrapperError],children:jsxRuntimeExports.jsxs("div",{style:{display:"flex",padding:1},onClick:e=>{e.stopPropagation();const mathField=this.mathField();if(!mathField){return}this.setState({cursorContext:getCursorContext(mathField)});},children:[jsxRuntimeExports.jsx("span",{className:className,ref:ref=>this.__mathFieldWrapperRef=ref,onFocus:()=>this.focus(),onBlur:()=>this.blur()}),jsxRuntimeExports.jsx(Popover,{opened:this.state.keypadOpen,dismissEnabled:true,rootBoundary:"document","aria-label":this.context.strings.mathInputTitle,"aria-describedby":`popover-content-${popoverContentUniqueId}`,content:()=>jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(HeadingMedium,{id:`popover-content-${popoverContentUniqueId}`,style:a11y.srOnly,children:this.context.strings.mathInputDescription}),jsxRuntimeExports.jsx(PopoverContentCore,{style:styles$H.popoverContent,children:jsxRuntimeExports.jsx(DesktopKeypad,{onAnalyticsEvent:this.props.onAnalyticsEvent,extraKeys:this.props.extraKeys,onClickKey:this.handleKeypadPress,cursorContext:this.state.cursorContext,convertDotToTimes:this.props.convertDotToTimes,...this.props.keypadButtonSets??mapButtonSets(this.props?.buttonSets),showDismiss:true})})]}),children:this.props.buttonsVisible==="never"?jsxRuntimeExports.jsx(MathInputIcon,{hovered:false,focused:false,active:false}):jsxRuntimeExports.jsx(Clickable,{"aria-label":this.state.keypadOpen?this.context.strings.closeKeypad:this.context.strings.openKeypad,role:"button",onClick:()=>this.state.keypadOpen?this.closeKeypad():this.openKeypad(),children:props=>jsxRuntimeExports.jsx(MathInputIcon,{active:this.state.keypadOpen,...props})})})]})})}constructor(...args){super(...args),this.__mathFieldWrapperRef=null,this.__mathField=null,this.state={focused:false,keypadOpen:this.props.buttonsVisible==="always"?true:false,cursorContext:CursorContext.NONE},this.insert=value=>{const input=this.mathField();const{locale}=this.context;const customKeyTranslator={...getKeyTranslator(locale,this.context.strings),FRAC:mathQuill=>{const contents=mathQuill.latex();mathQuill.typedText("/");if(mathQuill.latex()===contents){mathQuill.cmd("\\frac");}}};const inputModifier=customKeyTranslator[value];if(inputModifier){inputModifier(input,value);input?.focus();return}if(_(value).isFunction()){value(input);}else if(value[0]==="\\"){input?.cmd(value).focus();}else {input?.write(value).focus();}input?.focus();},this.mathField=()=>{if(!this.__mathField&&this.__mathFieldWrapperRef){const{locale}=this.context;this.__mathField=createMathField(this.__mathFieldWrapperRef,locale,this.props.mathInputStrings,baseConfig=>({...baseConfig,handlers:{edit:debounce(mathField=>{let value=mathField.latex();value=value.replace(/<>/g,"\\ne");if(convertDotToTimesByLocale(locale,this.props.convertDotToTimes)){value=value.replace(/\\cdot/g,"\\times");const left=mathField.cursor()[mathQuillInstance.L];if(left&&left.ctrlSeq==="\\cdot "){mathField.controller().backspace();mathField.cmd("\\times");}}else {value=value.replace(/\\times/g,"\\cdot");}if(this.props.value!==value){this.props.onChange(value);}this.setState({cursorContext:getCursorContext(mathField)});},100),enter:()=>{if(this.__mathFieldWrapperRef){$(this.__mathFieldWrapperRef).submit();}},upOutOf:mathField=>{mathField.typedText("^");}}}));}this.__mathField?.setAriaLabel(this.props.ariaLabel);return this.__mathField},this.focus=()=>{this.mathField()?.focus();this.setState({focused:true});},this.blur=()=>this.setState({focused:false}),this.handleKeypadPress=(key,e)=>{const{locale}=this.context;const translator=getKeyTranslator(locale,this.context.strings)[key];const mathField=this.mathField();if(mathField){if(translator){translator(mathField,key);}this.setState({cursorContext:getCursorContext(mathField)});}if(e?.type==="click"){this.focus();}if(key==="DISMISS"){this.closeKeypad();}};}}InnerMathInput.contextType=PerseusI18nContext;InnerMathInput.defaultProps={value:"",convertDotToTimes:false};class MathInput extends React.Component{blur(){this.inputRef.current?.blur();}focus(){this.inputRef.current?.focus();}insert(value){this.inputRef.current?.insert(value);}render(){return jsxRuntimeExports.jsx(InnerMathInput,{...this.props,ref:this.inputRef,mathInputStrings:this.context.strings})}constructor(...args){super(...args),this.inputRef=React.createRef();}}MathInput.contextType=MathInputI18nContext;MathInput.defaultProps={ariaLabel:"Math input"};const MathInputIcon=({hovered,focused,active})=>{let fillColor;switch(true){case focused||active:fillColor=color.white;break;case hovered:fillColor=color.blue;break;default:fillColor=color.offBlack;break}const dynamicClass=active||focused?styles$H.iconActive:styles$H.iconInactive;return jsxRuntimeExports.jsx(View,{style:[styles$H.iconContainer,dynamicClass],children:jsxRuntimeExports.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",fill:fillColor,viewBox:"0 0 256 256",children:jsxRuntimeExports.jsx("path",{d:"M112,72a8,8,0,0,1-8,8H40a8,8,0,0,1,0-16h64A8,8,0,0,1,112,72Zm-8,104H80V152a8,8,0,0,0-16,0v24H40a8,8,0,0,0,0,16H64v24a8,8,0,0,0,16,0V192h24a8,8,0,0,0,0-16Zm48,0h64a8,8,0,0,0,0-16H152a8,8,0,0,0,0,16Zm64,16H152a8,8,0,0,0,0,16h64a8,8,0,0,0,0-16Zm-61.66-90.34a8,8,0,0,0,11.32,0L184,83.31l18.34,18.35a8,8,0,0,0,11.32-11.32L195.31,72l18.35-18.34a8,8,0,0,0-11.32-11.32L184,60.69,165.66,42.34a8,8,0,0,0-11.32,11.32L172.69,72,154.34,90.34A8,8,0,0,0,154.34,101.66Z"})})})};const mapButtonSets=buttonSets=>{const keypadButtonSets={};if(!buttonSets){return keypadButtonSets}buttonSets.forEach(buttonSet=>{switch(buttonSet){case "advanced relations":keypadButtonSets.advancedRelations=true;break;case "basic relations":keypadButtonSets.basicRelations=true;break;case "basic+div":keypadButtonSets.divisionKey=true;break;case "logarithms":keypadButtonSets.logarithms=true;break;case "prealgebra":keypadButtonSets.preAlgebra=true;break;case "trig":keypadButtonSets.trigonometry=true;break;case "scientific":keypadButtonSets.scientific=true;break;}});return keypadButtonSets};const inputFocused={borderWidth:2,borderColor:color.blue,margin:-1};const styles$H=StyleSheet.create({iconContainer:{display:"flex",justifyContent:"center",height:"100%",padding:spacing.xxxSmall_4,borderRadius:1},iconInactive:{border:"2px solid transparent",backgroundColor:color.offBlack8},iconActive:{border:`2px solid ${color.white}`,backgroundColor:color.offBlack64},outerWrapper:{display:"inline-block",borderStyle:"solid",borderWidth:1,borderColor:color.offBlack50,borderRadius:3,background:color.white,":hover":inputFocused},wrapperFocused:inputFocused,wrapperError:{borderColor:color.red,background:color.fadedRed8,":hover":{borderColor:color.red}},popoverContent:{padding:0,paddingBottom:spacing.xxSmall_6,maxWidth:"initial"}});
1423
1421
 
1424
1422
  let _dependencies=null;const setDependencies=dependencies=>{_dependencies=dependencies;};const getDependencies=()=>{if(_dependencies){return _dependencies}throw new Error(["Perseus has not been provided required dependencies.","setDependencies(dependencies) must be called first.","Make sure Perseus is being imported from javascript/perseus/perseus.js."].join("\n"))};const DependenciesContext=React.createContext({analytics:{onAnalyticsEvent:async()=>{}},useVideo:()=>{throw new Error("useVideo dependency not provided in Perseus dependencies")}});const useDependencies=()=>{const deps=React.useContext(DependenciesContext);return deps};
1425
1423
 
@@ -1449,7 +1447,7 @@ const ApiOptions={propTypes:PropTypes.shape({isArticle:PropTypes.bool.isRequired
1449
1447
 
1450
1448
  const getPromptJSON$t=(renderProps,userInput)=>{return {type:"expression",label:renderProps.visibleLabel,userInput:{value:userInput}}};
1451
1449
 
1452
- const englishOperators={arctg:"arctan",cosec:"csc",cossec:"csc",cotg:"cot",ctg:"cot",sen:"sin",tg:"tan"};const anglicizeOperators=tex=>{return tex.replace(/\\operatorname{([a-z]+)}/g,(_,op)=>`\\${englishOperators[op]??op} `)};const normalizeTex=tex=>{return anglicizeOperators(tex)};class Expression extends React.Component{static getUserInputFromProps(props){return normalizeTex(props.value)}getUserInput(){return Expression.getUserInputFromProps(this.props)}getPromptJSON(){return getPromptJSON$t(this.props,this.getUserInput())}focusInputPath(inputPath){this.refs.input.focus();}blurInputPath(inputPath){if(typeof this.refs.input?.blur==="function"){this.refs.input?.blur();}}insert(keyPressed){this.refs.input.insert(keyPressed);}setInputValue(path,newValue,cb){this.props.onChange({value:newValue},cb);}render(){if(this.props.apiOptions.customKeypad){return jsxRuntimeExports.jsxs(View,{className:css(styles$C.mobileLabelInputWrapper),children:[!!this.props.visibleLabel&&jsxRuntimeExports.jsx(LabelSmall,{htmlFor:this._textareaId,tag:"label",children:this.props.visibleLabel}),jsxRuntimeExports.jsx(KeypadInput,{ref:"input",ariaLabel:this.props.ariaLabel||this.context.strings.mathInputBox,value:this.props.value,keypadElement:this.props.keypadElement,onChange:this.changeAndTrack,onFocus:()=>{this.props.keypadElement?.configure(this.props.keypadConfiguration,()=>{if(this._isMounted){this._handleFocus();}});},onBlur:this._handleBlur})]})}const className=classNames$1({"perseus-widget-expression":true,"show-error-tooltip":this.state.showErrorTooltip});const{ERROR_MESSAGE,ERROR_TITLE}=this.context.strings;return jsxRuntimeExports.jsxs(View,{className:css(styles$C.desktopLabelInputWrapper),children:[!!this.props.visibleLabel&&jsxRuntimeExports.jsx(LabelSmall,{htmlFor:this._textareaId,tag:"label",children:this.props.visibleLabel}),jsxRuntimeExports.jsxs("div",{className:className,onBlur:()=>this.state.invalid&&this.setState({showErrorTooltip:true,showErrorStyle:true}),onFocus:()=>this.setState({showErrorTooltip:false}),children:[jsxRuntimeExports.jsx(View,{style:a11y.srOnly,role:"alert",children:this.state.showErrorTooltip&&ERROR_TITLE+" "+ERROR_MESSAGE}),jsxRuntimeExports.jsx(Tooltip,{forceAnchorFocusivity:false,opened:this.state.showErrorTooltip,title:ERROR_TITLE,content:ERROR_MESSAGE,children:jsxRuntimeExports.jsx(MathInput,{ref:"input",value:this.props.value,onChange:this.changeAndTrack,convertDotToTimes:this.props.times,buttonSets:this.props.buttonSets,onFocus:this._handleFocus,onBlur:this._handleBlur,hasError:this.state.showErrorStyle,ariaLabel:this.props.ariaLabel||this.context.strings.mathInputBox,extraKeys:this.props.keypadConfiguration?.extraKeys,onAnalyticsEvent:this.props.analytics?.onAnalyticsEvent??(async()=>{})})})]})]})}constructor(...args){super(...args),this._textareaId=`expression_textarea_${Date.now()}`,this._isMounted=false,this.displayName="Expression",this.state={invalid:false,showErrorTooltip:false,showErrorStyle:false},this.componentDidMount=()=>{document.addEventListener("mousedown",this._handleMouseDown);this._isMounted=true;if(this.refs.input){const isMobile=this.props.apiOptions.customKeypad;const container=ReactDOM__default.findDOMNode(this.refs.input);const selector=isMobile?".mq-textarea > span":"textarea";const inputElement=container.querySelector(selector);inputElement?.setAttribute("id",this._textareaId);}},this.componentDidUpdate=prevProps=>{if(!_.isEqual(this.props.value,prevProps.value)||!_.isEqual(this.props.functions,prevProps.functions)){this.setState({invalid:false,showErrorTooltip:false,showErrorStyle:false});if(!this.parse(this.props.value,this.props).parsed){this.setState({invalid:true});}}},this.componentWillUnmount=()=>{this._isMounted=false;},this._handleMouseDown=()=>{if(this._isMounted&&this.state.showErrorTooltip){this.setState({showErrorTooltip:false});}},this.change=(...args)=>{return change.apply(this,args)},this.parse=(value,props)=>{const options=_.pick(props||this.props,"functions");_.extend(options,{decimal_separator:getDecimalSeparator(this.context.locale)});return KAS.parse(normalizeTex(value),options)},this.changeAndTrack=(e,cb)=>{this.change("value",e,cb);this.props.trackInteraction();},this._handleFocus=()=>{this.props.analytics?.onAnalyticsEvent({type:"perseus:expression-focused",payload:null});this.props.onFocus([]);},this._handleBlur=()=>{this.props.onBlur([]);},this.focus=()=>{if(this.props.apiOptions.customKeypad){this.refs.input.focus();}return true},this.getInputPaths=()=>{return [[]]};}}Expression.contextType=PerseusI18nContext;Expression.defaultProps={value:"",times:false,functions:[],buttonSets:["basic","trig","prealgebra","logarithms"],onFocus:()=>{},onBlur:()=>{},apiOptions:ApiOptions.defaults,linterContext:linterContextDefault};const styles$C=StyleSheet.create({mobileLabelInputWrapper:{padding:"15px 4px 0"},desktopLabelInputWrapper:{margin:"5px 5px 0"}});const ExpressionWithDependencies=React.forwardRef((props,ref)=>{const deps=useDependencies();return jsxRuntimeExports.jsx(Expression,{ref:ref,analytics:deps.analytics,...props})});ExpressionWithDependencies.getUserInputFromProps=Expression.getUserInputFromProps;var Expression$1 = {name:"expression",displayName:"Expression / Equation",accessible:true,widget:ExpressionWithDependencies,transform:widgetOptions=>{const{times,functions,buttonSets,buttonsVisible,visibleLabel,ariaLabel,extraKeys}=widgetOptions;return {keypadConfiguration:{keypadType:"EXPRESSION",extraKeys:extraKeys,times},times,functions,buttonSets,buttonsVisible,visibleLabel,ariaLabel}},version:expressionLogic.version,propUpgrades:expressionLogic.widgetOptionsUpgrades,isLintable:true,getOneCorrectAnswerFromRubric(rubric){const correctAnswers=(rubric.answerForms||[]).filter(answerForm=>answerForm.considered==="correct");if(correctAnswers.length===0){return}return correctAnswers[0].value}};
1450
+ const englishOperators={arctg:"arctan",cosec:"csc",cossec:"csc",cotg:"cot",ctg:"cot",sen:"sin",tg:"tan"};const anglicizeOperators=tex=>{return tex.replace(/\\operatorname{([a-z]+)}/g,(_,op)=>`\\${englishOperators[op]??op} `)};const normalizeTex=tex=>{return anglicizeOperators(tex)};class Expression extends React.Component{static getUserInputFromProps(props){return normalizeTex(props.value)}getUserInput(){return Expression.getUserInputFromProps(this.props)}getPromptJSON(){return getPromptJSON$t(this.props,this.getUserInput())}focusInputPath(inputPath){this.refs.input.focus();}blurInputPath(inputPath){if(typeof this.refs.input?.blur==="function"){this.refs.input?.blur();}}insert(keyPressed){this.refs.input.insert(keyPressed);}setInputValue(path,newValue,cb){this.props.onChange({value:newValue},cb);}render(){if(this.props.apiOptions.customKeypad){return jsxRuntimeExports.jsxs(View,{className:css(styles$G.mobileLabelInputWrapper),children:[!!this.props.visibleLabel&&jsxRuntimeExports.jsx(LabelSmall,{htmlFor:this._textareaId,tag:"label",children:this.props.visibleLabel}),jsxRuntimeExports.jsx(KeypadInput,{ref:"input",ariaLabel:this.props.ariaLabel||this.context.strings.mathInputBox,value:this.props.value,keypadElement:this.props.keypadElement,onChange:this.changeAndTrack,onFocus:()=>{this.props.keypadElement?.configure(this.props.keypadConfiguration,()=>{if(this._isMounted){this._handleFocus();}});},onBlur:this._handleBlur})]})}const className=classNames$1({"perseus-widget-expression":true,"show-error-tooltip":this.state.showErrorTooltip});const{ERROR_MESSAGE,ERROR_TITLE}=this.context.strings;return jsxRuntimeExports.jsxs(View,{className:css(styles$G.desktopLabelInputWrapper),children:[!!this.props.visibleLabel&&jsxRuntimeExports.jsx(LabelSmall,{htmlFor:this._textareaId,tag:"label",children:this.props.visibleLabel}),jsxRuntimeExports.jsxs("div",{className:className,onBlur:()=>this.state.invalid&&this.setState({showErrorTooltip:true,showErrorStyle:true}),onFocus:()=>this.setState({showErrorTooltip:false}),children:[jsxRuntimeExports.jsx(View,{style:a11y.srOnly,role:"alert",children:this.state.showErrorTooltip&&ERROR_TITLE+" "+ERROR_MESSAGE}),jsxRuntimeExports.jsx(Tooltip,{forceAnchorFocusivity:false,opened:this.state.showErrorTooltip,title:ERROR_TITLE,content:ERROR_MESSAGE,children:jsxRuntimeExports.jsx(MathInput,{ref:"input",value:this.props.value,onChange:this.changeAndTrack,convertDotToTimes:this.props.times,buttonSets:this.props.buttonSets,onFocus:this._handleFocus,onBlur:this._handleBlur,hasError:this.state.showErrorStyle,ariaLabel:this.props.ariaLabel||this.context.strings.mathInputBox,extraKeys:this.props.keypadConfiguration?.extraKeys,onAnalyticsEvent:this.props.analytics?.onAnalyticsEvent??(async()=>{})})})]})]})}constructor(...args){super(...args),this._textareaId=`expression_textarea_${Date.now()}`,this._isMounted=false,this.displayName="Expression",this.state={invalid:false,showErrorTooltip:false,showErrorStyle:false},this.componentDidMount=()=>{document.addEventListener("mousedown",this._handleMouseDown);this._isMounted=true;if(this.refs.input){const isMobile=this.props.apiOptions.customKeypad;const container=ReactDOM__default.findDOMNode(this.refs.input);const selector=isMobile?".mq-textarea > span":"textarea";const inputElement=container.querySelector(selector);inputElement?.setAttribute("id",this._textareaId);}},this.componentDidUpdate=prevProps=>{if(!_.isEqual(this.props.value,prevProps.value)||!_.isEqual(this.props.functions,prevProps.functions)){this.setState({invalid:false,showErrorTooltip:false,showErrorStyle:false});if(!this.parse(this.props.value,this.props).parsed){this.setState({invalid:true});}}},this.componentWillUnmount=()=>{this._isMounted=false;},this._handleMouseDown=()=>{if(this._isMounted&&this.state.showErrorTooltip){this.setState({showErrorTooltip:false});}},this.change=(...args)=>{return change.apply(this,args)},this.parse=(value,props)=>{const options=_.pick(props||this.props,"functions");_.extend(options,{decimal_separator:getDecimalSeparator(this.context.locale)});return KAS.parse(normalizeTex(value),options)},this.changeAndTrack=(e,cb)=>{this.change("value",e,cb);this.props.trackInteraction();},this._handleFocus=()=>{this.props.analytics?.onAnalyticsEvent({type:"perseus:expression-focused",payload:null});this.props.onFocus([]);},this._handleBlur=()=>{this.props.onBlur([]);},this.focus=()=>{if(this.props.apiOptions.customKeypad){this.refs.input.focus();}return true},this.getInputPaths=()=>{return [[]]};}}Expression.contextType=PerseusI18nContext;Expression.defaultProps={value:"",times:false,functions:[],buttonSets:["basic","trig","prealgebra","logarithms"],onFocus:()=>{},onBlur:()=>{},apiOptions:ApiOptions.defaults,linterContext:linterContextDefault};const styles$G=StyleSheet.create({mobileLabelInputWrapper:{padding:"15px 4px 0"},desktopLabelInputWrapper:{margin:"5px 5px 0"}});const ExpressionWithDependencies=React.forwardRef((props,ref)=>{const deps=useDependencies();return jsxRuntimeExports.jsx(Expression,{ref:ref,analytics:deps.analytics,...props})});ExpressionWithDependencies.getUserInputFromProps=Expression.getUserInputFromProps;var Expression$1 = {name:"expression",displayName:"Expression / Equation",accessible:true,widget:ExpressionWithDependencies,transform:widgetOptions=>{const{times,functions,buttonSets,buttonsVisible,visibleLabel,ariaLabel,extraKeys}=widgetOptions;return {keypadConfiguration:{keypadType:"EXPRESSION",extraKeys,times},times,functions,buttonSets,buttonsVisible,visibleLabel,ariaLabel}},version:expressionLogic.version,propUpgrades:expressionLogic.widgetOptionsUpgrades,isLintable:true,getOneCorrectAnswerFromRubric(rubric){const correctAnswers=(rubric.answerForms||[]).filter(answerForm=>answerForm.considered==="correct");if(correctAnswers.length===0){return}return correctAnswers[0].value}};
1453
1451
 
1454
1452
  class SimpleKeypadInput extends React.Component{componentDidMount(){this._isMounted=true;}componentWillUnmount(){this._isMounted=false;}focus(){this.inputRef.current?.focus(this.context.setKeypadActive);}blur(){this.inputRef.current?.blur();}getValue(){return this.props.value}render(){const _this=this;const{keypadElement,onFocus,value,...rest}=_this.props;return jsxRuntimeExports.jsx(KeypadInput,{ref:this.inputRef,keypadElement:keypadElement,onFocus:()=>{if(keypadElement){keypadElement.configure({keypadType:"FRACTION"},()=>{if(_this._isMounted){onFocus?.();}});}else {onFocus?.();}},value:value==null?"":""+value,...rest})}constructor(...args){super(...args),this._isMounted=false,this.inputRef=React.createRef();}}SimpleKeypadInput.contextType=KeypadContext;SimpleKeypadInput.propTypes={keypadElement:keypadElementPropType,onFocus:PropTypes.func,value:PropTypes.oneOfType([PropTypes.string,PropTypes.number])};
1455
1453
 
@@ -1461,7 +1459,7 @@ const defaultContext$2={assetStatuses:{},setAssetStatus:(assetKey,loaded)=>{}};c
1461
1459
 
1462
1460
  const svgLabelsRegex=/^web\+graphie:/;const svgLocalLabelsRegex$1=/^file\+graphie:/;function getRealImageUrl(graphieUrl){if(isLabeledSVG(graphieUrl)){return getSvgUrl(graphieUrl)}return graphieUrl}function isLabeledSVG(graphieUrl){return svgLabelsRegex.test(graphieUrl)||svgLocalLabelsRegex$1.test(graphieUrl)}function getBaseUrl(graphieUrl){return graphieUrl.replace(svgLabelsRegex,"https:").replace(svgLocalLabelsRegex$1,"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);})}
1463
1461
 
1464
- let supportsPassive=false;const nestedMap$2=function(children,func,context){if(Array.isArray(children)){return _.map(children,function(child){return nestedMap$2(child,func)})}return func.call(context,children)};function inputPathsEqual(a,b){if(a==null||b==null){return a==null===(b==null)}return a.length===b.length&&a.every((item,index)=>{return b[index]===item})}const rWidgetRule=/^\[\[\u2603 (([a-z-]+) ([0-9]+))\]\]/;const rTypeFromWidgetId=/^([a-z-]+) ([0-9]+)$/;const rWidgetParts=new RegExp(rWidgetRule.source+"$");const snowman="☃";const split="x".split(/(.)/g).length?function(str,r){return str.split(r)}:function(str,r){const output=[];let lastIndex=r.lastIndex=0;let match;while(match=r.exec(str)){const m=match;output.push(str.slice(lastIndex,m.index));output.push(...m.slice(1));lastIndex=m.index+m[0].length;}output.push(str.slice(lastIndex));return output};function firstNumericalParse$1(text){let first;const val=KhanAnswerTypes.predicate.createValidatorFunctional(function(ans){first=ans;return true},{simplify:"optional",inexact:true,forms:"integer, proper, improper, pi, log, mixed, decimal"});val(text);return first}function stringArrayOfSize$1(size){return _(size).times(function(){return ""})}function gridDimensionConfig(absTickStep,extent,dimensionConstraint,gridStep){const scale=scaleFromExtent(extent,dimensionConstraint);const stepPx=absTickStep*scale;const unityLabel=stepPx>30;return {scale:scale,tickStep:absTickStep/gridStep,unityLabel:unityLabel}}function getGridStep(range,step,boxSize){return _(2).times(function(i){const scale=scaleFromExtent(range[i],boxSize);const gridStep=gridStepFromTickStep(step[i],scale);return gridStep})}function snapStepFromGridStep(gridStep){return [gridStep[0]/2,gridStep[1]/2]}function gridStepFromTickStep(tickStep,scale){const tickWidth=tickStep*scale;const x=tickStep;const y=Math.pow(10,Math.floor(Math.log(x)/Math.LN10));const leadingDigit=Math.floor(x/y);if(tickWidth<25){return tickStep}if(tickWidth<50){if(leadingDigit===5){return tickStep}return tickStep/2}if(leadingDigit===1){return tickStep/2}if(leadingDigit===2){return tickStep/4}if(leadingDigit===5){return tickStep/5}}function scaleFromExtent(extent,dimensionConstraint){const span=extent[1]-extent[0];const scale=dimensionConstraint/span;return scale}function tickStepFromExtent(extent,dimensionConstraint){const span=extent[1]-extent[0];let tickFactor;if(15<span&&span<=20){tickFactor=23;}else if(span>100||span<5){tickFactor=10;}else {tickFactor=16;}const constraintFactor=dimensionConstraint/500;const desiredNumTicks=tickFactor*constraintFactor;return tickStepFromNumTicks(span,desiredNumTicks)}function tickStepFromNumTicks(span,numTicks){let step=Math.pow(10,Math.floor(Math.log(span/numTicks)/Math.LN10));const err=numTicks/span*step;if(err<=.15){step*=10;}else if(err<=.35){step*=5;}else if(err<=.75){step*=2;}return step}const constrainTickStep=(step,range)=>{const span=range[1]-range[0];const numTicks=span/step;if(numTicks<=10){return step}if(numTicks<=20){return step*2}return tickStepFromNumTicks(span,10)};function constrainedTickStepsFromTickSteps(tickSteps,ranges){return [constrainTickStep(tickSteps[0],ranges[0]),constrainTickStep(tickSteps[1],ranges[1])]}function parseQueryString(query){query=query||window.location.search.substring(1);const urlParams={};const a=/\+/g;const r=/([^&=]+)=?([^&]*)/g;const d=function(s){return decodeURIComponent(s.replace(a," "))};let e;while(e=r.exec(query)){const m=e;urlParams[d(m[1])]=d(m[2]);}return urlParams}function updateQueryString$2(uri,key,value){value=encodeURIComponent(value);const re=new RegExp("([?&])"+key+"=.*?(&|$)","i");const separator=uri.indexOf("?")!==-1?"&":"?";if(uri.match(re)){return uri.replace(re,"$1"+key+"="+value+"$2")}return uri+separator+key+"="+value}function strongEncodeURIComponent(str){return encodeURIComponent(str).replace(/['()!]/g,window.escape).replace(/\*/g,"%2A")}const touchHandlers={pointerDown:false,currentTouchIdentifier:null};function resetTouchHandlers(){Object.assign(touchHandlers,{pointerDown:false,currentTouchIdentifier:null});}function extractPointerLocation(event){let touchOrEvent;if(touchHandlers.pointerDown){if(touchHandlers.currentTouchIdentifier!=null){const len=event.changedTouches?event.changedTouches.length:0;for(let i=0;i<len;i++){if(event.changedTouches[i].identifier===touchHandlers.currentTouchIdentifier){touchOrEvent=event.changedTouches[i];}}}else {touchOrEvent=event;}const isEndish=event.type==="touchend"||event.type==="touchcancel";if(touchOrEvent&&isEndish){touchHandlers.pointerDown=false;touchHandlers.currentTouchIdentifier=null;}}else {touchHandlers.pointerDown=true;if(event.changedTouches){touchOrEvent=event.changedTouches[0];touchHandlers.currentTouchIdentifier=touchOrEvent.identifier;}else {touchOrEvent=event;}}if(touchOrEvent){return {left:touchOrEvent.pageX,top:touchOrEvent.pageY}}}const supportsPassiveEvents=()=>{try{const opts=Object.defineProperty({},"passive",{get:function(){supportsPassive=true;}});window.addEventListener("testPassive",null,opts);window.removeEventListener("testPassive",null,opts);}catch{}return supportsPassive};function captureScratchpadTouchStart$3(e){e.stopPropagation();}function getImageSize(url,callback){const img=new Image;img.onload=function(){if(img.width===0&&img.height===0){document.body?.appendChild(img);_.defer(function(){callback(img.clientWidth,img.clientHeight);document.body?.removeChild(img);});}else {callback(img.width,img.height);}};img.src=getRealImageUrl(url);}function getWordBeforeCursor(textarea){const text=textarea.value;const endPos=textarea.selectionStart-1;const startPos=Math.max(text.lastIndexOf("\n",endPos),text.lastIndexOf(" ",endPos))+1;return {string:text.substring(startPos,endPos+1),pos:{start:startPos,end:endPos}}}function moveCursor(textarea,pos){textarea.selectionStart=pos;textarea.selectionEnd=pos;}const textarea={getWordBeforeCursor,moveCursor};const unescapeMathMode$1=label=>label.startsWith("$")&&label.endsWith("$")?label.slice(1,-1):label;const Util={inputPathsEqual,nestedMap: nestedMap$2,rWidgetRule,rTypeFromWidgetId,rWidgetParts,snowman,split,firstNumericalParse: firstNumericalParse$1,stringArrayOfSize: stringArrayOfSize$1,gridDimensionConfig,getGridStep,snapStepFromGridStep,scaleFromExtent,tickStepFromExtent,gridStepFromTickStep,tickStepFromNumTicks,constrainedTickStepsFromTickSteps,parseQueryString,updateQueryString: updateQueryString$2,strongEncodeURIComponent,touchHandlers,resetTouchHandlers,extractPointerLocation,supportsPassiveEvents,captureScratchpadTouchStart: captureScratchpadTouchStart$3,getImageSize,getImageSizeModern:getImageSizeModern,getRealImageUrl:getRealImageUrl,isLabeledSVG:isLabeledSVG,getBaseUrl:getBaseUrl,getSvgUrl:getSvgUrl,getDataUrl:getDataUrl,textarea,unescapeMathMode: unescapeMathMode$1};
1462
+ let supportsPassive=false;const nestedMap$2=function(children,func,context){if(Array.isArray(children)){return _.map(children,function(child){return nestedMap$2(child,func)})}return func.call(context,children)};function inputPathsEqual(a,b){if(a==null||b==null){return a==null===(b==null)}return a.length===b.length&&a.every((item,index)=>{return b[index]===item})}const rWidgetRule=/^\[\[\u2603 (([a-z-]+) ([0-9]+))\]\]/;const rTypeFromWidgetId=/^([a-z-]+) ([0-9]+)$/;const rWidgetParts=new RegExp(rWidgetRule.source+"$");const snowman="☃";const split="x".split(/(.)/g).length?function(str,r){return str.split(r)}:function(str,r){const output=[];let lastIndex=r.lastIndex=0;let match;while(match=r.exec(str)){const m=match;output.push(str.slice(lastIndex,m.index));output.push(...m.slice(1));lastIndex=m.index+m[0].length;}output.push(str.slice(lastIndex));return output};function firstNumericalParse$1(text){let first;const val=KhanAnswerTypes.predicate.createValidatorFunctional(function(ans){first=ans;return true},{simplify:"optional",inexact:true,forms:"integer, proper, improper, pi, log, mixed, decimal"});val(text);return first}function stringArrayOfSize$1(size){return Array(size).fill("")}function stringArrayOfSize2D(opt){const{rows,columns}=opt;const rowArr=stringArrayOfSize$1(rows);return rowArr.map(()=>stringArrayOfSize$1(columns))}function gridDimensionConfig(absTickStep,extent,dimensionConstraint,gridStep){const scale=scaleFromExtent(extent,dimensionConstraint);const stepPx=absTickStep*scale;const unityLabel=stepPx>30;return {scale:scale,tickStep:absTickStep/gridStep,unityLabel:unityLabel}}function getGridStep(range,step,boxSize){return _(2).times(function(i){const scale=scaleFromExtent(range[i],boxSize);const gridStep=gridStepFromTickStep(step[i],scale);return gridStep})}function snapStepFromGridStep(gridStep){return [gridStep[0]/2,gridStep[1]/2]}function gridStepFromTickStep(tickStep,scale){const tickWidth=tickStep*scale;const x=tickStep;const y=Math.pow(10,Math.floor(Math.log(x)/Math.LN10));const leadingDigit=Math.floor(x/y);if(tickWidth<25){return tickStep}if(tickWidth<50){if(leadingDigit===5){return tickStep}return tickStep/2}if(leadingDigit===1){return tickStep/2}if(leadingDigit===2){return tickStep/4}if(leadingDigit===5){return tickStep/5}}function scaleFromExtent(extent,dimensionConstraint){const span=extent[1]-extent[0];const scale=dimensionConstraint/span;return scale}function tickStepFromExtent(extent,dimensionConstraint){const span=extent[1]-extent[0];let tickFactor;if(15<span&&span<=20){tickFactor=23;}else if(span>100||span<5){tickFactor=10;}else {tickFactor=16;}const constraintFactor=dimensionConstraint/500;const desiredNumTicks=tickFactor*constraintFactor;return tickStepFromNumTicks(span,desiredNumTicks)}function tickStepFromNumTicks(span,numTicks){let step=Math.pow(10,Math.floor(Math.log(span/numTicks)/Math.LN10));const err=numTicks/span*step;if(err<=.15){step*=10;}else if(err<=.35){step*=5;}else if(err<=.75){step*=2;}return step}const constrainTickStep=(step,range)=>{const span=range[1]-range[0];const numTicks=span/step;if(numTicks<=10){return step}if(numTicks<=20){return step*2}return tickStepFromNumTicks(span,10)};function constrainedTickStepsFromTickSteps(tickSteps,ranges){return [constrainTickStep(tickSteps[0],ranges[0]),constrainTickStep(tickSteps[1],ranges[1])]}function parseQueryString(query){query=query||window.location.search.substring(1);const urlParams={};const a=/\+/g;const r=/([^&=]+)=?([^&]*)/g;const d=function(s){return decodeURIComponent(s.replace(a," "))};let e;while(e=r.exec(query)){const m=e;urlParams[d(m[1])]=d(m[2]);}return urlParams}function updateQueryString$2(uri,key,value){value=encodeURIComponent(value);const re=new RegExp("([?&])"+key+"=.*?(&|$)","i");const separator=uri.indexOf("?")!==-1?"&":"?";if(uri.match(re)){return uri.replace(re,"$1"+key+"="+value+"$2")}return uri+separator+key+"="+value}function strongEncodeURIComponent(str){return encodeURIComponent(str).replace(/['()!]/g,window.escape).replace(/\*/g,"%2A")}const touchHandlers={pointerDown:false,currentTouchIdentifier:null};function resetTouchHandlers(){Object.assign(touchHandlers,{pointerDown:false,currentTouchIdentifier:null});}function extractPointerLocation(event){let touchOrEvent;if(touchHandlers.pointerDown){if(touchHandlers.currentTouchIdentifier!=null){const len=event.changedTouches?event.changedTouches.length:0;for(let i=0;i<len;i++){if(event.changedTouches[i].identifier===touchHandlers.currentTouchIdentifier){touchOrEvent=event.changedTouches[i];}}}else {touchOrEvent=event;}const isEndish=event.type==="touchend"||event.type==="touchcancel";if(touchOrEvent&&isEndish){touchHandlers.pointerDown=false;touchHandlers.currentTouchIdentifier=null;}}else {touchHandlers.pointerDown=true;if(event.changedTouches){touchOrEvent=event.changedTouches[0];touchHandlers.currentTouchIdentifier=touchOrEvent.identifier;}else {touchOrEvent=event;}}if(touchOrEvent){return {left:touchOrEvent.pageX,top:touchOrEvent.pageY}}}const supportsPassiveEvents=()=>{try{const opts=Object.defineProperty({},"passive",{get:function(){supportsPassive=true;}});window.addEventListener("testPassive",null,opts);window.removeEventListener("testPassive",null,opts);}catch{}return supportsPassive};function captureScratchpadTouchStart$4(e){e.stopPropagation();}function getImageSize(url,callback){const img=new Image;img.onload=function(){if(img.width===0&&img.height===0){document.body?.appendChild(img);_.defer(function(){callback(img.clientWidth,img.clientHeight);document.body?.removeChild(img);});}else {callback(img.width,img.height);}};img.src=getRealImageUrl(url);}function getWordBeforeCursor(textarea){const text=textarea.value;const endPos=textarea.selectionStart-1;const startPos=Math.max(text.lastIndexOf("\n",endPos),text.lastIndexOf(" ",endPos))+1;return {string:text.substring(startPos,endPos+1),pos:{start:startPos,end:endPos}}}function moveCursor(textarea,pos){textarea.selectionStart=pos;textarea.selectionEnd=pos;}const textarea={getWordBeforeCursor,moveCursor};const unescapeMathMode$1=label=>label.startsWith("$")&&label.endsWith("$")?label.slice(1,-1):label;const Util={inputPathsEqual,nestedMap: nestedMap$2,rWidgetRule,rTypeFromWidgetId,rWidgetParts,snowman,split,firstNumericalParse: firstNumericalParse$1,stringArrayOfSize: stringArrayOfSize$1,stringArrayOfSize2D,gridDimensionConfig,getGridStep,snapStepFromGridStep,scaleFromExtent,tickStepFromExtent,gridStepFromTickStep,tickStepFromNumTicks,constrainedTickStepsFromTickSteps,parseQueryString,updateQueryString: updateQueryString$2,strongEncodeURIComponent,touchHandlers,resetTouchHandlers,extractPointerLocation,supportsPassiveEvents,captureScratchpadTouchStart: captureScratchpadTouchStart$4,getImageSize,getImageSizeModern:getImageSizeModern,getRealImageUrl:getRealImageUrl,isLabeledSVG:isLabeledSVG,getBaseUrl:getBaseUrl,getSvgUrl:getSvgUrl,getDataUrl:getDataUrl,textarea,unescapeMathMode: unescapeMathMode$1};
1465
1463
 
1466
1464
  const Log={log:(message,extra)=>{getDependencies().Log.log(message,extra);},error:(message,kind,extra)=>{getDependencies().Log.error(message,kind,extra);}};
1467
1465
 
@@ -1518,6 +1516,20 @@ function getKey$2(eventName,id){return eventName+":"+id}function getEventName$2(
1518
1516
 
1519
1517
  let prefixedTransform=null;function computePrefixedTransform(){const el=document.createElement("div");const prefixes=["transform","msTransform","MozTransform","WebkitTransform","OTransform"];let correctPrefix=null;_.each(prefixes,function(prefix){if(typeof el.style[prefix]!=="undefined"){correctPrefix=prefix;}});return correctPrefix}let canUse3dTransform=null;function computeCanUse3dTransform(){const el=document.createElement("div");const prefix=InteractiveUtil.getPrefixedTransform();el.style[prefix]="translateZ(0px)";return !!el.style[prefix]}const FUNCTION_ARRAY_OPTIONS=["add","modify","draw","remove","constraints","onMoveStart","onMove","onMoveEnd","onClick"];const InteractiveUtil={assert:function(isTrue,message){if(!isTrue){throw new PerseusError("Assertion Error"+(message?": "+message:""),Errors.Internal)}},createGettersFor:function(Class,defaults){_.each(_.keys(defaults),function(key){if(Class.prototype[key]===undefined){Class.prototype[key]=function(){return this.state[key]};}});},addMovableHelperMethodsTo:function(Class){_.each(MovableHelperMethods,function(methodFunc,methodName){if(Class.prototype[methodName]===undefined){Class.prototype[methodName]=methodFunc;}});},arrayify:function(funcOrArray){if(funcOrArray==null){return []}if(_.isArray(funcOrArray)){return _.filter(_.flatten(funcOrArray),_.identity)}return [funcOrArray]},normalizeOptions:function(options){const result={...options};FUNCTION_ARRAY_OPTIONS.forEach(function(eventName){if(options[eventName]!==undefined){result[eventName]=InteractiveUtil.arrayify(options[eventName]);}});return result},getPrefixedTransform:function(){prefixedTransform=prefixedTransform||computePrefixedTransform();return prefixedTransform},getCanUse3dTransform:function(){if(canUse3dTransform==null){canUse3dTransform=computeCanUse3dTransform();}return canUse3dTransform}};
1520
1518
 
1519
+ function _class_private_field_loose_base(receiver, privateKey) {
1520
+ if (!Object.prototype.hasOwnProperty.call(receiver, privateKey)) {
1521
+ throw new TypeError("attempted to use private field on non-instance");
1522
+ }
1523
+
1524
+ return receiver;
1525
+ }
1526
+
1527
+ var id = 0;
1528
+
1529
+ function _class_private_field_loose_key(name) {
1530
+ return "__private_" + id++ + "_" + name;
1531
+ }
1532
+
1521
1533
  /*!
1522
1534
  * Raphael 1.5.2 - JavaScript Vector Library
1523
1535
  *
@@ -1571,7 +1583,7 @@ const reactRootCache=new WeakMap;function render(element,container){const childr
1571
1583
 
1572
1584
  function findChildOrAdd(elem,className){const $child=$(elem).find("."+className);if($child.length===0){return $("<span>").addClass(className).appendTo($(elem))}return $child}var Tex$1 = {processMath:async function(elem,text,force,callback){const $elem=$(elem);if($elem.attr("data-math-formula")==null||force){const $texHolder=findChildOrAdd($elem,"tex-holder");if(text==null&&$elem.attr("data-math-formula")){text=$elem.attr("data-math-formula");}text=text!=null?text+"":"";text=KhanMath.cleanMath(text);$elem.attr("data-math-formula",text);const{TeX}=await getDependencies();render(React.createElement(TeX,{children:text,onRender:callback}),$texHolder[0]);}}};
1573
1585
 
1574
- const{processMath: processMath$1}=Tex$1;function polar$2(r,th){if(typeof r==="number"){r=[r,r];}th=th*Math.PI/180;return [r[0]*Math.cos(th),r[1]*Math.sin(th)]}var _bounds=/*#__PURE__*/_$2("_bounds"),_drawingTransform=/*#__PURE__*/_$2("_drawingTransform");let Graphie$1 = class Graphie{init(options){let scale=options.scale||[40,40];scale=typeof scale==="number"?[scale,scale]:scale;if(options.range==null){throw new PerseusError("range should be specified in graph init",Errors.Internal)}_$1(this,_bounds)[_bounds]=new GraphBounds(...options.range);_$1(this,_drawingTransform)[_drawingTransform]=new DrawingTransform(this.raphael,scale,this.bounds());const[w,h]=this.drawingTransform().canvasDimensions();$(this.el).css({width:w,height:h});this.range=options.range;this.scale=scale;this.dimensions=[w,h];this.xpixels=w;this.ypixels=h;this.isMobile=options.isMobile??false;return this}graphInit(options){options=options||{};for(const[prop,val]of entries(options)){if(!prop.match(/.*Opacity$/)&&prop!=="range"&&typeof val==="number"){options[prop]=[val,val];}if(prop==="range"||prop==="gridRange"){options[prop]=normalizeRange(options[prop]);}}const range=normalizeRange(options.range||[[-10,10],[-10,10]]);const gridRange=normalizeRange(options.gridRange||range);const scale=options.scale||[20,20];const grid=options.grid!=null?options.grid:true;const gridOpacity=options.gridOpacity||.1;const gridStep=toPair(options.gridStep||[1,1]);const axes=options.axes!=null?options.axes:true;const axisArrows=options.axisArrows||"";const axisOpacity=options.axisOpacity||1;const axisCenter=options.axisCenter||[Math.min(Math.max(range[0][0],0),range[0][1]),Math.min(Math.max(range[1][0],0),range[1][1])];const axisLabels=options.axisLabels!=null?options.axisLabels:false;const ticks=options.ticks!=null?options.ticks:true;const tickStep=options.tickStep||[2,2];const tickLen=options.tickLen||[5,5];const tickOpacity=options.tickOpacity||1;const labels=options.labels||options.labelStep||false;const labelStep=options.labelStep||[1,1];const labelOpacity=options.labelOpacity||1;let unityLabels=options.unityLabels||false;const labelFormat=options.labelFormat||function(a){return a};let xLabelFormat=options.xLabelFormat||labelFormat;let yLabelFormat=options.yLabelFormat||labelFormat;const realRange=[[range[0][0]-(range[0][0]>0?1:0),range[0][1]+(range[0][1]<0?1:0)],[range[1][0]-(range[1][0]>0?1:0),range[1][1]+(range[1][1]<0?1:0)]];if(!Array.isArray(unityLabels)){unityLabels=[unityLabels,unityLabels];}const minusIgnorer=function(lf){return function(a){return (lf(a)+"").replace(/-(\d)/g,"\\llap{-}$1")}};xLabelFormat=minusIgnorer(xLabelFormat);yLabelFormat=minusIgnorer(yLabelFormat);this.init({range:realRange,scale:scale,isMobile:options.isMobile});if(grid){this.grid(gridRange[0],gridRange[1],{stroke:options.isMobile?KhanColors.GRAY_C:"#000000",opacity:options.isMobile?1:gridOpacity,step:gridStep,strokeWidth:options.isMobile?1:2});}if(axes){if(axisArrows==="<->"||axisArrows===true){const thisGraphie=this;this.style({stroke:options.isMobile?KhanColors.GRAY_G:"#000000",opacity:options.isMobile?1:axisOpacity,strokeWidth:options.isMobile?1:2,arrows:"->"},function(){if(range[1][0]<0&&range[1][1]>0){thisGraphie.path([axisCenter,[gridRange[0][0],axisCenter[1]]]);thisGraphie.path([axisCenter,[gridRange[0][1],axisCenter[1]]]);}if(range[0][0]<0&&range[0][1]>0){thisGraphie.path([axisCenter,[axisCenter[0],gridRange[1][0]]]);thisGraphie.path([axisCenter,[axisCenter[0],gridRange[1][1]]]);}});}else if(axisArrows==="->"||axisArrows===""){const thisGraphie=this;this.style({stroke:"#000000",opacity:axisOpacity,strokeWidth:2,arrows:axisArrows},function(){thisGraphie.path([[gridRange[0][0],axisCenter[1]],[gridRange[0][1],axisCenter[1]]]);thisGraphie.path([[axisCenter[0],gridRange[1][0]],[axisCenter[0],gridRange[1][1]]]);});}if(axisLabels&&axisLabels.length===2){this.label([gridRange[0][1],axisCenter[1]],axisLabels[0],"right");this.label([axisCenter[0],gridRange[1][1]],axisLabels[1],"above");}}if(ticks){const halfWidthTicks=options.isMobile;const thisGraphie=this;this.style({stroke:options.isMobile?KhanColors.GRAY_G:"#000000",opacity:options.isMobile?1:tickOpacity,strokeWidth:1},()=>{let step=gridStep[0]*tickStep[0];let len=tickLen[0]/scale[1];let start=gridRange[0][0];let stop=gridRange[0][1];if(range[1][0]<0&&range[1][1]>0){for(let x=step+axisCenter[0];x<=stop;x+=step){if(x<stop||!axisArrows){thisGraphie.line([x,-len+axisCenter[1]],[x,halfWidthTicks?0:len+axisCenter[1]]);}}for(let x=-step+axisCenter[0];x>=start;x-=step){if(x>start||!axisArrows){thisGraphie.line([x,-len+axisCenter[1]],[x,halfWidthTicks?0:len+axisCenter[1]]);}}}step=gridStep[1]*tickStep[1];len=tickLen[1]/scale[0];start=gridRange[1][0];stop=gridRange[1][1];if(range[0][0]<0&&range[0][1]>0){for(let y=step+axisCenter[1];y<=stop;y+=step){if(y<stop||!axisArrows){this.line([-len+axisCenter[0],y],[halfWidthTicks?0:len+axisCenter[0],y]);}}for(let y=-step+axisCenter[1];y>=start;y-=step){if(y>start||!axisArrows){this.line([-len+axisCenter[0],y],[halfWidthTicks?0:len+axisCenter[0],y]);}}}});}if(labels){const thisGraphie=this;this.style({stroke:options.isMobile?KhanColors.GRAY_G:"#000000",opacity:options.isMobile?1:labelOpacity},function(){let step=gridStep[0]*tickStep[0]*labelStep[0];let start=gridRange[0][0];let stop=gridRange[0][1];const xAxisPosition=axisCenter[0]<0?"above":"below";const yAxisPosition=axisCenter[0]<0?"right":"left";const xShowZero=axisCenter[0]===0&&axisCenter[1]!==0;const yShowZero=axisCenter[0]!==0&&axisCenter[1]===0;const axisOffCenter=axisCenter[0]!==0||axisCenter[1]!==0;const showUnityX=unityLabels[0]||axisOffCenter;const showUnityY=unityLabels[1]||axisOffCenter;for(let x=(xShowZero?0:step)+axisCenter[0];x<=stop;x+=step){if(x<stop||!axisArrows){thisGraphie.label([x,axisCenter[1]],xLabelFormat(x),xAxisPosition);}}for(let x=-step*(showUnityX?1:2)+axisCenter[0];x>=start;x-=step){if(x>start||!axisArrows){thisGraphie.label([x,axisCenter[1]],xLabelFormat(x),xAxisPosition);}}step=gridStep[1]*tickStep[1]*labelStep[1];start=gridRange[1][0];stop=gridRange[1][1];for(let y=(yShowZero?0:step)+axisCenter[1];y<=stop;y+=step){if(y<stop||!axisArrows){thisGraphie.label([axisCenter[0],y],yLabelFormat(y),yAxisPosition);}}for(let y=-step*(showUnityY?1:2)+axisCenter[1];y>=start;y-=step){if(y>start||!axisArrows){thisGraphie.label([axisCenter[0],y],yLabelFormat(y),yAxisPosition);}}});}}drawingTransform(){if(_$1(this,_drawingTransform)[_drawingTransform]==null){throw new Error("Can't get drawingTransform of an uninitialized Graphie")}return _$1(this,_drawingTransform)[_drawingTransform]}bounds(){if(_$1(this,_bounds)[_bounds]==null){throw new Error("Can't get bounds of an uninitialized Graphie")}return _$1(this,_bounds)[_bounds]}style(attrs,fn){const processed=this.processAttributes(attrs);if(typeof fn==="function"){const oldStyle=this.currentStyle;this.currentStyle={...this.currentStyle,...processed};const result=fn.call(this);this.currentStyle=oldStyle;return result}Object.assign(this.currentStyle,processed);}grid(xr,yr,style){return this.withStyle(style,()=>{const step=this.currentStyle.step||[1,1];const set=this.raphael.set();let x=step[0]*Math.ceil(xr[0]/step[0]);for(;x<=xr[1];x+=step[0]){set.push(this.line([x,yr[0]],[x,yr[1]]));}let y=step[1]*Math.ceil(yr[0]/step[1]);for(;y<=yr[1];y+=step[1]){set.push(this.line([xr[0],y],[xr[1],y]));}return set})}arc(center,radius,startAngle,endAngle,sector,style){return this.withStyle(style,()=>{startAngle=(startAngle%360+360)%360;endAngle=(endAngle%360+360)%360;const cent=this.scalePoint(center);const radii=this.scaleVector(radius);const startVector=polar$2(radius,startAngle);const endVector=polar$2(radius,endAngle);const round=x=>number.round(x,6);const startPoint=this.scalePoint([round(center[0]+startVector[0]),round(center[1]+startVector[1])]);const endPoint=this.scalePoint([round(center[0]+endVector[0]),round(center[1]+endVector[1])]);const largeAngle=((endAngle-startAngle)%360+360)%360>180;return this.raphael.path("M"+startPoint.join(" ")+"A"+radii.join(" ")+" 0 "+(largeAngle?1:0)+" 0 "+endPoint.join(" ")+(sector?"L"+cent.join(" ")+"z":""))})}circle(center,radius,style){return this.withStyle(style,()=>this.raphael.ellipse(...this.scalePoint(center),...this.scaleVector([radius,radius])))}rect(x,y,width,height,style){return this.withStyle(style,()=>{const corner=this.scalePoint([x,y+height]);const dims=this.scaleVector([width,height]);const elem=this.raphael.rect(...corner.concat(dims));if(this.isMobile){elem.node.style.shapeRendering="crispEdges";}return elem})}ellipse(center,radii,style){return this.withStyle(style,()=>this.raphael.ellipse(...this.scalePoint(center).concat(this.scaleVector(radii))))}fixedEllipse(center,radii,maxScale,padding,style){return this.withStyle(style,()=>{const scaledPoint=this.scalePoint(center);const scaledRadii=this.scaleVector(radii);const width=2*scaledRadii[0]*maxScale+padding;const height=2*scaledRadii[1]*maxScale+padding;const left=scaledPoint[0]-width/2;const top=scaledPoint[1]-height/2;const wrapper=document.createElement("div");$(wrapper).css({position:"absolute",width:width+"px",height:height+"px",left:left+"px",top:top+"px"});const localRaphael=Raphael$1(wrapper,width,height);const visibleShape=localRaphael.ellipse(width/2,height/2,scaledRadii[0],scaledRadii[1]);return {wrapper:wrapper,visibleShape:visibleShape}})}unstyledPath(points){const p=this.raphael.path(this.svgPath(points));p.graphiePath=points;return p}path(points,style){return this.withStyle(style,()=>{return this.unstyledPath(points)})}fixedPath(points,center,createPath){points=points.map(this.scalePoint);center=center?this.scalePoint(center):null;createPath=createPath||this.svgPath;const xs=points.map(p=>p[0]);const ys=points.map(p=>p[1]);const pathLeft=Math.min(...xs);const pathRight=Math.max(...xs);const pathTop=Math.min(...ys);const pathBottom=Math.max(...ys);const padding=[4,4];const topLeftOfBoundingBox=[pathLeft,pathTop];points=points.map(function(point){return vector$3.add(vector$3.subtract(point,topLeftOfBoundingBox),vector$3.scale(padding,.5))});const width=pathRight-pathLeft+padding[0];const height=pathBottom-pathTop+padding[1];const left=topLeftOfBoundingBox[0]-padding[0]/2;const top=topLeftOfBoundingBox[1]-padding[1]/2;const wrapper=document.createElement("div");$(wrapper).css({position:"absolute",width:width+"px",height:height+"px",left:left+"px",top:top+"px",transformOrigin:center?width/2+center[0]+"px "+(height/2+center[1])+"px":null});const localRaphael=Raphael$1(wrapper,width,height);const visibleShape=localRaphael.path(createPath(points));return {wrapper:wrapper,visibleShape:visibleShape}}scaledPath(points,style){return this.withStyle(style,()=>{const p=this.raphael.path(this.svgPath(points,true));p.graphiePath=points;return p})}line(start,end,style){return this.withStyle(style,()=>{const l=this.unstyledPath([start,end]);if(this.isMobile){l.node.style.shapeRendering="crispEdges";}return l})}parabola(a,b,c,style){return this.withStyle(style,()=>this.raphael.path(this.svgParabolaPath(a,b,c)))}fixedLine(start,end,thickness){const padding=[thickness,thickness];start=this.scalePoint(start);end=this.scalePoint(end);const extraOffset=[Math.min(start[0],end[0]),Math.min(start[1],end[1])];start=vector$3.add(vector$3.subtract(start,extraOffset),vector$3.scale(padding,.5));end=vector$3.add(vector$3.subtract(end,extraOffset),vector$3.scale(padding,.5));const left=extraOffset[0]-padding[0]/2;const top=extraOffset[1]-padding[1]/2;const width=Math.abs(start[0]-end[0])+padding[0];const height=Math.abs(start[1]-end[1])+padding[1];const wrapper=document.createElement("div");$(wrapper).css({position:"absolute",width:width+"px",height:height+"px",left:left+"px",top:top+"px",transformOrigin:start[0]+"px "+start[1]+"px"});const localRaphael=Raphael$1(wrapper,width,height);const path="M"+start[0]+" "+start[1]+" "+"L"+end[0]+" "+end[1];const visibleShape=localRaphael.path(path);visibleShape.graphiePath=[start,end];return {wrapper:wrapper,visibleShape:visibleShape}}sinusoid(a,b,c,d,style){return this.withStyle(style,()=>this.raphael.path(this.svgSinusoidPath(a,b,c,d)))}plotParametric(fn,range,style){return this.withStyle(style,()=>{const clip=xy=>{if(Math.abs(xy[1])>5e5){return [xy[0],Math.min(Math.max(xy[1],-5e5),5e5)]}return xy};const clippedFn=x=>clip(fn(x));const min=range[0];const max=range[1];let step=(max-min)/(this.currentStyle["plot-points"]||800);if(step===0){step=1;}const paths=this.raphael.set();let points=[];let lastY=clippedFn(min)[1];for(let t=min;t<=max;t+=step){const point=clippedFn(t);const y=point[1];if(y>0!==lastY>0&&Math.abs(y-lastY)>2*this.drawingTransform().pixelsPerUnitY()||isNaN(y)){paths.push(this.unstyledPath(points));points=[];}else {points.push(point);}lastY=y;}paths.push(this.unstyledPath(points));return paths})}plot(fn,range,style){return this.withStyle(style,()=>{const min=range[0];const max=range[1];if(!this.currentStyle["plot-points"]){this.currentStyle["plot-points"]=2*(max-min)*this.drawingTransform().pixelsPerUnitX();}const parametricFn=x=>[x,fn(x)];return this.plotParametric(parametricFn,range)})}withStyle(style,fn){const oldStyle=this.currentStyle;this.currentStyle={...this.currentStyle,...this.processAttributes(style)};const result=this.postprocessDrawingResult(fn());this.currentStyle=oldStyle;return result}postprocessDrawingResult(result){const type=result.constructor.prototype;if(type===Raphael$1.el||type===Raphael$1.st){result.attr(this.currentStyle);if(this.currentStyle.arrows){result=this.addArrowheads(result);}}else if(result instanceof $){result.css({...this.currentStyle,...SVG_SPECIFIC_STYLE_MASK});}return result}addArrowheads(path){const type=path.constructor.prototype;if(type===Raphael$1.el){if(path.type==="path"&&typeof path.arrowheadsDrawn==="undefined"){const w=path.attr("stroke-width");const s=.6+.4*w;const l=path.getTotalLength();const set=this.raphael.set();const head=this.raphael.path(this.isMobile?"M-4,4 C-4,4 -0.25,0 -0.25,0 C-0.25,0 -4,-4 -4,-4":"M-3 4 C-2.75 2.5 0 0.25 0.75 0C0 -0.25 -2.75 -2.5 -3 -4");const end=path.getPointAtLength(l-.4);const almostTheEnd=path.getPointAtLength(l-.75*s);const angle=Math.atan2(end.y-almostTheEnd.y,end.x-almostTheEnd.x)*180/Math.PI;const attrs=path.attr();delete attrs.path;let subpath=path.getSubpath(0,l-.75*s);subpath=this.raphael.path(subpath).attr(attrs);subpath.arrowheadsDrawn=true;path.remove();head.rotate(angle,this.isMobile?1e-5:.75,0).scale(s,s,.75,0).translate(almostTheEnd.x,almostTheEnd.y).attr(attrs).attr({"stroke-linejoin":"round","stroke-linecap":"round"});head.arrowheadsDrawn=true;set.push(subpath);set.push(head);return set}}else if(type===Raphael$1.st){for(let i=0,l=path.items.length;i<l;i++){this.addArrowheads(path.items[i]);}}return path}processAttributes(attrs){const transformers={scale:scale=>{this.drawingTransform().setScale(scale);},clipRect:pair=>{const point=pair[0];const size=pair[1];point[1]+=size[1];return {"clip-rect":this.scalePoint(point).concat(this.scaleVector(size)).join(" ")}},strokeWidth:function(val){return {"stroke-width":parseFloat(val)}},rx:val=>{return {rx:this.scaleVector([val,0])[0]}},ry:val=>{return {ry:this.scaleVector([0,val])[1]}},r:val=>{const scaled=this.scaleVector([val,val]);return {rx:scaled[0],ry:scaled[1]}}};const processed={};Object.entries(attrs||{}).forEach(function([key,value]){const transformer=transformers[key];if(typeof transformer==="function"){Object.assign(processed,transformer(value));}else {const dasherized=String(key).replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").replace(/([a-z\d])([A-Z])/g,"$1-$2").toLowerCase();processed[dasherized]=value;}});return processed}addMouseLayer(options){const localOptions={allowScratchpad:false,setDrawingAreaAvailable:function(){},...options};const mouselayerZIndex=2;this.mouselayer=Raphael$1(this.el,this.xpixels,this.ypixels);$(this.mouselayer.canvas).css("z-index",mouselayerZIndex);if(localOptions.onClick||localOptions.onMouseDown||localOptions.onMouseMove||localOptions.onMouseOver||localOptions.onMouseOut){const canvasClickTarget=this.mouselayer.rect(0,0,this.xpixels,this.ypixels).attr({fill:"#000",opacity:0});let isClickingCanvas=false;$(this.mouselayer.canvas).on("vmousedown",e=>{if(e.target===canvasClickTarget[0]){if(localOptions.onMouseDown){localOptions.onMouseDown(this.getMouseCoord(e));}isClickingCanvas=true;if(localOptions.onMouseMove){const handler=localOptions.onMouseMove;$(document).bind("vmousemove.mouseLayer",e=>{if(isClickingCanvas){e.preventDefault();handler(this.getMouseCoord(e));}});}$(document).bind("vmouseup.mouseLayer",e=>{$(document).unbind(".mouseLayer");if(isClickingCanvas&&localOptions.onClick){localOptions.onClick(this.getMouseCoord(e));}isClickingCanvas=false;});}});if(localOptions.onMouseOver){const handler=localOptions.onMouseOver;$(this.mouselayer.canvas).on("vmouseover",e=>{handler(this.getMouseCoord(e));});}if(localOptions.onMouseOut){const handler=localOptions.onMouseOut;$(this.mouselayer.canvas).on("vmouseout",e=>{handler(this.getMouseCoord(e));});}}if(!localOptions.allowScratchpad){localOptions.setDrawingAreaAvailable?.(false);}this._mouselayerWrapper=document.createElement("div");$(this._mouselayerWrapper).css({position:"absolute",left:0,top:0,zIndex:mouselayerZIndex});this._visiblelayerWrapper=document.createElement("div");$(this._visiblelayerWrapper).css({position:"absolute",left:0,top:0});const el=this.el;el.appendChild(this._visiblelayerWrapper);el.appendChild(this._mouselayerWrapper);this.addToMouseLayerWrapper=el=>{this._mouselayerWrapper?.appendChild(el);};this.addToVisibleLayerWrapper=el=>{this._visiblelayerWrapper?.appendChild(el);};}addToMouseLayerWrapper(el){throw new Error("addToMouseLayerWrapper is not ready. Call addMouseLayer() first.")}addToVisibleLayerWrapper(el){throw new Error("addToVisibleLayerWrapper is not ready. Call addMouseLayer() first.")}getMousePx(event){const offset=$(this.el).offset();const mouseX=event.pageX-offset.left;const mouseY=event.pageY-offset.top;return [mouseX,mouseY]}getMouseCoord(event){return this.unscalePoint(this.getMousePx(event))}constructor(el){Object.defineProperty(this,_bounds,{writable:true,value:void 0});Object.defineProperty(this,_drawingTransform,{writable:true,value:void 0});this.isMobile=false;this.currentStyle={"stroke-width":2,fill:"none"};this.label=(point,text,direction,arg4,arg5)=>{const style=typeof arg4==="object"?arg4:arg5;const latex=typeof arg4==="boolean"?arg4:true;return this.withStyle(style,()=>{const $span=$("<span>").addClass("graphie-label");const pad=this.currentStyle["label-distance"];$span.css({position:"absolute",padding:(pad!=null?pad:7)+"px",color:"black"}).data("labelDirection",direction).appendTo(this.el);$span.setPosition=point=>{const scaledPoint=this.scalePoint(point);$span.css({left:scaledPoint[0],top:scaledPoint[1]});};$span.setPosition(point);const span=$span[0];$span.processMath=function(math,force){processMath$1(span,math,force,function(){const width=span.scrollWidth;const height=span.scrollHeight;setLabelMargins(span,[width,height]);});};$span.processText=function(text){$span.html(text);const width=span.scrollWidth;const height=span.scrollHeight;setLabelMargins(span,[width,height]);};if(latex){$span.processMath(text,false);}else {$span.processText(text);}return $span})};this.svgPath=(points,alreadyScaled)=>{return points.map((point,i)=>{if(point===true){return "z"}const scaled=alreadyScaled?point:this.scalePoint(point);return (i===0?"M":"L")+KhanMath.bound(scaled[0])+" "+KhanMath.bound(scaled[1])}).join("")};this.svgParabolaPath=(a,b,c)=>{const computeParabola=function(x){return (a*x+b)*x+c};if(a===0){const points=[[this.bounds().xMin,computeParabola(this.bounds().xMin)],[this.bounds().xMax,computeParabola(this.bounds().xMax)]];return this.svgPath(points)}const xVertex=-b/(2*a);const distToEdge=Math.max(Math.abs(xVertex-this.bounds().xMin),Math.abs(xVertex-this.bounds().xMax));const xPoint=xVertex+distToEdge;const vertex=[xVertex,computeParabola(xVertex)];const point=[xPoint,computeParabola(xPoint)];const control=[vertex[0],vertex[1]-(point[1]-vertex[1])];const dx=Math.abs(vertex[0]-point[0]);const left=[vertex[0]-dx,point[1]];const right=[vertex[0]+dx,point[1]];const points=[left,control,right].map(this.scalePoint);const values=points.flat().map(KhanMath.bound);return "M"+values[0]+","+values[1]+" Q"+values[2]+","+values[3]+" "+values[4]+","+values[5]};this.svgSinusoidPath=(a,b,c,d)=>{const quarterPeriod=Math.abs(Math.PI/(2*b));const computeSine=function(x){return a*Math.sin(b*x-c)+d};const computeDerivative=function(x){return a*b*Math.cos(c-b*x)};const coordsForOffset=(initial,i)=>{const x0=initial+quarterPeriod*i;const x1=x0+quarterPeriod;const xCoords=[x0,x0*2/3+x1*1/3,x0*1/3+x1*2/3,x1];const yCoords=[computeSine(x0),computeSine(x0)+computeDerivative(x0)*(x1-x0)/3,computeSine(x1)-computeDerivative(x1)*(x1-x0)/3,computeSine(x1)];const points=vector$3.zip(xCoords,yCoords);return points.map(this.scalePoint)};const extent=this.bounds().width();const numQuarterPeriods=Math.ceil(extent/quarterPeriod)+1;let initial=c/b;const distToEdge=initial-this.bounds().xMin;initial-=quarterPeriod*Math.ceil(distToEdge/quarterPeriod);let coords=coordsForOffset(initial,0);let path="M"+coords[0][0]+","+coords[0][1]+" C"+coords[1][0]+","+coords[1][1]+" "+coords[2][0]+","+coords[2][1]+" "+coords[3][0]+","+coords[3][1];for(let i=1;i<numQuarterPeriods;i++){coords=coordsForOffset(initial,i);path+=" C"+coords[1][0]+","+coords[1][1]+" "+coords[2][0]+","+coords[2][1]+" "+coords[3][0]+","+coords[3][1];}return path};this.scalePoint=point=>{return this.drawingTransform().scalePoint(point)};this.scaleVector=point=>{return this.drawingTransform().scaleVector(point)};this.unscalePoint=point=>{return this.drawingTransform().unscalePoint(point)};this.unscaleVector=point=>{return this.drawingTransform().unscaleVector(point)};this.el=el;$(el).css("position","relative");this.raphael=Raphael$1(el);$(el).attr("aria-hidden","true");$(el).children("div").css("position","absolute");}};const labelDirections={center:[-0.5,-0.5],above:[-0.5,-1],"above right":[0,-1],right:[0,-0.5],"below right":[0,0],below:[-0.5,0],"below left":[-1,0],left:[-1,-0.5],"above left":[-1,-1]};function normalizeRange(range){function normalizeInterval(magnitude){if(typeof magnitude==="number"){return [-magnitude,magnitude]}else {return magnitude}}function getXAndYRanges(range){if(Array.isArray(range)){return range}else {return [range,range]}}if(range==null){return range}const[xRange,yRange]=getXAndYRanges(range);return [normalizeInterval(xRange),normalizeInterval(yRange)]}function toPair(x){if(Array.isArray(x)){return x}return [x,x]}const SVG_SPECIFIC_STYLE_MASK={"stroke-width":null};const setLabelMargins=function(span,size){const $span=$(span);const direction=$span.data("labelDirection");let[width,height]=size;if(width===0&&height===0){[width,height]=[1,1];Log.log("Label size was 0x0 in graphie.js; using 1x1 instead");}$span.css("visibility","");if(typeof direction==="number"){const x=Math.cos(direction);const y=Math.sin(direction);const scale=Math.min(width/2/Math.abs(x),height/2/Math.abs(y));$span.css({marginLeft:-width/2+x*scale,marginTop:-height/2-y*scale});}else {const currentHeightMatchesProps=span.scrollHeight===height;const $svgImage=$span.closest(".svg-image");const $graphie=$span.closest(".graphie");const $container=$svgImage.length>0?$svgImage:$graphie;$container.css("line-height","normal");if(currentHeightMatchesProps&&span.scrollHeight!==height){height=span.scrollHeight;}const widthValues=$container.css(["max-width","width"])??{"max-width":"0px"};const expectedWidth=widthValues["max-width"]!=="none"?widthValues["max-width"]:widthValues["width"];let scale=($container.width()??0)/parseInt(expectedWidth.replace(/px$/,""))*100;if(isNaN(scale)){scale=100;}else if(scale===0){scale=100;}const padding=$span.css("padding")??"0px";const currentPadding=padding!=="none"?padding:"0px";const newPadding=Math.round(parseInt(currentPadding.replace(/px$/,""))*scale)/100;const multipliers=labelDirections[direction||"center"];const styling={marginLeft:Math.round(width*multipliers[0]*scale)/100,marginTop:Math.round(height*multipliers[1]*scale)/100,padding:`${newPadding}px`};if(scale!==1){styling["fontSize"]=`${Math.round(scale*100)/100}%`;}$span.css(styling);}};const GraphUtils={Graphie: Graphie$1,createGraphie:function(el){return new Graphie$1(el)},unscaledSvgPath:function(points){if(points[0]===true){return ""}return points.map(function(point,i){if(point===true){return "z"}return (i===0?"M":"L")+point[0]+" "+point[1]}).join("")},getDistance:function(point1,point2){return point.distanceToPoint(point1,point2)},findAngleDeprecated:function(point1,point2,vertex){if(vertex===undefined){const x=point1[0]-point2[0];const y=point1[1]-point2[1];if(!x&&!y){return 0}return (180+Math.atan2(-y,-x)*180/Math.PI+360)%360}return GraphUtils.findAngleDeprecated(point1,vertex)-GraphUtils.findAngleDeprecated(point2,vertex)},graphs:{}};
1586
+ const{processMath: processMath$1}=Tex$1;function polar$2(r,th){if(typeof r==="number"){r=[r,r];}th=th*Math.PI/180;return [r[0]*Math.cos(th),r[1]*Math.sin(th)]}var _bounds=/*#__PURE__*/_class_private_field_loose_key("_bounds"),_drawingTransform=/*#__PURE__*/_class_private_field_loose_key("_drawingTransform");let Graphie$1 = class Graphie{init(options){let scale=options.scale||[40,40];scale=typeof scale==="number"?[scale,scale]:scale;if(options.range==null){throw new PerseusError("range should be specified in graph init",Errors.Internal)}_class_private_field_loose_base(this,_bounds)[_bounds]=new GraphBounds(...options.range);_class_private_field_loose_base(this,_drawingTransform)[_drawingTransform]=new DrawingTransform(this.raphael,scale,this.bounds());const[w,h]=this.drawingTransform().canvasDimensions();$(this.el).css({width:w,height:h});this.range=options.range;this.scale=scale;this.dimensions=[w,h];this.xpixels=w;this.ypixels=h;this.isMobile=options.isMobile??false;return this}graphInit(options){options=options||{};for(const[prop,val]of entries(options)){if(!prop.match(/.*Opacity$/)&&prop!=="range"&&typeof val==="number"){options[prop]=[val,val];}if(prop==="range"||prop==="gridRange"){options[prop]=normalizeRange(options[prop]);}}const range=normalizeRange(options.range||[[-10,10],[-10,10]]);const gridRange=normalizeRange(options.gridRange||range);const scale=options.scale||[20,20];const grid=options.grid!=null?options.grid:true;const gridOpacity=options.gridOpacity||.1;const gridStep=toPair(options.gridStep||[1,1]);const axes=options.axes!=null?options.axes:true;const axisArrows=options.axisArrows||"";const axisOpacity=options.axisOpacity||1;const axisCenter=options.axisCenter||[Math.min(Math.max(range[0][0],0),range[0][1]),Math.min(Math.max(range[1][0],0),range[1][1])];const axisLabels=options.axisLabels!=null?options.axisLabels:false;const ticks=options.ticks!=null?options.ticks:true;const tickStep=options.tickStep||[2,2];const tickLen=options.tickLen||[5,5];const tickOpacity=options.tickOpacity||1;const labels=options.labels||options.labelStep||false;const labelStep=options.labelStep||[1,1];const labelOpacity=options.labelOpacity||1;let unityLabels=options.unityLabels||false;const labelFormat=options.labelFormat||function(a){return a};let xLabelFormat=options.xLabelFormat||labelFormat;let yLabelFormat=options.yLabelFormat||labelFormat;const realRange=[[range[0][0]-(range[0][0]>0?1:0),range[0][1]+(range[0][1]<0?1:0)],[range[1][0]-(range[1][0]>0?1:0),range[1][1]+(range[1][1]<0?1:0)]];if(!Array.isArray(unityLabels)){unityLabels=[unityLabels,unityLabels];}const minusIgnorer=function(lf){return function(a){return (lf(a)+"").replace(/-(\d)/g,"\\llap{-}$1")}};xLabelFormat=minusIgnorer(xLabelFormat);yLabelFormat=minusIgnorer(yLabelFormat);this.init({range:realRange,scale:scale,isMobile:options.isMobile});if(grid){this.grid(gridRange[0],gridRange[1],{stroke:options.isMobile?KhanColors.GRAY_C:"#000000",opacity:options.isMobile?1:gridOpacity,step:gridStep,strokeWidth:options.isMobile?1:2});}if(axes){if(axisArrows==="<->"||axisArrows===true){const thisGraphie=this;this.style({stroke:options.isMobile?KhanColors.GRAY_G:"#000000",opacity:options.isMobile?1:axisOpacity,strokeWidth:options.isMobile?1:2,arrows:"->"},function(){if(range[1][0]<0&&range[1][1]>0){thisGraphie.path([axisCenter,[gridRange[0][0],axisCenter[1]]]);thisGraphie.path([axisCenter,[gridRange[0][1],axisCenter[1]]]);}if(range[0][0]<0&&range[0][1]>0){thisGraphie.path([axisCenter,[axisCenter[0],gridRange[1][0]]]);thisGraphie.path([axisCenter,[axisCenter[0],gridRange[1][1]]]);}});}else if(axisArrows==="->"||axisArrows===""){const thisGraphie=this;this.style({stroke:"#000000",opacity:axisOpacity,strokeWidth:2,arrows:axisArrows},function(){thisGraphie.path([[gridRange[0][0],axisCenter[1]],[gridRange[0][1],axisCenter[1]]]);thisGraphie.path([[axisCenter[0],gridRange[1][0]],[axisCenter[0],gridRange[1][1]]]);});}if(axisLabels&&axisLabels.length===2){this.label([gridRange[0][1],axisCenter[1]],axisLabels[0],"right");this.label([axisCenter[0],gridRange[1][1]],axisLabels[1],"above");}}if(ticks){const halfWidthTicks=options.isMobile;const thisGraphie=this;this.style({stroke:options.isMobile?KhanColors.GRAY_G:"#000000",opacity:options.isMobile?1:tickOpacity,strokeWidth:1},()=>{let step=gridStep[0]*tickStep[0];let len=tickLen[0]/scale[1];let start=gridRange[0][0];let stop=gridRange[0][1];if(range[1][0]<0&&range[1][1]>0){for(let x=step+axisCenter[0];x<=stop;x+=step){if(x<stop||!axisArrows){thisGraphie.line([x,-len+axisCenter[1]],[x,halfWidthTicks?0:len+axisCenter[1]]);}}for(let x=-step+axisCenter[0];x>=start;x-=step){if(x>start||!axisArrows){thisGraphie.line([x,-len+axisCenter[1]],[x,halfWidthTicks?0:len+axisCenter[1]]);}}}step=gridStep[1]*tickStep[1];len=tickLen[1]/scale[0];start=gridRange[1][0];stop=gridRange[1][1];if(range[0][0]<0&&range[0][1]>0){for(let y=step+axisCenter[1];y<=stop;y+=step){if(y<stop||!axisArrows){this.line([-len+axisCenter[0],y],[halfWidthTicks?0:len+axisCenter[0],y]);}}for(let y=-step+axisCenter[1];y>=start;y-=step){if(y>start||!axisArrows){this.line([-len+axisCenter[0],y],[halfWidthTicks?0:len+axisCenter[0],y]);}}}});}if(labels){const thisGraphie=this;this.style({stroke:options.isMobile?KhanColors.GRAY_G:"#000000",opacity:options.isMobile?1:labelOpacity},function(){let step=gridStep[0]*tickStep[0]*labelStep[0];let start=gridRange[0][0];let stop=gridRange[0][1];const xAxisPosition=axisCenter[0]<0?"above":"below";const yAxisPosition=axisCenter[0]<0?"right":"left";const xShowZero=axisCenter[0]===0&&axisCenter[1]!==0;const yShowZero=axisCenter[0]!==0&&axisCenter[1]===0;const axisOffCenter=axisCenter[0]!==0||axisCenter[1]!==0;const showUnityX=unityLabels[0]||axisOffCenter;const showUnityY=unityLabels[1]||axisOffCenter;for(let x=(xShowZero?0:step)+axisCenter[0];x<=stop;x+=step){if(x<stop||!axisArrows){thisGraphie.label([x,axisCenter[1]],xLabelFormat(x),xAxisPosition);}}for(let x=-step*(showUnityX?1:2)+axisCenter[0];x>=start;x-=step){if(x>start||!axisArrows){thisGraphie.label([x,axisCenter[1]],xLabelFormat(x),xAxisPosition);}}step=gridStep[1]*tickStep[1]*labelStep[1];start=gridRange[1][0];stop=gridRange[1][1];for(let y=(yShowZero?0:step)+axisCenter[1];y<=stop;y+=step){if(y<stop||!axisArrows){thisGraphie.label([axisCenter[0],y],yLabelFormat(y),yAxisPosition);}}for(let y=-step*(showUnityY?1:2)+axisCenter[1];y>=start;y-=step){if(y>start||!axisArrows){thisGraphie.label([axisCenter[0],y],yLabelFormat(y),yAxisPosition);}}});}}drawingTransform(){if(_class_private_field_loose_base(this,_drawingTransform)[_drawingTransform]==null){throw new Error("Can't get drawingTransform of an uninitialized Graphie")}return _class_private_field_loose_base(this,_drawingTransform)[_drawingTransform]}bounds(){if(_class_private_field_loose_base(this,_bounds)[_bounds]==null){throw new Error("Can't get bounds of an uninitialized Graphie")}return _class_private_field_loose_base(this,_bounds)[_bounds]}style(attrs,fn){const processed=this.processAttributes(attrs);if(typeof fn==="function"){const oldStyle=this.currentStyle;this.currentStyle={...this.currentStyle,...processed};const result=fn.call(this);this.currentStyle=oldStyle;return result}Object.assign(this.currentStyle,processed);}grid(xr,yr,style){return this.withStyle(style,()=>{const step=this.currentStyle.step||[1,1];const set=this.raphael.set();let x=step[0]*Math.ceil(xr[0]/step[0]);for(;x<=xr[1];x+=step[0]){set.push(this.line([x,yr[0]],[x,yr[1]]));}let y=step[1]*Math.ceil(yr[0]/step[1]);for(;y<=yr[1];y+=step[1]){set.push(this.line([xr[0],y],[xr[1],y]));}return set})}arc(center,radius,startAngle,endAngle,sector,style){return this.withStyle(style,()=>{startAngle=(startAngle%360+360)%360;endAngle=(endAngle%360+360)%360;const cent=this.scalePoint(center);const radii=this.scaleVector(radius);const startVector=polar$2(radius,startAngle);const endVector=polar$2(radius,endAngle);const round=x=>number.round(x,6);const startPoint=this.scalePoint([round(center[0]+startVector[0]),round(center[1]+startVector[1])]);const endPoint=this.scalePoint([round(center[0]+endVector[0]),round(center[1]+endVector[1])]);const largeAngle=((endAngle-startAngle)%360+360)%360>180;return this.raphael.path("M"+startPoint.join(" ")+"A"+radii.join(" ")+" 0 "+(largeAngle?1:0)+" 0 "+endPoint.join(" ")+(sector?"L"+cent.join(" ")+"z":""))})}circle(center,radius,style){return this.withStyle(style,()=>this.raphael.ellipse(...this.scalePoint(center),...this.scaleVector([radius,radius])))}rect(x,y,width,height,style){return this.withStyle(style,()=>{const corner=this.scalePoint([x,y+height]);const dims=this.scaleVector([width,height]);const elem=this.raphael.rect(...corner.concat(dims));if(this.isMobile){elem.node.style.shapeRendering="crispEdges";}return elem})}ellipse(center,radii,style){return this.withStyle(style,()=>this.raphael.ellipse(...this.scalePoint(center).concat(this.scaleVector(radii))))}fixedEllipse(center,radii,maxScale,padding,style){return this.withStyle(style,()=>{const scaledPoint=this.scalePoint(center);const scaledRadii=this.scaleVector(radii);const width=2*scaledRadii[0]*maxScale+padding;const height=2*scaledRadii[1]*maxScale+padding;const left=scaledPoint[0]-width/2;const top=scaledPoint[1]-height/2;const wrapper=document.createElement("div");$(wrapper).css({position:"absolute",width:width+"px",height:height+"px",left:left+"px",top:top+"px"});const localRaphael=Raphael$1(wrapper,width,height);const visibleShape=localRaphael.ellipse(width/2,height/2,scaledRadii[0],scaledRadii[1]);return {wrapper:wrapper,visibleShape:visibleShape}})}unstyledPath(points){const p=this.raphael.path(this.svgPath(points));p.graphiePath=points;return p}path(points,style){return this.withStyle(style,()=>{return this.unstyledPath(points)})}fixedPath(points,center,createPath){points=points.map(this.scalePoint);center=center?this.scalePoint(center):null;createPath=createPath||this.svgPath;const xs=points.map(p=>p[0]);const ys=points.map(p=>p[1]);const pathLeft=Math.min(...xs);const pathRight=Math.max(...xs);const pathTop=Math.min(...ys);const pathBottom=Math.max(...ys);const padding=[4,4];const topLeftOfBoundingBox=[pathLeft,pathTop];points=points.map(function(point){return vector$3.add(vector$3.subtract(point,topLeftOfBoundingBox),vector$3.scale(padding,.5))});const width=pathRight-pathLeft+padding[0];const height=pathBottom-pathTop+padding[1];const left=topLeftOfBoundingBox[0]-padding[0]/2;const top=topLeftOfBoundingBox[1]-padding[1]/2;const wrapper=document.createElement("div");$(wrapper).css({position:"absolute",width:width+"px",height:height+"px",left:left+"px",top:top+"px",transformOrigin:center?width/2+center[0]+"px "+(height/2+center[1])+"px":null});const localRaphael=Raphael$1(wrapper,width,height);const visibleShape=localRaphael.path(createPath(points));return {wrapper:wrapper,visibleShape:visibleShape}}scaledPath(points,style){return this.withStyle(style,()=>{const p=this.raphael.path(this.svgPath(points,true));p.graphiePath=points;return p})}line(start,end,style){return this.withStyle(style,()=>{const l=this.unstyledPath([start,end]);if(this.isMobile){l.node.style.shapeRendering="crispEdges";}return l})}parabola(a,b,c,style){return this.withStyle(style,()=>this.raphael.path(this.svgParabolaPath(a,b,c)))}fixedLine(start,end,thickness){const padding=[thickness,thickness];start=this.scalePoint(start);end=this.scalePoint(end);const extraOffset=[Math.min(start[0],end[0]),Math.min(start[1],end[1])];start=vector$3.add(vector$3.subtract(start,extraOffset),vector$3.scale(padding,.5));end=vector$3.add(vector$3.subtract(end,extraOffset),vector$3.scale(padding,.5));const left=extraOffset[0]-padding[0]/2;const top=extraOffset[1]-padding[1]/2;const width=Math.abs(start[0]-end[0])+padding[0];const height=Math.abs(start[1]-end[1])+padding[1];const wrapper=document.createElement("div");$(wrapper).css({position:"absolute",width:width+"px",height:height+"px",left:left+"px",top:top+"px",transformOrigin:start[0]+"px "+start[1]+"px"});const localRaphael=Raphael$1(wrapper,width,height);const path="M"+start[0]+" "+start[1]+" "+"L"+end[0]+" "+end[1];const visibleShape=localRaphael.path(path);visibleShape.graphiePath=[start,end];return {wrapper:wrapper,visibleShape:visibleShape}}sinusoid(a,b,c,d,style){return this.withStyle(style,()=>this.raphael.path(this.svgSinusoidPath(a,b,c,d)))}plotParametric(fn,range,style){return this.withStyle(style,()=>{const clip=xy=>{if(Math.abs(xy[1])>5e5){return [xy[0],Math.min(Math.max(xy[1],-5e5),5e5)]}return xy};const clippedFn=x=>clip(fn(x));const min=range[0];const max=range[1];let step=(max-min)/(this.currentStyle["plot-points"]||800);if(step===0){step=1;}const paths=this.raphael.set();let points=[];let lastY=clippedFn(min)[1];for(let t=min;t<=max;t+=step){const point=clippedFn(t);const y=point[1];if(y>0!==lastY>0&&Math.abs(y-lastY)>2*this.drawingTransform().pixelsPerUnitY()||isNaN(y)){paths.push(this.unstyledPath(points));points=[];}else {points.push(point);}lastY=y;}paths.push(this.unstyledPath(points));return paths})}plot(fn,range,style){return this.withStyle(style,()=>{const min=range[0];const max=range[1];if(!this.currentStyle["plot-points"]){this.currentStyle["plot-points"]=2*(max-min)*this.drawingTransform().pixelsPerUnitX();}const parametricFn=x=>[x,fn(x)];return this.plotParametric(parametricFn,range)})}withStyle(style,fn){const oldStyle=this.currentStyle;this.currentStyle={...this.currentStyle,...this.processAttributes(style)};const result=this.postprocessDrawingResult(fn());this.currentStyle=oldStyle;return result}postprocessDrawingResult(result){const type=result.constructor.prototype;if(type===Raphael$1.el||type===Raphael$1.st){result.attr(this.currentStyle);if(this.currentStyle.arrows){result=this.addArrowheads(result);}}else if(result instanceof $){result.css({...this.currentStyle,...SVG_SPECIFIC_STYLE_MASK});}return result}addArrowheads(path){const type=path.constructor.prototype;if(type===Raphael$1.el){if(path.type==="path"&&typeof path.arrowheadsDrawn==="undefined"){const w=path.attr("stroke-width");const s=.6+.4*w;const l=path.getTotalLength();const set=this.raphael.set();const head=this.raphael.path(this.isMobile?"M-4,4 C-4,4 -0.25,0 -0.25,0 C-0.25,0 -4,-4 -4,-4":"M-3 4 C-2.75 2.5 0 0.25 0.75 0C0 -0.25 -2.75 -2.5 -3 -4");const end=path.getPointAtLength(l-.4);const almostTheEnd=path.getPointAtLength(l-.75*s);const angle=Math.atan2(end.y-almostTheEnd.y,end.x-almostTheEnd.x)*180/Math.PI;const attrs=path.attr();delete attrs.path;let subpath=path.getSubpath(0,l-.75*s);subpath=this.raphael.path(subpath).attr(attrs);subpath.arrowheadsDrawn=true;path.remove();head.rotate(angle,this.isMobile?1e-5:.75,0).scale(s,s,.75,0).translate(almostTheEnd.x,almostTheEnd.y).attr(attrs).attr({"stroke-linejoin":"round","stroke-linecap":"round"});head.arrowheadsDrawn=true;set.push(subpath);set.push(head);return set}}else if(type===Raphael$1.st){for(let i=0,l=path.items.length;i<l;i++){this.addArrowheads(path.items[i]);}}return path}processAttributes(attrs){const transformers={scale:scale=>{this.drawingTransform().setScale(scale);},clipRect:pair=>{const point=pair[0];const size=pair[1];point[1]+=size[1];return {"clip-rect":this.scalePoint(point).concat(this.scaleVector(size)).join(" ")}},strokeWidth:function(val){return {"stroke-width":parseFloat(val)}},rx:val=>{return {rx:this.scaleVector([val,0])[0]}},ry:val=>{return {ry:this.scaleVector([0,val])[1]}},r:val=>{const scaled=this.scaleVector([val,val]);return {rx:scaled[0],ry:scaled[1]}}};const processed={};Object.entries(attrs||{}).forEach(function([key,value]){const transformer=transformers[key];if(typeof transformer==="function"){Object.assign(processed,transformer(value));}else {const dasherized=String(key).replace(/([A-Z]+)([A-Z][a-z])/g,"$1-$2").replace(/([a-z\d])([A-Z])/g,"$1-$2").toLowerCase();processed[dasherized]=value;}});return processed}addMouseLayer(options){const localOptions={allowScratchpad:false,setDrawingAreaAvailable:function(){},...options};const mouselayerZIndex=2;this.mouselayer=Raphael$1(this.el,this.xpixels,this.ypixels);$(this.mouselayer.canvas).css("z-index",mouselayerZIndex);if(localOptions.onClick||localOptions.onMouseDown||localOptions.onMouseMove||localOptions.onMouseOver||localOptions.onMouseOut){const canvasClickTarget=this.mouselayer.rect(0,0,this.xpixels,this.ypixels).attr({fill:"#000",opacity:0});let isClickingCanvas=false;$(this.mouselayer.canvas).on("vmousedown",e=>{if(e.target===canvasClickTarget[0]){if(localOptions.onMouseDown){localOptions.onMouseDown(this.getMouseCoord(e));}isClickingCanvas=true;if(localOptions.onMouseMove){const handler=localOptions.onMouseMove;$(document).bind("vmousemove.mouseLayer",e=>{if(isClickingCanvas){e.preventDefault();handler(this.getMouseCoord(e));}});}$(document).bind("vmouseup.mouseLayer",e=>{$(document).unbind(".mouseLayer");if(isClickingCanvas&&localOptions.onClick){localOptions.onClick(this.getMouseCoord(e));}isClickingCanvas=false;});}});if(localOptions.onMouseOver){const handler=localOptions.onMouseOver;$(this.mouselayer.canvas).on("vmouseover",e=>{handler(this.getMouseCoord(e));});}if(localOptions.onMouseOut){const handler=localOptions.onMouseOut;$(this.mouselayer.canvas).on("vmouseout",e=>{handler(this.getMouseCoord(e));});}}if(!localOptions.allowScratchpad){localOptions.setDrawingAreaAvailable?.(false);}this._mouselayerWrapper=document.createElement("div");$(this._mouselayerWrapper).css({position:"absolute",left:0,top:0,zIndex:mouselayerZIndex});this._visiblelayerWrapper=document.createElement("div");$(this._visiblelayerWrapper).css({position:"absolute",left:0,top:0});const el=this.el;el.appendChild(this._visiblelayerWrapper);el.appendChild(this._mouselayerWrapper);this.addToMouseLayerWrapper=el=>{this._mouselayerWrapper?.appendChild(el);};this.addToVisibleLayerWrapper=el=>{this._visiblelayerWrapper?.appendChild(el);};}addToMouseLayerWrapper(el){throw new Error("addToMouseLayerWrapper is not ready. Call addMouseLayer() first.")}addToVisibleLayerWrapper(el){throw new Error("addToVisibleLayerWrapper is not ready. Call addMouseLayer() first.")}getMousePx(event){const offset=$(this.el).offset();const mouseX=event.pageX-offset.left;const mouseY=event.pageY-offset.top;return [mouseX,mouseY]}getMouseCoord(event){return this.unscalePoint(this.getMousePx(event))}constructor(el){Object.defineProperty(this,_bounds,{writable:true,value:void 0});Object.defineProperty(this,_drawingTransform,{writable:true,value:void 0});this.isMobile=false;this.currentStyle={"stroke-width":2,fill:"none"};this.label=(point,text,direction,arg4,arg5)=>{const style=typeof arg4==="object"?arg4:arg5;const latex=typeof arg4==="boolean"?arg4:true;return this.withStyle(style,()=>{const $span=$("<span>").addClass("graphie-label");const pad=this.currentStyle["label-distance"];$span.css({position:"absolute",padding:(pad!=null?pad:7)+"px",color:"black"}).data("labelDirection",direction).appendTo(this.el);$span.setPosition=point=>{const scaledPoint=this.scalePoint(point);$span.css({left:scaledPoint[0],top:scaledPoint[1]});};$span.setPosition(point);const span=$span[0];$span.processMath=function(math,force){processMath$1(span,math,force,function(){const width=span.scrollWidth;const height=span.scrollHeight;setLabelMargins(span,[width,height]);});};$span.processText=function(text){$span.html(text);const width=span.scrollWidth;const height=span.scrollHeight;setLabelMargins(span,[width,height]);};if(latex){$span.processMath(text,false);}else {$span.processText(text);}return $span})};this.svgPath=(points,alreadyScaled)=>{return points.map((point,i)=>{if(point===true){return "z"}const scaled=alreadyScaled?point:this.scalePoint(point);return (i===0?"M":"L")+KhanMath.bound(scaled[0])+" "+KhanMath.bound(scaled[1])}).join("")};this.svgParabolaPath=(a,b,c)=>{const computeParabola=function(x){return (a*x+b)*x+c};if(a===0){const points=[[this.bounds().xMin,computeParabola(this.bounds().xMin)],[this.bounds().xMax,computeParabola(this.bounds().xMax)]];return this.svgPath(points)}const xVertex=-b/(2*a);const distToEdge=Math.max(Math.abs(xVertex-this.bounds().xMin),Math.abs(xVertex-this.bounds().xMax));const xPoint=xVertex+distToEdge;const vertex=[xVertex,computeParabola(xVertex)];const point=[xPoint,computeParabola(xPoint)];const control=[vertex[0],vertex[1]-(point[1]-vertex[1])];const dx=Math.abs(vertex[0]-point[0]);const left=[vertex[0]-dx,point[1]];const right=[vertex[0]+dx,point[1]];const points=[left,control,right].map(this.scalePoint);const values=points.flat().map(KhanMath.bound);return "M"+values[0]+","+values[1]+" Q"+values[2]+","+values[3]+" "+values[4]+","+values[5]};this.svgSinusoidPath=(a,b,c,d)=>{const quarterPeriod=Math.abs(Math.PI/(2*b));const computeSine=function(x){return a*Math.sin(b*x-c)+d};const computeDerivative=function(x){return a*b*Math.cos(c-b*x)};const coordsForOffset=(initial,i)=>{const x0=initial+quarterPeriod*i;const x1=x0+quarterPeriod;const xCoords=[x0,x0*2/3+x1*1/3,x0*1/3+x1*2/3,x1];const yCoords=[computeSine(x0),computeSine(x0)+computeDerivative(x0)*(x1-x0)/3,computeSine(x1)-computeDerivative(x1)*(x1-x0)/3,computeSine(x1)];const points=vector$3.zip(xCoords,yCoords);return points.map(this.scalePoint)};const extent=this.bounds().width();const numQuarterPeriods=Math.ceil(extent/quarterPeriod)+1;let initial=c/b;const distToEdge=initial-this.bounds().xMin;initial-=quarterPeriod*Math.ceil(distToEdge/quarterPeriod);let coords=coordsForOffset(initial,0);let path="M"+coords[0][0]+","+coords[0][1]+" C"+coords[1][0]+","+coords[1][1]+" "+coords[2][0]+","+coords[2][1]+" "+coords[3][0]+","+coords[3][1];for(let i=1;i<numQuarterPeriods;i++){coords=coordsForOffset(initial,i);path+=" C"+coords[1][0]+","+coords[1][1]+" "+coords[2][0]+","+coords[2][1]+" "+coords[3][0]+","+coords[3][1];}return path};this.scalePoint=point=>{return this.drawingTransform().scalePoint(point)};this.scaleVector=point=>{return this.drawingTransform().scaleVector(point)};this.unscalePoint=point=>{return this.drawingTransform().unscalePoint(point)};this.unscaleVector=point=>{return this.drawingTransform().unscaleVector(point)};this.el=el;$(el).css("position","relative");this.raphael=Raphael$1(el);$(el).attr("aria-hidden","true");$(el).children("div").css("position","absolute");}};const labelDirections={center:[-0.5,-0.5],above:[-0.5,-1],"above right":[0,-1],right:[0,-0.5],"below right":[0,0],below:[-0.5,0],"below left":[-1,0],left:[-1,-0.5],"above left":[-1,-1]};function normalizeRange(range){function normalizeInterval(magnitude){if(typeof magnitude==="number"){return [-magnitude,magnitude]}else {return magnitude}}function getXAndYRanges(range){if(Array.isArray(range)){return range}else {return [range,range]}}if(range==null){return range}const[xRange,yRange]=getXAndYRanges(range);return [normalizeInterval(xRange),normalizeInterval(yRange)]}function toPair(x){if(Array.isArray(x)){return x}return [x,x]}const SVG_SPECIFIC_STYLE_MASK={"stroke-width":null};const setLabelMargins=function(span,size){const $span=$(span);const direction=$span.data("labelDirection");let[width,height]=size;if(width===0&&height===0){[width,height]=[1,1];Log.log("Label size was 0x0 in graphie.js; using 1x1 instead");}$span.css("visibility","");if(typeof direction==="number"){const x=Math.cos(direction);const y=Math.sin(direction);const scale=Math.min(width/2/Math.abs(x),height/2/Math.abs(y));$span.css({marginLeft:-width/2+x*scale,marginTop:-height/2-y*scale});}else {const currentHeightMatchesProps=span.scrollHeight===height;const $svgImage=$span.closest(".svg-image");const $graphie=$span.closest(".graphie");const $container=$svgImage.length>0?$svgImage:$graphie;$container.css("line-height","normal");if(currentHeightMatchesProps&&span.scrollHeight!==height){height=span.scrollHeight;}const widthValues=$container.css(["max-width","width"])??{"max-width":"0px"};const expectedWidth=widthValues["max-width"]!=="none"?widthValues["max-width"]:widthValues["width"];let scale=($container.width()??0)/parseInt(expectedWidth.replace(/px$/,""))*100;if(isNaN(scale)){scale=100;}else if(scale===0){scale=100;}const padding=$span.css("padding")??"0px";const currentPadding=padding!=="none"?padding:"0px";const newPadding=Math.round(parseInt(currentPadding.replace(/px$/,""))*scale)/100;const multipliers=labelDirections[direction||"center"];const styling={marginLeft:Math.round(width*multipliers[0]*scale)/100,marginTop:Math.round(height*multipliers[1]*scale)/100,padding:`${newPadding}px`};if(scale!==1){styling["fontSize"]=`${Math.round(scale*100)/100}%`;}$span.css(styling);}};const GraphUtils={Graphie: Graphie$1,createGraphie:function(el){return new Graphie$1(el)},unscaledSvgPath:function(points){if(points[0]===true){return ""}return points.map(function(point,i){if(point===true){return "z"}return (i===0?"M":"L")+point[0]+" "+point[1]}).join("")},getDistance:function(point1,point2){return point.distanceToPoint(point1,point2)},findAngleDeprecated:function(point1,point2,vertex){if(vertex===undefined){const x=point1[0]-point2[0];const y=point1[1]-point2[1];if(!x&&!y){return 0}return (180+Math.atan2(-y,-x)*180/Math.PI+360)%360}return GraphUtils.findAngleDeprecated(point1,vertex)-GraphUtils.findAngleDeprecated(point2,vertex)},graphs:{}};
1575
1587
 
1576
1588
  (function($,window1,document1,undefined$1){if(typeof $==="undefined"){return}var dataPropertyName="virtualMouseBindings",touchTargetPropertyName="virtualTouchID",virtualEventNames="vmouseover vmousedown vmousemove vmouseup vclick vmouseout vmousecancel".split(" "),touchEventProps="clientX clientY pageX pageY screenX screenY".split(" "),mouseHookProps=$.event.mouseHooks?$.event.mouseHooks.props:[],mouseEventProps=$.event.props.concat(mouseHookProps),activeDocHandlers={},resetTimerID=0,startX=0,startY=0,didScroll=false,clickBlockList=[],blockMouseTriggers=false,blockTouchTriggers=false,eventCaptureSupported="addEventListener"in document1,$document=$(document1),nextTouchID=1,lastTouchID=0;$.vmouse={moveDistanceThreshold:10,clickDistanceThreshold:10,resetTimerDuration:1500};function getNativeEvent(event){while(event&&typeof event.originalEvent!=="undefined"){event=event.originalEvent;}return event}function createVirtualEvent(event,eventType){var t=event.type,oe,props,ne,prop,ct,touch,i,j,len;event=$.Event(event);event.type=eventType;oe=event.originalEvent;props=$.event.props;if(t.search(/mouse/)>-1){props=mouseEventProps;}if(oe){for(i=props.length,prop;i;){prop=props[--i];event[prop]=oe[prop];}}if(t.search(/mouse(down|up)|click/)>-1&&!event.which){event.which=1;}if(t.search(/^touch/)!==-1){ne=getNativeEvent(oe);t=ne.touches;ct=ne.changedTouches;touch=t&&t.length?t[0]:ct&&ct.length?ct[0]:undefined$1;if(touch){for(j=0,len=touchEventProps.length;j<len;j++){prop=touchEventProps[j];event[prop]=touch[prop];}}}return event}function getVirtualBindingFlags(element){var flags={},b,k;while(element){b=$.data(element,dataPropertyName);for(k in b){if(b[k]){flags[k]=flags.hasVirtualBinding=true;}}element=element.parentNode;}return flags}function getClosestElementWithVirtualBinding(element,eventType){var b;while(element){b=$.data(element,dataPropertyName);if(b&&(!eventType||b[eventType])){return element}element=element.parentNode;}return null}function enableTouchBindings(){blockTouchTriggers=false;}function disableTouchBindings(){blockTouchTriggers=true;}function enableMouseBindings(){lastTouchID=0;clickBlockList.length=0;blockMouseTriggers=false;disableTouchBindings();}function disableMouseBindings(){enableTouchBindings();}function startResetTimer(){clearResetTimer();resetTimerID=setTimeout(function(){resetTimerID=0;enableMouseBindings();},$.vmouse.resetTimerDuration);}function clearResetTimer(){if(resetTimerID){clearTimeout(resetTimerID);resetTimerID=0;}}function triggerVirtualEvent(eventType,event,flags){var ve;if(flags&&flags[eventType]||!flags&&getClosestElementWithVirtualBinding(event.target,eventType)){ve=createVirtualEvent(event,eventType);$(event.target).trigger(ve);}return ve}function mouseEventCallback(event){var touchID=$.data(event.target,touchTargetPropertyName);if(!blockMouseTriggers&&(!lastTouchID||lastTouchID!==touchID)){var ve=triggerVirtualEvent("v"+event.type,event);if(ve){if(ve.isDefaultPrevented()){event.preventDefault();}if(ve.isPropagationStopped()){event.stopPropagation();}if(ve.isImmediatePropagationStopped()){event.stopImmediatePropagation();}}}}function handleTouchStart(event){var touches=getNativeEvent(event).touches,target,flags;if(touches&&touches.length===1){target=event.target;flags=getVirtualBindingFlags(target);if(flags.hasVirtualBinding){lastTouchID=nextTouchID++;$.data(target,touchTargetPropertyName,lastTouchID);clearResetTimer();disableMouseBindings();didScroll=false;var t=getNativeEvent(event).touches[0];startX=t.pageX;startY=t.pageY;triggerVirtualEvent("vmouseover",event,flags);triggerVirtualEvent("vmousedown",event,flags);}}}function handleScroll(event){if(blockTouchTriggers){return}if(!didScroll){triggerVirtualEvent("vmousecancel",event,getVirtualBindingFlags(event.target));}didScroll=true;startResetTimer();}function handleTouchMove(event){if(blockTouchTriggers){return}var t=getNativeEvent(event).touches[0],didCancel=didScroll,moveThreshold=$.vmouse.moveDistanceThreshold,didScroll=didScroll||Math.abs(t.pageX-startX)>moveThreshold||Math.abs(t.pageY-startY)>moveThreshold,flags=getVirtualBindingFlags(event.target);if(didScroll&&!didCancel){triggerVirtualEvent("vmousecancel",event,flags);}triggerVirtualEvent("vmousemove",event,flags);startResetTimer();}function handleTouchEnd(event){if(blockTouchTriggers){return}disableTouchBindings();var flags=getVirtualBindingFlags(event.target),t;triggerVirtualEvent("vmouseup",event,flags);if(!didScroll){var ve=triggerVirtualEvent("vclick",event,flags);if(ve&&ve.isDefaultPrevented()){t=getNativeEvent(event).changedTouches[0];clickBlockList.push({touchID:lastTouchID,x:t.clientX,y:t.clientY});blockMouseTriggers=true;}}triggerVirtualEvent("vmouseout",event,flags);didScroll=false;startResetTimer();}function hasVirtualBindings(ele){var bindings=$.data(ele,dataPropertyName),k;if(bindings){for(k in bindings){if(bindings[k]){return true}}}return false}function dummyMouseHandler(){}function getSpecialEventObject(eventType){var realType=eventType.substr(1);return {setup:function(data,namespace){if(!hasVirtualBindings(this)){$.data(this,dataPropertyName,{});}var bindings=$.data(this,dataPropertyName);bindings[eventType]=true;activeDocHandlers[eventType]=(activeDocHandlers[eventType]||0)+1;if(activeDocHandlers[eventType]===1){$document.bind(realType,mouseEventCallback);}$(this).bind(realType,dummyMouseHandler);if(eventCaptureSupported){activeDocHandlers["touchstart"]=(activeDocHandlers["touchstart"]||0)+1;if(activeDocHandlers["touchstart"]===1){$document.bind("touchstart",handleTouchStart).bind("touchend",handleTouchEnd).bind("touchmove",handleTouchMove).bind("scroll",handleScroll);}}},teardown:function(data,namespace){--activeDocHandlers[eventType];if(!activeDocHandlers[eventType]){$document.unbind(realType,mouseEventCallback);}if(eventCaptureSupported){--activeDocHandlers["touchstart"];if(!activeDocHandlers["touchstart"]){$document.unbind("touchstart",handleTouchStart).unbind("touchmove",handleTouchMove).unbind("touchend",handleTouchEnd).unbind("scroll",handleScroll);}}var $this=$(this),bindings=$.data(this,dataPropertyName);if(bindings){bindings[eventType]=false;}$this.unbind(realType,dummyMouseHandler);if(!hasVirtualBindings(this)){$this.removeData(dataPropertyName);}}}}for(var i=0;i<virtualEventNames.length;i++){$.event.special[virtualEventNames[i]]=getSpecialEventObject(virtualEventNames[i]);}if(eventCaptureSupported){document1.addEventListener("click",function(e){var cnt=clickBlockList.length,target=e.target,x,y,ele,i,o;if(cnt){x=e.clientX;y=e.clientY;threshold=$.vmouse.clickDistanceThreshold;ele=target;while(ele){for(i=0;i<cnt;i++){o=clickBlockList[i];if(ele===target&&Math.abs(o.x-x)<threshold&&Math.abs(o.y-y)<threshold||$.data(ele,touchTargetPropertyName)===o.touchID){e.preventDefault();e.stopPropagation();return}}ele=ele.parentNode;}}},true);}})($,window,document);
1577
1589
 
@@ -1633,7 +1645,7 @@ function _noop(){}class InteractionTracker{constructor(trackApi,widgetType,widge
1633
1645
 
1634
1646
  const arrayRules={fence:{match:SimpleMarkdown.defaultRules.fence.match,order:1,parse:(capture,state,parse)=>({type:"codeBlock",lang:capture[2]||undefined,content:capture[3]})},paragraph:{match:SimpleMarkdown.defaultRules.paragraph.match,order:2,parse:(capture,state,parse)=>({content:capture[1]})}};const builtArrayParser=SimpleMarkdown.parserFor(arrayRules);const parseToArray=source=>{const paragraphedSource=source.replace(/^\n\s*\n/,"")+"\n\n";return builtArrayParser(paragraphedSource,{inline:false}).map(c=>{return c["content"]})};const joinFromArray=paragraphs=>paragraphs.join("\n\n");var JiptParagraphs = {parseToArray:parseToArray,joinFromArray:joinFromArray};
1635
1647
 
1636
- const exclamationIcon={path:"M6 11a1 1 0 1 1 0-2 1 1 0 0 1 0 2zm0-9a1 1 0 0 1 1 1v4a1 1 0 1 1-2 0V3a1 1 0 0 1 1-1z",height:12,width:12};class Lint extends React.Component{componentDidMount(){this._positionTimeout=window.setTimeout(this.getPosition);}componentWillUnmount(){window.clearTimeout(this._positionTimeout);}render(){const{children,inline,blockHighlight,insideTable}=this.props;if(insideTable){if(inline){return jsxRuntimeExports.jsx("span",{"data-lint-inside-table":"true",children:children})}return jsxRuntimeExports.jsx("div",{"data-lint-inside-table":"true",children:children})}if(blockHighlight){return jsxRuntimeExports.jsxs("span",{className:css(styles$B.lintContainer,styles$B.lintContainerBlock),children:[this.renderLink(styles$B.radioWidgetHoverTarget),jsxRuntimeExports.jsx("span",{children:children})]})}if(inline){return jsxRuntimeExports.jsxs("span",{className:css(styles$B.lintContainer),children:[this.renderLink(styles$B.inlineHoverTarget),jsxRuntimeExports.jsx("span",{children:children})]})}return jsxRuntimeExports.jsxs("div",{className:css(styles$B.lintContainer),children:[this.renderLink(styles$B.hoverTarget),jsxRuntimeExports.jsx("div",{children:children})]})}constructor(...args){super(...args),this.state={tooltipAbove:true},this.getPosition=()=>{const rect=ReactDOM__default.findDOMNode(this).getBoundingClientRect();this.setState({tooltipAbove:rect.top>100});},this.renderLink=style=>{const tooltipAbove=this.state.tooltipAbove;let severityStyle;let warningText;let warningTextStyle;if(this.props.severity===1){severityStyle=styles$B.indicatorError;warningText="Error";warningTextStyle=styles$B.publishBlockingError;}else if(this.props.severity===2){severityStyle=styles$B.indicatorWarning;warningText="Warning";warningTextStyle=styles$B.warning;}else {severityStyle=styles$B.indicatorGuideline;warningText="Recommendation";warningTextStyle=styles$B.warning;}return jsxRuntimeExports.jsxs("a",{href:`https://khanacademy.org/r/linter-rules#${this.props.ruleName}`,target:"lint-help-window",className:css(style),children:[jsxRuntimeExports.jsx("span",{className:css(styles$B.indicator,severityStyle),children:this.props.severity===1&&jsxRuntimeExports.jsx(InlineIcon,{...exclamationIcon})}),jsxRuntimeExports.jsxs("div",{className:css(styles$B.tooltip,tooltipAbove&&styles$B.tooltipAbove),children:[this.props.message.split("\n\n").map((m,i)=>jsxRuntimeExports.jsxs("p",{className:css(styles$B.tooltipParagraph),children:[jsxRuntimeExports.jsxs("span",{className:css(warningTextStyle),children:[warningText,":"," "]}),m]},i)),jsxRuntimeExports.jsx("div",{className:css(styles$B.tail,tooltipAbove&&styles$B.tailAbove)})]})]})};}}const styles$B=StyleSheet.create({lintContainer:{position:"relative"},lintContainerBlock:{display:"block"},hoverTarget:{position:"absolute",top:0,right:-40,display:"block",width:24,height:24,":hover > span":{backgroundColor:warningColorHover},":hover div":{display:"block"},":hover ~ div":{outline:"1px solid "+warningColor},":hover ~ div div[data-lint-inside-table]":{outline:"1px solid "+warningColor},":hover ~ div span[data-lint-inside-table]":{backgroundColor:warningColor,color:white}},inlineHoverTarget:{float:"right",position:"relative",marginRight:-40,display:"block",width:24,height:24,":hover > span":{backgroundColor:warningColorHover},":hover div":{display:"block"},":hover ~ span":{backgroundColor:warningColor,color:white}},radioWidgetHoverTarget:{position:"absolute",left:-40,display:"block",width:24,height:24,minWidth:264,":hover > span":{backgroundColor:warningColorHover},":hover > div":{display:"block",padding:8,width:280},":hover > div > div":{left:8},":hover ~ span":{backgroundColor:warningColor,color:white}},indicator:{alignItems:"center",borderRadius:4,color:"white",display:"flex",fontSize:12,height:8,justifyContent:"center",margin:8,width:8},indicatorError:{backgroundColor:"#be2612",borderRadius:8,height:16,width:16},indicatorWarning:{backgroundColor:"#f86700"},indicatorGuideline:{backgroundColor:"#ffbe26"},tooltip:{position:"absolute",right:-12,display:"none",zIndex:1e3,color:white,backgroundColor:gray17,opacity:.9,fontFamily:baseFontFamily,fontSize:"12px",lineHeight:"15px",width:"320px",borderRadius:"4px"},tooltipAbove:{bottom:32},tail:{position:"absolute",top:-12,right:16,width:0,height:0,borderLeft:"8px solid transparent",borderRight:"8px solid transparent",borderBottom:"12px solid "+gray17},tailAbove:{bottom:-12,borderBottom:"none",borderTop:"12px solid "+gray17,top:"auto"},tooltipParagraph:{margin:12},warning:{color:warningColor,fontFamily:boldFontFamily},publishBlockingError:{color:publishBlockingErrorColor}});
1648
+ const exclamationIcon={path:"M6 11a1 1 0 1 1 0-2 1 1 0 0 1 0 2zm0-9a1 1 0 0 1 1 1v4a1 1 0 1 1-2 0V3a1 1 0 0 1 1-1z",height:12,width:12};class Lint extends React.Component{componentDidMount(){this._positionTimeout=window.setTimeout(this.getPosition);}componentWillUnmount(){window.clearTimeout(this._positionTimeout);}render(){const{children,inline,blockHighlight,insideTable}=this.props;if(insideTable){if(inline){return jsxRuntimeExports.jsx("span",{"data-lint-inside-table":"true",children:children})}return jsxRuntimeExports.jsx("div",{"data-lint-inside-table":"true",children:children})}if(blockHighlight){return jsxRuntimeExports.jsxs("span",{className:css(styles$F.lintContainer,styles$F.lintContainerBlock),children:[this.renderLink(styles$F.radioWidgetHoverTarget),jsxRuntimeExports.jsx("span",{children:children})]})}if(inline){return jsxRuntimeExports.jsxs("span",{className:css(styles$F.lintContainer),children:[this.renderLink(styles$F.inlineHoverTarget),jsxRuntimeExports.jsx("span",{children:children})]})}return jsxRuntimeExports.jsxs("div",{className:css(styles$F.lintContainer),children:[this.renderLink(styles$F.hoverTarget),jsxRuntimeExports.jsx("div",{children:children})]})}constructor(...args){super(...args),this.state={tooltipAbove:true},this.getPosition=()=>{const rect=ReactDOM__default.findDOMNode(this).getBoundingClientRect();this.setState({tooltipAbove:rect.top>100});},this.renderLink=style=>{const tooltipAbove=this.state.tooltipAbove;let severityStyle;let warningText;let warningTextStyle;if(this.props.severity===1){severityStyle=styles$F.indicatorError;warningText="Error";warningTextStyle=styles$F.publishBlockingError;}else if(this.props.severity===2){severityStyle=styles$F.indicatorWarning;warningText="Warning";warningTextStyle=styles$F.warning;}else {severityStyle=styles$F.indicatorGuideline;warningText="Recommendation";warningTextStyle=styles$F.warning;}return jsxRuntimeExports.jsxs("a",{href:`https://khanacademy.org/r/linter-rules#${this.props.ruleName}`,target:"lint-help-window",className:css(style),children:[jsxRuntimeExports.jsx("span",{className:css(styles$F.indicator,severityStyle),children:this.props.severity===1&&jsxRuntimeExports.jsx(InlineIcon,{...exclamationIcon})}),jsxRuntimeExports.jsxs("div",{className:css(styles$F.tooltip,tooltipAbove&&styles$F.tooltipAbove),children:[this.props.message.split("\n\n").map((m,i)=>jsxRuntimeExports.jsxs("p",{className:css(styles$F.tooltipParagraph),children:[jsxRuntimeExports.jsxs("span",{className:css(warningTextStyle),children:[warningText,":"," "]}),m]},i)),jsxRuntimeExports.jsx("div",{className:css(styles$F.tail,tooltipAbove&&styles$F.tailAbove)})]})]})};}}const styles$F=StyleSheet.create({lintContainer:{position:"relative"},lintContainerBlock:{display:"block"},hoverTarget:{position:"absolute",top:0,right:-40,display:"block",width:24,height:24,":hover > span":{backgroundColor:warningColorHover},":hover div":{display:"block"},":hover ~ div":{outline:"1px solid "+warningColor},":hover ~ div div[data-lint-inside-table]":{outline:"1px solid "+warningColor},":hover ~ div span[data-lint-inside-table]":{backgroundColor:warningColor,color:white}},inlineHoverTarget:{float:"right",position:"relative",marginRight:-40,display:"block",width:24,height:24,":hover > span":{backgroundColor:warningColorHover},":hover div":{display:"block"},":hover ~ span":{backgroundColor:warningColor,color:white}},radioWidgetHoverTarget:{position:"absolute",left:-40,display:"block",width:24,height:24,minWidth:264,":hover > span":{backgroundColor:warningColorHover},":hover > div":{display:"block",padding:8,width:280},":hover > div > div":{left:8},":hover ~ span":{backgroundColor:warningColor,color:white}},indicator:{alignItems:"center",borderRadius:4,color:"white",display:"flex",fontSize:12,height:8,justifyContent:"center",margin:8,width:8},indicatorError:{backgroundColor:"#be2612",borderRadius:8,height:16,width:16},indicatorWarning:{backgroundColor:"#f86700"},indicatorGuideline:{backgroundColor:"#ffbe26"},tooltip:{position:"absolute",right:-12,display:"none",zIndex:1e3,color:white,backgroundColor:gray17,opacity:.9,fontFamily:baseFontFamily,fontSize:"12px",lineHeight:"15px",width:"320px",borderRadius:"4px"},tooltipAbove:{bottom:32},tail:{position:"absolute",top:-12,right:16,width:0,height:0,borderLeft:"8px solid transparent",borderRight:"8px solid transparent",borderBottom:"12px solid "+gray17},tailAbove:{bottom:-12,borderBottom:"none",borderTop:"12px solid "+gray17,top:"auto"},tooltipParagraph:{margin:12},warning:{color:warningColor,fontFamily:boldFontFamily},publishBlockingError:{color:publishBlockingErrorColor}});
1637
1649
 
1638
1650
  const rules$1={...pureMarkdownRules,columns:{...pureMarkdownRules.columns,react:(node,output,state)=>{return jsxRuntimeExports.jsxs("div",{className:"perseus-two-columns",children:[jsxRuntimeExports.jsx("div",{className:"perseus-column",children:jsxRuntimeExports.jsx("div",{className:"perseus-column-content",children:output(node.col1,state)})}),jsxRuntimeExports.jsx("div",{className:"perseus-column",children:jsxRuntimeExports.jsx("div",{className:"perseus-column-content",children:output(node.col2,state)})})]},state.key)}},crowdinId:{...pureMarkdownRules.crowdinId,react:(node,output,state)=>node.id},table:{...pureMarkdownRules.table,react:function(node,output,state){const table=SimpleMarkdown.defaultRules.table.react(node,output,state);if(!state.isMobile){return table}return React.cloneElement(table,{tabIndex:0})}},titledTable:{...pureMarkdownRules.titledTable,react:(node,output,state)=>{let contents;if(!node.table){contents="//invalid table//";}else if(node.table.type==="lint"){if(node.table.content?.type==="table"){contents=rules$1.lint.react({...node.table,content:{...node,table:node.table.content}},output,{...state,unwrapTitledTableContents:true});}else {contents=rules$1.lint.react(node.table,output,state);}}else {const tableOutput=SimpleMarkdown.defaultRules.table.react(node.table,output,state);const caption=jsxRuntimeExports.jsx("caption",{className:"perseus-table-title",children:output(node.title,state)},"caption");contents=React.cloneElement(tableOutput,null,[caption,...tableOutput.props.children]);}if(state.unwrapTitledTableContents){return contents}return jsxRuntimeExports.jsx("div",{className:"perseus-titled-table",children:contents},state.key)}},widget:{...pureMarkdownRules.widget,react:(node,output,state)=>{return jsxRuntimeExports.jsx("em",{children:`[Widget: ${node.id}]`},state.key)}},blockMath:{...pureMarkdownRules.blockMath,react:(node,output,state)=>{const{TeX}=getDependencies();return jsxRuntimeExports.jsx(TeX,{children:node.content},state.key)}},math:{...pureMarkdownRules.math,react:(node,output,state)=>{const{TeX}=getDependencies();return jsxRuntimeExports.jsx(TeX,{children:node.content},state.key)}},unescapedDollar:{...pureMarkdownRules.unescapedDollar,react:(node,output,state)=>{return "$"}},link:{...pureMarkdownRules.link,react:function(node,output,state){const link=SimpleMarkdown.defaultRules.link.react(node,output,state);const href=link.props.href;let rel=null;const isKAUrl=href?href.match(/https?:\/\/[^/]*khanacademy.org|^\//):false;if(!isKAUrl){rel="noopener noreferrer";}const newProps={...link.props,target:"_blank",href,rel};if(state.baseElements&&state.baseElements.Link){return state.baseElements.Link(newProps)}return React.cloneElement(link,newProps)}},codeBlock:{...pureMarkdownRules.codeBlock,react:(node,output,state)=>{if(node.lang==="alt"){return jsxRuntimeExports.jsx("div",{className:"perseus-markdown-alt perseus-sr-only",children:output(node.content,state)},state.key)}return SimpleMarkdown.defaultRules.codeBlock.react(node,output,state)}},lint:{...pureMarkdownRules.lint,react:(node,output,state)=>{return jsxRuntimeExports.jsx(Lint,{message:node.message,ruleName:node.ruleName,inline:isInline(node.content),blockHighlight:node.blockHighlight,insideTable:node.insideTable,severity:node.severity,children:output(node.content,state)})}}};function isInline(node){return !!(node&&node.type&&inlineNodeTypes.hasOwnProperty(node.type))}const inlineNodeTypes={text:true,math:true,unescapedDollar:true,link:true,img:true,strong:true,u:true,em:true,del:true,code:true};const builtParser$1=SimpleMarkdown.parserFor(rules$1);const parse$3=(source,state)=>{const paragraphedSource=source+"\n\n";return builtParser$1(paragraphedSource,{...state,inline:false})};const inlineParser=(source,state)=>{return builtParser$1(source,{...state,inline:true})};const traverseContent=(ast,cb)=>{if(_.isArray(ast)){_.each(ast,node=>traverseContent(node,cb));}else if(_.isObject(ast)){cb(ast);if(ast.type==="table"){traverseContent(ast.header,cb);traverseContent(ast.cells,cb);}else if(ast.type==="list"){traverseContent(ast.items,cb);}else if(ast.type==="titledTable"){traverseContent(ast.table,cb);}else if(ast.type==="columns"){traverseContent(ast.col1,cb);traverseContent(ast.col2,cb);}else if(_.isArray(ast.content)){traverseContent(ast.content,cb);}}};const getContent=ast=>{if(_.isArray(ast)){return _.flatten(_.map(ast,getContent))}if(ast.content&&_.isString(ast.content)){if(ast.type.toLowerCase().indexOf("code")!==-1){return ["",ast.content,""]}return [ast.content.replace(/\s+/g," ")]}const children=_.chain(ast).values().flatten().filter(object=>object!=null&&_.has(object,"type")).value();if(!children.length){return []}const nestedContent=getContent(children);if(ast.type==="paragraph"&&nestedContent.length){nestedContent[0]=nestedContent[0].replace(/^\s+/,"");const last=nestedContent.length-1;nestedContent[last]=nestedContent[last].replace(/\s+$/,"");}return nestedContent};const characterCount=source=>{const ast=parse$3(source);const content=getContent(ast).join("");return content.length};var PerseusMarkdown = {characterCount:characterCount,traverseContent:traverseContent,parse:parse$3,parseInline:inlineParser,reactFor:SimpleMarkdown.reactFor,ruleOutput:SimpleMarkdown.ruleOutput(rules$1,"react"),basicOutput:SimpleMarkdown.reactFor(SimpleMarkdown.ruleOutput(rules$1,"react")),sanitizeUrl:SimpleMarkdown.sanitizeUrl};
1639
1651
 
@@ -1675,13 +1687,13 @@ var widgets$1 = /*#__PURE__*/Object.freeze({
1675
1687
 
1676
1688
  class WidgetContainer extends React.Component{componentDidMount(){if(this.state.widgetProps.apiOptions.isMobile){const containerWidth=ReactDOM__default.findDOMNode(this).offsetWidth;this.setState({sizeClass:getClassFromWidth(containerWidth)});}}UNSAFE_componentWillReceiveProps(nextProps){if(this.props.type!==nextProps.type){throw new Error("WidgetContainer can't change widget type; set a different "+"key instead to recreate the container.")}}shouldComponentUpdate(nextProps,nextState){return this.props.shouldHighlight!==nextProps.shouldHighlight||this.props.type!==nextProps.type||this.state.widgetProps!==nextState.widgetProps||this.state.sizeClass!==nextState.sizeClass}render(){let className=classNames$1({"perseus-widget-container":true,"widget-highlight":this.props.shouldHighlight,"widget-nohighlight":!this.props.shouldHighlight,"perseus-widget__definition":this.props.type==="definition"});const type=this.props.type;const userAgent=navigator.userAgent;const WidgetType=getWidget(type);if(WidgetType==null){console.warn(`Widget type '${type}' not found!`);return jsxRuntimeExports.jsx("div",{className:className})}let subType="null";if(type==="interactive-graph"){const props=this.state.widgetProps;subType=props.graph?.type??"null";}let alignment=this.state.widgetProps.alignment;if(alignment==="default"){alignment=CoreWidgetRegistry.getDefaultAlignment(type);}className+=" widget-"+alignment;const apiOptions=this.state.widgetProps.apiOptions;const isStatic=this.state.widgetProps.static||apiOptions.readOnly;const staticContainerStyles={position:"relative",overflow:"visible"};const staticOverlayStyles={width:"100%",height:"100%",position:"absolute",top:0,left:0,zIndex:3};const linterContext=isLintable(type)?this.props.linterContext:{...this.props.linterContext,highlightLint:false};return jsxRuntimeExports.jsx("div",{className:className,style:isStatic?staticContainerStyles:{},children:jsxRuntimeExports.jsx(DependenciesContext.Consumer,{children:({analytics})=>jsxRuntimeExports.jsxs(ErrorBoundary,{metadata:{widget_type:type,widget_id:this.props.id},onError:error=>{analytics.onAnalyticsEvent({type:"perseus:widget-rendering-error:ti",payload:{widgetSubType:subType,widgetType:type,widgetId:this.props.id,message:error.message,userAgent:userAgent}});},children:[jsxRuntimeExports.jsx(WidgetType,{...this.state.widgetProps,linterContext:linterContext,containerSizeClass:this.state.sizeClass,ref:this.widgetRef}),isStatic&&jsxRuntimeExports.jsx("div",{style:staticOverlayStyles})]})})})}constructor(...args){super(...args),this.widgetRef=React.createRef(),this.state={sizeClass:containerSizeClass.MEDIUM,widgetProps:this.props.initialProps},this.getWidget=()=>{return this.widgetRef.current},this.replaceWidgetProps=newWidgetProps=>{this.setState({widgetProps:newWidgetProps});};}}WidgetContainer.defaultProps={linterContext:linterContextDefault};
1677
1689
 
1678
- const rContainsNonWhitespace=/\S/;const rImageURL=/(web\+graphie|https):\/\/[^\s]*/;const noopOnRender=()=>{};const SHOULD_CLEAR_WIDGETS_PROP_LIST=["content","problemNum","widgets"];const makeContainerId=id=>"container:"+id;const isIdPathPrefix=function(prefixArray,wholeArray){if(prefixArray===null||wholeArray===null){return prefixArray===wholeArray}return _.every(prefixArray,(elem,i)=>{if(wholeArray!=null){return _.isEqual(elem,wholeArray[i])}})};class Renderer extends React.Component{componentDidMount(){this._isMounted=true;this.handleRender({});this._currentFocus=null;if(this.props.serializedState){this.restoreSerializedState(this.props.serializedState);}if(this.props.linterContext.highlightLint){this._translationLinter.runLinter(this.props.content,this.handletranslationLintErrors);}}UNSAFE_componentWillReceiveProps(nextProps){if(!_.isEqual(_.pick(this.props,SHOULD_CLEAR_WIDGETS_PROP_LIST),_.pick(nextProps,SHOULD_CLEAR_WIDGETS_PROP_LIST))){this.setState(this._getInitialWidgetState(nextProps));}}shouldComponentUpdate(nextProps,nextState){if(this.props.alwaysUpdate){return true}const stateChanged=!_.isEqual(this.state,nextState);const propsChanged=!_.isEqual(this.props,nextProps);return propsChanged||stateChanged}UNSAFE_componentWillUpdate(nextProps,nextState){const oldJipt=this.shouldRenderJiptPlaceholder(this.props,this.state);const newJipt=this.shouldRenderJiptPlaceholder(nextProps,nextState);const oldContent=this.getContent(this.props,this.state);const newContent=this.getContent(nextProps,nextState);const oldHighlightedWidgets=this.props.highlightedWidgets;const newHighlightedWidgets=nextProps.highlightedWidgets;this.reuseMarkdown=!oldJipt&&!newJipt&&oldContent===newContent&&_.isEqual(this.state.translationLintErrors,nextState.translationLintErrors)&&(!this.props.linterContext.highlightLint||_.isEqual(this.props.widgets,nextProps.widgets))&&this.props.linterContext.highlightLint===nextProps.linterContext.highlightLint&&oldHighlightedWidgets===newHighlightedWidgets;}componentDidUpdate(prevProps,prevState){this.handleRender(prevProps);this.widgetIds.forEach(id=>{const container=this._widgetContainers.get(makeContainerId(id));container?.replaceWidgetProps(this.getWidgetProps(id));});if(this.props.serializedState&&!_.isEqual(this.props.serializedState,this.getSerializedState())){this.restoreSerializedState(this.props.serializedState);}if(this.props.linterContext.highlightLint){this._translationLinter.runLinter(this.props.content,this.handletranslationLintErrors);}}componentWillUnmount(){this.widgetIds=[];if(this.translationIndex!=null){getDependencies().rendererTranslationComponents.removeComponentAtIndex(this.translationIndex);}this._isMounted=false;}getWidgetProps(widgetId){const apiOptions=this.getApiOptions();const widgetProps=this.state.widgetProps[widgetId]||{};const widgetInfo=this.state.widgetInfo[widgetId];const reviewModeRubric=this.props.reviewMode&&widgetInfo?widgetInfo.options:null;if(!this._interactionTrackers){this._interactionTrackers={};}let interactionTracker=this._interactionTrackers[widgetId];if(!interactionTracker){interactionTracker=this._interactionTrackers[widgetId]=new InteractionTracker(apiOptions.trackInteraction,widgetInfo&&widgetInfo.type,widgetId,getTracking(widgetInfo&&widgetInfo.type));}return {...widgetProps,widgetId:widgetId,alignment:widgetInfo&&widgetInfo.alignment,static:widgetInfo?.static,problemNum:this.props.problemNum,apiOptions:this.getApiOptions(),keypadElement:this.props.keypadElement,questionCompleted:this.props.questionCompleted,showSolutions:this.props.showSolutions,onFocus:_.partial(this._onWidgetFocus,widgetId),onBlur:_.partial(this._onWidgetBlur,widgetId),findWidgets:this.findWidgets,reviewModeRubric:reviewModeRubric,reviewMode:this.props.reviewMode,onChange:(newProps,cb,silent=false)=>{this._setWidgetProps(widgetId,newProps,cb,silent);},trackInteraction:interactionTracker.track,isLastUsedWidget:widgetId===this.state.lastUsedWidgetId}}emptyWidgets(){return emptyWidgetsFunctional(this.state.widgetInfo,this.widgetIds,this.getUserInputMap(),this.context.locale)}getUserInput(){return this.widgetIds.map(id=>{const widget=this.getWidgetInstance(id);if(widget&&widget.getUserInput){return widget.getUserInput()}})}getUserInputMap(){const userInputMap={};this.widgetIds.forEach(id=>{const widget=this.getWidgetInstance(id);if(widget?.getUserInputMap){userInputMap[id]=widget.getUserInputMap();}else if(widget?.getUserInput){userInputMap[id]=widget.getUserInput();}});return userInputMap}getPromptJSON(){const{content}=this.props;const widgetJSON={};this.widgetIds.forEach(id=>{const widget=this.getWidgetInstance(id);widgetJSON[id]=widget?.getPromptJSON?.()||{};});return {content,widgets:widgetJSON}}score(){const scores=scoreWidgetsFunctional(this.state.widgetInfo,this.widgetIds,this.getUserInputMap(),this.context.locale);const combinedScore=flattenScores(scores);return combinedScore}render(){const apiOptions=this.getApiOptions();if(this.reuseMarkdown){return this.lastRenderedMarkdown}const content=this.getContent(this.props,this.state);this.widgetIds=[];if(this.shouldRenderJiptPlaceholder(this.props,this.state)){if(!this.translationIndex){this.translationIndex=getDependencies().rendererTranslationComponents.addComponent(this);}if(!apiOptions.isArticle){return jsxRuntimeExports.jsx(DefinitionProvider,{children:jsxRuntimeExports.jsx("div",{"data-perseus-component-index":this.translationIndex,children:content})})}}this._isTwoColumn=false;const parsedMarkdown=this.props.inline?PerseusMarkdown.parseInline(content,{isJipt:this.translationIndex!=null}):PerseusMarkdown.parse(content,{isJipt:this.translationIndex!=null});if(this.props.linterContext.highlightLint){const fullLinterContext={content:this.props.content,widgets:this.props.widgets,...this.props.linterContext};PerseusLinter.runLinter(parsedMarkdown,fullLinterContext,true);this._translationLinter.applyLintErrors(parsedMarkdown,[...this.state.translationLintErrors,...this.props.legacyPerseusLint||[]]);}const markdownContents=this.outputMarkdown(parsedMarkdown,{baseElements:apiOptions.baseElements});const className=classNames$1({[ClassNames.RENDERER]:true,[ClassNames.RESPONSIVE_RENDERER]:true,[ClassNames.TWO_COLUMN_RENDERER]:this._isTwoColumn});this.lastRenderedMarkdown=jsxRuntimeExports.jsx(DefinitionProvider,{children:jsxRuntimeExports.jsx("div",{className:className,children:markdownContents})});return this.lastRenderedMarkdown}constructor(props){super(props),this._widgetContainers=new Map,this.getApiOptions=()=>{return {...ApiOptions.defaults,...this.props.apiOptions}},this._getInitialWidgetState=props=>{const allWidgetInfo=getUpgradedWidgetOptions(props.widgets);return {widgetInfo:allWidgetInfo,widgetProps:this._getAllWidgetsStartProps(allWidgetInfo,props)}},this._getAllWidgetsStartProps=(allWidgetInfo,props)=>{const{apiOptions,problemNum}=props;const widgetsStartProps={};const{strings}=this.props;entries(allWidgetInfo).forEach(([key,widgetInfo])=>{widgetsStartProps[key]=getRendererPropsForWidgetInfo(widgetInfo,strings,problemNum);});apiOptions?.onWidgetStartProps?.(widgetsStartProps);return widgetsStartProps},this._getDefaultWidgetInfo=widgetId=>{const widgetIdParts=Util.rTypeFromWidgetId.exec(widgetId);if(widgetIdParts==null){return {}}return {type:widgetIdParts[1],graded:true,options:{}}},this._getWidgetInfo=widgetId=>{return this.state.widgetInfo[widgetId]||this._getDefaultWidgetInfo(widgetId)},this.renderWidget=(impliedType,id,state)=>{const widgetInfo=this.state.widgetInfo[id];if(widgetInfo&&widgetInfo.alignment==="full-width"){state.foundFullWidth=true;}if(widgetInfo){const type=widgetInfo&&widgetInfo.type||impliedType;const shouldHighlight=_.contains(this.props.highlightedWidgets,id);return jsxRuntimeExports.jsx(WidgetContainer,{id:id,ref:node=>{const containerId=makeContainerId(id);if(node!=null){this._widgetContainers.set(containerId,node);}else {this._widgetContainers.delete(containerId);}},type:type,initialProps:this.getWidgetProps(id),shouldHighlight:shouldHighlight,linterContext:PerseusLinter.pushContextStack(this.props.linterContext,"widget")},makeContainerId(id))}return null},this.getSerializedState=widgetProps=>{return mapObject(widgetProps||this.state.widgetProps,(props,widgetId)=>{const widget=this.getWidgetInstance(widgetId);if(widget&&widget.getSerializedState){return widget.getSerializedState()}return props})},this.restoreSerializedState=(serializedState,callback)=>{const serializedWidgetIds=_.keys(serializedState);const widgetPropIds=_.keys(this.state.widgetProps);if(serializedWidgetIds.length!==widgetPropIds.length||_.intersection(serializedWidgetIds,widgetPropIds).length!==serializedWidgetIds.length){Log.error("Refusing to restore bad serialized state:",Errors.Internal,{loggedMetadata:{serializedState:JSON.stringify(serializedState),currentProps:JSON.stringify(this.state.widgetProps)}});return}let numCallbacks=1;const fireCallback=()=>{--numCallbacks;if(callback&&numCallbacks===0){callback();}};this.setState({widgetProps:mapObject(serializedState,(props,widgetId)=>{const widget=this.getWidgetInstance(widgetId);if(widget&&widget.restoreSerializedState){++numCallbacks;const restoreResult=widget.restoreSerializedState(props,fireCallback);return _.extend({},this.state.widgetProps[widgetId],restoreResult)}return props})},()=>{setTimeout(fireCallback,0);});},this.showRationalesForCurrentlySelectedChoices=()=>{Object.keys(this.props.widgets).forEach(widgetId=>{const widget=this.getWidgetInstance(widgetId);if(widget&&widget.showRationalesForCurrentlySelectedChoices){widget.showRationalesForCurrentlySelectedChoices(this._getWidgetInfo(widgetId).options);}});},this.deselectIncorrectSelectedChoices=()=>{Object.keys(this.props.widgets).forEach(widgetId=>{const widget=this.getWidgetInstance(widgetId);if(widget&&widget.deselectIncorrectSelectedChoices){widget.deselectIncorrectSelectedChoices();}});},this.findInternalWidgets=filterCriterion=>{let filterFunc;if(typeof filterCriterion==="string"){if(filterCriterion.indexOf(" ")!==-1){const widgetId=filterCriterion;filterFunc=(id,widgetInfo,widget)=>id===widgetId;}else {const widgetType=filterCriterion;filterFunc=(id,widgetInfo,widget)=>{return widgetInfo.type===widgetType};}}else {filterFunc=filterCriterion;}const results=this.widgetIds.filter(id=>{const widgetInfo=this._getWidgetInfo(id);const widget=this.getWidgetInstance(id);return filterFunc(id,widgetInfo,widget)}).map(this.getWidgetInstance);return results},this.findWidgets=filterCriterion=>{return [...this.findInternalWidgets(filterCriterion),...this.props.findExternalWidgets(filterCriterion)]},this.getWidgetInstance=id=>{const ref=this._widgetContainers.get(makeContainerId(id));if(!ref){return null}return ref.getWidget()},this._onWidgetFocus=(id,focusPath=[])=>{if(!_.isArray(focusPath)){throw new PerseusError("widget props.onFocus focusPath must be an Array, "+"but was"+JSON.stringify(focusPath),Errors.Internal)}this._setCurrentFocus([id].concat(focusPath));},this._onWidgetBlur=(id,blurPath)=>{const blurringFocusPath=this._currentFocus;const fullPath=[id].concat(blurPath);if(!_.isEqual(fullPath,blurringFocusPath)){return}_.defer(()=>{if(_.isEqual(this._currentFocus,blurringFocusPath)){this._setCurrentFocus(null);}});},this.getContent=(props,state)=>{return state.jiptContent||props.content},this.shouldRenderJiptPlaceholder=(props,state)=>{return getDependencies().JIPT.useJIPT&&state.jiptContent==null&&props.content.indexOf("crwdns")!==-1},this.replaceJiptContent=(content,paragraphIndex)=>{if(paragraphIndex==null){this.setState({jiptContent:content});}else {const codeFenceRegex=/^\s*(`{3,}|~{3,})\s*(\S+)?\s*\n([\s\S]+?)\s*\1\s*$/;if(codeFenceRegex.test(content));else if(/\S\n\s*\n\S/.test(content)){content="$\\large{\\red{\\text{Please translate each "+"paragraph to a single paragraph.}}}$";}else if(/^\s*$/.test(content)){content="$\\large{\\red{\\text{Translated paragraph is "+"currently empty}}}$";}const allContent=this.getContent(this.props,this.state);const paragraphs=JiptParagraphs.parseToArray(allContent);paragraphs[paragraphIndex]=content;this.setState({jiptContent:JiptParagraphs.joinFromArray(paragraphs)});}},this.outputMarkdown=(ast,state)=>{if(_.isArray(ast)){const oldKey=state.key;const result=[];let lastWasString=false;for(let i=0;i<ast.length;i++){state.key=i;state.paragraphIndex=i;const nodeOut=this.outputMarkdown(ast[i],state);const isString=typeof nodeOut==="string";if(typeof nodeOut==="string"&&lastWasString){result[result.length-1]+=nodeOut;}else {result.push(nodeOut);}lastWasString=isString;}state.key=oldKey;return result}this._foundTextNodes=false;state.foundFullWidth=false;const output=this.outputNested(ast,state);let className;if(this.translationIndex!=null){className=null;}else {className=classNames$1({"perseus-paragraph-centered":!this._foundTextNodes,"perseus-paragraph-full-width":state.foundFullWidth&&ast.content.length===1});}return jsxRuntimeExports.jsx(QuestionParagraph,{className:className,translationIndex:this.translationIndex,paragraphIndex:state.paragraphIndex,inline:this.props.inline,children:jsxRuntimeExports.jsx(ErrorBoundary,{children:output})},state.key)},this.outputNested=(ast,state)=>{if(_.isArray(ast)){const oldKey=state.key;const result=[];let lastWasString=false;for(let i=0;i<ast.length;i++){state.key=i;const nodeOut=this.outputNested(ast[i],state);const isString=typeof nodeOut==="string";if(typeof nodeOut==="string"&&lastWasString){result[result.length-1]+=nodeOut;}else {result.push(nodeOut);}lastWasString=isString;}state.key=oldKey;return result}return this.outputNode(ast,this.outputNested,state)},this.outputNode=(node,nestedOutput,state)=>{const apiOptions=this.getApiOptions();const imagePlaceholder=apiOptions.imagePlaceholder;if(node.type==="widget"){const widgetPlaceholder=apiOptions.widgetPlaceholder;if(widgetPlaceholder){return widgetPlaceholder}this._foundTextNodes=true;if(this.widgetIds.includes(node.id)){return jsxRuntimeExports.jsx("span",{className:"renderer-widget-error",children:["Widget [[","☃"," ",node.id,"]] already exists."].join("")},state.key)}this.widgetIds.push(node.id);return this.renderWidget(node.widgetType,node.id,state)}if(node.type==="blockMath"){const content=preprocessTex(node.content);const innerStyle={overflowX:"auto",overflowY:"hidden",paddingTop:10,paddingBottom:10,marginTop:-10,marginBottom:-10};if(apiOptions.isMobile){const margin=16;const outerStyle={marginLeft:-16,marginRight:-16};const horizontalPadding={paddingLeft:margin,paddingRight:margin};const mobileInnerStyle={...innerStyle,...styles$A.mobileZoomableParentFix};return jsxRuntimeExports.jsx("div",{className:"perseus-block-math",style:outerStyle,children:jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx("div",{className:"perseus-block-math-inner",style:{...mobileInnerStyle,...horizontalPadding},children:jsxRuntimeExports.jsx(ZoomableTeX,{children:content})})})},state.key)}return jsxRuntimeExports.jsx("div",{className:"perseus-block-math",children:jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx("div",{className:"perseus-block-math-inner",style:innerStyle,children:jsxRuntimeExports.jsx(context$1.Consumer,{children:({setAssetStatus})=>jsxRuntimeExports.jsx(Tex,{setAssetStatus:setAssetStatus,children:content})})})})},state.key)}if(node.type==="math"){const tex=node.content;return jsxRuntimeExports.jsx("span",{style:{whiteSpace:"nowrap"},children:jsxRuntimeExports.jsxs(ErrorBoundary,{children:[jsxRuntimeExports.jsx("span",{}),jsxRuntimeExports.jsx(context$1.Consumer,{children:({setAssetStatus})=>jsxRuntimeExports.jsx(Tex,{onRender:this.props.onRender,setAssetStatus:setAssetStatus,children:tex})}),jsxRuntimeExports.jsx("span",{})]})},state.key)}if(node.type==="image"){if(imagePlaceholder){return imagePlaceholder}const extraAttrs=_.has(this.props.images,node.target)?this.props.images[node.target]:null;const responsive=!state.inTable;return jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx(context$1.Consumer,{children:({setAssetStatus})=>jsxRuntimeExports.jsx(SvgImage,{setAssetStatus:setAssetStatus,src:PerseusMarkdown.sanitizeUrl(node.target),alt:node.alt,title:node.title,responsive:responsive,onUpdate:this.props.onRender,zoomToFullSizeOnMobile:apiOptions.isMobile&&apiOptions.isArticle,...extraAttrs})})},state.key)}if(node.type==="columns"){this._isTwoColumn=true;return jsxRuntimeExports.jsx(ErrorBoundary,{children:PerseusMarkdown.ruleOutput(node,nestedOutput,state)},state.key)}if(node.type==="text"){if(rContainsNonWhitespace.test(node.content)){this._foundTextNodes=true;}if(imagePlaceholder&&rImageURL.test(node.content)){return imagePlaceholder}return node.content}if(node.type==="table"||node.type==="titledTable"){const output=PerseusMarkdown.ruleOutput(node,nestedOutput,{...state,isMobile:apiOptions.isMobile,inTable:true});if(!apiOptions.isMobile){return output}const outerStyle={marginLeft:-16,marginRight:-16};const innerStyle={paddingLeft:0,paddingRight:0};const mobileInnerStyle={...innerStyle,...styles$A.mobileZoomableParentFix};const wrappedOutput=jsxRuntimeExports.jsx("div",{style:{...mobileInnerStyle,overflowX:"auto"},children:jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx(Zoomable,{animateHeight:true,children:output})})});return jsxRuntimeExports.jsx("div",{style:outerStyle,children:wrappedOutput})}return jsxRuntimeExports.jsx(ErrorBoundary,{children:PerseusMarkdown.ruleOutput(node,nestedOutput,state)},state.key)},this.handleRender=prevProps=>{const onRender=this.props.onRender;const oldOnRender=prevProps.onRender;if(onRender!==noopOnRender||oldOnRender!==noopOnRender){const $images=$(ReactDOM__default.findDOMNode(this)).find("img");if(oldOnRender!==noopOnRender){$images.off("load",oldOnRender);}if(onRender!==noopOnRender){$images.on("load",onRender);}}onRender();},this._setCurrentFocus=path=>{const apiOptions=this.getApiOptions();if(!isIdPathPrefix(path,this._currentFocus)){const prevFocus=this._currentFocus;if(prevFocus){this.blurPath(prevFocus);}this._currentFocus=path;apiOptions.onFocusChange(this._currentFocus,prevFocus);}},this.focus=()=>{let id;let focusResult;for(let i=0;i<this.widgetIds.length;i++){const widgetId=this.widgetIds[i];const widget=this.getWidgetInstance(widgetId);const widgetFocusResult=widget?.focus?.();if(widgetFocusResult){id=widgetId;focusResult=widgetFocusResult;break}}if(id){let path;if(typeof focusResult==="object"){path=[id].concat(focusResult.path||[]);Log.error("Renderer received a focus result of type 'object' "+"instead of the expected type 'boolean'",Errors.Internal,{loggedMetadata:{focusResult:JSON.stringify(focusResult),currentProps:JSON.stringify(this.state.widgetProps)}});}else {path=[id];}this._setCurrentFocus(path);return true}},this.getDOMNodeForPath=path=>{const widgetId=_.first(path);const interWidgetPath=_.rest(path);const widget=this.getWidgetInstance(widgetId);if(widget?.getDOMNodeForPath){return widget.getDOMNodeForPath(interWidgetPath)}if(interWidgetPath.length===0){return ReactDOM__default.findDOMNode(widget)}},this.getInputPaths=()=>{const inputPaths=[];this.widgetIds.forEach(widgetId=>{const widget=this.getWidgetInstance(widgetId);if(widget&&widget.getInputPaths){const widgetInputPaths=widget.getInputPaths();widgetInputPaths.forEach(inputPath=>{const relativeInputPath=[widgetId].concat(inputPath);inputPaths.push(relativeInputPath);});}});return inputPaths},this.focusPath=path=>{if(_.isEqual(this._currentFocus,path)){return}if(this._currentFocus){this.blurPath(this._currentFocus);}const widgetId=_.first(path);const interWidgetPath=_.rest(path);const focusWidget=this.getWidgetInstance(widgetId);focusWidget?.focusInputPath?.(interWidgetPath);},this.blurPath=path=>{if(!_.isEqual(this._currentFocus,path)){return}const widgetId=_.first(path);const interWidgetPath=_.rest(path);const widget=this.getWidgetInstance(widgetId);if(widget){const blurWidget=this.getWidgetInstance(widgetId);blurWidget?.blurInputPath?.(interWidgetPath);}},this.blur=()=>{if(this._currentFocus){this.blurPath(this._currentFocus);}},this.serialize=()=>{const state={};_.each(this.state.widgetInfo,function(info,id){const widget=this.getWidgetInstance(id);const s=widget.serialize();if(!_.isEmpty(s)){state[id]=s;}},this);return state},this._setWidgetProps=(id,newProps,cb,silent)=>{this.setState(prevState=>{const widgetProps={...prevState.widgetProps,[id]:{...prevState.widgetProps[id],...newProps}};const lastUsedWidgetId=silent?prevState.lastUsedWidgetId:id;if(!silent){this.props.onSerializedStateUpdated(this.getSerializedState(widgetProps));}return {lastUsedWidgetId,widgetProps}},()=>{setTimeout(()=>{const cbResult=cb&&cb();if(!silent){this.props.onInteractWithWidget(id);}if(cbResult!==false){this._setCurrentFocus([id]);}},0);});},this.setInputValue=(path,newValue,cb)=>{const widgetId=_.first(path);const interWidgetPath=_.rest(path);const widget=this.getWidgetInstance(widgetId);widget?.setInputValue?.(interWidgetPath,newValue,cb);},this.getWidgetIds=()=>{return this.widgetIds},this.handletranslationLintErrors=lintErrors=>{if(!this._isMounted){return}this.setState({translationLintErrors:lintErrors});};this._translationLinter=new TranslationLinter;this.state={jiptContent:null,translationLintErrors:[],lastUsedWidgetId:null,...this._getInitialWidgetState(props)};}}Renderer.contextType=PerseusI18nContext;Renderer.defaultProps={content:"",widgets:{},images:{},highlightedWidgets:[],questionCompleted:false,showSolutions:"none",onRender:noopOnRender,onInteractWithWidget:function(){},findExternalWidgets:()=>[],alwaysUpdate:false,reviewMode:false,serializedState:null,onSerializedStateUpdated:()=>{},linterContext:PerseusLinter.linterContextDefault};const styles$A={mobileZoomableParentFix:{transform:"translate3d(0,0,0)"}};
1690
+ const rContainsNonWhitespace=/\S/;const rImageURL=/(web\+graphie|https):\/\/[^\s]*/;const noopOnRender=()=>{};const SHOULD_CLEAR_WIDGETS_PROP_LIST=["content","problemNum","widgets"];const makeContainerId=id=>"container:"+id;const isIdPathPrefix=function(prefixArray,wholeArray){if(prefixArray===null||wholeArray===null){return prefixArray===wholeArray}return _.every(prefixArray,(elem,i)=>{if(wholeArray!=null){return _.isEqual(elem,wholeArray[i])}})};class Renderer extends React.Component{componentDidMount(){this._isMounted=true;this.handleRender({});this._currentFocus=null;if(this.props.serializedState){this.restoreSerializedState(this.props.serializedState);}if(this.props.linterContext.highlightLint){this._translationLinter.runLinter(this.props.content,this.handletranslationLintErrors);}}UNSAFE_componentWillReceiveProps(nextProps){if(!_.isEqual(_.pick(this.props,SHOULD_CLEAR_WIDGETS_PROP_LIST),_.pick(nextProps,SHOULD_CLEAR_WIDGETS_PROP_LIST))){this.setState(this._getInitialWidgetState(nextProps));}}shouldComponentUpdate(nextProps,nextState){if(this.props.alwaysUpdate){return true}const stateChanged=!_.isEqual(this.state,nextState);const propsChanged=!_.isEqual(this.props,nextProps);return propsChanged||stateChanged}UNSAFE_componentWillUpdate(nextProps,nextState){const oldJipt=this.shouldRenderJiptPlaceholder(this.props,this.state);const newJipt=this.shouldRenderJiptPlaceholder(nextProps,nextState);const oldContent=this.getContent(this.props,this.state);const newContent=this.getContent(nextProps,nextState);const oldHighlightedWidgets=this.props.highlightedWidgets;const newHighlightedWidgets=nextProps.highlightedWidgets;this.reuseMarkdown=!oldJipt&&!newJipt&&oldContent===newContent&&_.isEqual(this.state.translationLintErrors,nextState.translationLintErrors)&&(!this.props.linterContext.highlightLint||_.isEqual(this.props.widgets,nextProps.widgets))&&this.props.linterContext.highlightLint===nextProps.linterContext.highlightLint&&oldHighlightedWidgets===newHighlightedWidgets;}componentDidUpdate(prevProps,prevState){this.handleRender(prevProps);this.widgetIds.forEach(id=>{const container=this._widgetContainers.get(makeContainerId(id));container?.replaceWidgetProps(this.getWidgetProps(id));});if(this.props.serializedState&&!_.isEqual(this.props.serializedState,this.getSerializedState())){this.restoreSerializedState(this.props.serializedState);}if(this.props.linterContext.highlightLint){this._translationLinter.runLinter(this.props.content,this.handletranslationLintErrors);}}componentWillUnmount(){this.widgetIds=[];if(this.translationIndex!=null){getDependencies().rendererTranslationComponents.removeComponentAtIndex(this.translationIndex);}this._isMounted=false;}getWidgetProps(widgetId){const apiOptions=this.getApiOptions();const widgetProps=this.state.widgetProps[widgetId]||{};const widgetInfo=this.state.widgetInfo[widgetId];const reviewModeRubric=this.props.reviewMode&&widgetInfo?widgetInfo.options:null;if(!this._interactionTrackers){this._interactionTrackers={};}let interactionTracker=this._interactionTrackers[widgetId];if(!interactionTracker){interactionTracker=this._interactionTrackers[widgetId]=new InteractionTracker(apiOptions.trackInteraction,widgetInfo&&widgetInfo.type,widgetId,getTracking(widgetInfo&&widgetInfo.type));}return {...widgetProps,widgetId:widgetId,alignment:widgetInfo&&widgetInfo.alignment,static:widgetInfo?.static,problemNum:this.props.problemNum,apiOptions:this.getApiOptions(),keypadElement:this.props.keypadElement,questionCompleted:this.props.questionCompleted,showSolutions:this.props.showSolutions,onFocus:_.partial(this._onWidgetFocus,widgetId),onBlur:_.partial(this._onWidgetBlur,widgetId),findWidgets:this.findWidgets,reviewModeRubric:reviewModeRubric,reviewMode:this.props.reviewMode,onChange:(newProps,cb,silent=false)=>{this._setWidgetProps(widgetId,newProps,cb,silent);},trackInteraction:interactionTracker.track,isLastUsedWidget:widgetId===this.state.lastUsedWidgetId}}emptyWidgets(){return emptyWidgetsFunctional(this.state.widgetInfo,this.widgetIds,this.getUserInputMap(),this.context.locale)}getUserInput(){return this.widgetIds.map(id=>{const widget=this.getWidgetInstance(id);if(widget&&widget.getUserInput){return widget.getUserInput()}})}getUserInputMap(){const userInputMap={};this.widgetIds.forEach(id=>{const widget=this.getWidgetInstance(id);if(widget?.getUserInputMap){userInputMap[id]=widget.getUserInputMap();}else if(widget?.getUserInput){userInputMap[id]=widget.getUserInput();}});return userInputMap}getPromptJSON(){const{content}=this.props;const widgetJSON={};this.widgetIds.forEach(id=>{const widget=this.getWidgetInstance(id);widgetJSON[id]=widget?.getPromptJSON?.()||{};});return {content,widgets:widgetJSON}}score(){const scores=scoreWidgetsFunctional(this.state.widgetInfo,this.widgetIds,this.getUserInputMap(),this.context.locale);const combinedScore=flattenScores(scores);return combinedScore}render(){const apiOptions=this.getApiOptions();if(this.reuseMarkdown){return this.lastRenderedMarkdown}const content=this.getContent(this.props,this.state);this.widgetIds=[];if(this.shouldRenderJiptPlaceholder(this.props,this.state)){if(!this.translationIndex){this.translationIndex=getDependencies().rendererTranslationComponents.addComponent(this);}if(!apiOptions.isArticle){return jsxRuntimeExports.jsx(DefinitionProvider,{children:jsxRuntimeExports.jsx("div",{"data-perseus-component-index":this.translationIndex,children:content})})}}this._isTwoColumn=false;const parsedMarkdown=this.props.inline?PerseusMarkdown.parseInline(content,{isJipt:this.translationIndex!=null}):PerseusMarkdown.parse(content,{isJipt:this.translationIndex!=null});if(this.props.linterContext.highlightLint){const fullLinterContext={content:this.props.content,widgets:this.props.widgets,...this.props.linterContext};PerseusLinter.runLinter(parsedMarkdown,fullLinterContext,true);this._translationLinter.applyLintErrors(parsedMarkdown,[...this.state.translationLintErrors,...this.props.legacyPerseusLint||[]]);}const markdownContents=this.outputMarkdown(parsedMarkdown,{baseElements:apiOptions.baseElements});const className=classNames$1({[ClassNames.RENDERER]:true,[ClassNames.RESPONSIVE_RENDERER]:true,[ClassNames.TWO_COLUMN_RENDERER]:this._isTwoColumn});this.lastRenderedMarkdown=jsxRuntimeExports.jsx(DefinitionProvider,{children:jsxRuntimeExports.jsx("div",{className:className,children:markdownContents})});return this.lastRenderedMarkdown}constructor(props){super(props),this._widgetContainers=new Map,this.getApiOptions=()=>{return {...ApiOptions.defaults,...this.props.apiOptions}},this._getInitialWidgetState=props=>{const allWidgetInfo=getUpgradedWidgetOptions(props.widgets);return {widgetInfo:allWidgetInfo,widgetProps:this._getAllWidgetsStartProps(allWidgetInfo,props)}},this._getAllWidgetsStartProps=(allWidgetInfo,props)=>{const{apiOptions,problemNum}=props;const widgetsStartProps={};const{strings}=this.props;entries(allWidgetInfo).forEach(([key,widgetInfo])=>{widgetsStartProps[key]=getRendererPropsForWidgetInfo(widgetInfo,strings,problemNum);});apiOptions?.onWidgetStartProps?.(widgetsStartProps);return widgetsStartProps},this._getDefaultWidgetInfo=widgetId=>{const widgetIdParts=Util.rTypeFromWidgetId.exec(widgetId);if(widgetIdParts==null){return {}}return {type:widgetIdParts[1],graded:true,options:{}}},this._getWidgetInfo=widgetId=>{return this.state.widgetInfo[widgetId]||this._getDefaultWidgetInfo(widgetId)},this.renderWidget=(impliedType,id,state)=>{const widgetInfo=this.state.widgetInfo[id];if(widgetInfo&&widgetInfo.alignment==="full-width"){state.foundFullWidth=true;}if(widgetInfo){const type=widgetInfo&&widgetInfo.type||impliedType;const shouldHighlight=_.contains(this.props.highlightedWidgets,id);return jsxRuntimeExports.jsx(WidgetContainer,{id:id,ref:node=>{const containerId=makeContainerId(id);if(node!=null){this._widgetContainers.set(containerId,node);}else {this._widgetContainers.delete(containerId);}},type:type,initialProps:this.getWidgetProps(id),shouldHighlight:shouldHighlight,linterContext:PerseusLinter.pushContextStack(this.props.linterContext,"widget")},makeContainerId(id))}return null},this.getSerializedState=widgetProps=>{return mapObject(widgetProps||this.state.widgetProps,(props,widgetId)=>{const widget=this.getWidgetInstance(widgetId);if(widget&&widget.getSerializedState){return widget.getSerializedState()}return props})},this.restoreSerializedState=(serializedState,callback)=>{const serializedWidgetIds=_.keys(serializedState);const widgetPropIds=_.keys(this.state.widgetProps);if(serializedWidgetIds.length!==widgetPropIds.length||_.intersection(serializedWidgetIds,widgetPropIds).length!==serializedWidgetIds.length){Log.error("Refusing to restore bad serialized state:",Errors.Internal,{loggedMetadata:{serializedState:JSON.stringify(serializedState),currentProps:JSON.stringify(this.state.widgetProps)}});return}let numCallbacks=1;const fireCallback=()=>{--numCallbacks;if(callback&&numCallbacks===0){callback();}};this.setState({widgetProps:mapObject(serializedState,(props,widgetId)=>{const widget=this.getWidgetInstance(widgetId);if(widget&&widget.restoreSerializedState){++numCallbacks;const restoreResult=widget.restoreSerializedState(props,fireCallback);return _.extend({},this.state.widgetProps[widgetId],restoreResult)}return props})},()=>{setTimeout(fireCallback,0);});},this.showRationalesForCurrentlySelectedChoices=()=>{Object.keys(this.props.widgets).forEach(widgetId=>{const widget=this.getWidgetInstance(widgetId);if(widget&&widget.showRationalesForCurrentlySelectedChoices){widget.showRationalesForCurrentlySelectedChoices(this._getWidgetInfo(widgetId).options);}});},this.deselectIncorrectSelectedChoices=()=>{Object.keys(this.props.widgets).forEach(widgetId=>{const widget=this.getWidgetInstance(widgetId);if(widget&&widget.deselectIncorrectSelectedChoices){widget.deselectIncorrectSelectedChoices();}});},this.findInternalWidgets=filterCriterion=>{let filterFunc;if(typeof filterCriterion==="string"){if(filterCriterion.indexOf(" ")!==-1){const widgetId=filterCriterion;filterFunc=(id,widgetInfo,widget)=>id===widgetId;}else {const widgetType=filterCriterion;filterFunc=(id,widgetInfo,widget)=>{return widgetInfo.type===widgetType};}}else {filterFunc=filterCriterion;}const results=this.widgetIds.filter(id=>{const widgetInfo=this._getWidgetInfo(id);const widget=this.getWidgetInstance(id);return filterFunc(id,widgetInfo,widget)}).map(this.getWidgetInstance);return results},this.findWidgets=filterCriterion=>{return [...this.findInternalWidgets(filterCriterion),...this.props.findExternalWidgets(filterCriterion)]},this.getWidgetInstance=id=>{const ref=this._widgetContainers.get(makeContainerId(id));if(!ref){return null}return ref.getWidget()},this._onWidgetFocus=(id,focusPath=[])=>{if(!_.isArray(focusPath)){throw new PerseusError("widget props.onFocus focusPath must be an Array, "+"but was"+JSON.stringify(focusPath),Errors.Internal)}this._setCurrentFocus([id].concat(focusPath));},this._onWidgetBlur=(id,blurPath)=>{const blurringFocusPath=this._currentFocus;const fullPath=[id].concat(blurPath);if(!_.isEqual(fullPath,blurringFocusPath)){return}_.defer(()=>{if(_.isEqual(this._currentFocus,blurringFocusPath)){this._setCurrentFocus(null);}});},this.getContent=(props,state)=>{return state.jiptContent||props.content},this.shouldRenderJiptPlaceholder=(props,state)=>{return getDependencies().JIPT.useJIPT&&state.jiptContent==null&&props.content.indexOf("crwdns")!==-1},this.replaceJiptContent=(content,paragraphIndex)=>{if(paragraphIndex==null){this.setState({jiptContent:content});}else {const codeFenceRegex=/^\s*(`{3,}|~{3,})\s*(\S+)?\s*\n([\s\S]+?)\s*\1\s*$/;if(codeFenceRegex.test(content));else if(/\S\n\s*\n\S/.test(content)){content="$\\large{\\red{\\text{Please translate each "+"paragraph to a single paragraph.}}}$";}else if(/^\s*$/.test(content)){content="$\\large{\\red{\\text{Translated paragraph is "+"currently empty}}}$";}const allContent=this.getContent(this.props,this.state);const paragraphs=JiptParagraphs.parseToArray(allContent);paragraphs[paragraphIndex]=content;this.setState({jiptContent:JiptParagraphs.joinFromArray(paragraphs)});}},this.outputMarkdown=(ast,state)=>{if(_.isArray(ast)){const oldKey=state.key;const result=[];let lastWasString=false;for(let i=0;i<ast.length;i++){state.key=i;state.paragraphIndex=i;const nodeOut=this.outputMarkdown(ast[i],state);const isString=typeof nodeOut==="string";if(typeof nodeOut==="string"&&lastWasString){result[result.length-1]+=nodeOut;}else {result.push(nodeOut);}lastWasString=isString;}state.key=oldKey;return result}this._foundTextNodes=false;state.foundFullWidth=false;const output=this.outputNested(ast,state);let className;if(this.translationIndex!=null){className=null;}else {className=classNames$1({"perseus-paragraph-centered":!this._foundTextNodes,"perseus-paragraph-full-width":state.foundFullWidth&&ast.content.length===1});}return jsxRuntimeExports.jsx(QuestionParagraph,{className:className,translationIndex:this.translationIndex,paragraphIndex:state.paragraphIndex,inline:this.props.inline,children:jsxRuntimeExports.jsx(ErrorBoundary,{children:output})},state.key)},this.outputNested=(ast,state)=>{if(_.isArray(ast)){const oldKey=state.key;const result=[];let lastWasString=false;for(let i=0;i<ast.length;i++){state.key=i;const nodeOut=this.outputNested(ast[i],state);const isString=typeof nodeOut==="string";if(typeof nodeOut==="string"&&lastWasString){result[result.length-1]+=nodeOut;}else {result.push(nodeOut);}lastWasString=isString;}state.key=oldKey;return result}return this.outputNode(ast,this.outputNested,state)},this.outputNode=(node,nestedOutput,state)=>{const apiOptions=this.getApiOptions();const imagePlaceholder=apiOptions.imagePlaceholder;if(node.type==="widget"){const widgetPlaceholder=apiOptions.widgetPlaceholder;if(widgetPlaceholder){return widgetPlaceholder}this._foundTextNodes=true;if(this.widgetIds.includes(node.id)){return jsxRuntimeExports.jsx("span",{className:"renderer-widget-error",children:["Widget [[","☃"," ",node.id,"]] already exists."].join("")},state.key)}this.widgetIds.push(node.id);return this.renderWidget(node.widgetType,node.id,state)}if(node.type==="blockMath"){const content=preprocessTex(node.content);const innerStyle={overflowX:"auto",overflowY:"hidden",paddingTop:10,paddingBottom:10,marginTop:-10,marginBottom:-10};if(apiOptions.isMobile){const margin=16;const outerStyle={marginLeft:-16,marginRight:-16};const horizontalPadding={paddingLeft:margin,paddingRight:margin};const mobileInnerStyle={...innerStyle,...styles$E.mobileZoomableParentFix};return jsxRuntimeExports.jsx("div",{className:"perseus-block-math",style:outerStyle,children:jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx("div",{className:"perseus-block-math-inner",style:{...mobileInnerStyle,...horizontalPadding},children:jsxRuntimeExports.jsx(ZoomableTeX,{children:content})})})},state.key)}return jsxRuntimeExports.jsx("div",{className:"perseus-block-math",children:jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx("div",{className:"perseus-block-math-inner",style:innerStyle,children:jsxRuntimeExports.jsx(context$1.Consumer,{children:({setAssetStatus})=>jsxRuntimeExports.jsx(Tex,{setAssetStatus:setAssetStatus,children:content})})})})},state.key)}if(node.type==="math"){const tex=node.content;return jsxRuntimeExports.jsx("span",{style:{whiteSpace:"nowrap"},children:jsxRuntimeExports.jsxs(ErrorBoundary,{children:[jsxRuntimeExports.jsx("span",{}),jsxRuntimeExports.jsx(context$1.Consumer,{children:({setAssetStatus})=>jsxRuntimeExports.jsx(Tex,{onRender:this.props.onRender,setAssetStatus:setAssetStatus,children:tex})}),jsxRuntimeExports.jsx("span",{})]})},state.key)}if(node.type==="image"){if(imagePlaceholder){return imagePlaceholder}const extraAttrs=_.has(this.props.images,node.target)?this.props.images[node.target]:null;const responsive=!state.inTable;return jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx(context$1.Consumer,{children:({setAssetStatus})=>jsxRuntimeExports.jsx(SvgImage,{setAssetStatus:setAssetStatus,src:PerseusMarkdown.sanitizeUrl(node.target),alt:node.alt,title:node.title,responsive:responsive,onUpdate:this.props.onRender,zoomToFullSizeOnMobile:apiOptions.isMobile&&apiOptions.isArticle,...extraAttrs})})},state.key)}if(node.type==="columns"){this._isTwoColumn=true;return jsxRuntimeExports.jsx(ErrorBoundary,{children:PerseusMarkdown.ruleOutput(node,nestedOutput,state)},state.key)}if(node.type==="text"){if(rContainsNonWhitespace.test(node.content)){this._foundTextNodes=true;}if(imagePlaceholder&&rImageURL.test(node.content)){return imagePlaceholder}return node.content}if(node.type==="table"||node.type==="titledTable"){const output=PerseusMarkdown.ruleOutput(node,nestedOutput,{...state,isMobile:apiOptions.isMobile,inTable:true});if(!apiOptions.isMobile){return output}const outerStyle={marginLeft:-16,marginRight:-16};const innerStyle={paddingLeft:0,paddingRight:0};const mobileInnerStyle={...innerStyle,...styles$E.mobileZoomableParentFix};const wrappedOutput=jsxRuntimeExports.jsx("div",{style:{...mobileInnerStyle,overflowX:"auto"},children:jsxRuntimeExports.jsx(ErrorBoundary,{children:jsxRuntimeExports.jsx(Zoomable,{animateHeight:true,children:output})})});return jsxRuntimeExports.jsx("div",{style:outerStyle,children:wrappedOutput})}return jsxRuntimeExports.jsx(ErrorBoundary,{children:PerseusMarkdown.ruleOutput(node,nestedOutput,state)},state.key)},this.handleRender=prevProps=>{const onRender=this.props.onRender;const oldOnRender=prevProps.onRender;if(onRender!==noopOnRender||oldOnRender!==noopOnRender){const $images=$(ReactDOM__default.findDOMNode(this)).find("img");if(oldOnRender!==noopOnRender){$images.off("load",oldOnRender);}if(onRender!==noopOnRender){$images.on("load",onRender);}}onRender();},this._setCurrentFocus=path=>{const apiOptions=this.getApiOptions();if(!isIdPathPrefix(path,this._currentFocus)){const prevFocus=this._currentFocus;if(prevFocus){this.blurPath(prevFocus);}this._currentFocus=path;apiOptions.onFocusChange(this._currentFocus,prevFocus);}},this.focus=()=>{let id;let focusResult;for(let i=0;i<this.widgetIds.length;i++){const widgetId=this.widgetIds[i];const widget=this.getWidgetInstance(widgetId);const widgetFocusResult=widget?.focus?.();if(widgetFocusResult){id=widgetId;focusResult=widgetFocusResult;break}}if(id){let path;if(typeof focusResult==="object"){path=[id].concat(focusResult.path||[]);Log.error("Renderer received a focus result of type 'object' "+"instead of the expected type 'boolean'",Errors.Internal,{loggedMetadata:{focusResult:JSON.stringify(focusResult),currentProps:JSON.stringify(this.state.widgetProps)}});}else {path=[id];}this._setCurrentFocus(path);return true}},this.getDOMNodeForPath=path=>{const widgetId=_.first(path);const interWidgetPath=_.rest(path);const widget=this.getWidgetInstance(widgetId);if(widget?.getDOMNodeForPath){return widget.getDOMNodeForPath(interWidgetPath)}if(interWidgetPath.length===0){return ReactDOM__default.findDOMNode(widget)}},this.getInputPaths=()=>{const inputPaths=[];this.widgetIds.forEach(widgetId=>{const widget=this.getWidgetInstance(widgetId);if(widget&&widget.getInputPaths){const widgetInputPaths=widget.getInputPaths();widgetInputPaths.forEach(inputPath=>{const relativeInputPath=[widgetId].concat(inputPath);inputPaths.push(relativeInputPath);});}});return inputPaths},this.focusPath=path=>{if(_.isEqual(this._currentFocus,path)){return}if(this._currentFocus){this.blurPath(this._currentFocus);}const widgetId=_.first(path);const interWidgetPath=_.rest(path);const focusWidget=this.getWidgetInstance(widgetId);focusWidget?.focusInputPath?.(interWidgetPath);},this.blurPath=path=>{if(!_.isEqual(this._currentFocus,path)){return}const widgetId=_.first(path);const interWidgetPath=_.rest(path);const widget=this.getWidgetInstance(widgetId);if(widget){const blurWidget=this.getWidgetInstance(widgetId);blurWidget?.blurInputPath?.(interWidgetPath);}},this.blur=()=>{if(this._currentFocus){this.blurPath(this._currentFocus);}},this.serialize=()=>{const state={};_.each(this.state.widgetInfo,function(info,id){const widget=this.getWidgetInstance(id);const s=widget.serialize();if(!_.isEmpty(s)){state[id]=s;}},this);return state},this._setWidgetProps=(id,newProps,cb,silent)=>{this.setState(prevState=>{const widgetProps={...prevState.widgetProps,[id]:{...prevState.widgetProps[id],...newProps}};const lastUsedWidgetId=silent?prevState.lastUsedWidgetId:id;if(!silent){this.props.onSerializedStateUpdated(this.getSerializedState(widgetProps));}return {lastUsedWidgetId,widgetProps}},()=>{setTimeout(()=>{const cbResult=cb&&cb();if(!silent){this.props.onInteractWithWidget(id);}if(cbResult!==false){this._setCurrentFocus([id]);}},0);});},this.setInputValue=(path,newValue,cb)=>{const widgetId=_.first(path);const interWidgetPath=_.rest(path);const widget=this.getWidgetInstance(widgetId);widget?.setInputValue?.(interWidgetPath,newValue,cb);},this.getWidgetIds=()=>{return this.widgetIds},this.handletranslationLintErrors=lintErrors=>{if(!this._isMounted){return}this.setState({translationLintErrors:lintErrors});};this._translationLinter=new TranslationLinter;this.state={jiptContent:null,translationLintErrors:[],lastUsedWidgetId:null,...this._getInitialWidgetState(props)};}}Renderer.contextType=PerseusI18nContext;Renderer.defaultProps={content:"",widgets:{},images:{},highlightedWidgets:[],questionCompleted:false,showSolutions:"none",onRender:noopOnRender,onInteractWithWidget:function(){},findExternalWidgets:()=>[],alwaysUpdate:false,reviewMode:false,serializedState:null,onSerializedStateUpdated:()=>{},linterContext:PerseusLinter.linterContextDefault};const styles$E={mobileZoomableParentFix:{transform:"translate3d(0,0,0)"}};
1679
1691
 
1680
- const{captureScratchpadTouchStart: captureScratchpadTouchStart$2}=Util;const InputWithExamples=forwardRef((props,ref)=>{const{shouldShowExamples=true,onFocus=()=>{},onBlur=()=>{},disabled=false,linterContext=PerseusLinter.linterContextDefault,className=""}=props;const context=React.useContext(PerseusI18nContext);const inputRef=React.useRef(null);const[inputFocused,setInputFocused]=React.useState(false);const id=useId();const ariaId=`aria-for-${id}`;useImperativeHandle(ref,()=>({current:inputRef.current,focus:()=>{if(inputRef.current){inputRef.current.focus();}},blur:()=>{if(inputRef.current){inputRef.current.blur();}}}));const getInputClassName=()=>{let inputClassName=ClassNames.INPUT;if(inputFocused){inputClassName+=" "+ClassNames.FOCUSED;}if(className){inputClassName+=" "+className;}return inputClassName};const handleFocus=()=>{onFocus();setInputFocused(true);};const handleBlur=()=>{onBlur();setInputFocused(false);};const renderInput=()=>{const examplesAria=props.shouldShowExamples?`${props.examples[0]}
1681
- ${props.examples.slice(1).join(", or\n")}`.replaceAll("*","").replaceAll("$","").replaceAll("\\ \\text{pi}"," pi").replaceAll("\\ "," and "):"";const inputProps={id:id,"aria-describedby":props.shouldShowExamples?ariaId:undefined,ref:inputRef,className:getInputClassName(),labelText:props.labelText,value:props.value,onFocus:handleFocus,onBlur:handleBlur,disabled:disabled,style:props.style,onChange:props.onChange,onTouchStart:captureScratchpadTouchStart$2,autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:"false"};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(TextInput,{...inputProps}),jsxRuntimeExports.jsx("span",{id:ariaId,style:{display:"none"},children:examplesAria})]})};const renderTooltipContent=()=>{return jsxRuntimeExports.jsx(TooltipContent,{children:jsxRuntimeExports.jsx("div",{id:id,className:"input-with-examples-tooltip",children:jsxRuntimeExports.jsx(Renderer,{content:examplesContent,linterContext:PerseusLinter.pushContextStack(linterContext,"input-with-examples"),strings:context.strings})})})};const examplesContent=props.examples.length<=2?props.examples.join(" "):props.examples.map((example,index)=>{return index===0&&example.startsWith("**")?`${example}
1692
+ const{captureScratchpadTouchStart: captureScratchpadTouchStart$3}=Util;const InputWithExamples=forwardRef((props,ref)=>{const{shouldShowExamples=true,onFocus=()=>{},onBlur=()=>{},disabled=false,linterContext=PerseusLinter.linterContextDefault,className=""}=props;const context=React.useContext(PerseusI18nContext);const inputRef=React.useRef(null);const[inputFocused,setInputFocused]=React.useState(false);const id=useId();const ariaId=`aria-for-${id}`;useImperativeHandle(ref,()=>({current:inputRef.current,focus:()=>{if(inputRef.current){inputRef.current.focus();}},blur:()=>{if(inputRef.current){inputRef.current.blur();}}}));const getInputClassName=()=>{let inputClassName=ClassNames.INPUT;if(inputFocused){inputClassName+=" "+ClassNames.FOCUSED;}if(className){inputClassName+=" "+className;}return inputClassName};const handleFocus=()=>{onFocus();setInputFocused(true);};const handleBlur=()=>{onBlur();setInputFocused(false);};const renderInput=()=>{const examplesAria=props.shouldShowExamples?`${props.examples[0]}
1693
+ ${props.examples.slice(1).join(", or\n")}`.replaceAll("*","").replaceAll("$","").replaceAll("\\ \\text{pi}"," pi").replaceAll("\\ "," and "):"";const inputProps={id:id,"aria-describedby":props.shouldShowExamples?ariaId:undefined,ref:inputRef,className:getInputClassName(),labelText:props.labelText,value:props.value,onFocus:handleFocus,onBlur:handleBlur,disabled:disabled,style:props.style,onChange:props.onChange,onTouchStart:captureScratchpadTouchStart$3,autoCapitalize:"off",autoComplete:"off",autoCorrect:"off",spellCheck:"false"};return jsxRuntimeExports.jsxs(jsxRuntimeExports.Fragment,{children:[jsxRuntimeExports.jsx(TextInput,{...inputProps}),jsxRuntimeExports.jsx("span",{id:ariaId,style:{display:"none"},children:examplesAria})]})};const renderTooltipContent=()=>{return jsxRuntimeExports.jsx(TooltipContent,{children:jsxRuntimeExports.jsx("div",{id:id,className:"input-with-examples-tooltip",children:jsxRuntimeExports.jsx(Renderer,{content:examplesContent,linterContext:PerseusLinter.pushContextStack(linterContext,"input-with-examples"),strings:context.strings})})})};const examplesContent=props.examples.length<=2?props.examples.join(" "):props.examples.map((example,index)=>{return index===0&&example.startsWith("**")?`${example}
1682
1694
  `:`- ${example}`}).join("\n");const showExamplesTooltip=shouldShowExamples&&inputFocused;return jsxRuntimeExports.jsx(Tooltip,{content:renderTooltipContent(),opened:showExamplesTooltip,placement:"bottom",children:renderInput()})});
1683
1695
 
1684
- const formExamples={integer:function(options,strings){return strings.integerExample},proper:function(options,strings){if(options.simplify==="optional"){return strings.properExample}return strings.simplifiedProperExample},improper:function(options,strings){if(options.simplify==="optional"){return strings.improperExample}return strings.simplifiedImproperExample},mixed:function(options,strings){return strings.mixedExample},decimal:function(options,strings){return strings.decimalExample},percent:function(options,strings){return strings.percentExample},pi:function(options,strings){return strings.piExample}};class InputNumber extends React.Component{static getUserInputFromProps(props){return {currentValue:props.currentValue}}getUserInput(){return InputNumber.getUserInputFromProps(this.props)}getPromptJSON(){return getPromptJSON$s(this.props,this.getUserInput())}examples(){const{strings}=this.context;const type=this.props.answerType;const forms=inputNumberAnswerTypes[type].forms.split(/\s*,\s*/);const examples=_.map(forms,form=>formExamples[form](this.props,strings));return [strings.yourAnswer].concat(examples)}render(){if(this.props.apiOptions.customKeypad){const input=jsxRuntimeExports.jsx(SimpleKeypadInput,{ref:"input",value:this.props.currentValue,keypadElement:this.props.keypadElement,onChange:this.handleChange,onFocus:this._handleFocus,onBlur:this._handleBlur});if(this.props.rightAlign){return jsxRuntimeExports.jsx("div",{className:"perseus-input-right-align",children:input})}return input}const inputStyles=[styles$z.default,this.props.size==="small"?styles$z.small:null,this.props.rightAlign?styles$z.rightAlign:styles$z.leftAlign];if(this.props.reviewMode&&!this.props.currentValue){inputStyles.push(styles$z.answerStateUnanswered);}return jsxRuntimeExports.jsx(InputWithExamples,{ref:"input",value:this.props.currentValue,onChange:this.handleChange,style:inputStyles,examples:this.examples(),shouldShowExamples:this.shouldShowExamples(),onFocus:this._handleFocus,onBlur:this._handleBlur,id:this.props.widgetId,disabled:this.props.apiOptions.readOnly,linterContext:this.props.linterContext})}constructor(...args){super(...args),this.shouldShowExamples=()=>{return this.props.answerType!=="number"},this.handleChange=(newValue,cb)=>{this.props.onChange({currentValue:newValue},cb);},this._handleFocus=()=>{this.props.onFocus([]);},this._handleBlur=()=>{this.props.onBlur([]);},this.focus=()=>{this.refs.input.focus();return true},this.focusInputPath=inputPath=>{this.refs.input.focus();},this.blurInputPath=inputPath=>{if(typeof this.refs.input?.blur==="function"){this.refs.input?.blur();}},this.getInputPaths=()=>{return [[]]},this.setInputValue=(path,newValue,cb)=>{this.props.onChange({currentValue:newValue},cb);};}}InputNumber.contextType=PerseusI18nContext;InputNumber.defaultProps={currentValue:"",size:"normal",answerType:"number",rightAlign:false,apiOptions:ApiOptions.defaults,linterContext:linterContextDefault};const styles$z=StyleSheet.create({default:{width:80,height:"auto"},small:{width:40},leftAlign:{paddingLeft:spacing.xxxSmall_4,paddingRight:0},rightAlign:{textAlign:"right",paddingLeft:0,paddingRight:spacing.xxxSmall_4},answerStateUnanswered:{backgroundColor:"#eee",border:"solid 1px #999"}});const propTransform$3=widgetOptions=>{const{simplify,size,answerType,rightAlign}=widgetOptions;return {simplify,size,answerType,rightAlign}};var InputNumber$1 = {name:"input-number",displayName:"Input number (deprecated - use numeric input instead)",hidden:true,widget:InputNumber,transform:propTransform$3,isLintable:true,getOneCorrectAnswerFromRubric(rubric){if(rubric.value==null){return}let answerString=String(rubric.value);if(rubric.inexact&&rubric.maxError){answerString+=" ± "+rubric.maxError;}return answerString}};
1696
+ const formExamples={integer:function(options,strings){return strings.integerExample},proper:function(options,strings){if(options.simplify==="optional"){return strings.properExample}return strings.simplifiedProperExample},improper:function(options,strings){if(options.simplify==="optional"){return strings.improperExample}return strings.simplifiedImproperExample},mixed:function(options,strings){return strings.mixedExample},decimal:function(options,strings){return strings.decimalExample},percent:function(options,strings){return strings.percentExample},pi:function(options,strings){return strings.piExample}};class InputNumber extends React.Component{static getUserInputFromProps(props){return {currentValue:props.currentValue}}getUserInput(){return InputNumber.getUserInputFromProps(this.props)}getPromptJSON(){return getPromptJSON$s(this.props,this.getUserInput())}examples(){const{strings}=this.context;const type=this.props.answerType;const forms=inputNumberAnswerTypes[type].forms.split(/\s*,\s*/);const examples=_.map(forms,form=>formExamples[form](this.props,strings));return [strings.yourAnswer].concat(examples)}render(){if(this.props.apiOptions.customKeypad){const input=jsxRuntimeExports.jsx(SimpleKeypadInput,{ref:"input",value:this.props.currentValue,keypadElement:this.props.keypadElement,onChange:this.handleChange,onFocus:this._handleFocus,onBlur:this._handleBlur});if(this.props.rightAlign){return jsxRuntimeExports.jsx("div",{className:"perseus-input-right-align",children:input})}return input}const inputStyles=[styles$D.default,this.props.size==="small"?styles$D.small:null,this.props.rightAlign?styles$D.rightAlign:styles$D.leftAlign];if(this.props.reviewMode&&!this.props.currentValue){inputStyles.push(styles$D.answerStateUnanswered);}return jsxRuntimeExports.jsx(InputWithExamples,{ref:"input",value:this.props.currentValue,onChange:this.handleChange,style:inputStyles,examples:this.examples(),shouldShowExamples:this.shouldShowExamples(),onFocus:this._handleFocus,onBlur:this._handleBlur,id:this.props.widgetId,disabled:this.props.apiOptions.readOnly,linterContext:this.props.linterContext})}constructor(...args){super(...args),this.shouldShowExamples=()=>{return this.props.answerType!=="number"},this.handleChange=(newValue,cb)=>{this.props.onChange({currentValue:newValue},cb);},this._handleFocus=()=>{this.props.onFocus([]);},this._handleBlur=()=>{this.props.onBlur([]);},this.focus=()=>{this.refs.input.focus();return true},this.focusInputPath=inputPath=>{this.refs.input.focus();},this.blurInputPath=inputPath=>{if(typeof this.refs.input?.blur==="function"){this.refs.input?.blur();}},this.getInputPaths=()=>{return [[]]},this.setInputValue=(path,newValue,cb)=>{this.props.onChange({currentValue:newValue},cb);};}}InputNumber.contextType=PerseusI18nContext;InputNumber.defaultProps={currentValue:"",size:"normal",answerType:"number",rightAlign:false,apiOptions:ApiOptions.defaults,linterContext:linterContextDefault};const styles$D=StyleSheet.create({default:{width:80,height:"auto"},small:{width:40},leftAlign:{paddingLeft:spacing.xxxSmall_4,paddingRight:0},rightAlign:{textAlign:"right",paddingLeft:0,paddingRight:spacing.xxxSmall_4},answerStateUnanswered:{backgroundColor:"#eee",border:"solid 1px #999"}});const propTransform$3=widgetOptions=>{const{simplify,size,answerType,rightAlign}=widgetOptions;return {simplify,size,answerType,rightAlign}};var InputNumber$1 = {name:"input-number",displayName:"Input number (deprecated - use numeric input instead)",hidden:true,widget:InputNumber,transform:propTransform$3,isLintable:true,getOneCorrectAnswerFromRubric(rubric){if(rubric.value==null){return}let answerString=String(rubric.value);if(rubric.inexact&&rubric.maxError){answerString+=" ± "+rubric.maxError;}return answerString}};
1685
1697
 
1686
1698
  const getPromptJSON$r=(renderProps,userInput)=>{return {type:"numeric-input",label:renderProps.labelText,userInput:{value:userInput.currentValue}}};
1687
1699
 
@@ -1701,9 +1713,9 @@ function addHighlight(existingHighlights,newHighlight){const newHighlights={};le
1701
1713
 
1702
1714
  function getRelativePosition(child,parent){return {left:child.left-parent.left,top:child.top-parent.top}}function getRelativeRect({left,top,width,height},parent){return {...getRelativePosition({left,top},parent),width,height}}function getClientRectsForTextInRange(range){const mutableRects=[];addClientRectsForTextInNodeAndRange(range.commonAncestorContainer,range,mutableRects);return mutableRects}function addClientRectsForTextInNodeAndRange(node,range,mutableRects){const nodeContentsRange=new Range;nodeContentsRange.selectNodeContents(node);if(node.nodeType===Node.TEXT_NODE){const intersectedRange=intersectRanges(range,nodeContentsRange);if(intersectedRange){addClientRectsForText(node,intersectedRange,mutableRects);}}else if(node.nodeType===Node.ELEMENT_NODE){if(!rangesOverlap(range,nodeContentsRange)){return}for(const child of Array.from(node.childNodes)){addClientRectsForTextInNodeAndRange(child,range,mutableRects);}}}function addClientRectsForText(textNode,textRange,mutableRects){const parentElement=textNode.parentElement;const computedStyle=window.getComputedStyle(parentElement);let lineHeight=null;if(typeof computedStyle.lineHeight==="string"&&computedStyle.lineHeight.endsWith("px")){const parsedLineHeight=parseFloat(computedStyle.lineHeight);if(!isNaN(parsedLineHeight)){lineHeight=parsedLineHeight;}}const boundingRects=Array.from(textRange.getClientRects());for(const boundingRect of boundingRects){const rect={left:boundingRect.left,top:boundingRect.top,height:boundingRect.height,width:boundingRect.width};if(lineHeight!==null){const heightIncrease=lineHeight-rect.height;rect.top-=heightIncrease;rect.height=lineHeight;}mutableRects.push(rect);}}
1703
1715
 
1704
- class HighlightRenderer extends React.PureComponent{UNSAFE_componentWillReceiveProps(nextProps){if(this.props.highlight!==nextProps.highlight||this.props.offsetParent!==nextProps.offsetParent){this.setState({cachedHighlightRects:this._computeRects(nextProps)});}}_computeRects(props){const{highlight,offsetParent}=props;const clientRects=getClientRectsForTextInRange(highlight.domRange);const{left,top}=offsetParent.getBoundingClientRect();const relativeRects=clientRects.map(rect=>getRelativeRect(rect,{left,top}));return relativeRects}_rectIsHovered(rect,mouseOffsetPosition){const positionWithinRect=getRelativePosition(mouseOffsetPosition,{left:rect.left,top:rect.top});return 0<=positionWithinRect.left&&positionWithinRect.left<rect.width&&0<=positionWithinRect.top&&positionWithinRect.top<rect.height}isHovered(mouseClientPosition){if(!mouseClientPosition){return false}const{offsetParent}=this.props;const{cachedHighlightRects}=this.state;const{left,top}=offsetParent.getBoundingClientRect();const mouseOffsetPosition=getRelativePosition(mouseClientPosition,{left,top});return cachedHighlightRects.some(rect=>this._rectIsHovered(rect,mouseOffsetPosition))}render(){const rects=this.state.cachedHighlightRects;return jsxRuntimeExports.jsx("div",{children:rects.map((rect,index)=>jsxRuntimeExports.jsx("div",{className:css(styles$y.highlightRect),style:{position:"absolute",width:rect.width,height:rect.height,top:rect.top,left:rect.left,zIndex:this.props.zIndexes.belowContent}},index))})}constructor(...args){super(...args),this.state={cachedHighlightRects:this._computeRects(this.props),tooltipIsHovered:false};}}const styles$y=StyleSheet.create({highlightRect:{background:"#fffabe"}});
1716
+ class HighlightRenderer extends React.PureComponent{UNSAFE_componentWillReceiveProps(nextProps){if(this.props.highlight!==nextProps.highlight||this.props.offsetParent!==nextProps.offsetParent){this.setState({cachedHighlightRects:this._computeRects(nextProps)});}}_computeRects(props){const{highlight,offsetParent}=props;const clientRects=getClientRectsForTextInRange(highlight.domRange);const{left,top}=offsetParent.getBoundingClientRect();const relativeRects=clientRects.map(rect=>getRelativeRect(rect,{left,top}));return relativeRects}_rectIsHovered(rect,mouseOffsetPosition){const positionWithinRect=getRelativePosition(mouseOffsetPosition,{left:rect.left,top:rect.top});return 0<=positionWithinRect.left&&positionWithinRect.left<rect.width&&0<=positionWithinRect.top&&positionWithinRect.top<rect.height}isHovered(mouseClientPosition){if(!mouseClientPosition){return false}const{offsetParent}=this.props;const{cachedHighlightRects}=this.state;const{left,top}=offsetParent.getBoundingClientRect();const mouseOffsetPosition=getRelativePosition(mouseClientPosition,{left,top});return cachedHighlightRects.some(rect=>this._rectIsHovered(rect,mouseOffsetPosition))}render(){const rects=this.state.cachedHighlightRects;return jsxRuntimeExports.jsx("div",{children:rects.map((rect,index)=>jsxRuntimeExports.jsx("div",{className:css(styles$C.highlightRect),style:{position:"absolute",width:rect.width,height:rect.height,top:rect.top,left:rect.left,zIndex:this.props.zIndexes.belowContent}},index))})}constructor(...args){super(...args),this.state={cachedHighlightRects:this._computeRects(this.props),tooltipIsHovered:false};}}const styles$C=StyleSheet.create({highlightRect:{background:"#fffabe"}});
1705
1717
 
1706
- class HighlightTooltip extends React.PureComponent{_getFocusRect(){const{focusNode,focusOffset,offsetParent}=this.props;const focusRange=document.createRange();focusRange.setStart(focusNode,focusOffset);focusRange.setEnd(focusNode,focusOffset);const focusRect=focusRange.getClientRects()[0];if(!focusRect){Log.log("[Highlighting] Known bug: Could not determine the focus "+'position, so did not show an "Add Highlight" tooltip. '+"https://app.asana.com/0/329800276300868/413878480039713 "+"(see also /r/asana-links)");return null}const{left,top}=offsetParent.getBoundingClientRect();const relativeFocusRect=getRelativeRect({left:focusRect.left,top:focusRect.top,width:focusRect.width,height:focusRect.height},{left,top});return relativeFocusRect}render(){const focusRect=this._getFocusRect();if(!focusRect){return null}const content=jsxRuntimeExports.jsx("div",{className:css(styles$x.tooltipLabel),onClick:this.props.onClick,children:this.props.label});const style={position:"absolute",left:focusRect.left,top:`calc(${Math.round(focusRect.top)}px + 0.95em)`,height:0};return jsxRuntimeExports.jsx("div",{style:style,onMouseEnter:this.props.onMouseEnter,onMouseLeave:this.props.onMouseLeave,children:jsxRuntimeExports.jsx(Tooltip,{content:content,opened:true,children:jsxRuntimeExports.jsx("div",{})})})}}const styles$x=StyleSheet.create({tooltipLabel:{userSelect:"none",fontFamily:`"Lato", sans-serif`,padding:`10px ${spacing.medium_16}px`,cursor:"pointer"}});
1718
+ class HighlightTooltip extends React.PureComponent{_getFocusRect(){const{focusNode,focusOffset,offsetParent}=this.props;const focusRange=document.createRange();focusRange.setStart(focusNode,focusOffset);focusRange.setEnd(focusNode,focusOffset);const focusRect=focusRange.getClientRects()[0];if(!focusRect){Log.log("[Highlighting] Known bug: Could not determine the focus "+'position, so did not show an "Add Highlight" tooltip. '+"https://app.asana.com/0/329800276300868/413878480039713 "+"(see also /r/asana-links)");return null}const{left,top}=offsetParent.getBoundingClientRect();const relativeFocusRect=getRelativeRect({left:focusRect.left,top:focusRect.top,width:focusRect.width,height:focusRect.height},{left,top});return relativeFocusRect}render(){const focusRect=this._getFocusRect();if(!focusRect){return null}const content=jsxRuntimeExports.jsx("div",{className:css(styles$B.tooltipLabel),onClick:this.props.onClick,children:this.props.label});const style={position:"absolute",left:focusRect.left,top:`calc(${Math.round(focusRect.top)}px + 0.95em)`,height:0};return jsxRuntimeExports.jsx("div",{style:style,onMouseEnter:this.props.onMouseEnter,onMouseLeave:this.props.onMouseLeave,children:jsxRuntimeExports.jsx(Tooltip,{content:content,opened:true,children:jsxRuntimeExports.jsx("div",{})})})}}const styles$B=StyleSheet.create({tooltipLabel:{userSelect:"none",fontFamily:`"Lato", sans-serif`,padding:`10px ${spacing.medium_16}px`,cursor:"pointer"}});
1707
1719
 
1708
1720
  class HighlightSetRenderer extends React.PureComponent{componentDidMount(){this._updateEditListeners(false,this.props.editable);}UNSAFE_componentWillReceiveProps(nextProps){this._updateEditListeners(this.props.editable,nextProps.editable);if(this.state.hoveredHighlightKey!=null&&!(this.state.hoveredHighlightKey in nextProps.highlights)){this.setState({hoveredHighlightKey:null});}if(this.state.hoveringTooltipFor!=null&&!(this.state.hoveringTooltipFor in nextProps.highlights)){this.setState({hoveringTooltipFor:null});}}componentWillUnmount(){this._updateEditListeners(this.props.editable,false);}_updateEditListeners(wasListening,willListen){if(!wasListening&&willListen){window.addEventListener("mousemove",this._handleMouseMove);}else if(wasListening&&!willListen){window.removeEventListener("mousemove",this._handleMouseMove);this.setState({hoveredHighlightKey:null,hoveringTooltipFor:null});}}_getHoveredHighlightKey(mouseClientPosition){const{hoveringTooltipFor}=this.state;if(typeof hoveringTooltipFor==="string"){return hoveringTooltipFor}const highlightKeys=Object.keys(this.props.highlights);return highlightKeys.find(key=>{const highlightRenderer=this._highlightRenderers[key];return highlightRenderer&&highlightRenderer.isHovered(mouseClientPosition)})}_renderTooltip(){const{hoveredHighlightKey}=this.state;if(hoveredHighlightKey==null){return null}const hoveredHighlight=this.props.highlights[hoveredHighlightKey];return jsxRuntimeExports.jsx(HighlightTooltip,{label:this.context.strings.removeHighlight,focusNode:hoveredHighlight.domRange.endContainer,focusOffset:hoveredHighlight.domRange.endOffset,offsetParent:this.props.offsetParent,onClick:()=>this.props.onRemoveHighlight(hoveredHighlightKey),onMouseEnter:()=>this.setState({hoveringTooltipFor:hoveredHighlightKey}),onMouseLeave:()=>this.setState({hoveringTooltipFor:null})})}render(){return jsxRuntimeExports.jsxs("div",{children:[Object.keys(this.props.highlights).map(key=>jsxRuntimeExports.jsx(HighlightRenderer,{ref:r=>{if(r){this._highlightRenderers[key]=r;}else {delete this._highlightRenderers[key];}},highlight:this.props.highlights[key],highlightKey:key,offsetParent:this.props.offsetParent,zIndexes:this.props.zIndexes},key)),this.props.editable&&this._renderTooltip()]})}constructor(...args){super(...args),this.state={hoveredHighlightKey:null,hoveringTooltipFor:null},this._highlightRenderers={},this._handleMouseMove=e=>{const mouseClientPosition={left:e.clientX,top:e.clientY};const hoveredHighlightKey=this._getHoveredHighlightKey(mouseClientPosition);this.setState({hoveredHighlightKey});};}}HighlightSetRenderer.contextType=PerseusI18nContext;
1709
1721
 
@@ -1713,13 +1725,13 @@ class HighlightingUI extends React.PureComponent{_handleAddHighlight(highlightTo
1713
1725
 
1714
1726
  class WordIndexer extends React.PureComponent{componentDidMount(){this._sendWordsUpdate();}componentDidUpdate(){this._sendWordsUpdate();}_sendWordsUpdate(){this.props.onWordsUpdate(this._getWordRanges());}_getWordRanges(){const container=this._container;if(!container){throw new PerseusError("invariant violation: `this._container` is not defined, but "+"this method is only called after mount/update",Errors.NotAllowed)}const treeWalker=container.ownerDocument.createTreeWalker(container,NodeFilter.SHOW_TEXT|NodeFilter.SHOW_ELEMENT,()=>NodeFilter.FILTER_ACCEPT,false);const index=[];let trailingWordRange=null;while(treeWalker.nextNode()){const node=treeWalker.currentNode;if(node.nodeType===Node.ELEMENT_NODE){const element=node;if(getComputedStyle(element).display!=="inline"){trailingWordRange=null;}}else if(node.nodeType===Node.TEXT_NODE){const text=node.nodeValue;const wordPattern=/\S+/g;let wordMatch;let newTrailingWordRange=null;while((wordMatch=wordPattern.exec(text))!==null){const startOffset=wordMatch.index;const endOffset=wordMatch.index+wordMatch[0].length;let range;if(startOffset===0&&trailingWordRange){range=trailingWordRange;range.setEnd(node,endOffset);}else {range=node.ownerDocument.createRange();range.setStart(node,startOffset);range.setEnd(node,endOffset);index.push(range);}if(endOffset===text.length){newTrailingWordRange=range;}}trailingWordRange=newTrailingWordRange;}}return index}render(){return jsxRuntimeExports.jsx("div",{ref:container=>this._container=container,children:this.props.children})}}
1715
1727
 
1716
- class HighlightableContent extends React.PureComponent{_buildHighlight(highlightRange){return buildHighlight(this._getDOMHighlights(),this.state.wordRanges,highlightRange)}_getDOMHighlights(){const{serializedHighlights}=this.props;const{wordRanges}=this.state;const domHighlights={};for(const key of Object.keys(serializedHighlights)){domHighlights[key]=deserializeHighlight(serializedHighlights[key],wordRanges);}return domHighlights}render(){const highlights=this._getDOMHighlights();const buildHighlight=r=>this._buildHighlight(r);return jsxRuntimeExports.jsxs("div",{className:css(styles$w.container),ref:container=>this._container=container,children:[jsxRuntimeExports.jsx("div",{children:this.props.enabled&&this._container&&this._content&&jsxRuntimeExports.jsx(HighlightingUI,{buildHighlight:buildHighlight,contentNode:this._content,editable:this.props.editable,highlights:highlights,offsetParent:this._container,zIndexes:{belowContent:0},onAddHighlight:this._handleAddHighlight,onRemoveHighlight:this._handleRemoveHighlight})}),jsxRuntimeExports.jsx("div",{className:css(styles$w.content),ref:content=>this._content=content,children:jsxRuntimeExports.jsx(WordIndexer,{onWordsUpdate:this._handleWordsUpdate,children:this.props.children})})]})}constructor(...args){super(...args),this.state={wordRanges:[]},this._handleAddHighlight=highlight=>{const newDomHighlights=addHighlight(this._getDOMHighlights(),highlight);const newSerializedHighlights={};for(const key of Object.keys(newDomHighlights)){newSerializedHighlights[key]=serializeHighlight(newDomHighlights[key]);}this.props.onSerializedHighlightsUpdate(newSerializedHighlights);},this._handleRemoveHighlight=keyToRemove=>{const{serializedHighlights}=this.props;const newSerializedHighlights={...serializedHighlights};delete newSerializedHighlights[keyToRemove];this.props.onSerializedHighlightsUpdate(newSerializedHighlights);},this._handleWordsUpdate=wordRanges=>{this.setState({wordRanges});};}}const styles$w=StyleSheet.create({container:{position:"relative",zIndex:0},content:{position:"relative",zIndex:1}});
1728
+ class HighlightableContent extends React.PureComponent{_buildHighlight(highlightRange){return buildHighlight(this._getDOMHighlights(),this.state.wordRanges,highlightRange)}_getDOMHighlights(){const{serializedHighlights}=this.props;const{wordRanges}=this.state;const domHighlights={};for(const key of Object.keys(serializedHighlights)){domHighlights[key]=deserializeHighlight(serializedHighlights[key],wordRanges);}return domHighlights}render(){const highlights=this._getDOMHighlights();const buildHighlight=r=>this._buildHighlight(r);return jsxRuntimeExports.jsxs("div",{className:css(styles$A.container),ref:container=>this._container=container,children:[jsxRuntimeExports.jsx("div",{children:this.props.enabled&&this._container&&this._content&&jsxRuntimeExports.jsx(HighlightingUI,{buildHighlight:buildHighlight,contentNode:this._content,editable:this.props.editable,highlights:highlights,offsetParent:this._container,zIndexes:{belowContent:0},onAddHighlight:this._handleAddHighlight,onRemoveHighlight:this._handleRemoveHighlight})}),jsxRuntimeExports.jsx("div",{className:css(styles$A.content),ref:content=>this._content=content,children:jsxRuntimeExports.jsx(WordIndexer,{onWordsUpdate:this._handleWordsUpdate,children:this.props.children})})]})}constructor(...args){super(...args),this.state={wordRanges:[]},this._handleAddHighlight=highlight=>{const newDomHighlights=addHighlight(this._getDOMHighlights(),highlight);const newSerializedHighlights={};for(const key of Object.keys(newDomHighlights)){newSerializedHighlights[key]=serializeHighlight(newDomHighlights[key]);}this.props.onSerializedHighlightsUpdate(newSerializedHighlights);},this._handleRemoveHighlight=keyToRemove=>{const{serializedHighlights}=this.props;const newSerializedHighlights={...serializedHighlights};delete newSerializedHighlights[keyToRemove];this.props.onSerializedHighlightsUpdate(newSerializedHighlights);},this._handleWordsUpdate=wordRanges=>{this.setState({wordRanges});};}}const styles$A=StyleSheet.create({container:{position:"relative",zIndex:0},content:{position:"relative",zIndex:1}});
1717
1729
 
1718
1730
  const getPromptJSON$o=renderProps=>{return {type:"passage",options:{passageTitle:renderProps.passageTitle,passageText:renderProps.passageText,footnotes:renderProps.footnotes}}};
1719
1731
 
1720
1732
  function getInitialParseState(){return {currentRef:[],useRefs:true,lastRef:0,firstSentenceRef:null,firstQuestionRef:null,lastFootnote:{id:0,text:""}}}class RefStart extends React.Component{render(){return jsxRuntimeExports.jsx("span",{style:REF_STYLE,children:"_"})}constructor(...args){super(...args),this.getRefContent=()=>{return this.props.refContent};}}class RefEnd extends React.Component{render(){return jsxRuntimeExports.jsx("span",{style:REF_STYLE,children:"_"})}}const AltText=({id,number})=>{const{strings}=usePerseusI18n();return jsxRuntimeExports.jsx("span",{className:"perseus-sr-only",children:strings[id]({number})},"alt-text")};const rules={newline:SimpleMarkdown.defaultRules.newline,paragraph:SimpleMarkdown.defaultRules.paragraph,escape:SimpleMarkdown.defaultRules.escape,passageFootnote:{order:SimpleMarkdown.defaultRules.escape.order+.1,match:SimpleMarkdown.inlineRegex(/^\^/),parse:(capture,parse,state)=>{const id=state.lastFootnote.id+1;const footnote={id:id,text:id===1?"*":""+id};if(state.lastFootnote.text==="*"){state.lastFootnote.text=""+state.lastFootnote.id;}state.lastFootnote=footnote;return footnote},react:(node,output,state)=>{return jsxRuntimeExports.jsx("sup",{children:node.text},state.key)}},refStart:{order:SimpleMarkdown.defaultRules.escape.order+.2,match:function(source){const capture=/^\{\{/.exec(source);if(capture){let closeIndex=2;let refNestingLevel=0;while(closeIndex<source.length){const token=source.slice(closeIndex,closeIndex+2);if(token==="{{"){refNestingLevel++;closeIndex++;}else if(token==="}}"){if(refNestingLevel>0){refNestingLevel--;closeIndex++;}else {break}}closeIndex++;}capture[1]=source.slice(2,closeIndex);return capture}return null},parse:(capture,parse,state)=>{if(!state.useRefs){return {ref:null,refContent:null}}const ref=state.lastRef+1;state.lastRef=ref;state.currentRef.push(ref);const refContent=parse("(“"+capture[1]+"”)\n\n",_.defaults({useRefs:false},getInitialParseState()));return {ref:ref,refContent:refContent}},react:(node,output,state)=>{const ref=node.ref;if(ref==null){return null}const refContent=output(node.refContent,{});return jsxRuntimeExports.jsx(RefStart,{ref:START_REF_PREFIX+ref,refContent:refContent},START_REF_PREFIX+ref)}},refEnd:{order:SimpleMarkdown.defaultRules.escape.order+.3,match:SimpleMarkdown.inlineRegex(/^\}\}/),parse:(capture,parse,state)=>{if(!state.useRefs){return {ref:null}}const ref=state.currentRef.pop()||null;return {ref:ref}},react:(node,output,state)=>{if(node.ref!=null){return jsxRuntimeExports.jsx(RefEnd,{ref:END_REF_PREFIX+node.ref},END_REF_PREFIX+node.ref)}return null}},squareLabel:{order:SimpleMarkdown.defaultRules.escape.order+.4,match:SimpleMarkdown.inlineRegex(/^\[\[(\w+)\]\]( *)/),parse:(capture,parse,state)=>{if(!state.firstQuestionRef){state.firstQuestionRef=capture[1];}return {content:capture[1],space:capture[2].length>0}},react:(node,output,state)=>{return [jsxRuntimeExports.jsx("span",{className:"perseus-passage-square-label",style:LABEL_OUTER_STYLE,"aria-hidden":"true",children:jsxRuntimeExports.jsx("span",{style:SQUARE_LABEL_STYLE,children:node.content})},"visual-square"),jsxRuntimeExports.jsx(AltText,{id:"questionMarker",number:node.content},"alt-text"),node.space?" ":null]}},circleLabel:{order:SimpleMarkdown.defaultRules.escape.order+.5,match:SimpleMarkdown.inlineRegex(/^\(\((\w+)\)\)( *)/),parse:(capture,parse,state)=>{return {content:capture[1],space:capture[2].length>0}},react:(node,output,state)=>{return [jsxRuntimeExports.jsx("span",{className:"perseus-passage-circle-label",style:LABEL_OUTER_STYLE,"aria-hidden":true,children:jsxRuntimeExports.jsx("span",{style:CIRCLE_LABEL_STYLE,children:node.content})},"visual-circle"),jsxRuntimeExports.jsx(AltText,{id:"circleMarker",number:node.content},"alt-text"),node.space?" ":null]}},squareBracketRef:{order:SimpleMarkdown.defaultRules.escape.order+.6,match:SimpleMarkdown.inlineRegex(/^\[(\d+)\]( *)/),parse:(capture,parse,state)=>{if(!state.firstSentenceRef){state.firstSentenceRef=capture[1];}return {content:capture[1],space:capture[2].length>0}},react:(node,output,state)=>{return [jsxRuntimeExports.jsxs("span",{className:"perseus-passage-bracket-label","aria-hidden":"true",children:["[",node.content,"]"]},"visual-brackets"),jsxRuntimeExports.jsx(AltText,{id:"sentenceMarker",number:node.content},"alt-text"),node.space?" ":null]}},highlight:{order:SimpleMarkdown.defaultRules.escape.order+.7,match:SimpleMarkdown.inlineRegex(/^{highlighting.start}(.+?){highlighting.end}/),parse:(capture,parse,state)=>{return {content:capture[1]}},react:(node,output,state)=>{return [jsxRuntimeExports.jsx("span",{className:"perseus-highlight",children:node.content},0)]}},reviewHighlight:{order:SimpleMarkdown.defaultRules.escape.order+.7,match:SimpleMarkdown.inlineRegex(/^{review-highlighting.start}(.+?){review-highlighting.end}/),parse:(capture,parse,state)=>{return {content:capture[1]}},react:(node,output,state)=>{return [jsxRuntimeExports.jsx("span",{className:"perseus-review-highlight",children:node.content},0)]}},strong:SimpleMarkdown.defaultRules.strong,u:SimpleMarkdown.defaultRules.u,em:SimpleMarkdown.defaultRules.em,del:SimpleMarkdown.defaultRules.del,text:{...SimpleMarkdown.defaultRules.text,react(node,output,state){return jsxRuntimeExports.jsx("span",{children:node.content},state.key)}}};const START_REF_PREFIX="start-ref-";const END_REF_PREFIX="end-ref-";const REF_STYLE={display:"inline-block",width:0,visibility:"hidden"};const LABEL_OUTER_STYLE={display:"inline",whiteSpace:"nowrap"};const SQUARE_LABEL_STYLE={display:"inline-block",color:"rgb(255, 255, 255)",backgroundColor:"rgb(90, 90, 90)",paddingLeft:10,paddingRight:10,userSelect:"none",WebkitUserSelect:"none"};const CIRCLE_LABEL_STYLE={display:"inline-block",color:"rgb(255, 255, 255)",backgroundColor:"rgb(90, 90, 90)",userSelect:"none",WebkitUserSelect:"none",width:22,height:22,borderRadius:"50%",textAlign:"center"};const builtParser=SimpleMarkdown.parserFor(rules);const parse$2=(source,state)=>{state=state||{};const paragraphedSource=source+"\n\n";return builtParser(paragraphedSource,_.extend(state,getInitialParseState()))};const output=SimpleMarkdown.reactFor(SimpleMarkdown.ruleOutput(rules,"react"));var PassageMarkdown = {parse: parse$2,output,START_REF_PREFIX,END_REF_PREFIX,getInitialParseState};
1721
1733
 
1722
- class LineHeightMeasurer extends React.Component{measureLineHeight(){if(!this._line){return 0}return this._line.clientHeight}render(){return jsxRuntimeExports.jsx("div",{className:css(styles$v.measurer),"aria-hidden":"true",children:jsxRuntimeExports.jsx("div",{ref:ref=>this._line=ref,className:"paragraph",children:"Line Height Measurement"})})}}const styles$v=StyleSheet.create({measurer:{position:"absolute",top:0,left:0,visibility:"hidden",zIndex:-1}});class Passage extends React.Component{componentDidMount(){this._updateState();this._onResize=_.throttle(()=>{if(this.shouldRenderJipt()){return}this._lineHeightMeasurerRef?.measureLineHeight();this._updateState();},500);window.addEventListener("resize",this._onResize);this._stylesAppiedTimer=window.setTimeout(()=>{this.setState({stylesAreApplied:true});},0);}shouldComponentUpdate(nextProps,nextState){return !_.isEqual(this.props,nextProps)||!_.isEqual(this.state,nextState)}componentDidUpdate(){this._updateState();}componentWillUnmount(){window.removeEventListener("resize",this._onResize);clearTimeout(this._stylesAppiedTimer);}_updateState(){if(this.shouldRenderJipt()){return}this.setState({nLines:this._measureLines(),startLineNumbersAfter:this._getInitialLineNumber()});}_measureLines(){const renderer=ReactDOM.findDOMNode(this._contentRef);const contentsHeight=$(renderer).height();const lineHeight=this._getLineHeight();const nLines=Math.round(contentsHeight/lineHeight);return nLines}_getInitialLineNumber(){let isPassageBeforeThisPassage=true;const passagesBeforeUs=this.props.findWidgets((id,widgetInfo)=>{if(widgetInfo.type!=="passage"){return false}if(id===this.props.widgetId){isPassageBeforeThisPassage=false;}return isPassageBeforeThisPassage}).filter(isPassageWidget);return passagesBeforeUs.map(passageWidget=>{return passageWidget.getLineCount()}).reduce((a,b)=>a+b,0)}_getLineHeight(){return this._lineHeightMeasurerRef?.measureLineHeight()||0}getLineCount(){if(this.state.nLines!=null){return this.state.nLines}return this._measureLines()}_getStartRefLineNumber(referenceNumber){const refRef=PassageMarkdown.START_REF_PREFIX+referenceNumber;const ref=this.refs[refRef];if(!ref){return null}const $ref=$(ReactDOM.findDOMNode(ref));let $refText=$ref.next();if($refText.length===0){$refText=$ref;}const vPos=$refText.offset().top;return this.state.startLineNumbersAfter+1+this._convertPosToLineNumber(vPos)}_getEndRefLineNumber(referenceNumber){const refRef=PassageMarkdown.END_REF_PREFIX+referenceNumber;const ref=this.refs[refRef];if(!ref){return null}const $ref=$(ReactDOM.findDOMNode(ref));let $refText=$ref.prev();if($refText.length===0){$refText=$ref;}const height=$refText.height();const vPos=$refText.offset().top;let line=this._convertPosToLineNumber(vPos+height);if(height===0){line+=1;}return this.state.startLineNumbersAfter+line}_convertPosToLineNumber(absoluteVPos){const content=ReactDOM.findDOMNode(this._contentRef);const relativeVPos=absoluteVPos-$(content).offset().top;const lineHeight=this._getLineHeight();const line=Math.round(relativeVPos/lineHeight);return line}_getRefContent(referenceNumber){const refRef=PassageMarkdown.START_REF_PREFIX+referenceNumber;const ref=this.refs[refRef];if(!ref){return null}return ref.getRefContent()}getReference(referenceNumber){const refStartLine=this._getStartRefLineNumber(referenceNumber);const refEndLine=this._getEndRefLineNumber(referenceNumber);if(refStartLine==null||refEndLine==null){return null}const refContent=this._getRefContent(referenceNumber);return {startLine:refStartLine,endLine:refEndLine,content:refContent}}getPromptJSON(){return getPromptJSON$o(this.props)}_renderInstructions(parseState){const firstQuestionNumber=parseState.firstQuestionRef;const firstSentenceRef=parseState.firstSentenceRef;const{strings}=this.context;let instructions="";if(firstQuestionNumber){instructions+=strings.symbolPassage({questionSymbol:"[["+firstQuestionNumber+"]]",questionNumber:firstQuestionNumber});}if(firstSentenceRef){instructions+=strings.symbolQuestion({sentenceSymbol:"["+firstSentenceRef+"]"});}const parsedInstructions=PassageMarkdown.parse(instructions);return jsxRuntimeExports.jsx("div",{className:"perseus-widget-passage-instructions",children:PassageMarkdown.output(parsedInstructions)})}shouldRenderJipt(){const{JIPT}=getDependencies();return JIPT.useJIPT&&this.props.passageText.indexOf("crwdns")!==-1}_renderContent(parsed){const enabled=this.state.stylesAreApplied;const editable=!this.props.reviewMode;return jsxRuntimeExports.jsx(HighlightableContent,{editable:editable,enabled:enabled,onSerializedHighlightsUpdate:this._handleSerializedHighlightsUpdate,serializedHighlights:this.props.highlights,children:jsxRuntimeExports.jsxs("div",{ref:ref=>this._contentRef=ref,children:[jsxRuntimeExports.jsx(LineHeightMeasurer,{ref:ref=>this._lineHeightMeasurerRef=ref}),PassageMarkdown.output(parsed)]})})}_hasFootnotes(){const rawContent=this.props.footnotes;const isEmpty=/^\s*$/.test(rawContent);return !isEmpty}_renderFootnotes(){const rawContent=this.props.footnotes;const parsed=PassageMarkdown.parse(rawContent);return PassageMarkdown.output(parsed)}render(){const{strings}=this.context;let lineNumbers;const nLines=this.state.nLines;if(this.props.showLineNumbers&&nLines){lineNumbers=_.range(1,nLines+1).map(lineN=>{const lineAt=lineN+this.state.startLineNumbersAfter;if(lineAt===4){const translatedLine=strings.lineLabel;return jsxRuntimeExports.jsx("span",{className:"line-marker",children:translatedLine},"line-marker")}return jsxRuntimeExports.jsx("span",{children:lineAt},lineN)});}const parseState=PassageMarkdown.getInitialParseState();const re=/("{1})([^"]*)("{1})/g;const doubleQuoteParsedContent=this.props.passageText.replace(re,"“$2”");const parsedContent=PassageMarkdown.parse(doubleQuoteParsedContent,parseState);const hasTitle=/\S/.test(this.props.passageTitle);return jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsxs("div",{className:"perseus-widget-passage-container",children:[this._renderInstructions(parseState),jsxRuntimeExports.jsxs("div",{className:"perseus-widget-passage",children:[hasTitle&&jsxRuntimeExports.jsx("h3",{className:"passage-title",children:jsxRuntimeExports.jsx(Renderer,{content:this.props.passageTitle,linterContext:this.props.linterContext,strings:strings})}),lineNumbers&&jsxRuntimeExports.jsx("div",{className:"line-numbers","aria-hidden":true,children:lineNumbers}),!hasTitle&&jsxRuntimeExports.jsx("h3",{className:"perseus-sr-only",children:strings.beginningPassage}),jsxRuntimeExports.jsx("div",{className:"passage-text",children:this.shouldRenderJipt()?jsxRuntimeExports.jsx(Renderer,{content:this.props.passageText,strings:strings}):this._renderContent(parsedContent)}),this._hasFootnotes()&&[jsxRuntimeExports.jsx("h4",{className:"perseus-sr-only",children:strings.beginningFootnotes},"footnote-start"),jsxRuntimeExports.jsx("div",{className:"footnotes",children:this._renderFootnotes()},"footnotes")],jsxRuntimeExports.jsx("div",{className:"perseus-sr-only",children:strings.endPassage})]})]})})}constructor(...args){super(...args),this.isWidget=true,this.state={nLines:null,startLineNumbersAfter:0,stylesAreApplied:false},this._handleSerializedHighlightsUpdate=serializedHighlights=>{this.props.onChange({highlights:serializedHighlights});};}}Passage.contextType=PerseusI18nContext;Passage.defaultProps={passageTitle:"",passageText:"",footnotes:"",showLineNumbers:true,highlights:{},linterContext:linterContextDefault};var Passage$1 = {name:"passage",displayName:"Passage (SAT only)",hidden:true,widget:Passage,transform:editorProps=>{return _.pick(editorProps,"passageTitle","passageText","footnotes","showLineNumbers")},isLintable:true};
1734
+ class LineHeightMeasurer extends React.Component{measureLineHeight(){if(!this._line){return 0}return this._line.clientHeight}render(){return jsxRuntimeExports.jsx("div",{className:css(styles$z.measurer),"aria-hidden":"true",children:jsxRuntimeExports.jsx("div",{ref:ref=>this._line=ref,className:"paragraph",children:"Line Height Measurement"})})}}const styles$z=StyleSheet.create({measurer:{position:"absolute",top:0,left:0,visibility:"hidden",zIndex:-1}});class Passage extends React.Component{componentDidMount(){this._updateState();this._onResize=_.throttle(()=>{if(this.shouldRenderJipt()){return}this._lineHeightMeasurerRef?.measureLineHeight();this._updateState();},500);window.addEventListener("resize",this._onResize);this._stylesAppiedTimer=window.setTimeout(()=>{this.setState({stylesAreApplied:true});},0);}shouldComponentUpdate(nextProps,nextState){return !_.isEqual(this.props,nextProps)||!_.isEqual(this.state,nextState)}componentDidUpdate(){this._updateState();}componentWillUnmount(){window.removeEventListener("resize",this._onResize);clearTimeout(this._stylesAppiedTimer);}_updateState(){if(this.shouldRenderJipt()){return}this.setState({nLines:this._measureLines(),startLineNumbersAfter:this._getInitialLineNumber()});}_measureLines(){const renderer=ReactDOM.findDOMNode(this._contentRef);const contentsHeight=$(renderer).height();const lineHeight=this._getLineHeight();const nLines=Math.round(contentsHeight/lineHeight);return nLines}_getInitialLineNumber(){let isPassageBeforeThisPassage=true;const passagesBeforeUs=this.props.findWidgets((id,widgetInfo)=>{if(widgetInfo.type!=="passage"){return false}if(id===this.props.widgetId){isPassageBeforeThisPassage=false;}return isPassageBeforeThisPassage}).filter(isPassageWidget);return passagesBeforeUs.map(passageWidget=>{return passageWidget.getLineCount()}).reduce((a,b)=>a+b,0)}_getLineHeight(){return this._lineHeightMeasurerRef?.measureLineHeight()||0}getLineCount(){if(this.state.nLines!=null){return this.state.nLines}return this._measureLines()}_getStartRefLineNumber(referenceNumber){const refRef=PassageMarkdown.START_REF_PREFIX+referenceNumber;const ref=this.refs[refRef];if(!ref){return null}const $ref=$(ReactDOM.findDOMNode(ref));let $refText=$ref.next();if($refText.length===0){$refText=$ref;}const vPos=$refText.offset().top;return this.state.startLineNumbersAfter+1+this._convertPosToLineNumber(vPos)}_getEndRefLineNumber(referenceNumber){const refRef=PassageMarkdown.END_REF_PREFIX+referenceNumber;const ref=this.refs[refRef];if(!ref){return null}const $ref=$(ReactDOM.findDOMNode(ref));let $refText=$ref.prev();if($refText.length===0){$refText=$ref;}const height=$refText.height();const vPos=$refText.offset().top;let line=this._convertPosToLineNumber(vPos+height);if(height===0){line+=1;}return this.state.startLineNumbersAfter+line}_convertPosToLineNumber(absoluteVPos){const content=ReactDOM.findDOMNode(this._contentRef);const relativeVPos=absoluteVPos-$(content).offset().top;const lineHeight=this._getLineHeight();const line=Math.round(relativeVPos/lineHeight);return line}_getRefContent(referenceNumber){const refRef=PassageMarkdown.START_REF_PREFIX+referenceNumber;const ref=this.refs[refRef];if(!ref){return null}return ref.getRefContent()}getReference(referenceNumber){const refStartLine=this._getStartRefLineNumber(referenceNumber);const refEndLine=this._getEndRefLineNumber(referenceNumber);if(refStartLine==null||refEndLine==null){return null}const refContent=this._getRefContent(referenceNumber);return {startLine:refStartLine,endLine:refEndLine,content:refContent}}getPromptJSON(){return getPromptJSON$o(this.props)}_renderInstructions(parseState){const firstQuestionNumber=parseState.firstQuestionRef;const firstSentenceRef=parseState.firstSentenceRef;const{strings}=this.context;let instructions="";if(firstQuestionNumber){instructions+=strings.symbolPassage({questionSymbol:"[["+firstQuestionNumber+"]]",questionNumber:firstQuestionNumber});}if(firstSentenceRef){instructions+=strings.symbolQuestion({sentenceSymbol:"["+firstSentenceRef+"]"});}const parsedInstructions=PassageMarkdown.parse(instructions);return jsxRuntimeExports.jsx("div",{className:"perseus-widget-passage-instructions",children:PassageMarkdown.output(parsedInstructions)})}shouldRenderJipt(){const{JIPT}=getDependencies();return JIPT.useJIPT&&this.props.passageText.indexOf("crwdns")!==-1}_renderContent(parsed){const enabled=this.state.stylesAreApplied;const editable=!this.props.reviewMode;return jsxRuntimeExports.jsx(HighlightableContent,{editable:editable,enabled:enabled,onSerializedHighlightsUpdate:this._handleSerializedHighlightsUpdate,serializedHighlights:this.props.highlights,children:jsxRuntimeExports.jsxs("div",{ref:ref=>this._contentRef=ref,children:[jsxRuntimeExports.jsx(LineHeightMeasurer,{ref:ref=>this._lineHeightMeasurerRef=ref}),PassageMarkdown.output(parsed)]})})}_hasFootnotes(){const rawContent=this.props.footnotes;const isEmpty=/^\s*$/.test(rawContent);return !isEmpty}_renderFootnotes(){const rawContent=this.props.footnotes;const parsed=PassageMarkdown.parse(rawContent);return PassageMarkdown.output(parsed)}render(){const{strings}=this.context;let lineNumbers;const nLines=this.state.nLines;if(this.props.showLineNumbers&&nLines){lineNumbers=_.range(1,nLines+1).map(lineN=>{const lineAt=lineN+this.state.startLineNumbersAfter;if(lineAt===4){const translatedLine=strings.lineLabel;return jsxRuntimeExports.jsx("span",{className:"line-marker",children:translatedLine},"line-marker")}return jsxRuntimeExports.jsx("span",{children:lineAt},lineN)});}const parseState=PassageMarkdown.getInitialParseState();const re=/("{1})([^"]*)("{1})/g;const doubleQuoteParsedContent=this.props.passageText.replace(re,"“$2”");const parsedContent=PassageMarkdown.parse(doubleQuoteParsedContent,parseState);const hasTitle=/\S/.test(this.props.passageTitle);return jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsxs("div",{className:"perseus-widget-passage-container",children:[this._renderInstructions(parseState),jsxRuntimeExports.jsxs("div",{className:"perseus-widget-passage",children:[hasTitle&&jsxRuntimeExports.jsx("h3",{className:"passage-title",children:jsxRuntimeExports.jsx(Renderer,{content:this.props.passageTitle,linterContext:this.props.linterContext,strings:strings})}),lineNumbers&&jsxRuntimeExports.jsx("div",{className:"line-numbers","aria-hidden":true,children:lineNumbers}),!hasTitle&&jsxRuntimeExports.jsx("h3",{className:"perseus-sr-only",children:strings.beginningPassage}),jsxRuntimeExports.jsx("div",{className:"passage-text",children:this.shouldRenderJipt()?jsxRuntimeExports.jsx(Renderer,{content:this.props.passageText,strings:strings}):this._renderContent(parsedContent)}),this._hasFootnotes()&&[jsxRuntimeExports.jsx("h4",{className:"perseus-sr-only",children:strings.beginningFootnotes},"footnote-start"),jsxRuntimeExports.jsx("div",{className:"footnotes",children:this._renderFootnotes()},"footnotes")],jsxRuntimeExports.jsx("div",{className:"perseus-sr-only",children:strings.endPassage})]})]})})}constructor(...args){super(...args),this.isWidget=true,this.state={nLines:null,startLineNumbersAfter:0,stylesAreApplied:false},this._handleSerializedHighlightsUpdate=serializedHighlights=>{this.props.onChange({highlights:serializedHighlights});};}}Passage.contextType=PerseusI18nContext;Passage.defaultProps={passageTitle:"",passageText:"",footnotes:"",showLineNumbers:true,highlights:{},linterContext:linterContextDefault};var Passage$1 = {name:"passage",displayName:"Passage (SAT only)",hidden:true,widget:Passage,transform:editorProps=>{return _.pick(editorProps,"passageTitle","passageText","footnotes","showLineNumbers")},isLintable:true};
1723
1735
 
1724
1736
  function isPassageWidget(widget){return widget instanceof Passage}
1725
1737
 
@@ -1731,27 +1743,43 @@ if(typeof HTMLElement!=="undefined"&&!HTMLElement.prototype.scrollTo){HTMLElemen
1731
1743
 
1732
1744
  const BASE_ICON_SIZE=10;class Icon extends React.Component{render(){const{color,pathClassName,className,title,style,alt}=this.props;let{icon,size}=this.props;let units="";if(typeof icon==="string"){icon={path:icon,width:BASE_ICON_SIZE,height:BASE_ICON_SIZE};}if(typeof size!=="number"){size=1;units="em";}const height=size;const width=height/icon.height*icon.width;const xMin=0;const yMin=0;const focusable=!!this.props.focusable;return jsxRuntimeExports.jsxs("svg",{role:"img",alt:alt,"aria-label":title,"aria-hidden":title?null:true,className:className,style:style,focusable:focusable.toString(),width:width+units,height:height+units,viewBox:`${xMin} ${yMin} ${icon.width} ${icon.height}`,children:[!!title&&jsxRuntimeExports.jsx("title",{children:title}),jsxRuntimeExports.jsx("path",{className:pathClassName,fill:color,d:icon.path})]})}}Icon.defaultProps={color:"currentColor"};
1733
1745
 
1734
- function getA11yText(letter,checked,correct,crossedOut,showCorrectness,strings){if(showCorrectness&&correct){if(checked){return strings.choiceCheckedCorrect({letter})}if(crossedOut){return strings.choiceCrossedOutCorrect({letter})}return strings.choiceCorrect({letter})}if(showCorrectness&&!correct){if(checked){return strings.choiceCheckedIncorrect({letter})}if(crossedOut){return strings.choiceCrossedOutIncorrect({letter})}return strings.choiceIncorrect({letter})}if(checked){return strings.choiceChecked({letter})}if(crossedOut){return strings.choiceCrossedOut({letter})}return strings.choice({letter})}
1746
+ function getA11yText$1(letter,checked,correct,crossedOut,showCorrectness,strings){if(showCorrectness&&correct){if(checked){return strings.choiceCheckedCorrect({letter})}if(crossedOut){return strings.choiceCrossedOutCorrect({letter})}return strings.choiceCorrect({letter})}if(showCorrectness&&!correct){if(checked){return strings.choiceCheckedIncorrect({letter})}if(crossedOut){return strings.choiceCrossedOutIncorrect({letter})}return strings.choiceIncorrect({letter})}if(checked){return strings.choiceChecked({letter})}if(crossedOut){return strings.choiceCrossedOut({letter})}return strings.choice({letter})}
1735
1747
 
1736
- const FocusRing=function({visible=true,color=kaGreen,multipleSelect=false,children}){const borderColor=visible?color:"transparent";const borderRadius=multipleSelect?5:"50%";const style={borderColor,borderRadius};return jsxRuntimeExports.jsx("span",{"data-testid":"focus-ring",className:css(styles$u.ring),style:style,children:children})};const styles$u=StyleSheet.create({ring:{margin:"auto",display:"inline-block",borderWidth:2,padding:2,borderStyle:"solid"}});
1748
+ const FocusRing=function({visible=true,color=kaGreen,multipleSelect=false,children}){const borderColor=visible?color:"transparent";const borderRadius=multipleSelect?5:"50%";const style={borderColor,borderRadius};return jsxRuntimeExports.jsx("span",{"data-testid":"focus-ring",className:css(styles$y.ring),style:style,children:children})};const styles$y=StyleSheet.create({ring:{margin:"auto",display:"inline-block",borderWidth:2,padding:2,borderStyle:"solid"}});
1737
1749
 
1738
1750
  function getChoiceLetter(pos,strings){const lettersString=strings.letters;const letters=lettersString.split(" ");if(pos<letters.length){return letters[pos]}return " "}
1739
1751
 
1740
- const CHOICE_ICON_SIZE=24;const styles$t=StyleSheet.create({iconWrapper:{display:"inline-block",position:"relative"}});
1752
+ const CHOICE_ICON_SIZE=24;const styles$x=StyleSheet.create({iconWrapper:{display:"inline-block",position:"relative"}});
1753
+
1754
+ const CROSS_OUT_LINE_PADDING=2;const CROSS_OUT_LINE_SIZE=CHOICE_ICON_SIZE+CROSS_OUT_LINE_PADDING*2;const CrossOutLine=function(props){return jsxRuntimeExports.jsx("svg",{width:CROSS_OUT_LINE_SIZE,height:CROSS_OUT_LINE_SIZE,viewBox:`0 0 ${CROSS_OUT_LINE_SIZE} ${CROSS_OUT_LINE_SIZE}`,className:css(styles$w.crossOutLine),"data-testid":"choice-icon__cross-out-line",children:jsxRuntimeExports.jsx("line",{x1:CROSS_OUT_LINE_PADDING,x2:CROSS_OUT_LINE_SIZE-CROSS_OUT_LINE_PADDING,y1:CROSS_OUT_LINE_SIZE-CROSS_OUT_LINE_PADDING,y2:CROSS_OUT_LINE_PADDING,stroke:props.color,strokeWidth:"2",strokeLinecap:"round"})})};const styles$w=StyleSheet.create({crossOutLine:{position:"absolute",top:`2px`,left:`2px`}});
1741
1755
 
1742
- const CROSS_OUT_LINE_PADDING=2;const CROSS_OUT_LINE_SIZE=CHOICE_ICON_SIZE+CROSS_OUT_LINE_PADDING*2;const CrossOutLine=function(props){return jsxRuntimeExports.jsx("svg",{width:CROSS_OUT_LINE_SIZE,height:CROSS_OUT_LINE_SIZE,viewBox:`0 0 ${CROSS_OUT_LINE_SIZE} ${CROSS_OUT_LINE_SIZE}`,className:css(styles$s.crossOutLine),"data-testid":"choice-icon__cross-out-line",children:jsxRuntimeExports.jsx("line",{x1:CROSS_OUT_LINE_PADDING,x2:CROSS_OUT_LINE_SIZE-CROSS_OUT_LINE_PADDING,y1:CROSS_OUT_LINE_SIZE-CROSS_OUT_LINE_PADDING,y2:CROSS_OUT_LINE_PADDING,stroke:props.color,strokeWidth:"2",strokeLinecap:"round"})})};const styles$s=StyleSheet.create({crossOutLine:{position:"absolute",top:`2px`,left:`2px`}});
1756
+ function ChoiceInner$1(props){const{pos,showCorrectness,correct}=props;const{strings}=usePerseusI18n();const letter=getChoiceLetter(pos,strings);if(!showCorrectness){return jsxRuntimeExports.jsx("span",{children:letter})}if(correct){return jsxRuntimeExports.jsx(InlineIcon,{...iconCheck,style:{position:"relative",top:-1}})}return jsxRuntimeExports.jsx(InlineIcon,{...iconMinus})}const ChoiceIcon$1=function(props){const{checked,crossedOut,showCorrectness,correct,focused,hovered,multipleSelect,pos,previouslyAnswered,pressed}=props;const choiceIsChecked=checked||showCorrectness&&!correct&&previouslyAnswered;const choiceStyling=[styles$v.choiceBase,multipleSelect?styles$v.multiSelectShape:styles$v.singleSelectShape,showCorrectness?styles$v.choiceHasIcon:styles$v.choiceHasLetter,choiceIsChecked?styles$v.choiceIsChecked:styles$v.choiceIsUnchecked];let crossOutColor;if(showCorrectness&&correct&&checked){choiceStyling.push(styles$v.choiceCorrect);crossOutColor=color.green;}else if(showCorrectness&&!correct&&(checked||previouslyAnswered)){choiceStyling.push(styles$v.choiceIncorrect);crossOutColor=color.red;}else if(checked){choiceStyling.push(styles$v.choiceNeutral);crossOutColor=color.blue;}else if(pressed){choiceStyling.push(styles$v.activeNeutral);crossOutColor=color.blue;}else {choiceStyling.push(styles$v.uncheckedColors);crossOutColor=color.offBlack64;}return jsxRuntimeExports.jsxs("div",{className:css(styles$x.iconWrapper),children:[jsxRuntimeExports.jsx(FocusRing,{color:color.blue,visible:focused||hovered,multipleSelect:multipleSelect,children:jsxRuntimeExports.jsx("div",{"data-testid":"choice-icon__library-choice-icon",className:css(...choiceStyling),"data-is-radio-icon":true,children:jsxRuntimeExports.jsx("div",{className:css(styles$v.innerWrapper),children:jsxRuntimeExports.jsx(ChoiceInner$1,{pos:pos,showCorrectness:showCorrectness,correct:correct})})})}),crossedOut&&jsxRuntimeExports.jsx(CrossOutLine,{color:crossOutColor})]})};const styles$v=StyleSheet.create({innerWrapper:{width:CHOICE_ICON_SIZE,height:CHOICE_ICON_SIZE,display:"flex",alignItems:"center",justifyContent:"center"},choiceBase:{width:CHOICE_ICON_SIZE,height:CHOICE_ICON_SIZE,boxSizing:"border-box",borderStyle:"solid",borderWidth:2,fontFamily:baseFontFamily,fontWeight:"bold",display:"flex",alignItems:"center",justifyContent:"center"},choiceHasLetter:{fontSize:12},choiceHasIcon:{fontSize:CHOICE_ICON_SIZE},choiceIsChecked:{color:color.white},choiceIsUnchecked:{color:color.offBlack64},choiceCorrect:{backgroundColor:color.green,borderColor:color.green},choiceIncorrect:{backgroundColor:color.red,borderColor:color.red},choiceNeutral:{backgroundColor:color.blue,borderColor:color.blue},activeNeutral:{color:color.blue,borderColor:color.blue,backgroundColor:"transparent"},multiSelectShape:{borderRadius:3},singleSelectShape:{borderRadius:CHOICE_ICON_SIZE},uncheckedColors:{borderColor:color.offBlack64}});
1757
+
1758
+ function renderText$1(checked,correct,crossedOut,strings){if(correct){if(checked){return strings.correctSelected}if(crossedOut){return strings.correctCrossedOut}return strings.correct}if(checked){return strings.incorrectSelected}return strings.incorrect}const OptionStatus$1=function(props){const{checked,correct,crossedOut,previouslyAnswered,reviewMode}=props;const{strings}=usePerseusI18n();if(!reviewMode&&!previouslyAnswered){return null}let textStyle;if(correct){textStyle=styles$u.correct;}else {if(checked||previouslyAnswered){textStyle=styles$u.incorrectAnswered;}else {textStyle=styles$u.incorrect;}}return jsxRuntimeExports.jsx("div",{className:css(styles$u.text,textStyle),children:renderText$1(checked,correct,crossedOut,strings)})};const styles$u=StyleSheet.create({text:{alignItems:"center",display:"flex",fontSize:12,height:32,textTransform:"uppercase"},correct:{color:color.green},incorrectAnswered:{color:color.red},incorrect:{color:color.offBlack64}});
1759
+
1760
+ const intermediateCheckboxPadding$1=`16px 16px`;const intermediateCheckboxPaddingPhone$1=`12px 16px`;const ellipsisHorizontalIcon$1={path:"M27.218 6.82l0 13.578q0 2.852-1.984 4.836t-4.836 1.984l-13.578 0q-2.852 0-4.836-1.984t-1.984-4.836l0-13.578q0-2.852 1.984-4.836t4.836-1.984l13.578 0q2.852 0 4.836 1.984t1.984 4.836zm36.27 0l0 13.578q0 2.852-1.984 4.836t-4.836 1.984l-13.578 0q-2.852 0-4.836-1.984t-1.984-4.836l0-13.578q0-2.852 1.984-4.836t4.836-1.984l13.578 0q2.852 0 4.836 1.984t1.984 4.836zm36.27 0l0 13.578q0 2.852-1.984 4.836t-4.836 1.984l-13.578 0q-2.852 0-4.836-1.984t-1.984-4.836l0-13.578q0-2.852 1.984-4.836t4.836-1.984l13.578 0q2.852 0 4.836 1.984t1.984 4.836z",width:100,height:27.284};const Choice$2=function(props){const{disabled=false,checked=false,content,crossedOut,showCorrectness,multipleSelect,onChange=newValues=>{},reviewMode,correct=false,apiOptions=ApiOptions.defaults,previouslyAnswered=false,pos=0,showRationale=false,rationale,forwardedRef}=props;const[isInputFocused,setIsInputFocused]=useState(false);const{strings}=usePerseusI18n();useEffect(()=>{if(isInputFocused&&disabled){setIsInputFocused(false);}},[disabled,isInputFocused,setIsInputFocused]);function sendChange(newValues){const updatedChecked=newValues.checked??checked;const updatedCrossedOut=newValues.crossedOut??crossedOut;onChange({checked:updatedChecked,crossedOut:updatedCrossedOut});}const descriptionClassName=classNames$1("description",css(styles$t.description));const rationaleClassName=classNames$1("perseus-radio-rationale-content",css(styles$t.rationale));const showDimmed=!reviewMode&&apiOptions.readOnly||crossedOut;const letter=getChoiceLetter(pos,strings);const a11yText=getA11yText$1(letter,checked,correct,crossedOut,showCorrectness,strings);return jsxRuntimeExports.jsxs("div",{style:{dispay:"flex",flexDirection:"column",color:color.offBlack},className:descriptionClassName,children:[jsxRuntimeExports.jsxs("div",{style:{display:"flex",flexDirection:"row",opacity:showDimmed?.5:1,overflowX:"auto",overflowY:"hidden"},children:[jsxRuntimeExports.jsx("div",{className:"perseus-sr-only",children:jsxRuntimeExports.jsxs("label",{children:[a11yText,"   ",content,jsxRuntimeExports.jsx("input",{type:multipleSelect?"checkbox":"radio",checked:checked,onClick:()=>{sendChange({checked:!checked,crossedOut:false});},onChange:()=>{},disabled:disabled||apiOptions.readOnly,tabIndex:-1,className:ClassNames.RADIO.OPTION_CONTENT})]})}),jsxRuntimeExports.jsx(Clickable,{onClick:()=>{sendChange({checked:!checked,crossedOut:false});},disabled:disabled||apiOptions.readOnly,style:{flex:1,color:color.offBlack,userSelect:"text"},ref:forwardedRef,"aria-hidden":"true",children:({hovered,focused,pressed})=>jsxRuntimeExports.jsxs("div",{style:{display:"flex",flexDirection:"row",justifyContent:"center",alignContent:"center",paddingTop:spacing.xSmall_8,paddingBottom:spacing.xSmall_8,paddingLeft:spacing.xSmall_8},children:[jsxRuntimeExports.jsx(ChoiceIcon$1,{pos:pos,correct:correct,crossedOut:crossedOut,pressed:pressed,focused:focused,checked:checked,hovered:hovered,showCorrectness:showCorrectness,multipleSelect:multipleSelect,reviewMode:reviewMode,previouslyAnswered:previouslyAnswered}),jsxRuntimeExports.jsxs("span",{style:{paddingLeft:spacing.small_12,textAlign:"left",flex:1,paddingTop:4},children:[jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsx(OptionStatus$1,{checked:checked,correct:correct,crossedOut:crossedOut,previouslyAnswered:previouslyAnswered,reviewMode:reviewMode})}),jsxRuntimeExports.jsx("div",{children:content})]})]})}),apiOptions.crossOutEnabled&&!reviewMode&&jsxRuntimeExports.jsx(Popover,{dismissEnabled:true,content:({close})=>jsxRuntimeExports.jsx(PopoverContent,{title:strings.crossOut,content:strings.crossOutOption,closeButtonVisible:true,actions:jsxRuntimeExports.jsxs(View,{children:[jsxRuntimeExports.jsx(Strut,{size:spacing.medium_16}),jsxRuntimeExports.jsx(Button,{kind:"primary","aria-label":strings.crossOutChoice({letter:getChoiceLetter(pos,strings)}),disabled:apiOptions.readOnly||reviewMode,onClick:()=>{if(!crossedOut){sendChange({checked:false,crossedOut:true});}else {sendChange({crossedOut:false});}close();},children:crossedOut?strings.bringBack:strings.crossOut})]})}),children:({open})=>jsxRuntimeExports.jsx(Clickable,{onClick:open,"aria-label":strings.openMenuForChoice({letter:getChoiceLetter(pos,strings)}),style:{alignSelf:"center",padding:"5px",display:"flex",justifyContent:"center",alignItems:"center",marginLeft:"10px"},children:({hovered,focused,pressed})=>jsxRuntimeExports.jsx(Icon,{icon:ellipsisHorizontalIcon$1,size:3,color:color.offBlack64})})})]}),showRationale&&jsxRuntimeExports.jsx("div",{className:rationaleClassName,"data-testid":`perseus-radio-rationale-content-${pos}`,children:rationale})]})};const styles$t=StyleSheet.create({description:{display:"inline-block",width:"100%"},rationale:{display:"block",padding:intermediateCheckboxPadding$1,paddingTop:0,marginLeft:54,color:color.offBlack64,[mediaQueries.smOrSmaller]:{padding:intermediateCheckboxPaddingPhone$1,paddingTop:0}}});var Choice$3 = React.forwardRef((props,ref)=>jsxRuntimeExports.jsx(Choice$2,{...props,forwardedRef:ref}));
1761
+
1762
+ const ChoiceNoneAbove$2=function({content,forwardedRef,showContent=true,...rest}){const{strings}=usePerseusI18n();const choiceProps={...rest,content:showContent?content:jsxRuntimeExports.jsx(Renderer,{content:strings.noneOfTheAbove,strings:strings},"noneOfTheAboveRenderer")};return jsxRuntimeExports.jsx(Choice$3,{...choiceProps,ref:forwardedRef})};var ChoiceNoneAbove$3 = React.forwardRef((props,ref)=>jsxRuntimeExports.jsx(ChoiceNoneAbove$2,{...props,forwardedRef:ref}));
1763
+
1764
+ const{captureScratchpadTouchStart: captureScratchpadTouchStart$2}=Util;function getInstructionsText$1(multipleSelect,countChoices,numCorrect,strings){if(multipleSelect){if(usesNumCorrect(multipleSelect,!!countChoices,numCorrect)){return strings.chooseNumAnswers({numCorrect:String(numCorrect)})}return strings.chooseAllAnswers}return strings.chooseOneAnswer}const BaseRadio$1=function({apiOptions,reviewModeRubric,reviewMode,choices,editMode=false,multipleSelect=false,labelWrap,countChoices,numCorrect,isLastUsedWidget,onChange,registerFocusFunction}){const{strings}=usePerseusI18n();const prevReviewModeRubric=useRef();const choiceRefs=useRef([]);useEffect(()=>{if(apiOptions.canScrollPage&&isLastUsedWidget&&reviewModeRubric&&!prevReviewModeRubric.current){const checkedIndex=choices.findIndex(c=>c.checked);if(checkedIndex>=0){const ref=choiceRefs.current[checkedIndex];const anyNode=ReactDOM__default.findDOMNode(ref.current);const buttonNode=anyNode;if(buttonNode){scrollElementIntoView(buttonNode);}}}prevReviewModeRubric.current=reviewModeRubric;},[apiOptions,choices,isLastUsedWidget,reviewModeRubric]);function updateChoice(choiceIndex,newValues){let newCheckedList;if(newValues.checked&&!multipleSelect){newCheckedList=choices.map(_=>false);}else {newCheckedList=choices.map(c=>c.checked);}const newCrossedOutList=choices.map(c=>c.crossedOut);newCheckedList[choiceIndex]=newValues.checked;newCrossedOutList[choiceIndex]=newValues.crossedOut;onChange({checked:newCheckedList,crossedOut:newCrossedOutList});}registerFocusFunction?.(choiceIndex=>{const ref=choiceRefs.current[choiceIndex||0];const anyNode=ReactDOM__default.findDOMNode(ref.current);const buttonNode=anyNode;if(buttonNode){buttonNode.focus();}else {return false}return true});const isMobile=apiOptions.isMobile;const firstChoiceHighlighted=choices[0].highlighted;const lastChoiceHighlighted=choices[choices.length-1].highlighted;const className=classNames$1("perseus-widget-radio",!editMode&&"perseus-rendered-radio",css(styles$s.radio,styles$s.responsiveRadioContainer,firstChoiceHighlighted&&isMobile&&styles$s.radioContainerFirstHighlighted,lastChoiceHighlighted&&isMobile&&styles$s.radioContainerLastHighlighted));const instructionsClassName=classNames$1("instructions",css(styles$s.instructions,isMobile&&styles$s.instructionsMobile));const instructions=getInstructionsText$1(multipleSelect,countChoices,numCorrect,strings);const responsiveClassName=css(styles$s.responsiveFieldset);const fieldset=jsxRuntimeExports.jsxs("fieldset",{className:`perseus-widget-radio-fieldset ${responsiveClassName}`,children:[jsxRuntimeExports.jsx("legend",{className:"perseus-sr-only",children:instructions}),jsxRuntimeExports.jsx("div",{className:instructionsClassName,"aria-hidden":"true",children:instructions}),jsxRuntimeExports.jsx("ul",{className:className,style:{listStyle:"none"},children:choices.map((choice,i)=>{let Element=Choice$3;const ref=React.createRef();choiceRefs.current[i]=ref;const elementProps={apiOptions:apiOptions,multipleSelect:multipleSelect,checked:choice.checked,crossedOut:choice.crossedOut,previouslyAnswered:choice.previouslyAnswered,reviewMode,correct:choice.correct,rationale:choice.rationale,content:choice.content,disabled:apiOptions.readOnly||choice.disabled,showCorrectness:reviewMode||!!choice.showCorrectness,showRationale:choice.hasRationale&&(reviewMode||choice.showRationale),pos:i,onChange:newValues=>{if(editMode){return}updateChoice(i,newValues);}};if(choice.isNoneOfTheAbove){Element=ChoiceNoneAbove$3;_.extend(elementProps,{showContent:choice.revealNoneOfTheAbove});}const nextChoice=choices[i+1];const nextChoiceHighlighted=!!nextChoice&&nextChoice.highlighted;const aphroditeClassName=checked=>{return css(styles$s.item,styles$s.responsiveItem,checked&&styles$s.selectedItem,checked&&choice.highlighted&&styles$s.aboveBackdrop,checked&&choice.highlighted&&apiOptions.isMobile&&styles$s.aboveBackdropMobile,nextChoiceHighlighted&&apiOptions.isMobile&&styles$s.nextHighlighted)};aphroditeClassName(true);let correctnessClass;if(reviewMode&&reviewModeRubric){correctnessClass=reviewModeRubric.choices[i].correct?ClassNames.CORRECT:ClassNames.INCORRECT;}const className=classNames$1(aphroditeClassName(choice.checked),ClassNames.RADIO.OPTION,choice.checked&&ClassNames.RADIO.SELECTED,correctnessClass);let listElem=null;let clickHandler;if(editMode){clickHandler=e=>{let elem=e.target;while(elem&&elem!==listElem){if(elem.getAttribute("data-is-radio-icon")){updateChoice(i,{checked:!choice.checked,crossedOut:choice.crossedOut});return}elem=elem.parentNode;}};}return jsxRuntimeExports.jsx("li",{ref:e=>listElem=e,className:className,onClick:clickHandler,onTouchStart:labelWrap?undefined:captureScratchpadTouchStart$2,children:jsxRuntimeExports.jsx(Element,{...elementProps,ref:ref})},i)})})]});return jsxRuntimeExports.jsx("div",{className:css(styles$s.responsiveContainer),children:fieldset})};const styles$s=StyleSheet.create({instructions:{display:"block",color:gray17,fontSize:14,lineHeight:1.25,fontFamily:"inherit",fontStyle:"normal",fontWeight:"bold",marginBottom:16},instructionsMobile:{fontSize:18,[mediaQueries.smOrSmaller]:{fontSize:16},[mediaQueries.xl]:{fontSize:20}},radio:{padding:0},responsiveRadioContainer:{borderBottom:`1px solid ${radioBorderColor$1}`,borderTop:`1px solid ${radioBorderColor$1}`,width:"auto",[mediaQueries.smOrSmaller]:{marginLeft:negativePhoneMargin,marginRight:negativePhoneMargin}},radioContainerFirstHighlighted:{borderTop:`1px solid rgba(0, 0, 0, 0)`},radioContainerLastHighlighted:{borderBottom:`1px solid rgba(0, 0, 0, 0)`},item:{marginLeft:20},responsiveItem:{marginLeft:0,padding:0,":not(:last-child)":{borderBottom:`1px solid ${radioBorderColor$1}`}},selectedItem:{background:"white"},aboveBackdrop:{position:"relative",zIndex:1062},aboveBackdropMobile:{boxShadow:"0 0 4px 0 rgba(0, 0, 0, 0.2),"+"0 0 2px 0 rgba(0, 0, 0, 0.1)",":not(:last-child)":{borderBottom:`1px solid rgba(0, 0, 0, 0)`}},nextHighlighted:{":not(:last-child)":{borderBottom:`1px solid rgba(0, 0, 0, 0)`}},responsiveContainer:{overflow:"auto",marginLeft:negativePhoneMargin,paddingLeft:phoneMargin},responsiveFieldset:{paddingRight:phoneMargin,minWidth:"auto"}});
1765
+
1766
+ let Radio$3 = class Radio extends React.Component{static getUserInputFromProps(props,unshuffle=true){if(props.choiceStates){const choiceStates=props.choiceStates;const choicesSelected=choiceStates.map(()=>false);for(let i=0;i<choicesSelected.length;i++){const index=unshuffle?props.choices[i].originalIndex:i;choicesSelected[index]=choiceStates[i].selected;}return {choicesSelected}}const{values}=props;if(values){const choicesSelected=[...values];const valuesLength=values.length;for(let i=0;i<valuesLength;i++){const index=unshuffle?props.choices[i].originalIndex:i;choicesSelected[index]=values[i];}return {choicesSelected}}return {choicesSelected:props.choices.map(()=>false)}}componentDidUpdate(prevProps){if(this.props.showSolutions==="selected"&&prevProps.showSolutions!=="selected"){this.showRationalesForCurrentlySelectedChoices(this.props);}}focus(choiceIndex){if(this.focusFunction){return this.focusFunction(choiceIndex)}return false}registerFocusFunction(fun){this.focusFunction=fun;}getUserInput(){return Radio.getUserInputFromProps(this.props)}getPromptJSON(){const userInput=Radio.getUserInputFromProps(this.props,false);return getPromptJSON$q(this.props,userInput)}render(){const{choices}=this.props;const{strings}=this.context;let choiceStates;if(this.props.static){choiceStates=choices.map(choice=>({selected:!!choice.correct,crossedOut:false,readOnly:true,highlighted:false,rationaleShown:true,correctnessShown:true,previouslyAnswered:false}));}else if(this.props.showSolutions==="all"){choiceStates=choices.map(({correct})=>({selected:!!correct,crossedOut:false,readOnly:true,highlighted:false,rationaleShown:true,correctnessShown:true,previouslyAnswered:false}));}else if(this.props.choiceStates){choiceStates=this.props.choiceStates;}else if(this.props.values){choiceStates=this.props.values.map(val=>({selected:val,crossedOut:false,readOnly:false,highlighted:false,rationaleShown:false,correctnessShown:false,previouslyAnswered:false}));}else {choiceStates=choices.map(()=>({selected:false,crossedOut:false,readOnly:false,highlighted:false,rationaleShown:false,correctnessShown:false,previouslyAnswered:false}));}const choicesProp=choices.map((choice,i)=>{const content=choice.isNoneOfTheAbove&&!choice.content?strings.noneOfTheAbove:choice.content;const{selected,crossedOut,rationaleShown,correctnessShown,readOnly,highlighted,previouslyAnswered}=choiceStates[i];const reviewChoice=this.props.reviewModeRubric?.choices[i];return {content:this._renderRenderer(content),checked:selected,correct:choice.correct===undefined?!!reviewChoice&&!!reviewChoice.correct:choice.correct,disabled:readOnly,hasRationale:!!choice.clue,rationale:this._renderRenderer(choice.clue),showRationale:rationaleShown,showCorrectness:correctnessShown,isNoneOfTheAbove:!!choice.isNoneOfTheAbove,revealNoneOfTheAbove:!!(this.props.questionCompleted&&selected),crossedOut,highlighted,previouslyAnswered:previouslyAnswered}});return jsxRuntimeExports.jsx(BaseRadio$1,{labelWrap:true,multipleSelect:this.props.multipleSelect,countChoices:this.props.countChoices,numCorrect:this.props.numCorrect,choices:choicesProp,onChange:this.updateChoices,reviewModeRubric:this.props.reviewModeRubric,reviewMode:this.props.reviewMode,deselectEnabled:this.props.deselectEnabled,apiOptions:this.props.apiOptions,isLastUsedWidget:this.props.isLastUsedWidget,registerFocusFunction:i=>this.registerFocusFunction(i)})}constructor(...args){super(...args),this._renderRenderer=(content="")=>{let nextPassageRefId=1;const widgets={};const modContent=content.replace(/\{\{passage-ref (\d+) (\d+)(?: "([^"]*)")?\}\}/g,(match,passageNum,refNum,summaryText)=>{const widgetId="passage-ref "+nextPassageRefId;nextPassageRefId++;widgets[widgetId]={type:"passage-ref",graded:false,options:{passageNumber:parseInt(passageNum),referenceNumber:parseInt(refNum),summaryText:summaryText},version:PassageRef$1.version};return "[["+Util.snowman+" "+widgetId+"]]"});return jsxRuntimeExports.jsx(Renderer,{content:modContent,widgets:widgets,findExternalWidgets:this.props.findWidgets,alwaysUpdate:true,linterContext:{...this.props.linterContext,blockHighlight:true},strings:this.context.strings},"choiceContentRenderer")},this.updateChoices=newValueLists=>{const{choiceStates,choices}=this.props;const newChoiceStates=choiceStates?choiceStates.map(state=>({...state})):choices.map(()=>({selected:false,crossedOut:false,highlighted:false,rationaleShown:false,correctnessShown:false,previouslyAnswered:false,readOnly:false}));newChoiceStates.forEach((choiceState,i)=>{choiceState.selected=newValueLists.checked[i];choiceState.crossedOut=newValueLists.crossedOut[i];});this.props.onChange({choiceStates:newChoiceStates});this.props.trackInteraction();},this.showRationalesForCurrentlySelectedChoices=rubric=>{const{choiceStates}=this.props;if(choiceStates){const score=scoreRadio(this.getUserInput(),rubric);const widgetCorrect=score.type==="points"&&score.total===score.earned;const newStates=choiceStates.map(state=>({...state,highlighted:state.selected,rationaleShown:state.selected||state.rationaleShown||widgetCorrect,readOnly:state.selected||state.readOnly||widgetCorrect||this.props.showSolutions!=="none",correctnessShown:state.selected||state.correctnessShown,previouslyAnswered:state.previouslyAnswered||state.selected}));this.props.onChange({choiceStates:newStates},null,true);}},this.deselectIncorrectSelectedChoices=()=>{if(this.props.choiceStates){const newStates=this.props.choiceStates.map((state,i)=>({...state,selected:state.selected&&!!this.props.choices[i].correct,highlighted:false}));this.props.onChange({choiceStates:newStates},null,false);}};}};Radio$3.contextType=PerseusI18nContext;Radio$3.defaultProps={choices:[],multipleSelect:false,countChoices:false,deselectEnabled:false,linterContext:linterContextDefault,showSolutions:"none"};
1767
+
1768
+ const ChoiceNoneAbove=function({content,forwardedRef,showContent=true,...rest}){const{strings}=usePerseusI18n();const choiceProps={...rest,content:showContent?content:jsxRuntimeExports.jsx(Renderer,{content:strings.noneOfTheAbove,strings:strings},"noneOfTheAboveRenderer")};return jsxRuntimeExports.jsx(Choice$3,{...choiceProps,ref:forwardedRef})};var ChoiceNoneAbove$1 = React.forwardRef((props,ref)=>jsxRuntimeExports.jsx(ChoiceNoneAbove,{...props,forwardedRef:ref}));
1769
+
1770
+ function getA11yText(letter,checked,correct,crossedOut,showCorrectness,strings){if(showCorrectness&&correct){if(checked){return strings.choiceCheckedCorrect({letter})}if(crossedOut){return strings.choiceCrossedOutCorrect({letter})}return strings.choiceCorrect({letter})}if(showCorrectness&&!correct){if(checked){return strings.choiceCheckedIncorrect({letter})}if(crossedOut){return strings.choiceCrossedOutIncorrect({letter})}return strings.choiceIncorrect({letter})}if(checked){return strings.choiceChecked({letter})}if(crossedOut){return strings.choiceCrossedOut({letter})}return strings.choice({letter})}
1743
1771
 
1744
- function ChoiceInner(props){const{pos,showCorrectness,correct}=props;const{strings}=usePerseusI18n();const letter=getChoiceLetter(pos,strings);if(!showCorrectness){return jsxRuntimeExports.jsx("span",{children:letter})}if(correct){return jsxRuntimeExports.jsx(InlineIcon,{...iconCheck,style:{position:"relative",top:-1}})}return jsxRuntimeExports.jsx(InlineIcon,{...iconMinus})}const ChoiceIcon=function(props){const{checked,crossedOut,showCorrectness,correct,focused,hovered,multipleSelect,pos,previouslyAnswered,pressed}=props;const choiceIsChecked=checked||showCorrectness&&!correct&&previouslyAnswered;const choiceStyling=[styles$r.choiceBase,multipleSelect?styles$r.multiSelectShape:styles$r.singleSelectShape,showCorrectness?styles$r.choiceHasIcon:styles$r.choiceHasLetter,choiceIsChecked?styles$r.choiceIsChecked:styles$r.choiceIsUnchecked];let crossOutColor;if(showCorrectness&&correct&&checked){choiceStyling.push(styles$r.choiceCorrect);crossOutColor=color.green;}else if(showCorrectness&&!correct&&(checked||previouslyAnswered)){choiceStyling.push(styles$r.choiceIncorrect);crossOutColor=color.red;}else if(checked){choiceStyling.push(styles$r.choiceNeutral);crossOutColor=color.blue;}else if(pressed){choiceStyling.push(styles$r.activeNeutral);crossOutColor=color.blue;}else {choiceStyling.push(styles$r.uncheckedColors);crossOutColor=color.offBlack64;}return jsxRuntimeExports.jsxs("div",{className:css(styles$t.iconWrapper),children:[jsxRuntimeExports.jsx(FocusRing,{color:color.blue,visible:focused||hovered,multipleSelect:multipleSelect,children:jsxRuntimeExports.jsx("div",{"data-testid":"choice-icon__library-choice-icon",className:css(...choiceStyling),"data-is-radio-icon":true,children:jsxRuntimeExports.jsx("div",{className:css(styles$r.innerWrapper),children:jsxRuntimeExports.jsx(ChoiceInner,{pos:pos,showCorrectness:showCorrectness,correct:correct})})})}),crossedOut&&jsxRuntimeExports.jsx(CrossOutLine,{color:crossOutColor})]})};const styles$r=StyleSheet.create({innerWrapper:{width:CHOICE_ICON_SIZE,height:CHOICE_ICON_SIZE,display:"flex",alignItems:"center",justifyContent:"center"},choiceBase:{width:CHOICE_ICON_SIZE,height:CHOICE_ICON_SIZE,boxSizing:"border-box",borderStyle:"solid",borderWidth:2,fontFamily:baseFontFamily,fontWeight:"bold",display:"flex",alignItems:"center",justifyContent:"center"},choiceHasLetter:{fontSize:12},choiceHasIcon:{fontSize:CHOICE_ICON_SIZE},choiceIsChecked:{color:color.white},choiceIsUnchecked:{color:color.offBlack64},choiceCorrect:{backgroundColor:color.green,borderColor:color.green},choiceIncorrect:{backgroundColor:color.red,borderColor:color.red},choiceNeutral:{backgroundColor:color.blue,borderColor:color.blue},activeNeutral:{color:color.blue,borderColor:color.blue,backgroundColor:"transparent"},multiSelectShape:{borderRadius:3},singleSelectShape:{borderRadius:CHOICE_ICON_SIZE},uncheckedColors:{borderColor:color.offBlack64}});
1772
+ function ChoiceInner(props){const{pos,showCorrectness,correct}=props;const{strings}=usePerseusI18n();const letter=getChoiceLetter(pos,strings);if(!showCorrectness){return jsxRuntimeExports.jsx("span",{children:letter})}if(correct){return jsxRuntimeExports.jsx(InlineIcon,{...iconCheck,style:{position:"relative",top:-1}})}return jsxRuntimeExports.jsx(InlineIcon,{...iconMinus})}const ChoiceIcon=function(props){const{checked,crossedOut,showCorrectness,correct,focused,hovered,multipleSelect,pos,previouslyAnswered,pressed}=props;const choiceIsChecked=checked||showCorrectness&&!correct&&previouslyAnswered;const choiceStyling=[styles$r.choiceBase,multipleSelect?styles$r.multiSelectShape:styles$r.singleSelectShape,showCorrectness?styles$r.choiceHasIcon:styles$r.choiceHasLetter,choiceIsChecked?styles$r.choiceIsChecked:styles$r.choiceIsUnchecked];let crossOutColor;if(showCorrectness&&correct&&checked){choiceStyling.push(styles$r.choiceCorrect);crossOutColor=color.green;}else if(showCorrectness&&!correct&&(checked||previouslyAnswered)){choiceStyling.push(styles$r.choiceIncorrect);crossOutColor=color.red;}else if(checked){choiceStyling.push(styles$r.choiceNeutral);crossOutColor=color.blue;}else if(pressed){choiceStyling.push(styles$r.activeNeutral);crossOutColor=color.blue;}else {choiceStyling.push(styles$r.uncheckedColors);crossOutColor=color.offBlack64;}return jsxRuntimeExports.jsxs("div",{className:css(styles$x.iconWrapper),children:[jsxRuntimeExports.jsx(FocusRing,{color:color.blue,visible:focused||hovered,multipleSelect:multipleSelect,children:jsxRuntimeExports.jsx("div",{"data-testid":"choice-icon__library-choice-icon",className:css(...choiceStyling),"data-is-radio-icon":true,children:jsxRuntimeExports.jsx("div",{className:css(styles$r.innerWrapper),children:jsxRuntimeExports.jsx(ChoiceInner,{pos:pos,showCorrectness:showCorrectness,correct:correct})})})}),crossedOut&&jsxRuntimeExports.jsx(CrossOutLine,{color:crossOutColor})]})};const styles$r=StyleSheet.create({innerWrapper:{width:CHOICE_ICON_SIZE,height:CHOICE_ICON_SIZE,display:"flex",alignItems:"center",justifyContent:"center"},choiceBase:{width:CHOICE_ICON_SIZE,height:CHOICE_ICON_SIZE,boxSizing:"border-box",borderStyle:"solid",borderWidth:2,fontFamily:baseFontFamily,fontWeight:"bold",display:"flex",alignItems:"center",justifyContent:"center"},choiceHasLetter:{fontSize:12},choiceHasIcon:{fontSize:CHOICE_ICON_SIZE},choiceIsChecked:{color:color.white},choiceIsUnchecked:{color:color.offBlack64},choiceCorrect:{backgroundColor:color.green,borderColor:color.green},choiceIncorrect:{backgroundColor:color.red,borderColor:color.red},choiceNeutral:{backgroundColor:color.blue,borderColor:color.blue},activeNeutral:{color:color.blue,borderColor:color.blue,backgroundColor:"transparent"},multiSelectShape:{borderRadius:3},singleSelectShape:{borderRadius:CHOICE_ICON_SIZE},uncheckedColors:{borderColor:color.offBlack64}});
1745
1773
 
1746
1774
  function renderText(checked,correct,crossedOut,strings){if(correct){if(checked){return strings.correctSelected}if(crossedOut){return strings.correctCrossedOut}return strings.correct}if(checked){return strings.incorrectSelected}return strings.incorrect}const OptionStatus=function(props){const{checked,correct,crossedOut,previouslyAnswered,reviewMode}=props;const{strings}=usePerseusI18n();if(!reviewMode&&!previouslyAnswered){return null}let textStyle;if(correct){textStyle=styles$q.correct;}else {if(checked||previouslyAnswered){textStyle=styles$q.incorrectAnswered;}else {textStyle=styles$q.incorrect;}}return jsxRuntimeExports.jsx("div",{className:css(styles$q.text,textStyle),children:renderText(checked,correct,crossedOut,strings)})};const styles$q=StyleSheet.create({text:{alignItems:"center",display:"flex",fontSize:12,height:32,textTransform:"uppercase"},correct:{color:color.green},incorrectAnswered:{color:color.red},incorrect:{color:color.offBlack64}});
1747
1775
 
1748
1776
  const intermediateCheckboxPadding=`16px 16px`;const intermediateCheckboxPaddingPhone=`12px 16px`;const ellipsisHorizontalIcon={path:"M27.218 6.82l0 13.578q0 2.852-1.984 4.836t-4.836 1.984l-13.578 0q-2.852 0-4.836-1.984t-1.984-4.836l0-13.578q0-2.852 1.984-4.836t4.836-1.984l13.578 0q2.852 0 4.836 1.984t1.984 4.836zm36.27 0l0 13.578q0 2.852-1.984 4.836t-4.836 1.984l-13.578 0q-2.852 0-4.836-1.984t-1.984-4.836l0-13.578q0-2.852 1.984-4.836t4.836-1.984l13.578 0q2.852 0 4.836 1.984t1.984 4.836zm36.27 0l0 13.578q0 2.852-1.984 4.836t-4.836 1.984l-13.578 0q-2.852 0-4.836-1.984t-1.984-4.836l0-13.578q0-2.852 1.984-4.836t4.836-1.984l13.578 0q2.852 0 4.836 1.984t1.984 4.836z",width:100,height:27.284};const Choice=function(props){const{disabled=false,checked=false,content,crossedOut,showCorrectness,multipleSelect,onChange=newValues=>{},reviewMode,correct=false,apiOptions=ApiOptions.defaults,previouslyAnswered=false,pos=0,showRationale=false,rationale,forwardedRef}=props;const[isInputFocused,setIsInputFocused]=useState(false);const{strings}=usePerseusI18n();useEffect(()=>{if(isInputFocused&&disabled){setIsInputFocused(false);}},[disabled,isInputFocused,setIsInputFocused]);function sendChange(newValues){const updatedChecked=newValues.checked??checked;const updatedCrossedOut=newValues.crossedOut??crossedOut;onChange({checked:updatedChecked,crossedOut:updatedCrossedOut});}const descriptionClassName=classNames$1("description",css(styles$p.description));const rationaleClassName=classNames$1("perseus-radio-rationale-content",css(styles$p.rationale));const showDimmed=!reviewMode&&apiOptions.readOnly||crossedOut;const letter=getChoiceLetter(pos,strings);const a11yText=getA11yText(letter,checked,correct,crossedOut,showCorrectness,strings);return jsxRuntimeExports.jsxs("div",{style:{dispay:"flex",flexDirection:"column",color:color.offBlack},className:descriptionClassName,children:[jsxRuntimeExports.jsxs("div",{style:{display:"flex",flexDirection:"row",opacity:showDimmed?.5:1,overflowX:"auto",overflowY:"hidden"},children:[jsxRuntimeExports.jsx("div",{className:"perseus-sr-only",children:jsxRuntimeExports.jsxs("label",{children:[a11yText,"   ",content,jsxRuntimeExports.jsx("input",{type:multipleSelect?"checkbox":"radio",checked:checked,onClick:()=>{sendChange({checked:!checked,crossedOut:false});},onChange:()=>{},disabled:disabled||apiOptions.readOnly,tabIndex:-1,className:ClassNames.RADIO.OPTION_CONTENT})]})}),jsxRuntimeExports.jsx(Clickable,{onClick:()=>{sendChange({checked:!checked,crossedOut:false});},disabled:disabled||apiOptions.readOnly,style:{flex:1,color:color.offBlack,userSelect:"text"},ref:forwardedRef,"aria-hidden":"true",children:({hovered,focused,pressed})=>jsxRuntimeExports.jsxs("div",{style:{display:"flex",flexDirection:"row",justifyContent:"center",alignContent:"center",paddingTop:spacing.xSmall_8,paddingBottom:spacing.xSmall_8,paddingLeft:spacing.xSmall_8},children:[jsxRuntimeExports.jsx(ChoiceIcon,{pos:pos,correct:correct,crossedOut:crossedOut,pressed:pressed,focused:focused,checked:checked,hovered:hovered,showCorrectness:showCorrectness,multipleSelect:multipleSelect,reviewMode:reviewMode,previouslyAnswered:previouslyAnswered}),jsxRuntimeExports.jsxs("span",{style:{paddingLeft:spacing.small_12,textAlign:"left",flex:1,paddingTop:4},children:[jsxRuntimeExports.jsx("div",{children:jsxRuntimeExports.jsx(OptionStatus,{checked:checked,correct:correct,crossedOut:crossedOut,previouslyAnswered:previouslyAnswered,reviewMode:reviewMode})}),jsxRuntimeExports.jsx("div",{children:content})]})]})}),apiOptions.crossOutEnabled&&!reviewMode&&jsxRuntimeExports.jsx(Popover,{dismissEnabled:true,content:({close})=>jsxRuntimeExports.jsx(PopoverContent,{title:strings.crossOut,content:strings.crossOutOption,closeButtonVisible:true,actions:jsxRuntimeExports.jsxs(View,{children:[jsxRuntimeExports.jsx(Strut,{size:spacing.medium_16}),jsxRuntimeExports.jsx(Button,{kind:"primary","aria-label":strings.crossOutChoice({letter:getChoiceLetter(pos,strings)}),disabled:apiOptions.readOnly||reviewMode,onClick:()=>{if(!crossedOut){sendChange({checked:false,crossedOut:true});}else {sendChange({crossedOut:false});}close();},children:crossedOut?strings.bringBack:strings.crossOut})]})}),children:({open})=>jsxRuntimeExports.jsx(Clickable,{onClick:open,"aria-label":strings.openMenuForChoice({letter:getChoiceLetter(pos,strings)}),style:{alignSelf:"center",padding:"5px",display:"flex",justifyContent:"center",alignItems:"center",marginLeft:"10px"},children:({hovered,focused,pressed})=>jsxRuntimeExports.jsx(Icon,{icon:ellipsisHorizontalIcon,size:3,color:color.offBlack64})})})]}),showRationale&&jsxRuntimeExports.jsx("div",{className:rationaleClassName,"data-testid":`perseus-radio-rationale-content-${pos}`,children:rationale})]})};const styles$p=StyleSheet.create({description:{display:"inline-block",width:"100%"},rationale:{display:"block",padding:intermediateCheckboxPadding,paddingTop:0,marginLeft:54,color:color.offBlack64,[mediaQueries.smOrSmaller]:{padding:intermediateCheckboxPaddingPhone,paddingTop:0}}});var Choice$1 = React.forwardRef((props,ref)=>jsxRuntimeExports.jsx(Choice,{...props,forwardedRef:ref}));
1749
1777
 
1750
- const ChoiceNoneAbove=function({content,forwardedRef,showContent=true,...rest}){const{strings}=usePerseusI18n();const choiceProps={...rest,content:showContent?content:jsxRuntimeExports.jsx(Renderer,{content:strings.noneOfTheAbove,strings:strings},"noneOfTheAboveRenderer")};return jsxRuntimeExports.jsx(Choice$1,{...choiceProps,ref:forwardedRef})};var ChoiceNoneAbove$1 = React.forwardRef((props,ref)=>jsxRuntimeExports.jsx(ChoiceNoneAbove,{...props,forwardedRef:ref}));
1778
+ const{captureScratchpadTouchStart: captureScratchpadTouchStart$1}=Util;function getInstructionsText(multipleSelect,countChoices,numCorrect,strings){if(multipleSelect){if(usesNumCorrect(multipleSelect,!!countChoices,numCorrect)){return strings.chooseNumAnswers({numCorrect:String(numCorrect)})}return strings.chooseAllAnswers}return strings.chooseOneAnswer}const BaseRadio=function({apiOptions,reviewModeRubric,reviewMode,choices,editMode=false,multipleSelect=false,labelWrap,countChoices,numCorrect,isLastUsedWidget,onChange,registerFocusFunction}){const{strings}=usePerseusI18n();const prevReviewModeRubric=useRef();const choiceRefs=useRef([]);useEffect(()=>{if(apiOptions.canScrollPage&&isLastUsedWidget&&reviewModeRubric&&!prevReviewModeRubric.current){const checkedIndex=choices.findIndex(c=>c.checked);if(checkedIndex>=0){const ref=choiceRefs.current[checkedIndex];const anyNode=ReactDOM__default.findDOMNode(ref.current);const buttonNode=anyNode;if(buttonNode){scrollElementIntoView(buttonNode);}}}prevReviewModeRubric.current=reviewModeRubric;},[apiOptions,choices,isLastUsedWidget,reviewModeRubric]);function updateChoice(choiceIndex,newValues){let newCheckedList;if(newValues.checked&&!multipleSelect){newCheckedList=choices.map(_=>false);}else {newCheckedList=choices.map(c=>c.checked);}const newCrossedOutList=choices.map(c=>c.crossedOut);newCheckedList[choiceIndex]=newValues.checked;newCrossedOutList[choiceIndex]=newValues.crossedOut;onChange({checked:newCheckedList,crossedOut:newCrossedOutList});}registerFocusFunction?.(choiceIndex=>{const ref=choiceRefs.current[choiceIndex||0];const anyNode=ReactDOM__default.findDOMNode(ref.current);const buttonNode=anyNode;if(buttonNode){buttonNode.focus();}else {return false}return true});const isMobile=apiOptions.isMobile;const firstChoiceHighlighted=choices[0].highlighted;const lastChoiceHighlighted=choices[choices.length-1].highlighted;const className=classNames$1("perseus-widget-radio",!editMode&&"perseus-rendered-radio",css(styles$o.radio,styles$o.responsiveRadioContainer,firstChoiceHighlighted&&isMobile&&styles$o.radioContainerFirstHighlighted,lastChoiceHighlighted&&isMobile&&styles$o.radioContainerLastHighlighted));const instructionsClassName=classNames$1("instructions",css(styles$o.instructions,isMobile&&styles$o.instructionsMobile));const instructions=getInstructionsText(multipleSelect,countChoices,numCorrect,strings);const responsiveClassName=css(styles$o.responsiveFieldset);const fieldset=jsxRuntimeExports.jsxs("fieldset",{className:`perseus-widget-radio-fieldset ${responsiveClassName}`,"data-feature-flag":"feature flag is ON",children:[jsxRuntimeExports.jsx("legend",{className:"perseus-sr-only",children:instructions}),jsxRuntimeExports.jsx("div",{className:instructionsClassName,"aria-hidden":"true",children:instructions}),jsxRuntimeExports.jsx("ul",{className:className,style:{listStyle:"none"},children:choices.map((choice,i)=>{let Element=Choice$1;const ref=React.createRef();choiceRefs.current[i]=ref;const elementProps={apiOptions:apiOptions,multipleSelect:multipleSelect,checked:choice.checked,crossedOut:choice.crossedOut,previouslyAnswered:choice.previouslyAnswered,reviewMode,correct:choice.correct,rationale:choice.rationale,content:choice.content,disabled:apiOptions.readOnly||choice.disabled,showCorrectness:reviewMode||!!choice.showCorrectness,showRationale:choice.hasRationale&&(reviewMode||choice.showRationale),pos:i,onChange:newValues=>{if(editMode){return}updateChoice(i,newValues);}};if(choice.isNoneOfTheAbove){Element=ChoiceNoneAbove$1;_.extend(elementProps,{showContent:choice.revealNoneOfTheAbove});}const nextChoice=choices[i+1];const nextChoiceHighlighted=!!nextChoice&&nextChoice.highlighted;const aphroditeClassName=checked=>{return css(styles$o.item,styles$o.responsiveItem,checked&&styles$o.selectedItem,checked&&choice.highlighted&&styles$o.aboveBackdrop,checked&&choice.highlighted&&apiOptions.isMobile&&styles$o.aboveBackdropMobile,nextChoiceHighlighted&&apiOptions.isMobile&&styles$o.nextHighlighted)};aphroditeClassName(true);let correctnessClass;if(reviewMode&&reviewModeRubric){correctnessClass=reviewModeRubric.choices[i].correct?ClassNames.CORRECT:ClassNames.INCORRECT;}const className=classNames$1(aphroditeClassName(choice.checked),ClassNames.RADIO.OPTION,choice.checked&&ClassNames.RADIO.SELECTED,correctnessClass);let listElem=null;let clickHandler;if(editMode){clickHandler=e=>{let elem=e.target;while(elem&&elem!==listElem){if(elem.getAttribute("data-is-radio-icon")){updateChoice(i,{checked:!choice.checked,crossedOut:choice.crossedOut});return}elem=elem.parentNode;}};}return jsxRuntimeExports.jsx("li",{ref:e=>listElem=e,className:className,onClick:clickHandler,onTouchStart:labelWrap?undefined:captureScratchpadTouchStart$1,children:jsxRuntimeExports.jsx(Element,{...elementProps,ref:ref})},i)})})]});return jsxRuntimeExports.jsx("div",{className:css(styles$o.responsiveContainer),children:fieldset})};const styles$o=StyleSheet.create({instructions:{display:"block",color:gray17,fontSize:14,lineHeight:1.25,fontFamily:"inherit",fontStyle:"normal",fontWeight:"bold",marginBottom:16},instructionsMobile:{fontSize:18,[mediaQueries.smOrSmaller]:{fontSize:16},[mediaQueries.xl]:{fontSize:20}},radio:{padding:0},responsiveRadioContainer:{borderBottom:`1px solid ${radioBorderColor$1}`,borderTop:`1px solid ${radioBorderColor$1}`,width:"auto",[mediaQueries.smOrSmaller]:{marginLeft:negativePhoneMargin,marginRight:negativePhoneMargin}},radioContainerFirstHighlighted:{borderTop:`1px solid rgba(0, 0, 0, 0)`},radioContainerLastHighlighted:{borderBottom:`1px solid rgba(0, 0, 0, 0)`},item:{marginLeft:20},responsiveItem:{marginLeft:0,padding:0,":not(:last-child)":{borderBottom:`1px solid ${radioBorderColor$1}`}},selectedItem:{background:"white"},aboveBackdrop:{position:"relative",zIndex:1062},aboveBackdropMobile:{boxShadow:"0 0 4px 0 rgba(0, 0, 0, 0.2),"+"0 0 2px 0 rgba(0, 0, 0, 0.1)",":not(:last-child)":{borderBottom:`1px solid rgba(0, 0, 0, 0)`}},nextHighlighted:{":not(:last-child)":{borderBottom:`1px solid rgba(0, 0, 0, 0)`}},responsiveContainer:{overflow:"auto",marginLeft:negativePhoneMargin,paddingLeft:phoneMargin},responsiveFieldset:{paddingRight:phoneMargin,minWidth:"auto"}});
1751
1779
 
1752
- const{captureScratchpadTouchStart: captureScratchpadTouchStart$1}=Util;function getInstructionsText(multipleSelect,countChoices,numCorrect,strings){if(multipleSelect){if(usesNumCorrect(multipleSelect,!!countChoices,numCorrect)){return strings.chooseNumAnswers({numCorrect:String(numCorrect)})}return strings.chooseAllAnswers}return strings.chooseOneAnswer}const BaseRadio=function({apiOptions,reviewModeRubric,reviewMode,choices,editMode=false,multipleSelect=false,labelWrap,countChoices,numCorrect,isLastUsedWidget,onChange,registerFocusFunction}){const{strings}=usePerseusI18n();const prevReviewModeRubric=useRef();const choiceRefs=useRef([]);useEffect(()=>{if(apiOptions.canScrollPage&&isLastUsedWidget&&reviewModeRubric&&!prevReviewModeRubric.current){const checkedIndex=choices.findIndex(c=>c.checked);if(checkedIndex>=0){const ref=choiceRefs.current[checkedIndex];const anyNode=ReactDOM__default.findDOMNode(ref.current);const buttonNode=anyNode;if(buttonNode){scrollElementIntoView(buttonNode);}}}prevReviewModeRubric.current=reviewModeRubric;},[apiOptions,choices,isLastUsedWidget,reviewModeRubric]);function updateChoice(choiceIndex,newValues){let newCheckedList;if(newValues.checked&&!multipleSelect){newCheckedList=choices.map(_=>false);}else {newCheckedList=choices.map(c=>c.checked);}const newCrossedOutList=choices.map(c=>c.crossedOut);newCheckedList[choiceIndex]=newValues.checked;newCrossedOutList[choiceIndex]=newValues.crossedOut;onChange({checked:newCheckedList,crossedOut:newCrossedOutList});}registerFocusFunction?.(choiceIndex=>{const ref=choiceRefs.current[choiceIndex||0];const anyNode=ReactDOM__default.findDOMNode(ref.current);const buttonNode=anyNode;if(buttonNode){buttonNode.focus();}else {return false}return true});const isMobile=apiOptions.isMobile;const firstChoiceHighlighted=choices[0].highlighted;const lastChoiceHighlighted=choices[choices.length-1].highlighted;const className=classNames$1("perseus-widget-radio",!editMode&&"perseus-rendered-radio",css(styles$o.radio,styles$o.responsiveRadioContainer,firstChoiceHighlighted&&isMobile&&styles$o.radioContainerFirstHighlighted,lastChoiceHighlighted&&isMobile&&styles$o.radioContainerLastHighlighted));const instructionsClassName=classNames$1("instructions",css(styles$o.instructions,isMobile&&styles$o.instructionsMobile));const instructions=getInstructionsText(multipleSelect,countChoices,numCorrect,strings);const responsiveClassName=css(styles$o.responsiveFieldset);const fieldset=jsxRuntimeExports.jsxs("fieldset",{className:`perseus-widget-radio-fieldset ${responsiveClassName}`,children:[jsxRuntimeExports.jsx("legend",{className:"perseus-sr-only",children:instructions}),jsxRuntimeExports.jsx("div",{className:instructionsClassName,"aria-hidden":"true",children:instructions}),jsxRuntimeExports.jsx("ul",{className:className,style:{listStyle:"none"},children:choices.map((choice,i)=>{let Element=Choice$1;const ref=React.createRef();choiceRefs.current[i]=ref;const elementProps={apiOptions:apiOptions,multipleSelect:multipleSelect,checked:choice.checked,crossedOut:choice.crossedOut,previouslyAnswered:choice.previouslyAnswered,reviewMode,correct:choice.correct,rationale:choice.rationale,content:choice.content,disabled:apiOptions.readOnly||choice.disabled,showCorrectness:reviewMode||!!choice.showCorrectness,showRationale:choice.hasRationale&&(reviewMode||choice.showRationale),pos:i,onChange:newValues=>{if(editMode){return}updateChoice(i,newValues);}};if(choice.isNoneOfTheAbove){Element=ChoiceNoneAbove$1;_.extend(elementProps,{showContent:choice.revealNoneOfTheAbove});}const nextChoice=choices[i+1];const nextChoiceHighlighted=!!nextChoice&&nextChoice.highlighted;const aphroditeClassName=checked=>{return css(styles$o.item,styles$o.responsiveItem,checked&&styles$o.selectedItem,checked&&choice.highlighted&&styles$o.aboveBackdrop,checked&&choice.highlighted&&apiOptions.isMobile&&styles$o.aboveBackdropMobile,nextChoiceHighlighted&&apiOptions.isMobile&&styles$o.nextHighlighted)};aphroditeClassName(true);let correctnessClass;if(reviewMode&&reviewModeRubric){correctnessClass=reviewModeRubric.choices[i].correct?ClassNames.CORRECT:ClassNames.INCORRECT;}const className=classNames$1(aphroditeClassName(choice.checked),ClassNames.RADIO.OPTION,choice.checked&&ClassNames.RADIO.SELECTED,correctnessClass);let listElem=null;let clickHandler;if(editMode){clickHandler=e=>{let elem=e.target;while(elem&&elem!==listElem){if(elem.getAttribute("data-is-radio-icon")){updateChoice(i,{checked:!choice.checked,crossedOut:choice.crossedOut});return}elem=elem.parentNode;}};}return jsxRuntimeExports.jsx("li",{ref:e=>listElem=e,className:className,onClick:clickHandler,onTouchStart:labelWrap?undefined:captureScratchpadTouchStart$1,children:jsxRuntimeExports.jsx(Element,{...elementProps,ref:ref})},i)})})]});return jsxRuntimeExports.jsx("div",{className:css(styles$o.responsiveContainer),children:fieldset})};const styles$o=StyleSheet.create({instructions:{display:"block",color:gray17,fontSize:14,lineHeight:1.25,fontFamily:"inherit",fontStyle:"normal",fontWeight:"bold",marginBottom:16},instructionsMobile:{fontSize:18,[mediaQueries.smOrSmaller]:{fontSize:16},[mediaQueries.xl]:{fontSize:20}},radio:{padding:0},responsiveRadioContainer:{borderBottom:`1px solid ${radioBorderColor$1}`,borderTop:`1px solid ${radioBorderColor$1}`,width:"auto",[mediaQueries.smOrSmaller]:{marginLeft:negativePhoneMargin,marginRight:negativePhoneMargin}},radioContainerFirstHighlighted:{borderTop:`1px solid rgba(0, 0, 0, 0)`},radioContainerLastHighlighted:{borderBottom:`1px solid rgba(0, 0, 0, 0)`},item:{marginLeft:20},responsiveItem:{marginLeft:0,padding:0,":not(:last-child)":{borderBottom:`1px solid ${radioBorderColor$1}`}},selectedItem:{background:"white"},aboveBackdrop:{position:"relative",zIndex:1062},aboveBackdropMobile:{boxShadow:"0 0 4px 0 rgba(0, 0, 0, 0.2),"+"0 0 2px 0 rgba(0, 0, 0, 0.1)",":not(:last-child)":{borderBottom:`1px solid rgba(0, 0, 0, 0)`}},nextHighlighted:{":not(:last-child)":{borderBottom:`1px solid rgba(0, 0, 0, 0)`}},responsiveContainer:{overflow:"auto",marginLeft:negativePhoneMargin,paddingLeft:phoneMargin},responsiveFieldset:{paddingRight:phoneMargin,minWidth:"auto"}});
1780
+ let Radio$2 = class Radio extends React.Component{static getUserInputFromProps(props,unshuffle=true){if(props.choiceStates){const choiceStates=props.choiceStates;const choicesSelected=choiceStates.map(()=>false);for(let i=0;i<choicesSelected.length;i++){const index=unshuffle?props.choices[i].originalIndex:i;choicesSelected[index]=choiceStates[i].selected;}return {choicesSelected}}const{values}=props;if(values){const choicesSelected=[...values];const valuesLength=values.length;for(let i=0;i<valuesLength;i++){const index=unshuffle?props.choices[i].originalIndex:i;choicesSelected[index]=values[i];}return {choicesSelected}}return {choicesSelected:props.choices.map(()=>false)}}componentDidUpdate(prevProps){if(this.props.showSolutions==="selected"&&prevProps.showSolutions!=="selected"){this.showRationalesForCurrentlySelectedChoices(this.props);}}focus(choiceIndex){if(this.focusFunction){return this.focusFunction(choiceIndex)}return false}registerFocusFunction(fun){this.focusFunction=fun;}getUserInput(){return Radio.getUserInputFromProps(this.props)}getPromptJSON(){const userInput=Radio.getUserInputFromProps(this.props,false);return getPromptJSON$q(this.props,userInput)}render(){const{choices}=this.props;const{strings}=this.context;let choiceStates;if(this.props.static){choiceStates=choices.map(choice=>({selected:!!choice.correct,crossedOut:false,readOnly:true,highlighted:false,rationaleShown:true,correctnessShown:true,previouslyAnswered:false}));}else if(this.props.showSolutions==="all"){choiceStates=choices.map(({correct})=>({selected:!!correct,crossedOut:false,readOnly:true,highlighted:false,rationaleShown:true,correctnessShown:true,previouslyAnswered:false}));}else if(this.props.choiceStates){choiceStates=this.props.choiceStates;}else if(this.props.values){choiceStates=this.props.values.map(val=>({selected:val,crossedOut:false,readOnly:false,highlighted:false,rationaleShown:false,correctnessShown:false,previouslyAnswered:false}));}else {choiceStates=choices.map(()=>({selected:false,crossedOut:false,readOnly:false,highlighted:false,rationaleShown:false,correctnessShown:false,previouslyAnswered:false}));}const choicesProp=choices.map((choice,i)=>{const content=choice.isNoneOfTheAbove&&!choice.content?strings.noneOfTheAbove:choice.content;const{selected,crossedOut,rationaleShown,correctnessShown,readOnly,highlighted,previouslyAnswered}=choiceStates[i];const reviewChoice=this.props.reviewModeRubric?.choices[i];return {content:this._renderRenderer(content),checked:selected,correct:choice.correct===undefined?!!reviewChoice&&!!reviewChoice.correct:choice.correct,disabled:readOnly,hasRationale:!!choice.clue,rationale:this._renderRenderer(choice.clue),showRationale:rationaleShown,showCorrectness:correctnessShown,isNoneOfTheAbove:!!choice.isNoneOfTheAbove,revealNoneOfTheAbove:!!(this.props.questionCompleted&&selected),crossedOut,highlighted,previouslyAnswered:previouslyAnswered}});console.log("This is the new radio component.");return jsxRuntimeExports.jsx(BaseRadio,{labelWrap:true,multipleSelect:this.props.multipleSelect,countChoices:this.props.countChoices,numCorrect:this.props.numCorrect,choices:choicesProp,onChange:this.updateChoices,reviewModeRubric:this.props.reviewModeRubric,reviewMode:this.props.reviewMode,deselectEnabled:this.props.deselectEnabled,apiOptions:this.props.apiOptions,isLastUsedWidget:this.props.isLastUsedWidget,registerFocusFunction:i=>this.registerFocusFunction(i)})}constructor(...args){super(...args),this._renderRenderer=(content="")=>{let nextPassageRefId=1;const widgets={};const modContent=content.replace(/\{\{passage-ref (\d+) (\d+)(?: "([^"]*)")?\}\}/g,(match,passageNum,refNum,summaryText)=>{const widgetId="passage-ref "+nextPassageRefId;nextPassageRefId++;widgets[widgetId]={type:"passage-ref",graded:false,options:{passageNumber:parseInt(passageNum),referenceNumber:parseInt(refNum),summaryText:summaryText},version:PassageRef$1.version};return "[["+Util.snowman+" "+widgetId+"]]"});return jsxRuntimeExports.jsx(Renderer,{content:modContent,widgets:widgets,findExternalWidgets:this.props.findWidgets,alwaysUpdate:true,linterContext:{...this.props.linterContext,blockHighlight:true},strings:this.context.strings},"choiceContentRenderer")},this.updateChoices=newValueLists=>{const{choiceStates,choices}=this.props;const newChoiceStates=choiceStates?choiceStates.map(state=>({...state})):choices.map(()=>({selected:false,crossedOut:false,highlighted:false,rationaleShown:false,correctnessShown:false,previouslyAnswered:false,readOnly:false}));newChoiceStates.forEach((choiceState,i)=>{choiceState.selected=newValueLists.checked[i];choiceState.crossedOut=newValueLists.crossedOut[i];});this.props.onChange({choiceStates:newChoiceStates});this.props.trackInteraction();},this.showRationalesForCurrentlySelectedChoices=rubric=>{const{choiceStates}=this.props;if(choiceStates){const score=scoreRadio(this.getUserInput(),rubric);const widgetCorrect=score.type==="points"&&score.total===score.earned;const newStates=choiceStates.map(state=>({...state,highlighted:state.selected,rationaleShown:state.selected||state.rationaleShown||widgetCorrect,readOnly:state.selected||state.readOnly||widgetCorrect||this.props.showSolutions!=="none",correctnessShown:state.selected||state.correctnessShown,previouslyAnswered:state.previouslyAnswered||state.selected}));this.props.onChange({choiceStates:newStates},null,true);}},this.deselectIncorrectSelectedChoices=()=>{if(this.props.choiceStates){const newStates=this.props.choiceStates.map((state,i)=>({...state,selected:state.selected&&!!this.props.choices[i].correct,highlighted:false}));this.props.onChange({choiceStates:newStates},null,false);}};}};Radio$2.contextType=PerseusI18nContext;Radio$2.defaultProps={choices:[],multipleSelect:false,countChoices:false,deselectEnabled:false,linterContext:linterContextDefault,showSolutions:"none"};
1753
1781
 
1754
- let Radio$1 = class Radio extends React.Component{static getUserInputFromProps(props,unshuffle=true){if(props.choiceStates){const choiceStates=props.choiceStates;const choicesSelected=choiceStates.map(()=>false);for(let i=0;i<choicesSelected.length;i++){const index=unshuffle?props.choices[i].originalIndex:i;choicesSelected[index]=choiceStates[i].selected;}return {choicesSelected}}const{values}=props;if(values){const choicesSelected=[...values];const valuesLength=values.length;for(let i=0;i<valuesLength;i++){const index=unshuffle?props.choices[i].originalIndex:i;choicesSelected[index]=values[i];}return {choicesSelected}}return {choicesSelected:props.choices.map(()=>false)}}componentDidUpdate(prevProps){if(this.props.showSolutions==="selected"&&prevProps.showSolutions!=="selected"){this.showRationalesForCurrentlySelectedChoices(this.props);}}focus(choiceIndex){if(this.focusFunction){return this.focusFunction(choiceIndex)}return false}registerFocusFunction(fun){this.focusFunction=fun;}getUserInput(){return Radio.getUserInputFromProps(this.props)}getPromptJSON(){const userInput=Radio.getUserInputFromProps(this.props,false);return getPromptJSON$q(this.props,userInput)}render(){const{choices}=this.props;const{strings}=this.context;let choiceStates;if(this.props.static){choiceStates=choices.map(choice=>({selected:!!choice.correct,crossedOut:false,readOnly:true,highlighted:false,rationaleShown:true,correctnessShown:true,previouslyAnswered:false}));}else if(this.props.showSolutions==="all"){choiceStates=choices.map(({correct})=>({selected:!!correct,crossedOut:false,readOnly:true,highlighted:false,rationaleShown:true,correctnessShown:true,previouslyAnswered:false}));}else if(this.props.choiceStates){choiceStates=this.props.choiceStates;}else if(this.props.values){choiceStates=this.props.values.map(val=>({selected:val,crossedOut:false,readOnly:false,highlighted:false,rationaleShown:false,correctnessShown:false,previouslyAnswered:false}));}else {choiceStates=choices.map(()=>({selected:false,crossedOut:false,readOnly:false,highlighted:false,rationaleShown:false,correctnessShown:false,previouslyAnswered:false}));}const choicesProp=choices.map((choice,i)=>{const content=choice.isNoneOfTheAbove&&!choice.content?strings.noneOfTheAbove:choice.content;const{selected,crossedOut,rationaleShown,correctnessShown,readOnly,highlighted,previouslyAnswered}=choiceStates[i];const reviewChoice=this.props.reviewModeRubric?.choices[i];return {content:this._renderRenderer(content),checked:selected,correct:choice.correct===undefined?!!reviewChoice&&!!reviewChoice.correct:choice.correct,disabled:readOnly,hasRationale:!!choice.clue,rationale:this._renderRenderer(choice.clue),showRationale:rationaleShown,showCorrectness:correctnessShown,isNoneOfTheAbove:!!choice.isNoneOfTheAbove,revealNoneOfTheAbove:!!(this.props.questionCompleted&&selected),crossedOut,highlighted,previouslyAnswered:previouslyAnswered}});return jsxRuntimeExports.jsx(BaseRadio,{labelWrap:true,multipleSelect:this.props.multipleSelect,countChoices:this.props.countChoices,numCorrect:this.props.numCorrect,choices:choicesProp,onChange:this.updateChoices,reviewModeRubric:this.props.reviewModeRubric,reviewMode:this.props.reviewMode,deselectEnabled:this.props.deselectEnabled,apiOptions:this.props.apiOptions,isLastUsedWidget:this.props.isLastUsedWidget,registerFocusFunction:i=>this.registerFocusFunction(i)})}constructor(...args){super(...args),this._renderRenderer=(content="")=>{let nextPassageRefId=1;const widgets={};const modContent=content.replace(/\{\{passage-ref (\d+) (\d+)(?: "([^"]*)")?\}\}/g,(match,passageNum,refNum,summaryText)=>{const widgetId="passage-ref "+nextPassageRefId;nextPassageRefId++;widgets[widgetId]={type:"passage-ref",graded:false,options:{passageNumber:parseInt(passageNum),referenceNumber:parseInt(refNum),summaryText:summaryText},version:PassageRef$1.version};return "[["+Util.snowman+" "+widgetId+"]]"});return jsxRuntimeExports.jsx(Renderer,{content:modContent,widgets:widgets,findExternalWidgets:this.props.findWidgets,alwaysUpdate:true,linterContext:{...this.props.linterContext,blockHighlight:true},strings:this.context.strings},"choiceContentRenderer")},this.updateChoices=newValueLists=>{const{choiceStates,choices}=this.props;const newChoiceStates=choiceStates?choiceStates.map(state=>({...state})):choices.map(()=>({selected:false,crossedOut:false,highlighted:false,rationaleShown:false,correctnessShown:false,previouslyAnswered:false,readOnly:false}));newChoiceStates.forEach((choiceState,i)=>{choiceState.selected=newValueLists.checked[i];choiceState.crossedOut=newValueLists.crossedOut[i];});this.props.onChange({choiceStates:newChoiceStates});this.props.trackInteraction();},this.showRationalesForCurrentlySelectedChoices=rubric=>{const{choiceStates}=this.props;if(choiceStates){const score=scoreRadio(this.getUserInput(),rubric);const widgetCorrect=score.type==="points"&&score.total===score.earned;const newStates=choiceStates.map(state=>({...state,highlighted:state.selected,rationaleShown:state.selected||state.rationaleShown||widgetCorrect,readOnly:state.selected||state.readOnly||widgetCorrect||this.props.showSolutions!=="none",correctnessShown:state.selected||state.correctnessShown,previouslyAnswered:state.previouslyAnswered||state.selected}));this.props.onChange({choiceStates:newStates},null,true);}},this.deselectIncorrectSelectedChoices=()=>{if(this.props.choiceStates){const newStates=this.props.choiceStates.map((state,i)=>({...state,selected:state.selected&&!!this.props.choices[i].correct,highlighted:false}));this.props.onChange({choiceStates:newStates},null,false);}};}};Radio$1.contextType=PerseusI18nContext;Radio$1.defaultProps={choices:[],multipleSelect:false,countChoices:false,deselectEnabled:false,linterContext:linterContextDefault,showSolutions:"none"};
1782
+ let Radio$1 = class Radio extends Radio$3{focus(choiceIndex){if(this.radioRef.current){return this.radioRef.current.focus(choiceIndex)}return false}render(){const RadioProper=this.ffIsOn?Radio$2:Radio$3;return jsxRuntimeExports.jsx(RadioProper,{ref:this.radioRef,...this.props})}constructor(props){super(props),this.ffIsOn=false,this.radioRef=React.createRef();this.ffIsOn=props.apiOptions.flags?.["new-radio-widget"]??false;}};
1755
1783
 
1756
1784
  const _choiceTransform=(widgetOptions,strings,problemNum)=>{const _maybeRandomize=function(array){const randomSeed=problemNum===undefined?random:problemNum;return widgetOptions.randomize?shuffle(array,randomSeed??0):array};const _addNoneOfAbove=function(choices){let noneOfTheAbove=null;const newChoices=choices.filter((choice,index)=>{if(choice.isNoneOfTheAbove){noneOfTheAbove=choice;return false}return true});if(noneOfTheAbove){newChoices.push(noneOfTheAbove);}return newChoices};const enforceOrdering=choices=>{const ReversedChoices=[[strings.false,strings.true],[strings.no,strings.yes]];const content=choices.map(c=>c.content);if(ReversedChoices.some(reversed=>_.isEqual(content,reversed))){return [choices[1],choices[0]]}return choices};const choices=widgetOptions.choices.map((choice,i)=>{return {...choice,originalIndex:i,correct:Boolean(choice.correct)}});return _addNoneOfAbove(enforceOrdering(_maybeRandomize(choices)))};const transform$1=(widgetOptions,strings,problemNum)=>{const choices=_choiceTransform(widgetOptions,strings,problemNum);const{hasNoneOfTheAbove,multipleSelect,countChoices,deselectEnabled,numCorrect}=widgetOptions;return {numCorrect:numCorrect,hasNoneOfTheAbove,multipleSelect,countChoices,deselectEnabled,choices,selectedChoices:_.pluck(choices,"correct")}};var Radio = {name:"radio",displayName:"Radio / Multiple choice",accessible:true,widget:Radio$1,transform:transform$1,staticTransform:transform$1,version:radioLogic.version,propUpgrades:radioLogic.widgetOptionsUpgrades,isLintable:true};
1757
1785
 
@@ -1902,7 +1930,7 @@ function SVGLine(props){const{start,end,style,className,testId}=props;return jsx
1902
1930
 
1903
1931
  const{calculateAngleInDegrees: calculateAngleInDegrees$3}=angles;function Vector(props){const{interactiveColor}=useGraphConfig();const{tail,tip,color=interactiveColor,style,testId}=props;const[tailPx,tipPx]=useTransformVectorsToPixels(tail,tip);const direction=vec.sub(tipPx,tailPx);const angle=calculateAngleInDegrees$3(direction);return jsxRuntimeExports.jsxs("g",{style:{stroke:color,strokeWidth:2},"data-testid":testId,children:[jsxRuntimeExports.jsx(SVGLine,{start:tailPx,end:tipPx,style:style}),jsxRuntimeExports.jsx(Arrowhead,{angle:angle,tip:tip,color:color})]})}
1904
1932
 
1905
- function srFormatNumber(a,locale,maximumFractionDigits){const piBasedNumber=getPiMultiple(a);if(piBasedNumber){return piBasedNumber}return (0+a).toLocaleString(locale,{maximumFractionDigits:maximumFractionDigits??3,useGrouping:false})}function getPiMultiple(a){if(Number.isInteger(a)||a===0||a>1e12){return null}const piCoefficient=a/Math.PI;const truncatedCoefficient=parseFloat(piCoefficient.toFixed(12));if(Number.isInteger(truncatedCoefficient)){if(truncatedCoefficient===1){return "π"}if(truncatedCoefficient===-1){return "-π"}return truncatedCoefficient+"π"}const acceptableDivisors=[2,3,4,6];for(const divisor of acceptableDivisors){const coefficientNumerator=parseFloat((piCoefficient*divisor).toFixed(12));if(Number.isInteger(coefficientNumerator)){if(coefficientNumerator===1){return "π/"+divisor}if(coefficientNumerator===-1){return "-π/"+divisor}return coefficientNumerator+"π/"+divisor}}return null}
1933
+ function srFormatNumber(a,locale,maximumFractionDigits){const piBasedNumber=getPiMultiple(a);if(piBasedNumber){return piBasedNumber}return (0+a).toLocaleString(locale,{maximumFractionDigits:maximumFractionDigits??3,useGrouping:false})}function getPiMultiple(a){if(Number.isInteger(a)||a===0||a>1e12){return null}const piCoefficient=a/Math.PI;const truncatedCoefficient=parseFloat(piCoefficient.toFixed(12));if(Number.isInteger(truncatedCoefficient)){return truncatedCoefficient+"π"}const acceptableDivisors=[2,3,4,6];for(const divisor of acceptableDivisors){const coefficientNumerator=parseFloat((piCoefficient*divisor).toFixed(12));if(Number.isInteger(coefficientNumerator)){return coefficientNumerator+"π/"+divisor}}return null}
1906
1934
 
1907
1935
  const getIntersectionOfRayWithBox=(initialPoint,throughPoint,box)=>{const[[xMin,xMax],[yMin,yMax]]=box;const[aX,aY]=initialPoint;const[bX,bY]=throughPoint;const yDiff=bY-aY;const xDiff=bX-aX;const slope=yDiff/xDiff;const inverseSlope=1/slope;const xExtreme=xDiff<0?xMin:xMax;const yExtreme=yDiff<0?yMin:yMax;const yAtXExtreme=aY+(xExtreme-aX)*slope;const xAtYExtreme=aX+(yExtreme-aY)*inverseSlope;switch(true){case isBetween(yAtXExtreme,yMin,yMax):return [xExtreme,yAtXExtreme];case isBetween(xAtYExtreme,xMin,xMax):return [xAtYExtreme,yExtreme];default:return [xExtreme,yExtreme]}};function isBetween(x,low,high){return x>=low&&x<=high}function getArrayWithoutDuplicates(array){const returnArray=[];for(const coordPair of array){if(!returnArray.some(([x,y])=>x===coordPair[0]&&y===coordPair[1])){returnArray.push(coordPair);}}return returnArray}function getSlopeStringForLine(line,strings){const slope=(line[1][1]-line[0][1])/(line[1][0]-line[0][0]);if(!Number.isFinite(slope)){return strings.srLinearGraphSlopeVertical}if(slope===0){return strings.srLinearGraphSlopeHorizontal}return slope>0?strings.srLinearGraphSlopeIncreasing:strings.srLinearGraphSlopeDecreasing}function getInterceptStringForLine(line,strings,locale){const slope=(line[1][1]-line[0][1])/(line[1][0]-line[0][0]);const xIntercept=(0-line[0][1])/slope+line[0][0];const yIntercept=line[0][1]-slope*line[0][0];const overlapsXAxis=line[0][1]===0&&line[1][1]===0;const overlapsYAxis=line[0][0]===0&&line[1][0]===0;const hasXIntercept=Number.isFinite(xIntercept)&&!overlapsXAxis;const hasYIntercept=Number.isFinite(yIntercept)&&!overlapsYAxis;if(hasXIntercept&&hasYIntercept){return xIntercept===0&&yIntercept===0?strings.srLinearGraphOriginIntercept:strings.srLinearGraphBothIntercepts({xIntercept:srFormatNumber(xIntercept,locale),yIntercept:srFormatNumber(yIntercept,locale)})}return hasXIntercept?strings.srLinearGraphXOnlyIntercept({xIntercept:srFormatNumber(xIntercept,locale)}):strings.srLinearGraphYOnlyIntercept({yIntercept:srFormatNumber(yIntercept,locale)})}function getCoordQuadrant(coord){const[unroundedX,unroundedY]=coord;const x=Number(unroundedX.toFixed(3));const y=Number(unroundedY.toFixed(3));if(x===0&&y===0){return "origin"}if(y===0){return "x-axis"}if(x===0){return "y-axis"}if(x>0&&y>0){return 1}if(x<0&&y>0){return 2}if(x<0&&y<0){return 3}return 4}function getQuadraticVertexString(vertex,strings){const location=getCoordQuadrant(vertex);switch(location){case "origin":return strings.srQuadraticGraphVertexOrigin;case "x-axis":return strings.srQuadraticGraphVertexXAxis;case "y-axis":return strings.srQuadraticGraphVertexYAxis;default:return strings.srQuadraticGraphVertexQuadrant({quadrant:location})}}function getQuadraticPointString(pointNumber,coord,strings,locale){const location=getCoordQuadrant(coord);const[x,y]=coord;switch(location){case "origin":return strings.srQuadraticPointOrigin({pointNumber:pointNumber});case "x-axis":case "y-axis":return strings.srQuadraticPointAxis({pointNumber:pointNumber,x:srFormatNumber(x,locale),y:srFormatNumber(y,locale)});default:return strings.srQuadraticPointQuadrant({pointNumber:pointNumber,quadrant:location,x:srFormatNumber(x,locale),y:srFormatNumber(y,locale)})}}function getQuadraticXIntercepts(a,b,c){if(a===0){if(b===0){return []}return [-c/b]}const discriminant=b*b-4*a*c;if(discriminant<0){return []}const x1=(-b+Math.sqrt(discriminant))/(2*a);const x2=(-b-Math.sqrt(discriminant))/(2*a);if(x1===x2){return [x1]}return [x1,x2]}function getAngleFromPoints(points,i){if(i<0||i>=points.length||!Number.isInteger(i)){return null}if(points.length<3){return null}const point=points.at(i);const pt1=points.at(i-1);const pt2=points[(i+1)%points.length];if(!point||!pt1||!pt2){return null}const a=vec.dist(point,pt1);const b=vec.dist(point,pt2);const c=vec.dist(pt1,pt2);let lawOfCosinesRadicand=(a**2+b**2-c**2)/(2*a*b);if(lawOfCosinesRadicand<-1||lawOfCosinesRadicand>1){lawOfCosinesRadicand=Math.round(lawOfCosinesRadicand);}const angle=Math.acos(lawOfCosinesRadicand);return angle}function getSideLengthsFromPoints(points,i,isPolygonOpen){if(i<0||i>=points.length||!Number.isInteger(i)){return []}if(points.length<2){return []}const returnArray=[];const point=points[i];const point1Index=i===0?points.length-1:i-1;const point1=points[point1Index];const side1=i!==point1Index?vec.dist(point,point1):null;if(side1&&!(isPolygonOpen&&i===0)){returnArray.push({pointIndex:point1Index,sideLength:side1});}const point2Index=(i+1)%points.length;const point2=points[point2Index];const side2=i!==point2Index&&point2Index!==point1Index?vec.dist(point,point2):null;if(side2&&!(isPolygonOpen&&i===points.length-1)){returnArray.push({pointIndex:point2Index,sideLength:side2});}return returnArray}function getPolygonSideString(sideLength,pointIndex,strings,locale){return Number.isInteger(sideLength)?strings.srPolygonSideLength({pointNum:pointIndex+1,length:`${sideLength}`}):strings.srPolygonSideLengthApprox({pointNum:pointIndex+1,length:srFormatNumber(sideLength,locale,1)})}
1908
1936
 
@@ -2050,7 +2078,7 @@ const getPromptJSON$1=userInput=>{return {type:"sorter",userInput:{values:userIn
2050
2078
 
2051
2079
  class Sorter extends React.Component{componentDidMount(){this._isMounted=true;}componentWillUnmount(){this._isMounted=false;}getUserInput(){const options=this.refs.sortable.getOptions();return {options,changed:this.state.changed}}getPromptJSON(){return getPromptJSON$1(this.getUserInput())}render(){const options=shuffle(this.props.correct,this.props.problemNum,true);const{apiOptions}=this.props;const marginPx=apiOptions.isMobile?8:5;return jsxRuntimeExports.jsx("div",{className:"perseus-widget-sorter perseus-clearfix",children:jsxRuntimeExports.jsx(Sortable,{options:options,layout:this.props.layout,margin:marginPx,padding:this.props.padding,onChange:this.handleChange,linterContext:this.props.linterContext,ref:"sortable"})})}constructor(...args){super(...args),this._isMounted=false,this.state={changed:false},this.handleChange=e=>{if(!this._isMounted){return}this.setState({changed:true},()=>{setTimeout(()=>{this.props.onChange(e);this.props.trackInteraction();},0);});},this.moveOptionToIndex=(option,index)=>{this.refs.sortable.moveOptionToIndex(option,index);};}}Sorter.defaultProps={correct:[],layout:"horizontal",padding:true,problemNum:0,onChange:function(){},linterContext:linterContextDefault};var Sorter$1 = {name:"sorter",displayName:"Sorter",widget:Sorter,isLintable:true};
2052
2080
 
2053
- const{assert}=InteractiveUtil;const getInputPath=function(row,column){return [""+row,""+column]};const getDefaultPath=function(){return getInputPath(0,0)};const getRowFromPath=function(path){assert(_.isArray(path)&&path.length===2);return +path[0]};const getColumnFromPath=function(path){assert(_.isArray(path)&&path.length===2);return +path[1]};const getRefForPath=function(path){const row=getRowFromPath(path);const column=getColumnFromPath(path);return "answer"+row+","+column};class Table extends React.Component{getUserInput(){return _.map(this.props.answers,_.clone)}getDOMNodeForPath(path){const inputID=getRefForPath(path);return ReactDOM__default.findDOMNode(this.refs[inputID])}render(){const rows=this._getRows();const columns=this._getColumns();const headers=this.props.headers;let InputComponent;let inputStyle;const extraInputProps={};if(this.props.apiOptions.customKeypad){InputComponent=SimpleKeypadInput;inputStyle={width:80};extraInputProps.keypadElement=this.props.keypadElement;}else {InputComponent="input";inputStyle={};}return jsxRuntimeExports.jsxs("table",{className:"perseus-widget-table-of-values non-markdown",children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsx("tr",{children:_.map(headers,(header,i)=>{if(this.props.editableHeaders){return jsxRuntimeExports.jsx("th",{children:jsxRuntimeExports.jsx(this.props.Editor,{ref:"columnHeader"+i,apiOptions:this.props.apiOptions,content:header,widgetEnabled:false,onChange:_.partial(this.onHeaderChange,i)})},i)}return jsxRuntimeExports.jsx("th",{children:jsxRuntimeExports.jsx(Renderer,{content:header,linterContext:this.props.linterContext,strings:this.context.strings})},i)})})}),jsxRuntimeExports.jsx("tbody",{children:_(rows).times(r=>{return jsxRuntimeExports.jsx("tr",{children:_(columns).times(c=>{return jsxRuntimeExports.jsx("td",{children:jsxRuntimeExports.jsx(InputComponent,{ref:getRefForPath(getInputPath(r,c)),type:"text",value:this.props.answers[r][c],disabled:this.props.apiOptions.readOnly,onFocus:_.partial(this._handleFocus,getInputPath(r,c)),onBlur:_.partial(this._handleBlur,getInputPath(r,c)),onChange:_.partial(this.onValueChange,r,c),style:inputStyle,...extraInputProps})},c)})},r)})})]})}constructor(...args){super(...args),this._getRows=()=>{return this.props.answers.length},this._getColumns=()=>{return this.props.answers[0].length},this.onValueChange=(row,column,eventOrValue)=>{const answers=_.map(this.props.answers,_.clone);answers[row][column]=eventOrValue.target?eventOrValue.target.value:eventOrValue;this.props.onChange({answers:answers});this.props.trackInteraction();},this.onHeaderChange=(index,e)=>{const headers=this.props.headers.slice();headers[index]=e.content;this.props.onChange({headers:headers});},this._handleFocus=inputPath=>{this.props.onFocus(inputPath);},this._handleBlur=inputPath=>{this.props.onBlur(inputPath);},this.focus=()=>{this.focusInputPath(getDefaultPath());return true},this.focusInputPath=path=>{const inputID=getRefForPath(path);const inputComponent=this.refs[inputID];if(this.props.apiOptions.customKeypad){inputComponent.focus();}else {ReactDOM__default.findDOMNode(inputComponent).focus();}},this.blurInputPath=path=>{const inputID=getRefForPath(path);const inputComponent=this.refs[inputID];if(this.props.apiOptions.customKeypad){inputComponent.blur();}else {ReactDOM__default.findDOMNode(inputComponent).blur();}},this.getInputPaths=()=>{const rows=this._getRows();const columns=this._getColumns();const inputPaths=[];_(rows).times(r=>{_(columns).times(c=>{const inputPath=getInputPath(r,c);inputPaths.push(inputPath);});});return inputPaths},this.setInputValue=(path,newValue,cb)=>{const row=getRowFromPath(path);const column=getColumnFromPath(path);const answers=_.map(this.props.answers,_.clone);answers[row][column]=newValue;this.props.onChange({answers:answers},cb);};}}Table.contextType=PerseusI18nContext;Table.defaultProps=function(){const defaultRows=4;const defaultColumns=1;const blankAnswers=_(defaultRows).times(function(){return Util.stringArrayOfSize(defaultColumns)});return {apiOptions:ApiOptions.defaults,headers:[""],editableHeaders:false,rows:defaultRows,columns:defaultColumns,answers:blankAnswers,linterContext:linterContextDefault}}();const propTransform=editorProps=>{const rows=editorProps.answers.length;const columns=editorProps.answers[0].length;const blankAnswers=_(rows).times(function(){return Util.stringArrayOfSize(columns)});return _.extend({},editorProps,{answers:blankAnswers})};var Table$1 = {name:"table",displayName:"Table (deprecated - use markdown table instead)",accessible:true,widget:Table,transform:propTransform,hidden:true,isLintable:true};
2081
+ const{assert}=InteractiveUtil;function getInputPath(row,column){return [""+row,""+column]}function getDefaultPath(){return getInputPath(0,0)}function getRowFromPath(path){assert(Array.isArray(path)&&path.length===2);return +path[0]}function getColumnFromPath(path){assert(Array.isArray(path)&&path.length===2);return +path[1]}function getRefForPath(path){const row=getRowFromPath(path);const column=getColumnFromPath(path);return "answer"+row+","+column}class Table extends React.Component{_getRows(){return this.props.answers.length}_getColumns(){return this.props.answers[0].length}_getAnswersClone(){return JSON.parse(JSON.stringify(this.props.answers))}getUserInput(){return this._getAnswersClone()}onValueChange(row,column,eventOrValue){const answers=this._getAnswersClone();answers[row][column]=eventOrValue.target?eventOrValue.target.value:eventOrValue;this.props.onChange({answers:answers});this.props.trackInteraction();}onHeaderChange(index,e){const headers=this.props.headers.slice();headers[index]=e.content;this.props.onChange({headers:headers});}_handleFocus(inputPath){this.props.onFocus(inputPath);}_handleBlur(inputPath){this.props.onBlur(inputPath);}focus(){this.focusInputPath(getDefaultPath());return true}focusInputPath(path){const inputID=getRefForPath(path);const inputComponent=this.answerRefs[inputID];if(this.props.apiOptions.customKeypad){inputComponent.focus();}else {ReactDOM__default.findDOMNode(inputComponent).focus();}}blurInputPath(path){const inputID=getRefForPath(path);const inputComponent=this.answerRefs[inputID];if(this.props.apiOptions.customKeypad){inputComponent.blur();}else {ReactDOM__default.findDOMNode(inputComponent).blur();}}getDOMNodeForPath(path){const inputID=getRefForPath(path);const inputRef=this.answerRefs[inputID];return ReactDOM__default.findDOMNode(inputRef)}getInputPaths(){const rows=this._getRows();const columns=this._getColumns();const inputPaths=[];for(let r=0;r<rows;r++){for(let c=0;c<columns;c++){const inputPath=getInputPath(r,c);inputPaths.push(inputPath);}}return inputPaths}setInputValue(path,newValue,cb){const typedPath=path;const row=getRowFromPath(typedPath);const column=getColumnFromPath(typedPath);const answers=this._getAnswersClone();answers[row][column]=newValue;this.props.onChange({answers:answers},cb);}render(){const headers=this.props.headers;let InputComponent;let inputStyle;const extraInputProps={};if(this.props.apiOptions.customKeypad){InputComponent=SimpleKeypadInput;inputStyle={width:80};extraInputProps.keypadElement=this.props.keypadElement;}else {InputComponent="input";inputStyle={};}return jsxRuntimeExports.jsxs("table",{className:"perseus-widget-table-of-values non-markdown",children:[jsxRuntimeExports.jsx("thead",{children:jsxRuntimeExports.jsx("tr",{children:headers.map((header,i)=>{if(this.props.editableHeaders){return jsxRuntimeExports.jsx("th",{children:jsxRuntimeExports.jsx(this.props.Editor,{ref:ref=>{this.headerRefs["columnHeader"+i]=ref;},apiOptions:this.props.apiOptions,content:header,widgetEnabled:false,onChange:e=>this.onHeaderChange(i,e)})},i)}return jsxRuntimeExports.jsx("th",{children:jsxRuntimeExports.jsx(Renderer,{content:header,linterContext:this.props.linterContext,strings:this.context.strings})},i)})})}),jsxRuntimeExports.jsx("tbody",{children:this.props.answers.map((rowArr,r)=>{return jsxRuntimeExports.jsx("tr",{children:rowArr.map((answer,c)=>{return jsxRuntimeExports.jsx("td",{children:jsxRuntimeExports.jsx(InputComponent,{ref:ref=>{this.answerRefs[getRefForPath(getInputPath(r,c))]=ref;},type:"text",value:answer,disabled:this.props.apiOptions.readOnly,onFocus:()=>this._handleFocus(getInputPath(r,c)),onBlur:()=>this._handleBlur(getInputPath(r,c)),onChange:e=>this.onValueChange(r,c,e),style:inputStyle,...extraInputProps})},c)})},r)})})]})}constructor(...args){super(...args),this.headerRefs={},this.answerRefs={};}}Table.contextType=PerseusI18nContext;Table.defaultProps=function(){const defaultRows=4;const defaultColumns=1;const blankAnswers=Util.stringArrayOfSize2D({rows:defaultRows,columns:defaultColumns});return {apiOptions:ApiOptions.defaults,headers:[""],editableHeaders:false,rows:defaultRows,columns:defaultColumns,answers:blankAnswers,linterContext:linterContextDefault}}();function propTransform(options){const rows=options.rows;const columns=options.columns;const blankAnswers=Util.stringArrayOfSize2D({rows,columns});return {...options,answers:blankAnswers}}var Table$1 = {name:"table",displayName:"Table (deprecated - use markdown table instead)",accessible:true,widget:Table,transform:propTransform,hidden:true,isLintable:true};
2054
2082
 
2055
2083
  const getPromptJSON=()=>{return getUnsupportedPromptJSON("video")};
2056
2084
 
@@ -2062,13 +2090,13 @@ var extraWidgets = [Categorizer$1,CSProgram$1,Dropdown$1,Explanation$1,Definitio
2062
2090
 
2063
2091
  const init=function(){registerWidgets(basicWidgets);registerWidgets(extraWidgets);replaceDeprecatedWidgets();};
2064
2092
 
2065
- const libName="@khanacademy/perseus";const libVersion="60.0.2";addLibraryVersionToPerseusDebug(libName,libVersion);
2093
+ const libName="@khanacademy/perseus";const libVersion="61.0.1";addLibraryVersionToPerseusDebug(libName,libVersion);
2066
2094
 
2067
- const apiVersion={major:12,minor:0};const itemDataVersion={major:0,minor:1};
2095
+ const apiVersion={major:12,minor:0};
2068
2096
 
2069
2097
  var allWidgets = [...basicWidgets,...extraWidgets];
2070
2098
 
2071
- registerWidgets(allWidgets);const ItemVersion=getVersionVector();ItemVersion["::renderer::"]=itemDataVersion;
2099
+ registerWidgets(allWidgets);const ItemVersion=getVersionVector();
2072
2100
 
2073
2101
  class ArticleRenderer extends React.Component{componentDidMount(){this._currentFocus=null;}shouldComponentUpdate(nextProps){return nextProps!==this.props}render(){const apiOptions={...ApiOptions.defaults,...this.props.apiOptions,isArticle:true};const classes=classNames$1({"framework-perseus":true,"perseus-article":true,[ClassNames.MOBILE]:apiOptions.isMobile});const sections=this._sections().map((section,sectionIndex)=>{return jsxRuntimeExports.jsx("div",{className:"clearfix",children:createElement(Renderer,{...section,ref:elem=>{if(elem){this.sectionRenderers[sectionIndex]=elem;}},key:sectionIndex,key_:sectionIndex,keypadElement:this.props.keypadElement,apiOptions:{...apiOptions,onFocusChange:(newFocusPath,oldFocusPath)=>{this._handleFocusChange(newFocusPath&&[sectionIndex].concat(newFocusPath),oldFocusPath&&[sectionIndex].concat(oldFocusPath));}},linterContext:PerseusLinter.pushContextStack(this.props.linterContext,"article"),legacyPerseusLint:this.props.legacyPerseusLint,strings:this.context.strings})},sectionIndex)});return jsxRuntimeExports.jsx("div",{className:classes,children:jsxRuntimeExports.jsx(DependenciesContext.Provider,{value:this.props.dependencies,children:sections})})}constructor(props){super(props),this.sectionRenderers=[],this._handleFocusChange=(newFocusPath,oldFocusPath)=>{if(newFocusPath){this._setCurrentFocus(newFocusPath);}else {this._onRendererBlur(oldFocusPath);}},this._setCurrentFocus=newFocusPath=>{const{keypadElement,apiOptions}=this.props;const{isMobile}=apiOptions;const prevFocusPath=this._currentFocus;this._currentFocus=newFocusPath;let didFocusInput=false;let focusedInput;if(this._currentFocus){const[sectionIndex,...focusPath]=this._currentFocus;const inputPaths=this.sectionRenderers[sectionIndex].getInputPaths();didFocusInput=inputPaths.some(inputPath=>{return Util.inputPathsEqual(inputPath,focusPath)});focusedInput=this.sectionRenderers[sectionIndex].getDOMNodeForPath(focusPath);}const{onFocusChange}=this.props.apiOptions;if(onFocusChange){setTimeout(()=>{const keypadDomNode=keypadElement?.getDOMNode();const keypadHeight=keypadDomNode&&didFocusInput?keypadDomNode.getBoundingClientRect().height:0;onFocusChange(this._currentFocus,prevFocusPath,keypadHeight,didFocusInput?focusedInput:null);},0);}if(keypadElement&&isMobile){if(didFocusInput){keypadElement.activate();}else {keypadElement.dismiss();}}},this._onRendererBlur=blurPath=>{const blurringFocusPath=this._currentFocus;if(!Util.inputPathsEqual(blurPath,blurringFocusPath)){return}setTimeout(()=>{if(Util.inputPathsEqual(this._currentFocus,blurringFocusPath)){this._setCurrentFocus(null);}});},this.blur=()=>{if(this._currentFocus){const[sectionIndex,...inputPath]=this._currentFocus;this.sectionRenderers[sectionIndex].blurPath(inputPath);}},this._sections=()=>{const sections=Array.isArray(this.props.json)?this.props.json:[this.props.json];if(getDependencies().JIPT.useJIPT){const paragraphs=[];for(const section of sections){JiptParagraphs.parseToArray(section.content).forEach(paragraph=>{paragraphs.push({...section,content:paragraph});});}return paragraphs}return sections};}}ArticleRenderer.contextType=PerseusI18nContext;ArticleRenderer.defaultProps={apiOptions:ApiOptions.defaults,useNewStyles:false,linterContext:PerseusLinter.linterContextDefault};
2074
2102
 
@@ -2104,7 +2132,7 @@ ${items.join("\n")}
2104
2132
  | --- | --- |`;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}
2105
2133
  ${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 getImagesWithoutAltData(perseusRenderer){if(!perseusRenderer.widgets){return ""}const imgsWithoutAltData=[];Object.entries(perseusRenderer.widgets).forEach(([widgetId,widget])=>{if(!widget.options){return}if(widget.type==="image"&&!widget.options.alt&&widget.options.backgroundImage?.url){imgsWithoutAltData.push({widgetId,imgUrl:widget.options.backgroundImage.url});}});return JSON.stringify(imgsWithoutAltData)}const INDIVIDUAL_ANSWER_WIDGETS=["interactive-graph","categorizer","grapher"];const SUPPORTED_WIDGETS=["radio","numeric-input","input-number","expression",...INDIVIDUAL_ANSWER_WIDGETS];const isWrongAnswerSupported=(widgetIds,widgetMap)=>{return widgetIds.length!==0&&widgetIds.every(widgetId=>SUPPORTED_WIDGETS.includes(getWidgetTypeByWidgetId(widgetId,widgetMap)))};const shouldHaveIndividualAnswer=(widgetId,widgetMap)=>{return INDIVIDUAL_ANSWER_WIDGETS.includes(getWidgetTypeByWidgetId(widgetId,widgetMap))};const getAnswerFromUserInput=(widgetType,userInput)=>{switch(widgetType){case "categorizer":return userInput.values;case "input-number":return userInput.currentValue;case "numeric-input":return userInput.currentValue;case "radio":return userInput.choicesSelected}return userInput};const getCorrectAnswerForWidgetId=(widgetId,itemData)=>{const rubric=itemData.question.widgets[widgetId].options;const widgetMap=getWidgetsMapFromItemData(itemData);const widgetType=getWidgetTypeByWidgetId(widgetId,widgetMap);const widget=getWidgetExport(widgetType);return widget?.getOneCorrectAnswerFromRubric?.(rubric)};const isWidgetIdInContent=(perseusItem,widgetId)=>{return perseusItem.question.content.indexOf(widgetId)!==-1};const getValidWidgetIds=perseusItem=>{const{widgets}=perseusItem.question;return keys(widgets).filter(id=>isWidgetIdInContent(perseusItem,id))};
2106
2134
 
2107
- const genericPerseusItemData={question:{content:"",images:{},widgets:{}},answerArea:{calculator:false,chi2Table:false,periodicTable:false,tTable:false,zTable:false,financialCalculatorMonthlyPayment:false,financialCalculatorTotalAmount:false,financialCalculatorTimeToPayOff:false,periodicTableWithKey:false},itemDataVersion:{major:0,minor:1},hints:[],answer:null};function generateTestPerseusItem(customFields={}){return {...genericPerseusItemData,...customFields}}function generateTestRadioWidget(){return {type:"radio",options:{choices:[]}}}function generateTestInteractiveGraphWidget(){return {type:"interactive-graph",options:{step:[1,1],gridStep:[1,1],snapStep:[1,1],markings:"graph",labels:["x","y"],showProtractor:false,range:[[-10,10],[-10,10]],graph:{type:"angle"},correct:{type:"angle"}}}}function generateTestCategorizerWidget(){return {type:"categorizer",options:{items:[],categories:[],randomizeItems:false,static:false,values:[]}}}function generateTestExpressionWidget(){return {type:"expression",options:{answerForms:[],buttonSets:["basic"],functions:[],times:false}}}function generateTestNumericInputWidget(){return {type:"numeric-input",options:{answers:[],labelText:"",size:"normal",coefficient:false,static:false}}}
2135
+ function generateTestRadioWidget(){return {type:"radio",options:{choices:[]}}}function generateTestInteractiveGraphWidget(){return {type:"interactive-graph",options:{step:[1,1],gridStep:[1,1],snapStep:[1,1],markings:"graph",labels:["x","y"],showProtractor:false,range:[[-10,10],[-10,10]],graph:{type:"angle"},correct:{type:"angle"}}}}function generateTestCategorizerWidget(){return {type:"categorizer",options:{items:[],categories:[],randomizeItems:false,static:false,values:[]}}}function generateTestExpressionWidget(){return {type:"expression",options:{answerForms:[],buttonSets:["basic"],functions:[],times:false}}}function generateTestNumericInputWidget(){return {type:"numeric-input",options:{answers:[],labelText:"",size:"normal",coefficient:false,static:false}}}
2108
2136
 
2109
2137
  const widgetNameToEnum={categorizer:"CATEGORIZER","cs-program":"CS_PROGRAM",definition:"DEFINITION","deprecated-standin":"DEPRECATED_STANDIN",dropdown:"DROPDOWN",explanation:"EXPLANATION",expression:"EXPRESSION","graded-group-set":"GRADED_GROUP_SET","graded-group":"GRADED_GROUP",grapher:"GRAPHER",group:"GROUP",iframe:"IFRAME",image:"IMAGE","input-number":"INPUT_NUMBER",interaction:"INTERACTIVE","interactive-graph":"INTERACTIVE_GRAPH","label-image":"LABEL_IMAGE","lights-puzzle":"LIGHTS_PUZZLE",matcher:"MATCHER",matrix:"MATRIX",measurer:"MEASURER","molecule-renderer":"MOLECULE","number-line":"NUMBER_LINE","numeric-input":"NUMERIC_INPUT",orderer:"ORDERER",passage:"PASSAGE","passage-ref":"PASSAGE_REF","passage-ref-target":"PASSAGE_REF_TARGET","phet-simulation":"PHET_SIMULATION",plotter:"PLOTTER","python-program":"PYTHON_PROGRAM","reaction-diagram":"REACTION_DIAGRAM",radio:"RADIO",sequence:"SEQUENCE",simulator:"SIMULATOR",sorter:"SORTER",table:"TABLE",video:"VIDEO"};function convertWidgetNameToEnum(name){const widgetEnum=widgetNameToEnum[name];if(!widgetEnum){throw new Error(`Unknown widget name: ${name}`)}return widgetEnum}
2110
2138
 
@@ -2112,5 +2140,5 @@ const EditorJsonify={serialize:function(){return _.omit(this.props,denylist)}};
2112
2140
 
2113
2141
  const GrapherUtil={DEFAULT_GRAPHER_PROPS,chooseType,defaultPlotProps,getEquationString,typeToButton};const ScoringUtil={keScoreFromPerseusScore};
2114
2142
 
2115
- export { ApiOptions, ArticleRenderer, BaseRadio, Categorizer$1 as Categorizer, changeable as Changeable, ClassNames, dependencies as Dependencies, EditorJsonify, Expression, GrapherUtil, Grapher$1 as GrapherWidget, HintRenderer, HintsRenderer, InputNumber$1 as InputNumber, InteractiveGraph$1 as InteractiveGraphWidget, JiptParagraphs, KhanColors, context as LoadingContext, Log, Matrix$1 as MatrixWidget, NumericInput$1 as NumericInput, PerseusI18nContext, PerseusI18nContextProvider, PerseusMarkdown, Plotter$1 as PlotterWidget, Radio, Renderer, ScoringUtil, ref as ServerItemRenderer, Table$1 as TableWidget, Util, denylist as WIDGET_PROP_DENYLIST, widgets$1 as Widgets, apiVersion, bodyXsmallBold, components, containerSizeClass, contentHasWidgetType, convertWidgetNameToEnum, displaySigFigs, generateTestCategorizerWidget, generateTestExpressionWidget, generateTestInteractiveGraphWidget, generateTestNumericInputWidget, generateTestPerseusItem, generateTestRadioWidget, genericPerseusItemData, getAngleCoords, getAnswerFromUserInput, getAnswersFromWidgets, getCircleCoords, getCorrectAnswerForWidgetId, getImagesWithoutAltData, getInteractiveBoxFromSizeClass, getLineCoords, getLinearSystemCoords, getPointCoords, getPolygonCoords, getQuadraticCoords, getSegmentCoords, getSinusoidCoords, getValidWidgetIds, getWidgetFromWidgetMap, getWidgetSubTypeByWidgetId, getWidgetTypeByWidgetId, getWidgetsFromWidgetMap, getWidgetsMapFromItemData, iconChevronDown, iconTrash, init, injectWidgets, interactiveSizes$1 as interactiveSizes, isItemRenderableByVersion, isWidgetIdInContent, isWrongAnswerSupported, itemDataVersion, ItemVersion as itemVersion, libVersion, makeSafeUrl, mathOnlyParser, parseDataFromJSONP, preprocessTex, registerAllWidgetsForTesting, shouldHaveIndividualAnswer, traverse, usePerseusI18n, violatingWidgets, allWidgets as widgets };
2143
+ export { ApiOptions, ArticleRenderer, BaseRadio$1 as BaseRadio, Categorizer$1 as Categorizer, changeable as Changeable, ClassNames, dependencies as Dependencies, EditorJsonify, Expression, GrapherUtil, Grapher$1 as GrapherWidget, HintRenderer, HintsRenderer, InputNumber$1 as InputNumber, InteractiveGraph$1 as InteractiveGraphWidget, JiptParagraphs, KhanColors, context as LoadingContext, Log, Matrix$1 as MatrixWidget, NumericInput$1 as NumericInput, PerseusI18nContext, PerseusI18nContextProvider, PerseusMarkdown, Plotter$1 as PlotterWidget, Radio, Renderer, ScoringUtil, ref as ServerItemRenderer, Table$1 as TableWidget, Util, denylist as WIDGET_PROP_DENYLIST, widgets$1 as Widgets, apiVersion, bodyXsmallBold, components, containerSizeClass, contentHasWidgetType, convertWidgetNameToEnum, displaySigFigs, generateTestCategorizerWidget, generateTestExpressionWidget, generateTestInteractiveGraphWidget, generateTestNumericInputWidget, generateTestRadioWidget, getAngleCoords, getAnswerFromUserInput, getAnswersFromWidgets, getCircleCoords, getCorrectAnswerForWidgetId, getImagesWithoutAltData, getInteractiveBoxFromSizeClass, getLineCoords, getLinearSystemCoords, getPointCoords, getPolygonCoords, getQuadraticCoords, getSegmentCoords, getSinusoidCoords, getValidWidgetIds, getWidgetFromWidgetMap, getWidgetSubTypeByWidgetId, getWidgetTypeByWidgetId, getWidgetsFromWidgetMap, getWidgetsMapFromItemData, iconChevronDown, iconTrash, init, injectWidgets, interactiveSizes$1 as interactiveSizes, isItemRenderableByVersion, isWidgetIdInContent, isWrongAnswerSupported, ItemVersion as itemVersion, libVersion, makeSafeUrl, mathOnlyParser, parseDataFromJSONP, preprocessTex, registerAllWidgetsForTesting, shouldHaveIndividualAnswer, traverse, usePerseusI18n, violatingWidgets, allWidgets as widgets };
2116
2144
  //# sourceMappingURL=index.js.map