diff --git a/cypress/e2e/DoenetML/tagSpecific/answer.cy.js b/cypress/e2e/DoenetML/tagSpecific/answer.cy.js index 1256579885..c5820020f9 100644 --- a/cypress/e2e/DoenetML/tagSpecific/answer.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/answer.cy.js @@ -1110,7 +1110,7 @@ describe('Answer Tag Tests', function () { cy.log("Pressing enter does not submit") - cy.get(textinputAnchor).type(`{enter}`); + cy.get(textinputAnchor).type(`{enter}`).blur(); cy.log('Test value displayed in browser') cy.get(textinputAnchor).should('have.value', ' hello there \n'); diff --git a/cypress/e2e/DoenetML/tagSpecific/graph.cy.js b/cypress/e2e/DoenetML/tagSpecific/graph.cy.js index 2f701b19b3..c0d7465df5 100644 --- a/cypress/e2e/DoenetML/tagSpecific/graph.cy.js +++ b/cypress/e2e/DoenetML/tagSpecific/graph.cy.js @@ -1979,4 +1979,33 @@ describe('Graph Tag Tests', function () { }); + it('show border', () => { + cy.window().then(async (win) => { + win.postMessage({ + doenetML: ` + a + + + + + + + + + + `}, "*"); + }); + + cy.get('#\\/_text1').should('have.text', 'a') //wait for page to load + + // not sure what to test as don't know how to check renderer... + cy.window().then(async (win) => { + let stateVariables = await win.returnAllStateVariables1(); + expect(stateVariables["/_graph1"].stateValues.showBorder).eq(true); + expect(stateVariables["/_graph2"].stateValues.showBorder).eq(true); + expect(stateVariables["/_graph3"].stateValues.showBorder).eq(false); + }) + + }); + }); \ No newline at end of file diff --git a/src/Core/components/Graph.js b/src/Core/components/Graph.js index 2ae1f527e5..070c69d0d9 100644 --- a/src/Core/components/Graph.js +++ b/src/Core/components/Graph.js @@ -196,6 +196,14 @@ export default class Graph extends BlockComponent { defaultValue: false, public: true, }; + + attributes.showBorder = { + createComponentOfType: "boolean", + createStateVariable: "showBorder", + defaultValue: true, + public: true, + forRenderer: true, + }; return attributes; } diff --git a/src/Viewer/core.js b/src/Viewer/core.js index 1dbf73069f..a8f214d97e 100644 --- a/src/Viewer/core.js +++ b/src/Viewer/core.js @@ -15,7 +15,7 @@ var Core=function(){"use strict";class ParameterStack{constructor(e){this.stack= //!!This function should only be called if bottom has coefficient 1 and divides the top (e.g., bottom was computed using mono_gcd)!! if(!Array.isArray(t)||"monomial"!==t[0])return 1===t?e:Array.isArray(e)&&"monomial"===e[0]?[e[0],evaluate_numbers(["/",e[1],t]),e[2]]:evaluate_numbers(["/",e,t]);if(!Array.isArray(e)||"monomial"!==e[0])return;let n=e[2],r=t[2],a=[],i=n.length,s=r.length,o=0,l=0;for(;o=0;){var r=[];r.push([e[2][t][1],n]),n=["polynomial",e[2][t][0],r],t-=1}return n}function max_div_init(e,t){if(0===e)return 0;let n=e,r=[];for(;Array.isArray(n)&&"polynomial"===n[0];){let e=n[1],t=n[2],a=t[t.length-1][0];n=t[t.length-1][1],r.push([e,a])}let a=["monomial",n,r],i=t.length;for(var s=0;s0?choice_lowest_degree(i):0}function update_hij_table(e,t,n){let r=t.length;t.push(n);let a=0,i=1,s=[];for(;i0?choice_lowest_degree(s):0}function choice_lowest_degree(e){let t=[],n=e.length;for(a=0;a15?n:(t=Math.round(t),round_numbers_to_precision_sub(n,t))}const round_numbers_to_precision_sub=function(e,t=14){if("number"==typeof e&&Number.isFinite(e)&&0!==e){const n=math$1.floor(math$1.log10(math$1.abs(e))),r=t-n-1;return r<0?parseFloat(toFixed(e,r)+"0".repeat(math$1.abs(r))):parseFloat(toFixed(e,r))}return Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_precision_sub(e,t)))]:e};function round_numbers_to_decimals(e,t=14){var n=get_tree(e);if(!Number.isFinite(t))throw Error("For round_numbers_to_decimals, ndecimals must be a number");return t=Math.round(t),t=Math.max(-330,Math.min(330,t)),round_numbers_to_decimals_sub(n,t)}const round_numbers_to_decimals_sub=function(e,t=0){return"number"==typeof e?t<0?parseFloat(toFixed(e,t)+"0".repeat(math$1.abs(t))):parseFloat(toFixed(e,t)):Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_decimals_sub(e,t)))]:e};var round=Object.freeze({__proto__:null,round_numbers_to_precision:round_numbers_to_precision,round_numbers_to_decimals:round_numbers_to_decimals});const match=function(e,t,n){let r=get_tree(e),a=get_tree(t);return match$2(r,a,n)};var match$1=Object.freeze({__proto__:null,match:match});const expression_to_tree$1=[simplify$1,differentiation,normalization,arithmetic,transformation,solve,sets,matrix$1,rational,round],expression_to_other=[variables$1,printing,equality,integration,evaluation,analytic,sign_error,match$1];function abs(e){return["apply","abs",get_tree(e)]}function exp(e){return["apply","exp",get_tree(e)]}function log(e){return["apply","log",get_tree(e)]}function log10(e){return["apply","log10",get_tree(e)]}function sign(e){return["apply","sign",get_tree(e)]}function sqrt(e){return["apply","sqrt",get_tree(e)]}function conj(e){return["apply","conj",get_tree(e)]}function im(e){return["apply","im",get_tree(e)]}function re(e){return["apply","re",get_tree(e)]}function factorial(e){return["apply","factorial",get_tree(e)]}function gamma(e){return["apply","gamma",get_tree(e)]}function erf(e){return["apply","erf",get_tree(e)]}function acos(e){return["apply","acos",get_tree(e)]}function acosh(e){return["apply","acosh",get_tree(e)]}function acot(e){return["apply","acot",get_tree(e)]}function acoth(e){return["apply","acoth",get_tree(e)]}function acsc(e){return["apply","acsc",get_tree(e)]}function acsch(e){return["apply","acsch",get_tree(e)]}function asec(e){return["apply","asec",get_tree(e)]}function asech(e){return["apply","asech",get_tree(e)]}function asin(e){return["apply","asin",get_tree(e)]}function asinh(e){return["apply","asinh",get_tree(e)]}function atan(e){return["apply","atan",get_tree(e)]}function atanh(e){return["apply","atanh",get_tree(e)]}function cos(e){return["apply","cos",get_tree(e)]}function cosh(e){return["apply","cosh",get_tree(e)]}function cot(e){return["apply","cot",get_tree(e)]}function coth(e){return["apply","coth",get_tree(e)]}function csc(e){return["apply","csc",get_tree(e)]}function csch(e){return["apply","csch",get_tree(e)]}function sec(e){return["apply","sec",get_tree(e)]}function sech(e){return["apply","sech",get_tree(e)]}function sin(e){return["apply","sin",get_tree(e)]}function sinh(e){return["apply","sinh",get_tree(e)]}function tan(e){return["apply","tan",get_tree(e)]}function tanh(e){return["apply","tanh",get_tree(e)]}function atan2(e,t){return["apply","atan2",["tuple",get_tree(e),get_tree(t)]]}var standard=Object.freeze({__proto__:null,abs:abs,exp:exp,log:log,log10:log10,sign:sign,sqrt:sqrt,conj:conj,im:im,re:re,factorial:factorial,gamma:gamma,erf:erf,acos:acos,acosh:acosh,acot:acot,acoth:acoth,acsc:acsc,acsch:acsch,asec:asec,asech:asech,asin:asin,asinh:asinh,atan:atan,atanh:atanh,cos:cos,cosh:cosh,cot:cot,coth:coth,csc:csc,csch:csch,sec:sec,sech:sech,sin:sin,sinh:sinh,tan:tan,tanh:tanh,atan2:atan2});const expression_to_tree=[standard],whitespace_rule="\\s|\\\\,|\\\\!|\\\\ |\\\\>|\\\\;|\\\\:|\\\\quad\\b|\\\\qquad\\b",sci_notat_exp_regex="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))?",number_rules_sci=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex,"NUMBER"]],number_rules_non_sci=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_latex_rules=[["\\*","*"],["\\/","/"],["-","-"],["\\+","+"],["\\^","^"],["\\(","("],["\\\\left\\s*\\(","("],["\\\\bigl\\s*\\(","("],["\\\\Bigl\\s*\\(","("],["\\\\biggl\\s*\\(","("],["\\\\Biggl\\s*\\(","("],["\\)",")"],["\\\\right\\s*\\)",")"],["\\\\bigr\\s*\\)",")"],["\\\\Bigr\\s*\\)",")"],["\\\\biggr\\s*\\)",")"],["\\\\Biggr\\s*\\)",")"],["\\[","["],["\\\\left\\s*\\[","["],["\\\\bigl\\s*\\[","["],["\\\\Bigl\\s*\\[","["],["\\\\biggl\\s*\\[","["],["\\\\Biggl\\s*\\[","["],["\\]","]"],["\\\\right\\s*\\]","]"],["\\\\bigr\\s*\\]","]"],["\\\\Bigr\\s*\\]","]"],["\\\\biggr\\s*\\]","]"],["\\\\Biggr\\s*\\]","]"],["\\|","|"],["\\\\left\\s*\\|","|L"],["\\\\bigl\\s*\\|","|L"],["\\\\Bigl\\s*\\|","|L"],["\\\\biggl\\s*\\|","|L"],["\\\\Biggl\\s*\\|","|L"],["\\\\right\\s*\\|","|"],["\\\\bigr\\s*\\|","|"],["\\\\Bigr\\s*\\|","|"],["\\\\biggr\\s*\\|","|"],["\\\\Biggr\\s*\\|","|"],["\\\\big\\s*\\|","|"],["\\\\Big\\s*\\|","|"],["\\\\bigg\\s*\\|","|"],["\\\\Bigg\\s*\\|","|"],["{","{"],["}","}"],["\\\\{","LBRACE"],["\\\\left\\s*\\\\{","LBRACE"],["\\\\bigl\\s*\\\\{","LBRACE"],["\\\\Bigl\\s*\\\\{","LBRACE"],["\\\\biggl\\s*\\\\{","LBRACE"],["\\\\Biggl\\s*\\\\{","LBRACE"],["\\\\}","RBRACE"],["\\\\right\\s*\\\\}","RBRACE"],["\\\\bigr\\s*\\\\}","RBRACE"],["\\\\Bigr\\s*\\\\}","RBRACE"],["\\\\biggr\\s*\\\\}","RBRACE"],["\\\\Biggr\\s*\\\\}","RBRACE"],["\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\left\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\right\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\left\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\right\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\left\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\right\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\cdot(?![a-zA-Z])","*"],["\\\\div(?![a-zA-Z])","/"],["\\\\times(?![a-zA-Z])","*"],[",",","],[":",":"],["\\\\mid(?![a-zA-Z])","MID"],["\\\\vartheta(?![a-zA-Z])","LATEXCOMMAND","\\theta"],["\\\\varepsilon(?![a-zA-Z])","LATEXCOMMAND","\\epsilon"],["\\\\varrho(?![a-zA-Z])","LATEXCOMMAND","\\rho"],["\\\\varphi(?![a-zA-Z])","LATEXCOMMAND","\\phi"],["\\\\infty(?![a-zA-Z])","INFINITY"],["\\\\asin(?![a-zA-Z])","LATEXCOMMAND","\\arcsin"],["\\\\acos(?![a-zA-Z])","LATEXCOMMAND","\\arccos"],["\\\\atan(?![a-zA-Z])","LATEXCOMMAND","\\arctan"],["\\\\sqrt(?![a-zA-Z])","SQRT"],["\\\\land(?![a-zA-Z])","AND"],["\\\\wedge(?![a-zA-Z])","AND"],["\\\\lor(?![a-zA-Z])","OR"],["\\\\vee(?![a-zA-Z])","OR"],["\\\\lnot(?![a-zA-Z])","NOT"],["=","="],["\\\\neq(?![a-zA-Z])","NE"],["\\\\ne(?![a-zA-Z])","NE"],["\\\\not\\s*=","NE"],["\\\\leq(?![a-zA-Z])","LE"],["\\\\le(?![a-zA-Z])","LE"],["\\\\geq(?![a-zA-Z])","GE"],["\\\\ge(?![a-zA-Z])","GE"],["<","<"],["\\\\lt(?![a-zA-Z])","<"],[">",">"],["\\\\gt(?![a-zA-Z])",">"],["\\\\forall(?![a-zA-Z])","FORALL"],["\\\\exists(?![a-zA-Z])","EXISTS"],["\\\\in(?![a-zA-Z])","IN"],["\\\\notin(?![a-zA-Z])","NOTIN"],["\\\\not\\s*\\\\in(?![a-zA-Z])","NOTIN"],["\\\\ni(?![a-zA-Z])","NI"],["\\\\not\\s*\\\\ni(?![a-zA-Z])","NOTNI"],["\\\\subset(?![a-zA-Z])","SUBSET"],["\\\\subseteq(?![a-zA-Z])","SUBSETEQ"],["\\\\not\\s*\\\\subset(?![a-zA-Z])","NOTSUBSET"],["\\\\not\\s*\\\\subseteq(?![a-zA-Z])","NOTSUBSETEQ"],["\\\\supset(?![a-zA-Z])","SUPERSET"],["\\\\supseteq(?![a-zA-Z])","SUPERSETEQ"],["\\\\not\\s*\\\\supset(?![a-zA-Z])","NOTSUPERSET"],["\\\\not\\s*\\\\supseteq(?![a-zA-Z])","NOTSUPERSETEQ"],["\\\\cup(?![a-zA-Z])","UNION"],["\\\\cap(?![a-zA-Z])","INTERSECT"],["\\\\perp(?![a-zA-Z])","PERP"],["\\\\bot(?![a-zA-Z])","PERP"],["\\\\parallel(?![a-zA-Z])","PARALLEL"],["\\\\\\|","PARALLEL"],["\\\\angle(?![a-zA-Z])","ANGLE"],["\\\\int(?![a-zA-Z])","INT"],["!","!"],["'","'"],["_","_"],["&","&"],["\\\\ldots(?![a-zA-Z])","LDOTS"],["\\\\\\\\","LINEBREAK"],["\\\\begin\\s*{\\s*[a-zA-Z0-9]+\\s*}","BEGINENVIRONMENT"],["\\\\end\\s*{\\s*[a-zA-Z0-9]+\\s*}","ENDENVIRONMENT"],["\\\\operatorname\\s*{\\s*[a-zA-Z0-9\\+\\-]+\\s*}","VARMULTICHAR"],["\\\\[a-zA-Z]+(?![a-zA-Z])","LATEXCOMMAND"],["\\\\[$%]","LATEXCOMMAND"],["[a-zA-Z_$%]","VAR"]],allowSimplifiedFunctionApplicationDefault=!0,allowedLatexSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","angle","circ","%","$"],appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","conj","Re","Im","det","trace","nPr","nCr","floor","ceil","round"],functionSymbolsDefault=["f","g"],operatorSymbolsDefault={frac:{nargs:2,substitute:"/"},binom:{nargs:2},vec:{nargs:1},overline:{nargs:1,substitute:"linesegment",remove_products:!0}},unitsDefault=get_all_units();unitsDefault.circ=unitsDefault.deg,unitsDefault.circ.substitute="deg",unitsDefault.circ.isExponent=!0,delete unitsDefault.deg;const parseLeibnizNotationDefault=!0;class latexToAst$1{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault,allowedLatexSymbols:t=allowedLatexSymbolsDefault,appliedFunctionSymbols:n=appliedFunctionSymbolsDefault,functionSymbols:r=functionSymbolsDefault,operatorSymbols:a=operatorSymbolsDefault,units:i=unitsDefault,parseLeibnizNotation:s=parseLeibnizNotationDefault,parseScientificNotation:o=!0}={}){this.allowSimplifiedFunctionApplication=e,this.allowedLatexSymbols=t,this.appliedFunctionSymbols=n,this.functionSymbols=r,this.operatorSymbols=a,this.units=i,this.parseLeibnizNotation=s;let l=base_latex_rules;l=o?[...number_rules_sci,...l]:[...number_rules_non_sci,...l],this.lexer=new lexer(l,whitespace_rule)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});if(":"!==this.token.token_type&&"MID"!==this.token.token_type)return n;let r=":"===this.token.token_type?":":"|";return this.advance(),[r,n,this.statement_a()]}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type[0])throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];if("FORALL"===this.token.token_type||"EXISTS"===this.token.token_type){let t=this.token.token_type.toLowerCase();return this.advance(),[t,this.relation(e)]}for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUBSETEQ"===this.token.token_type||"NOTSUBSETEQ"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type||"SUPERSETEQ"===this.token.token_type||"NOTSUPERSETEQ"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]),t&&(r=["+",r]);["+","-","UNION","INTERSECT","PERP","PARALLEL"].includes(this.token.token_type);){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return this.convert_units_in_term(flatten(t))}convert_units_in_term(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let e=n.length;for(let[t,r]of n.entries()){let a=this.units[r];if(a){if(a.prefix&&t0){let i,s=r;return a.substitute&&(s=a.substitute),i=1===t?["unit",n[0],s]:["unit",["*",...n.slice(0,t).map(this.convert_units_in_term.bind(this))],s],t===e-1?i:this.convert_units_in_term(["*",i,...n.slice(t+1)])}}}return[t,...n.map(this.convert_units_in_term.bind(this))]}if("/"===t)return["/",this.convert_units_in_term(n[0]),this.convert_units_in_term(n[1])];if("^"===t){let e=this.units[n[1]];if(e&&e.isExponent){let t=n[1];return e.substitute&&(t=e.substitute),["unit",n[0],t]}return[t,...n.map(this.convert_units_in_term.bind(this))]}return[t,...n.map(this.convert_units_in_term.bind(this))]}factor(e){if("+"===this.token.token_text){this.advance();let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){this.advance();let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}let t=this.nonMinusFactor(e);return!1===t&&"PERP"===this.token.token_type&&(t="perp",this.advance()),t}nonMinusFactor(e){for(var t=this.baseFactor(e);"^"===this.token.token_type||"!"===this.token.token_type||"'"===this.token.token_type;)!1===t&&(t="_"),"^"===this.token.token_type?(this.advance(),t=["^",t,this.get_subsuperscript(e)]):"!"===this.token.token_type?(t=["apply","factorial",t],this.advance()):(t=["prime",t],this.advance());return t}get_single_digit_as_number(){if("NUMBER"===this.token.token_type&&"."!==this.token.token_text[0]){let e=Number(this.token.token_text[0]);return this.token.token_text.length>1&&this.lexer.unput(this.token.token_text.slice(1)),this.advance(),e}return null}get_subsuperscript({parse_absolute_value:e}){let t=this.get_single_digit_as_number();if(null!==t)return t;if(["+","-","PERP"].includes(this.token.token_type)){let e=this.token.token_type.toLowerCase();return this.advance(),e}{let t=this.baseFactor({parse_absolute_value:e,in_subsuperscript_with_no_delimiters:!0});return!1===t&&(t="_"),t}}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1,in_subsuperscript_with_no_delimiters:r=!1}={}){var a=!1;if("BEGINENVIRONMENT"===this.token.token_type){let e=/\\begin\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1];if(["matrix","pmatrix","bmatrix"].includes(e)){let n=0,r=0,i=[],s=[],o=0,l=this.token.token_type;for(this.advance();"ENDENVIRONMENT"!==this.token.token_type;)"&"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),l=this.token.token_type,this.advance()):"LINEBREAK"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,o=0,s=[],l=this.token.token_type,this.advance()):(s.push(this.statement({parse_absolute_value:t})),o+=1,l=" ");if(/\\end\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1]!==e)throw new ParseError("Expecting \\end{"+e+"}",this.lexer.location);"&"===l&&(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,this.advance(),a=["matrix",["tuple",n,r]];let u=["tuple"];for(let e of i){let t=["tuple"].concat(e);for(let n=e.length;n=2?a[0]="("===n||"{"===n?"tuple":"["===n?"array":"LBRACE"===n?"set":"altvector":"LBRACE"===n&&("|"===a[0]||a[0],a=["set",a]);this.advance()}else if("|"!==this.token.token_type[0]||!t||0!==e&&n&&"L"!==this.token.token_type[1]){if("LFLOOR"===this.token.token_type||"LCEIL"===this.token.token_type){let e,t;if("LFLOOR"===this.token.token_type?(e="RFLOOR",t="floor"):"LCEIL"===this.token.token_type&&(e="RCEIL",t="ceil"),this.advance(),a=["apply",t,a=this.statement()],this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance()}else if("ANGLE"===this.token.token_type)if(this.advance(),"{"===this.token.token_type||"("===this.token.token_type){let e;e="{"===this.token.token_type?"}":")",this.advance();let t=this.statement_list();if(this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance(),"list"===t[0]?a=["angle",...t.slice(1)]:"*"===t[0]&&(a=["angle",t])}else{let e=[],n=this.nonMinusFactor({parse_absolute_value:t});for(;!1!==n;)e.push(n),n=this.nonMinusFactor({parse_absolute_value:t});a=0===e.length?"angle":["angle",...e]}else if("INT"===this.token.token_type){this.advance();let e="int";"_"===this.token.token_type&&(this.advance(),e=["_",e,this.get_subsuperscript({parse_absolute_value:t})]),"^"===this.token.token_type&&(this.advance(),e=["^",e,this.get_subsuperscript({parse_absolute_value:t})]);let n=flatten(this.term({parse_absolute_value:t}));if(Array.isArray(n)&&"*"===n[0]){let e=[];for(let t=0;tn)return!1;if(s===n){if("}"!==this.token.token_type)return!1;this.advance();let s="derivative_leibniz";"∂"===t&&(s="partial_"+s),e=[s],1===n?e.push(r):e.push(["tuple",r,n]);let o=[];for(let e=0;e,larger":function(e){return[">",e[0],e[1]]},"<=,smallerEq":function(e){return["le",e[0],e[1]]},">=,largerEq":function(e){return["ge",e[0],e[1]]},"!=,unequal":function(e){return["ne",e[0],e[1]]},"!,factorial":function(e){return["apply","factorial",e[0]]}};class mathjsToAst{convert(e){if(e.isConstantNode)return e.value;if(e.isSymbolNode)return e.name;if(e.isOperatorNode){var t=[e.op,e.fn].join(",");if(t in operators)return operators[t](e.args.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Unsupported operator: "+e.op+", "+e.fn)}if(e.isFunctionNode){var n=e.args.map(function(e,t){return this.convert(e)}.bind(this));n=n.length>1?["tuple"].concat(n):n[0];var r=["apply",e.name];return r.push(n),r}if(e.isArrayNode)return["vector"].concat(e.args.map(function(e,t){return this.convert(e)}.bind(this)));if(e.isParenthesisNode)return this.convert(e.content);throw Error("Unsupported node type: "+e.type)}}class mathjsToGuppy{constructor(){this.mathjsToAst=new mathjsToAst,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.mathjsToAst.convert(e))}}class mathjsToLatex{constructor(){this.mathjsToAst=new mathjsToAst,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.mathjsToAst.convert(e))}}class mathjsToText{constructor(){this.mathjsToAst=new mathjsToAst,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.mathjsToAst.convert(e))}}function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n0)return parse$1(e);if("number"===n&&!1===isNaN(e))return t.long?fmtLong(e):fmtShort(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$1(e){if(!((e=String(e)).length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(e){return e>=d?Math.round(e/d)+"d":e>=h?Math.round(e/h)+"h":e>=m?Math.round(e/m)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function fmtLong(e){return plural(e,d,"day")||plural(e,h,"hour")||plural(e,m,"minute")||plural(e,s,"second")||e+" ms"}function plural(e,t,n){if(!(e=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())}(browser,browser.exports);var debug=browser.exports("xml-parser"),xmlParser=parse;function parse(e){return e=(e=e.trim()).replace(//g,""),{declaration:function(){if(n(/^<\?xml\s*/)){for(var e={attributes:{}};!r()&&!a("?>");){var i=t();if(!i)return e;e.attributes[i.name]=i.value}return n(/\?>\s*/),e}}(),root:function i(){debug("tag %j",e);var s=n(/^<([\w-:.]+)\s*/);if(s){for(var o,l={name:s[1],attributes:{},children:[]};!(r()||a(">")||a("?>")||a("/>"));){var u=t();if(!u)return l;l.attributes[u.name]=u.value}if(n(/^\s*\/>\s*/))return l;for(n(/\??>\s*/),l.content=function(){debug("content %j",e);var t=n(/^([^<]*)/);return t?t[1]:""}();o=i();)l.children.push(o);return n(/^<\/[\w-:.]+>\s*/),l}}()};function t(){debug("attribute %j",e);var t,r=n(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);if(r)return{name:r[1],value:(t=r[2],t.replace(/^['"]|['"]$/g,""))}}function n(t){var n=e.match(t);if(n)return e=e.slice(n[0].length),n}function r(){return 0==e.length}function a(t){return 0==e.indexOf(t)}}const entities={"Α":"\\Alpha","Α":"\\Alpha","Α":"\\Alpha","\\u0391;":"\\Alpha","Β":"\\Beta","Β":"\\Beta","Β":"\\Beta","\\u0392;":"\\Beta","Γ":"\\Gamma","Γ":"\\Gamma","Γ":"\\Gamma","\\u0393;":"\\Gamma","Δ":"\\Delta","Δ":"\\Delta","Δ":"\\Delta","\\u0394;":"\\Delta","Ε":"\\Epsilon","Ε":"\\Epsilon","Ε":"\\Epsilon","\\u0395;":"\\Epsilon","Ζ":"\\Zeta","Ζ":"\\Zeta","Ζ":"\\Zeta","\\u0396;":"\\Zeta","Η":"\\Eta","Η":"\\Eta","Η":"\\Eta","\\u0397;":"\\Eta","Θ":"\\Theta","Θ":"\\Theta","Θ":"\\Theta","\\u0398;":"\\Theta","Ι":"\\Iota","Ι":"\\Iota","Ι":"\\Iota","\\u0399;":"\\Iota","Κ":"\\Kappa","Κ":"\\Kappa","Κ":"\\Kappa","\\u039A;":"\\Kappa","Λ":"\\Lambda","Λ":"\\Lambda","Λ":"\\Lambda","\\u039B;":"\\Lambda","Μ":"\\Mu","Μ":"\\Mu","Μ":"\\Mu","\\u039C;":"\\Mu","Ν":"\\Nu","Ν":"\\Nu","Ν":"\\Nu","\\u039D;":"\\Nu","Ξ":"\\Xi","Ξ":"\\Xi","Ξ":"\\Xi","\\u039E;":"\\Xi","Ο":"\\Omicron","Ο":"\\Omicron","Ο":"\\Omicron","\\u039F;":"\\Omicron","Π":"\\Pi","Π":"\\Pi","Π":"\\Pi","\\u03A0;":"\\Pi","Ρ":"\\Rho","Ρ":"\\Rho","Ρ":"\\Rho","\\u03A1;":"\\Rho","Σ":"\\Sigma","Σ":"\\Sigma","Σ":"\\Sigma","\\u03A3;":"\\Sigma","Τ":"\\Tau","Τ":"\\Tau","Τ":"\\Tau","\\u03A4;":"\\Tau","Υ":"\\Upsilon","Υ":"\\Upsilon","Υ":"\\Upsilon","\\u03A5;":"\\Upsilon","Φ":"\\Phi","Φ":"\\Phi","Φ":"\\Phi","\\u03A6;":"\\Phi","Χ":"\\Chi","Χ":"\\Chi","Χ":"\\Chi","\\u03A7;":"\\Chi","Ψ":"\\Psi","Ψ":"\\Psi","Ψ":"\\Psi","\\u03A8;":"\\Psi","Ω":"\\Omega","Ω":"\\Omega","Ω":"\\Omega","\\u03A9;":"\\Omega","α":"\\alpha","α":"\\alpha","α":"\\alpha","\\u03B1;":"\\alpha","β":"\\beta","β":"\\beta","β":"\\beta","\\u03B2;":"\\beta","γ":"\\gamma","γ":"\\gamma","γ":"\\gamma","\\u03B3;":"\\gamma","δ":"\\delta","δ":"\\delta","δ":"\\delta","\\u03B4;":"\\delta","ε":"\\epsilon","ε":"\\epsilon","ε":"\\epsilon","\\u03B5;":"\\epsilon","ζ":"\\zeta","ζ":"\\zeta","ζ":"\\zeta","\\u03B6;":"\\zeta","η":"\\eta","η":"\\eta","η":"\\eta","\\u03B7;":"\\eta","θ":"\\theta","θ":"\\theta","θ":"\\theta","\\u03B8;":"\\theta","ι":"\\iota","ι":"\\iota","ι":"\\iota","\\u03B9;":"\\iota","κ":"\\kappa","κ":"\\kappa","κ":"\\kappa","\\u03BA;":"\\kappa","λ":"\\lambda","λ":"\\lambda","λ":"\\lambda","\\u03BB;":"\\lambda","μ":"\\mu","μ":"\\mu","μ":"\\mu","\\u03BC;":"\\mu","ν":"\\nu","ν":"\\nu","ν":"\\nu","\\u03BD;":"\\nu","ξ":"\\xi","ξ":"\\xi","ξ":"\\xi","\\u03BE;":"\\xi","ο":"\\omicron","ο":"\\omicron","ο":"\\omicron","\\u03BF;":"\\omicron","π":"\\pi","π":"\\pi","π":"\\pi","\\u03C0;":"\\pi","ρ":"\\rho","ρ":"\\rho","ρ":"\\rho","\\u03C1;":"\\rho","ς":"\\sigma",";":"\\sigma","ς":"\\sigma","\\u03C2;":"\\sigma","σ":"\\sigma","σ":"\\sigma","σ":"\\sigma","\\u03C3;":"\\sigma","τ":"\\tau","τ":"\\tau","τ":"\\tau","\\u03C4;":"\\tau","υ":"\\upsilon","υ":"\\upsilon","υ":"\\upsilon","\\u03C5;":"\\upsilon","φ":"\\phi","φ":"\\phi","φ":"\\phi","\\u03C6;":"\\phi","χ":"\\chi","χ":"\\chi","χ":"\\chi","\\u03C7;":"\\chi","ψ":"\\psi","ψ":"\\psi","ψ":"\\psi","\\u03C8;":"\\psi","ω":"\\omega","ω":"\\omega","ω":"\\omega","\\u03C9;":"\\omega","−":"-","−":"-","∞":"\\infty","∞":"\\infty","∞":"\\infty","⋅":"\\cdot","⋅":"\\cdot","⋅":"\\cdot","×":"\\times","×":"\\times","×":"\\times"};class mmlToLatex{parse(e){return"mi"===e.name?entities[e.content]?entities[e.content]:e.content.length>1?"\\"+e.content:e.content:"mn"===e.name?e.content:"msup"===e.name?this.parse(e.children[0])+"^{"+this.parse(e.children[1])+"}":"mroot"===e.name?"\\sqrt["+this.parse(e.children[1])+"]{"+this.parse(e.children[1])+"}":"mfrac"===e.name?"\\frac{"+this.parse(e.children[0])+"}{"+this.parse(e.children[1])+"}":"msqrt"===e.name?"\\sqrt{"+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+"}":"mo"===e.name?entities[e.content]?entities[e.content]:"⁡"===e.content?" ":e.content:"mrow"===e.name&&"MJX-TeXAtom-ORD"===e.attributes.class?e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" "):"math"===e.name||"mrow"===e.name?"("+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+")":void 0}convert(e){return this.parse(xmlParser(e).root)}}class mmlToAst$1{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1}convert(e){return this.latexToAst.convert(this.mmlToLatex.convert(e))}}class mmlToGuppy{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToMathjs{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToText{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class textToGuppy{constructor(){this.textToAst=new textToAst$4,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.textToAst.convert(e))}}class textToLatex{constructor(){this.textToAst=new textToAst$4,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.textToAst.convert(e))}}class textToMathjs{constructor(){this.textToAst=new textToAst$4,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.textToAst.convert(e))}}var converters=Object.freeze({__proto__:null,astToLatexObj:astToLatex$1,astToTextObj:astToText$2,astToGuppyObj:astToGuppy$1,astToMathjsObj:astToMathjs$1,latexToAstObj:latexToAst$1,latexToGuppyObj:latexToGuppy,latexToMathjsObj:latexToMathjs,latexToTextObj:latexToText,mathjsToAstObj:mathjsToAst,mathjsToGuppyObj:mathjsToGuppy,mathjsToLatexObj:mathjsToLatex,mathjsToTextObj:mathjsToText,mmlToAstObj:mmlToAst$1,mmlToGuppyObj:mmlToGuppy,mmlToLatexObj:mmlToLatex,mmlToMathjsObj:mmlToMathjs,mmlToTextObj:mmlToText,textToAstObj:textToAst$4,textToGuppyObj:textToGuppy,textToLatexObj:textToLatex,textToMathjsObj:textToMathjs,astToGLSL:astToGLSL$1}),textToAst=new textToAst$4,latexToAst=new latexToAst$1,mmlToAst=new mmlToAst$1,utils={match:match$2,flatten:flatten$5,unflattenLeft:unflattenLeft,unflattenRight:unflattenRight};function Expression(e,t){this.tree=flatten$5(e),this.context=t,this.toJSON=function(){let e={objectType:"math-expression",tree:this.tree},t={};for(let e in this.context.assumptions)Object.keys(this.context.assumptions[e]).length>0&&(t[e]=this.context.assumptions[e]);return Object.keys(t).length>0&&(e.assumptions=t),e}}function extend(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)t?function(){var t=r;e[t]=function(){return this.fromAst(n[t].apply(null,arguments))}}():e[r]=n[r]})),e}function extend_prototype(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)!function(){var a=r;e[a]=function(){var e=[this].concat(Array.prototype.slice.call(arguments));return t?this.context.fromAst(n[a].apply(null,e)):n[a].apply(null,e)}}()})),e}function create_from_multiple(e,t){if(Array.isArray(e)||"number"==typeof e)return new Expression(e,Context);if("string"==typeof e)try{return new Expression(textToAst.convert(e),Context)}catch(t){try{return new Expression(latexToAst.convert(e),Context)}catch(n){try{return new Expression(mmlToAst.convert(e),Context)}catch(r){if(-1!==e.indexOf("\\"))throw n;if(-1!==e.indexOf(">>2]>>>24-i%4*8&255;t[r+i>>>2]|=s<<24-(r+i)%4*8}else for(i=0;i>>2]=n[i>>>2];return this.sigBytes+=a,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n,r=[],a=function(t){var n=987654321,r=4294967295;return function(){var a=((n=36969*(65535&n)+(n>>16)&r)<<16)+(t=18e3*(65535&t)+(t>>16)&r)&r;return a/=4294967296,(a+=.5)*(e.random()>.5?1:-1)}},i=0;i>>2]>>>24-a%4*8&255;r.push((i>>>4).toString(16)),r.push((15&i).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},u=o.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,r=[],a=0;a>>2]>>>24-a%4*8&255;r.push(String.fromCharCode(i))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},c=o.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},p=a.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=c.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,a=n.sigBytes,i=this.blockSize,o=a/(4*i),l=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*i,u=e.min(4*l,a);if(l){for(var c=0;c>>31}var p=(r<<5|r>>>27)+l+i[u];p+=u<20?1518500249+(a&s|~a&o):u<40?1859775393+(a^s^o):u<60?(a&s|a&o|s&o)-1894007588:(a^s^o)-899497514,l=o,o=s,s=a<<30|a>>>2,a=r,r=p}n[0]=n[0]+r|0,n[1]=n[1]+a|0,n[2]=n[2]+s|0,n[3]=n[3]+o|0,n[4]=n[4]+l|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=Math.floor(n/4294967296),t[15+(r+64>>>9<<4)]=n,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=r._createHelper(s),e.HmacSHA1=r._createHmacHelper(s)}(),CryptoJS.SHA1);var sha1=sha1$1.exports,encBase64={exports:{}};!function(e,t){e.exports=function(e){return function(){var t=e,n=t.lib.WordArray;function r(e,t,r){for(var a=[],i=0,s=0;s>>6-s%4*2;a[i>>>2]|=(o|l)<<24-i%4*8,i++}return n.create(a,i)}t.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,r=this._map;e.clamp();for(var a=[],i=0;i>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,o=0;o<4&&i+.75*o>>6*(3-o)&63));var l=r.charAt(64);if(l)for(;a.length%4;)a.push(l);return a.join("")},parse:function(e){var t=e.length,n=this._map,a=this._reverseMap;if(!a){a=this._reverseMap=[];for(var i=0;iArray.isArray(t)?e.concat(flattenDeep(t)):e.concat(t)),[])}function flattenLevels(e,t){return console.log(`levels: ${t}`),e.reduce(((e,n)=>Array.isArray(n)&&t>1?e.concat(flattenLevels(n,t-1)):e.concat(n)),[])}class Subset{union(e){return this.complement().intersect(e.complement()).complement()}intersectWithOpenInterval(e){return this.intersect(e)}setMinus(e){return this.intersect(e.complement())}symmetricDifference(e){return this.setMinus(e).union(e.setMinus(this))}equals(e){return this.symmetricDifference(e).isEmpty()}toJSON(){return{objectType:"subset",data:Object.assign({},this),subsetType:this.constructor.subsetType}}static reviver(e,t){if(t&&"subset"===t.objectType&&void 0!==t.subsetType){if("emptySet"===t.subsetType)return new EmptySet;if("realLine"===t.subsetType)return new RealLine;if("singleton"===t.subsetType)return new Singleton(t.data.element);if("union"===t.subsetType)return new Union(t.data.subsets);if("openInterval"===t.subsetType)return new OpenInterval(t.data.left,t.data.right)}return t}copy(){return this.constructor.reviver(null,this.toJSON())}}class EmptySet extends Subset{static subsetType="emptySet";union(e){return e}intersect(){return new EmptySet}contains(){return!1}isEmpty(){return!0}complement(){return new RealLine}toString(){return"∅"}toMathExpression(){return me$3.fromAst("∅")}}class RealLine extends Subset{static subsetType="realLine";union(){return new RealLine}intersect(e){return e}contains(){return!0}complement(){return new EmptySet}isEmpty(){return!1}toString(){return"ℝ"}toMathExpression(){return me$3.fromAst("R")}}class Singleton extends Subset{static subsetType="singleton";constructor(e){if(super(),!Number.isFinite(e))return new EmptySet;this.element=e}union(e){return e.contains(this.element)?e:new Union([e,this])}intersect(e){return e.contains(this.element)?new Singleton(this.element):new EmptySet}isEmpty(){return!1}contains(e){return e===this.element}complement(){return new Union([new OpenInterval(-1/0,this.element),new OpenInterval(this.element,1/0)])}toString(){return`{${this.element}}`}toMathExpression(){return me$3.fromAst(["set",this.element])}}class Union extends Subset{static subsetType="union";intersect(e){return new Union(this.subsets.map((t=>e.intersect(t))))}toString(){return this.subsets.map((e=>e.toString())).join(" U ")}toMathExpression(){return me$3.fromAst(["union",...this.subsets.map((e=>e.toMathExpression().tree))])}constructor(e){super();let t=e.filter((e=>!e.isEmpty()));if(0===t.length)return new EmptySet;t=t.reduce(((e,t)=>t instanceof Union?e.concat(t.subsets):e.concat(t)),[]),this.subsets=[];for(let e=0;ea&&s.elementi.left&&at.contains(e)))}isEmpty(){return this.subsets.every((e=>e.isEmpty()))}complement(){return this.subsets.map((e=>e.complement())).reduce(((e,t)=>e.intersect(t)))}}class Interval$1 extends Subset{constructor(e,t){return super(),this.left=e,this.right=t,this.left<=this.right?this.left===-1/0&&this.right===1/0?new RealLine:this:new EmptySet}}class OpenInterval extends Interval$1{static subsetType="openInterval";constructor(e,t){return super(e,t),e===t?new EmptySet:this}intersect(e){return e.intersectWithOpenInterval(this)}intersectWithOpenInterval(e){return new OpenInterval(Math.max(this.left,e.left),Math.min(this.right,e.right))}complement(){return new Union([new OpenClosedInterval(-1/0,this.left),new ClosedOpenInterval(this.right,1/0)])}isEmpty(){return this.left>=this.right}contains(e){return e>this.left&&ebuildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if("intersect"===n||"and"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new RealLine:n.reduce(((e,t)=>e.intersect(t)))}if("set"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if(["<","le",">","ge","=","ne"].includes(n)){let r=e[1],a=!1;if(!Number.isFinite(r))if(deepCompare(r,t))a=!0;else if(r=me$3.fromAst(r).evaluate_to_constant(),!Number.isFinite(r)&&r!==1/0&&r!==-1/0)return new EmptySet;let i=e[2],s=!1;if(!Number.isFinite(i))if(deepCompare(i,t))s=!0;else if(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0)return new EmptySet;return a?s?new EmptySet:"<"===n?new OpenInterval(-1/0,i):"le"===n?new OpenClosedInterval(-1/0,i):">"===n?new OpenInterval(i,1/0):"ge"===n?new ClosedOpenInterval(i,1/0):"="===n?Number.isFinite(i)?new Singleton(i):new EmptySet:Number.isFinite(i)?new Union([new OpenInterval(-1/0,i),new OpenInterval(i,1/0)]):new RealLine:s?"<"===n?new OpenInterval(r,1/0):"le"===n?new ClosedOpenInterval(r,1/0):">"===n?new OpenInterval(-1/0,r):"ge"===n?new OpenClosedInterval(-1/0,r):"="===n?Number.isFinite(r)?new Singleton(r):new EmptySet:Number.isFinite(r)?new Union([new OpenInterval(-1/0,r),new OpenInterval(r,1/0)]):new RealLine:new EmptySet}if(["lts","gts"].includes(n)){let r=e[1].slice(1),a=e[2].slice(1);if(3!==r.length||!deepCompare(r[1],t))return new EmptySet;"gts"===n&&(r.reverse(),a.reverse());let i=r[0];if(!Number.isFinite(i)&&(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0))return new EmptySet;let s=r[2];return Number.isFinite(s)||(s=me$3.fromAst(s).evaluate_to_constant(),Number.isFinite(s)||s===1/0||s===-1/0)?a[0]?a[1]?new OpenInterval(i,s):new OpenClosedInterval(i,s):a[1]?new ClosedOpenInterval(i,s):new ClosedInterval(i,s):new EmptySet}if("|"===n){let t=e[1];return buildSubsetFromIntervals(e[2],t)}if("^"!==n||"C"!==e[2]&&"c"!==e[2]){if("in"===n)return deepCompare(e[1],t)?buildSubsetFromIntervals(e[2],t):new EmptySet;if("ni"===n)return deepCompare(e[2],t)?buildSubsetFromIntervals(e[1],t):new EmptySet;if("notin"===n){if(deepCompare(e[1],t)){let n=buildSubsetFromIntervals(e[2],t);if(n)return n.complement()}return new EmptySet}if("notni"===n){if(deepCompare(e[2],t)){let n=buildSubsetFromIntervals(e[1],t);if(n)return n.complement()}return new EmptySet}{let t=me$3.fromAst(e).evaluate_to_constant();return Number.isFinite(t)?new Singleton(t):new EmptySet}}{let n=buildSubsetFromIntervals(e[1],t);return n?n.complement():new EmptySet}}function buildSubsetFromMathExpression(e,t){return buildSubsetFromIntervals(e.to_intervals().tree,t.tree)}function deepClone(e,t,n){if(Object(e)!==e||e instanceof Function)return e;if(void 0!==t&&e instanceof t)return e;if(e instanceof me$3.class||e instanceof theModule.Subset)return e.copy();if(void 0===n&&(n=new WeakMap),Array.isArray(e))return[...e.map((e=>deepClone(e,t,n)))];if(e.constructor===Object&&0===Object.entries(e).length)return{};if(n.has(e))return n.get(e);try{var r=new e.constructor}catch(t){r=Object.create(Object.getPrototypeOf(e))}return e instanceof Map?Array.from(e,(([e,a])=>r.set(deepClone(e,t,n),deepClone(a,t,n)))):e instanceof Set&&Array.from(e,(e=>r.add(deepClone(e,t,n)))),n.set(e,r),Object.assign(r,...Object.keys(e).map((r=>({[r]:deepClone(e[r],t,n)}))))}function deepCompare(e,t,n){var r,a;return r=[],a=[],function e(t,i){var s;if(Number.isNaN(t)&&Number.isNaN(i))return!0;if(t===i)return!0;if(void 0!==n&&t instanceof n&&i instanceof n)return t.componentName===i.componentName;if(t instanceof me$3.class&&i instanceof me$3.class)return e(t.tree,i.tree);if("function"==typeof t&&"function"==typeof i||t instanceof Date&&i instanceof Date||t instanceof RegExp&&i instanceof RegExp||t instanceof String&&i instanceof String||t instanceof Number&&i instanceof Number)return t.toString()===i.toString();if(!(t instanceof Object&&i instanceof Object))return!1;if(t.isPrototypeOf(i)||i.isPrototypeOf(t))return!1;if(t.constructor!==i.constructor)return!1;if(t.prototype!==i.prototype)return!1;if(r.indexOf(t)>-1||a.indexOf(i)>-1)return!1;for(s in i){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1}for(s in t){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1;switch(typeof t[s]){case"object":case"function":if(r.push(t),a.push(i),!e(t[s],i[s]))return!1;r.pop(),a.pop();break;default:if(!(t[s]===i[s]||Number.isNaN(t[s])&&Number.isNaN(i[s])))return!1}}return!0}(e,t)}function breakStringsAndOthersIntoComponentsByStringCommas(e){return null}function returnBreakStringsSugarFunction({childrenToComponentFunction:e,mustStripOffOuterParentheses:t=!1}){return function({matchedChildren:n}){let r=0,a=[],i=[],s=!1,o=n.length;if(t){let e=n[0];if("string"!=typeof e||"("!==e.trimLeft()[0])return{success:!1}}for(let[e,l]of n.entries()){if("string"!=typeof l){i.push(l);continue}let u=l.trim();if(0===e&&t&&"("===u[0]){let e=n[o-1];if("string"==typeof e){let t=e.trimRight();")"===t[t.length-1]&&(s=!0,u=u.substring(1))}}let c=0;for(let t=0;tc&&i.push(u.substring(c,t)),a.push(i),i=[],c=t+1)}u.length>c&&i.push(u.substring(c,u.length))}return 0!==r?{success:!1}:(a.push(i),{success:!0,newChildren:a.map(e)})}}function breakEmbeddedStringByCommas({childrenList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=e.substring(i,a).trim();r.push(t)}n.push(r),r=[],i=a+1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t?{success:!1}:(n.push(r),{success:!0,pieces:n})}function breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:t=!1}){let n=0,r=[],a=[];for(let i of e){if("string"!=typeof i){0===n?r.push([i]):a.push(i);continue}let e=i.trim(),s=0;for(let i=0;is){let n=t?i:i+1,r=e.substring(s,n).trim();r.length>0&&a.push(r)}r.push(a),a=[],s=i+1}n--}else if(0===n&&!o.match(/\s/))return{success:!1}}if(e.length>s){let t=e.substring(s,e.length).trim();a.push(t)}}return 0!==n?{success:!1}:(a.length>0&&r.push(a),{success:!0,pieces:r})}var global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof e&&(e=NodeType.match(e)),t=>{let n=e(t);return void 0===n?null:[this,n]}}}NodeProp.closedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.group=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null);class NodeType{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):noProps,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(null==e.name?8:0),r=new NodeType(e.name||"",t,e.id,n);if(e.props)for(let n of e.props)if(Array.isArray(n)||(n=n(r)),n){if(n[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[n[0].id]=n[1]}return r}prop(e){return this.props[e.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(e){if("string"==typeof e){if(this.name==e)return!0;let t=this.prop(NodeProp.group);return!!t&&t.indexOf(e)>-1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(" "))t[r]=e[n];return e=>{for(let n=e.prop(NodeProp.group),r=-1;r<(n?n.length:0);r++){let a=t[r<0?e.name:n[r]];if(a)return a}}}}NodeType.none=new NodeType("",Object.create(null),0,8);class NodeSet{constructor(e){this.types=e;for(let t=0;te.node;;){let s=!1;if(e.from<=a&&e.to>=r&&(e.type.isAnonymous||!1!==t(e.type,e.from,e.to,i))){if(e.firstChild())continue;e.type.isAnonymous||(s=!0)}for(;s&&n&&n(e.type,e.from,e.to,i),s=e.type.isAnonymous,!e.nextSibling();){if(!e.parent())return;s=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,((e,t,n)=>new Tree(this.type,e,t,n,this.propValues)),e.makeTree||((e,t,n)=>new Tree(NodeType.none,e,t,n)))}static build(e){return buildTree(e)}}Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new FlatBufferCursor(this.buffer,this.index)}}class TreeBuffer{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return NodeType.none}toString(){let e=[];for(let t=0;t0));o=i[o+3]);return s}slice(e,t,n,r){let a=this.buffer,i=new Uint16Array(t-e);for(let r=e,s=0;r=t&&nt;case 1:return n<=t&&r>t;case 2:return r>t;case 4:return!0}}function enterUnfinishedNodesBefore(e,t){let n=e.childBefore(t);for(;n;){let t=n.lastChild;if(!t||t.to!=n.to)break;t.type.isError&&t.from==t.to?(e=n,n=t.prevSibling):n=t}return e}function resolveNode(e,t,n,r){for(var a;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to0?s.length:-1;e!=l;e+=t){let l=s[e],u=o[e]+i._from;if(checkSide(r,n,u,u+l.length))if(l instanceof TreeBuffer){if(2&a)continue;let s=l.findChild(0,l.buffer.length,t,n-u,r);if(s>-1)return new BufferNode(new BufferContext(i,l,e,u),null,s)}else if(1&a||!l.type.isAnonymous||hasChild(l)){let s;if(!(1&a)&&l.props&&(s=l.prop(NodeProp.mounted))&&!s.overlay)return new TreeNode(s.tree,u,e,i);let o=new TreeNode(l,u,e,i);return 1&a||!o.type.isAnonymous?o:o.nextChild(t<0?l.children.length-1:0,t,n,r)}}if(1&a||!i.type.isAnonymous)return null;if(e=i.index>=0?i.index+t:t<0?-1:i._parent.node.children.length,i=i._parent,!i)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this.node.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this.node.children.length-1,-1,e,-2)}enter(e,t,n=!0,r=!0){let a;if(n&&(a=this.node.prop(NodeProp.mounted))&&a.overlay){let n=e-this.from;for(let{from:e,to:r}of a.overlay)if((t>0?e<=n:e=n:r>n))return new TreeNode(a.tree,a.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,r?0:2)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get cursor(){return new TreeCursor(this)}get tree(){return this.node}toTree(){return this.node}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}toString(){return this.node.toString()}}function getChildren(e,t,n,r){let a=e.cursor,i=[];if(!a.firstChild())return i;if(null!=n)for(;!a.type.is(n);)if(!a.nextSibling())return i;for(;;){if(null!=r&&a.type.is(r))return i;if(a.type.is(t)&&i.push(a.node),!a.nextSibling())return null==r?i:[]}}class BufferContext{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}}class BufferNode{constructor(e,t,n){this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}child(e,t,n){let{buffer:r}=this.context,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,n);return a<0?null:new BufferNode(this.context,this,a)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,n,r=!0){if(!r)return null;let{buffer:a}=this.context,i=a.findChild(this.index+4,a.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return i<0?null:new BufferNode(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new BufferNode(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new BufferNode(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get cursor(){return new TreeCursor(this)}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,a=n.buffer[this.index+3];if(a>r){let i=n.buffer[this.index+1],s=n.buffer[this.index+2];e.push(n.slice(r,a,i,s)),t.push(0)}return new Tree(this.type,e,t,this.to-this.from)}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}}class TreeCursor{constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof TreeNode)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let t=e._parent;t;t=t._parent)this.stack.unshift(t.index);this.bufferNode=e,this.yieldBuf(e.index)}}get name(){return this.type.name}yieldNode(e){return!!e&&(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0)}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return!!e&&(e instanceof TreeNode?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)))}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree.node.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return!(a<0)&&(this.stack.push(this.index),this.yieldBuf(a))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=!0,r=!0){return this.buffer?!!r&&this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n&&!(1&this.mode),r))}parent(){if(!this.buffer)return this.yieldNode(1&this.mode?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=1&this.mode?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return!!this._tree._parent&&this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode));let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let e=n<0?0:this.stack[n]+4;if(this.index!=e)return this.yieldBuf(t.findChild(e,this.index,-1,0,4))}else{let e=t.buffer[this.index+3];if(e<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(e)}return n<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let r=t+e,a=e<0?-1:n.node.children.length;r!=a;r+=e){let e=n.node.children[r];if(1&this.mode||e instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let i=e;i;i=i._parent)if(i.index==r){if(r==this.index)return i;t=i,n=a+1;break e}r=this.stack[--a]}for(let e=n;ee instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e)))}function buildTree(e){var t;let{buffer:n,nodeSet:r,maxBufferLength:a=DefaultBufferLength,reused:i=[],minRepeatType:s=r.types.length}=e,o=Array.isArray(n)?new FlatBufferCursor(n,n.length):n,l=r.types,u=0,c=0;function p(e,t,n,f,y){let{id:g,start:b,end:v,size:N}=o,T=c;for(;N<0;){if(o.next(),-1==N){let t=i[g];return n.push(t),void f.push(b-e)}if(-3==N)return void(u=g);if(-4==N)return void(c=g);throw new RangeError(`Unrecognized record size: ${N}`)}let C,A,V=l[g],x=b-e;if(v-b<=a&&(A=function(e,t){let n=o.fork(),r=0,i=0,l=0,u=n.end-a,c={size:0,start:0,skip:0};e:for(let a=n.pos-e;n.pos>a;){let e=n.size;if(n.id==t&&e>=0){c.size=r,c.start=i,c.skip=l,l+=4,r+=4,n.next();continue}let o=n.pos-e;if(e<0||o=s?4:0,d=n.start;for(n.next();n.pos>o;){if(n.size<0){if(-3!=n.size)break e;p+=4}else n.id>=s&&(p+=4);n.next()}i=d,r+=e,l+=p}(t<0||r==e)&&(c.size=r,c.start=i,c.skip=l);return c.size>4?c:void 0}(o.pos-t,y))){let t=new Uint16Array(A.size-A.skip),n=o.pos-A.size,a=t.length;for(;o.pos>n;)a=h(A.start,t,a);C=new TreeBuffer(t,v-A.start,r),x=A.start-e}else{let e=o.pos-N;o.next();let t=[],n=[],r=g>=s?g:-1,i=0,l=v;for(;o.pos>e;)r>=0&&o.id==r&&o.size>=0?(o.end<=l-a&&(d(t,n,b,i,o.end,l,r,T),i=t.length,l=o.end),o.next()):p(b,e,t,n,r);if(r>=0&&i>0&&i-1&&i>0){let e=function(e){return(t,n,r)=>{let a,i,s=0,o=t.length-1;if(o>=0&&(a=t[o])instanceof Tree){if(!o&&a.type==e&&a.length==r)return a;(i=a.prop(NodeProp.lookAhead))&&(s=n[o]+a.length+i)}return m(e,t,n,r,s)}}(V);C=balanceRange(V,t,n,0,t.length,0,v-b,e,e)}else C=m(V,t,n,v-b,T-v)}n.push(C),f.push(x)}function d(e,t,n,a,i,s,o,l){let u=[],c=[];for(;e.length>a;)u.push(e.pop()),c.push(t.pop()+n-i);e.push(m(r.types[o],u,c,s-i,l-s)),t.push(i-n)}function m(e,t,n,r,a=0,i){if(u){let e=[NodeProp.contextHash,u];i=i?[e].concat(i):[e]}if(a>25){let e=[NodeProp.lookAhead,a];i=i?[e].concat(i):[e]}return new Tree(e,t,n,r,i)}function h(e,t,n){let{id:r,start:a,end:i,size:l}=o;if(o.next(),l>=0&&r4){let r=o.pos-(l-4);for(;o.pos>r;)n=h(e,t,n)}t[--n]=s,t[--n]=i-e,t[--n]=a-e,t[--n]=r}else-3==l?u=r:-4==l&&(c=r);return n}let f=[],y=[];for(;o.pos>0;)p(e.start||0,e.bufferStart||0,f,y,-1);let g=null!==(t=e.length)&&void 0!==t?t:f.length?y[0]+f[0].length:0;return new Tree(l[e.topID],f.reverse(),y.reverse(),g)}const nodeSizeCache=new WeakMap;function nodeSize(e,t){if(!e.isAnonymous||t instanceof TreeBuffer||t.type!=e)return 1;let n=nodeSizeCache.get(t);if(null==n){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof Tree)){n=1;break}n+=nodeSize(e,r)}nodeSizeCache.set(t,n)}return n}function balanceRange(e,t,n,r,a,i,s,o,l){let u=0;for(let n=r;n=c)break;h+=t}if(u==a+1){if(h>c){let e=n[a];t(e.children,e.positions,0,e.children.length,r[a]+o);continue}p.push(n[a])}else{let t=r[u-1]+n[u-1].length-m;p.push(balanceRange(e,n,r,a,u,m,t,null,l))}d.push(m+o-i)}}(t,n,r,a,0),(o||l)(p,d,s)}class Parser$1{startParse(e,t,n){return"string"==typeof e&&(e=new StringInput(e)),n=n?n.length?n.map((e=>new Range(e.from,e.to))):[new Range(0,0)]:[new Range(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let e=r.advance();if(e)return e}}}class StringInput{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new NodeProp({perNode:!0});class Stack$1{constructor(e,t,n,r,a,i,s,o,l,u=0,c){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=a,this.score=i,this.buffer=s,this.bufferBase=o,this.curContext=l,this.lookAhead=u,this.parent=c}toString(){return`[${this.stack.filter(((e,t)=>t%3==0)).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,n=0){let r=e.parser.context;return new Stack$1(e,[],t,n,n,0,[],0,r?new StackContext(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,n=65535&e,{parser:r}=this.p,a=r.dynamicPrecedence(n);if(a&&(this.score+=a),0==t)return this.pushState(r.getGoto(this.state,n,!0),this.reducePos),ni;)this.stack.pop();this.reduceContext(n,s)}storeNode(e,t,n,r=4,a=!1){if(0==e){let e=this,r=this.buffer.length;if(0==r&&e.parent&&(r=e.bufferBase-e.parent.bufferBase,e=e.parent),r>0&&0==e.buffer[r-4]&&e.buffer[r-1]>-1){if(t==n)return;if(e.buffer[r-2]>=t)return void(e.buffer[r-2]=n)}}if(a&&this.pos!=n){let a=this.buffer.length;if(a>0&&0!=this.buffer[a-4])for(;a>0&&this.buffer[a-2]>n;)this.buffer[a]=this.buffer[a-4],this.buffer[a+1]=this.buffer[a-3],this.buffer[a+2]=this.buffer[a-2],this.buffer[a+3]=this.buffer[a-1],a-=4,r>4&&(r-=4);this.buffer[a]=e,this.buffer[a+1]=t,this.buffer[a+2]=n,this.buffer[a+3]=r}else this.buffer.push(e,t,n,r)}shift(e,t,n){let r=this.pos;if(131072&e)this.pushState(65535&e,this.pos);else if(0==(262144&e)){let a=e,{parser:i}=this.p;(n>this.pos||t<=i.maxNode)&&(this.pos=n,i.stateFlag(a,1)||(this.reducePos=n)),this.pushState(a,r),this.shiftContext(t,r),t<=i.maxNode&&this.buffer.push(t,r,n,4)}else this.pos=n,this.shiftContext(t,r),t<=this.p.parser.maxNode&&this.buffer.push(t,r,n,4)}apply(e,t,n){65536&e?this.reduce(e):this.shift(e,t,n)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let n=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new Stack$1(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,n,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new SimulatedStack(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(0==(65536&n))return!0;if(0==n)return!1;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r,a=0;a1&t&&e==r))||n.push(t[e],r)}t=n}let n=[];for(let e=0;e>19,r=65535&e,a=this.stack.length-3*n;if(a<0||t.getGoto(this.stack[a],r,!1)<0)return!1;this.storeNode(0,this.reducePos,this.reducePos,4,!0),this.score-=100}return this.reduce(e),!0}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:e}=this.p;return 65535==e.data[e.stateSlot(this.state,1)]&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class StackContext{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}var Recover;!function(e){e[e.Insert=200]="Insert",e[e.Delete=190]="Delete",e[e.Reduce=100]="Reduce",e[e.MaxNext=4]="MaxNext",e[e.MaxInsertStackDepth=300]="MaxInsertStackDepth",e[e.DampenInsertStackDepth=120]="DampenInsertStackDepth"}(Recover||(Recover={}));class SimulatedStack{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=65535&e,n=e>>19;0==n?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(n-1);let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class StackBufferCursor{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,0==this.index&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new StackBufferCursor(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;null!=e&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new StackBufferCursor(this.stack,this.pos,this.index)}}class CachedToken{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const nullToken=new CachedToken;class InputStream{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,a=this.pos+e;for(;an.to:a>=n.to;){if(r==this.ranges.length-1)return null;let e=this.ranges[++r];a+=e.from-n.to,n=e}return a}peek(e){let t,n,r=this.chunkOff+e;if(r>=0&&r=this.chunk2Pos&&tr.to&&(this.chunk2=this.chunk2.slice(0,r.to-t)),n=this.chunk2.charCodeAt(0)}}return t>=this.token.lookAhead&&(this.token.lookAhead=t+1),n}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(null==n||n=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=nullToken,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}}class TokenGroup{constructor(e,t){this.data=e,this.id=t}token(e,t){readToken(this.data,e,t,this.id)}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class ExternalTokenizer{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function readToken(e,t,n,r){let a=0,i=1<0){let n=e[r];if(o.allows(n)&&(-1==t.token.value||t.token.value==n||s.overrides(n,t.token.value))){t.acceptToken(n);break}}for(let r=t.next,i=0,s=e[a+2];i>1,l=n+o+(o<<1),u=e[l],c=e[l+1];if(r=c)){a=e[l+2],t.advance();continue e}i=o+1}}break}}function decodeArray(e,t=Uint16Array){if("string"!=typeof e)return e;let n=null;for(let r=0,a=0;r=92&&t--,t>=34&&t--;let a=t-32;if(a>=46&&(a-=46,n=!0),i+=a,n)break;i*=46}n?n[a++]=i:n=new t(i)}return n}const verbose=void 0!==browser$1&&/\bparse\b/.test(browser$1.env.LOG);let stackIDs=null;var Safety,Rec;function cutAt(e,t,n){let r=e.fullCursor();for(r.moveTo(t);;)if(!(n<0?r.childBefore(t):r.childAfter(t)))for(;;){if((n<0?r.tot)&&!r.type.isError)return n<0?Math.max(0,Math.min(r.to-1,t-25)):Math.min(e.length,Math.max(r.from+1,t+25));if(n<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return n<0?0:e.length}}!function(e){e[e.Margin=25]="Margin"}(Safety||(Safety={}));class FragmentCursor{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?cutAt(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?cutAt(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=i,null;if(a instanceof Tree){if(i==e){if(i=Math.max(this.safeFrom,e)&&(this.trees.push(a),this.start.push(i),this.index.push(0))}else this.index[t]++,this.nextStart=i+a.length}}}class TokenCache{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map((e=>new CachedToken))}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:a}=r,i=r.stateSlot(e.state,3),s=e.curContext?e.curContext.hash:0,o=0;for(let r=0;ru.end+25&&(o=Math.max(u.lookAhead,o)),0!=u.value)){let r=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!l.extend&&(n=u,t>r))break}}for(;this.actions.length>t;)this.actions.pop();return o&&e.setLookAhead(o),n||e.pos!=this.stream.end||(n=new CachedToken,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new CachedToken,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){if(t.token(this.stream.reset(n.pos,e),n),e.value>-1){let{parser:t}=n.p;for(let r=0;r=0&&n.p.parser.dialect.allows(a>>1)){0==(1&a)?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=Math.min(n.p.stream.end,n.pos+1)}putAction(e,t,n,r){for(let t=0;t4*e.bufferLength?new FragmentCursor(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e,t,n=this.stacks,r=this.minStackPos,a=this.stacks=[];for(let i=0;ir)a.push(s);else{if(this.advanceStack(s,a,n))continue;{e||(e=[],t=[]),e.push(s);let n=this.tokens.getMainToken(s);t.push(n.value,n.end)}}break}}if(!a.length){let t=e&&findFinished(e);if(t)return this.stackToTree(t);if(this.parser.strict)throw verbose&&e&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+r);this.recovering||(this.recovering=5)}if(this.recovering&&e){let n=null!=this.stoppedAt&&e[0].pos>this.stoppedAt?e[0]:this.runRecovery(e,t,a);if(n)return this.stackToTree(n.forceAll())}if(this.recovering){let e=1==this.recovering?1:3*this.recovering;if(a.length>e)for(a.sort(((e,t)=>t.score-e.score));a.length>e;)a.pop();a.some((e=>e.reducePos>r))&&this.recovering--}else if(a.length>1)e:for(let e=0;e500&&r.buffer.length>500){if(!((t.score-r.score||t.buffer.length-r.buffer.length)>0)){a.splice(e--,1);continue e}a.splice(n--,1)}}}this.minStackPos=a[0].pos;for(let e=1;e ":"";if(null!=this.stoppedAt&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let s=this.fragments.nodeAt(r);s;){let r=this.parser.nodeSet.types[s.type.id]==s.type?a.getGoto(e.state,s.type.id):-1;if(r>-1&&s.length&&(!t||(s.prop(NodeProp.contextHash)||0)==n))return e.useNode(s,r),verbose&&console.log(i+this.stackID(e)+` (via reuse of ${a.getName(s.type.id)})`),!0;if(!(s instanceof Tree)||0==s.children.length||s.positions[0]>0)break;let o=s.children[0];if(!(o instanceof Tree&&0==s.positions[0]))break;s=o}}let s=a.stateSlot(e.state,4);if(s>0)return e.reduce(s),verbose&&console.log(i+this.stackID(e)+` (via always-reduce ${a.getName(65535&s)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let o=this.tokens.getActions(e);for(let s=0;sr?t.push(d):n.push(d)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return pushStackDedup(e,t),!0}}runRecovery(e,t,n){let r=null,a=!1;for(let i=0;i ":"";if(s.deadEnd){if(a)continue;if(a=!0,s.restart(),verbose&&console.log(u+this.stackID(s)+" (restarted)"),this.advanceFully(s,n))continue}let c=s.split(),p=u;for(let e=0;c.forceReduce()&&e<10;e++){if(verbose&&console.log(p+this.stackID(c)+" (via force-reduce)"),this.advanceFully(c,n))break;verbose&&(p=this.stackID(c)+" -> ")}for(let e of s.recoverByInsert(o))verbose&&console.log(u+this.stackID(e)+" (via recover-insert)"),this.advanceFully(e,n);this.stream.end>s.pos?(l==s.pos&&(l++,o=0),s.recoverByDelete(o,l),verbose&&console.log(u+this.stackID(s)+` (via recover-delete ${this.parser.getName(o)})`),pushStackDedup(s,n)):(!r||r.scoree;class ContextTracker{constructor(e){this.start=e.start,this.shift=e.shift||id,this.reduce=e.reduce||id,this.reuse=e.reuse||id,this.hash=e.hash||(()=>0),this.strict=!1!==e.strict}}class LRParser extends Parser$1{constructor(e){if(super(),this.wrappers=[],13!=e.version)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (13)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let n=0;ne.topRules[t][1])),r=[];for(let e=0;e=0)a(r,e,t[n++]);else{let i=t[n+-r];for(let s=-r;s>0;s--)a(t[n++],e,i);n++}}}this.nodeSet=new NodeSet(t.map(((t,a)=>NodeType.define({name:a>=this.minRepeatTerm?void 0:t,id:a,props:r[a],top:n.indexOf(a)>-1,error:0==a,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1})))),this.strict=!1,this.bufferLength=DefaultBufferLength;let i=decodeArray(e.tokenData);if(this.context=e.context,this.specialized=new Uint16Array(e.specialized?e.specialized.length:0),this.specializers=[],e.specialized)for(let t=0;t"number"==typeof e?new TokenGroup(i,e):e)),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new Parse(this,e,t,n);for(let a of this.wrappers)r=a(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let a=r[t+1];;){let t=r[a++],i=1&t,s=r[a++];if(i&&n)return s;for(let n=a+(t>>1);a0}validAction(e,t){if(t==this.stateSlot(e,4))return!0;for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])return!1;n=pair(this.data,n+2)}if(t==pair(this.data,n+1))return!0}}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])break;n=pair(this.data,n+2)}if(0==(1&this.data[n+2])){let e=this.data[n+1];t.some(((t,n)=>1&n&&t==e))||t.push(this.data[n],e)}}return t}overrides(e,t){let n=findOffset(this.data,this.tokenPrecTable,t);return n<0||findOffset(this.data,this.tokenPrecTable,e){let n=e.tokenizers.find((e=>e.from==t));return n?n.to:t}))),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),null!=e.strict&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),null!=e.bufferLength&&(t.bufferLength=e.bufferLength),t}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return null==t?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map((()=>!1));if(e)for(let r of e.split(" ")){let e=t.indexOf(r);e>=0&&(n[e]=!0)}let r=null;for(let e=0;ee)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.score=65&&e<=90||95==e||e>=97&&e<=122||e>=161}function isSpace(e){return 9==e||10==e||13==e||32==e}let cachedName=null,cachedInput=null,cachedPos=0;function tagNameAfter(e,t){let n=e.pos+t;if(cachedInput==e&&cachedPos==n)return cachedName;for(;isSpace(e.peek(t));)t++;let r="";for(;;){let n=e.peek(t);if(!nameChar(n))break;r+=String.fromCharCode(n),t++}return cachedInput=e,cachedPos=n,cachedName=r||null}function ElementContext(e,t){this.name=e,this.parent=t,this.hash=t?t.hash:0;for(let t=0;tt==StartTag?new ElementContext(tagNameAfter(r,1)||"",e):e,reduce:(e,t)=>t==Element&&e?e.parent:e,reuse(e,t,n,r){let a=t.type.id;return a==StartTag||a==OpenTag?new ElementContext(tagNameAfter(r,1)||"",e):e},hash:e=>e?e.hash:0,strict:!1}),startTag=new ExternalTokenizer(((e,t)=>{if(60==e.next)if(e.advance(),47==e.next){e.advance();let n=tagNameAfter(e,0);if(!n)return e.acceptToken(incompleteStartCloseTag);if(t.context&&n.toLowerCase()==t.context.name.toLowerCase())return e.acceptToken(StartCloseTag);for(let r=t.context;r;r=r.parent)if(r.name==n)return e.acceptToken(MissingCloseTag,-2);e.acceptToken(mismatchedStartCloseTag)}else if(33!=e.next&&63!=e.next&&!isSpace(e.next))return e.acceptToken(StartTag)}),{contextual:!0});function scanTo(e,t){return new ExternalTokenizer((n=>{for(let r=0,a=0;;a++){if(n.next<0){a&&n.acceptToken(e);break}if(n.next==t.charCodeAt(r)){if(r++,r==t.length){a>t.length&&n.acceptToken(e,1-t.length);break}}else r=0;n.advance()}}))}const commentContent=scanTo(commentContent$1,"--\x3e"),parser=LRParser.deserialize({version:13,states:"*[OQOTOOO]OYO'#CdOeO`O'#CfO!OOTO'#CeOOOP'#Ce'#CeOOOP'#Cx'#CxOOOP'#Co'#CoQQOTOOOOOQ'#Cp'#CpO!VOYO,59OOOOP,59O,59OO!_OpO,59QO!mO`O'#ClOOOP'#DT'#DTOOOP'#Cu'#CuO!rOTO,59PO!yO`O'#CmOOOP,59P,59POOOP-E6m-E6mOOOQ-E6n-E6nOOOP1G.j1G.jOOOO'#Cq'#CqO#ROpO1G.lO#aOpO'#ChOOOO'#Cr'#CrO#rOpO1G.lOOOP1G.l1G.lOOOP1G.t1G.tO#}OWO,59WOOOP-E6s-E6sOOOP1G.k1G.kO$SO`O,59XO$[OWO,59XOOOO-E6o-E6oO$dOpO7+$WOOOP7+$W7+$WOOOP7+$`7+$`O$oOpO,59SO%QOWO,59SOOOO-E6p-E6pOOOP1G.r1G.rO%]OWO1G.sO%]OWO1G.sOOOP1G.s1G.sOOOP< tag. Found ${e.slice(a-1,i)}`)}n.firstChild();let t=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=!0}else{n.nextSibling();let a=e.substring(n.from+1,n.to-1);if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=a}n.parent()}n.parent();let s=n.to,o={componentType:r,props:{...i},children:[]};for(;n.nextSibling();)if("Text"===n.name){let t=e.substring(n.from,n.to);""!==t&&o.children.push(t)}else{if("Element"!==n.name){if("CloseTag"===n.name)break;if("Comment"===n.name)continue;throw"MismatchedCloseTag"===n.name?Error(`Invalid DoenetML at position ${n.from}. Mismatched closing tag. Expected . Found ${e.slice(n.from,n.to)}.`):Error(`Invalid DoenetML at position ${n.from}. Expected a closing tag. Instead found ${e.slice(n.from,n.to)}.`)}o.children.push(t(n.node.cursor))}return o.range={openBegin:a,openEnd:s,closeBegin:n.from,closeEnd:n.to},o}if("SelfClosingTag"===n.name){n.firstChild(),n.nextSibling();let t=e.substring(n.from,n.to),r=n.from,a={};for(;n.nextSibling();){if("Attribute"!==n.name)throw Error(`Invalid DoenetML at positions ${n.from} to ${n.to}. Error in self-closing <${t}/> tag.`);n.firstChild();let r=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);a[r]=!0}else{if(n.nextSibling(),r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);let i=e.substring(n.from+1,n.to-1);a[r]=i}n.parent()}let i={selfCloseBegin:r,selfCloseEnd:n.to+2};return{componentType:t,props:{...a},children:[],range:i}}throw Error("Non SelfClosingTag/OpenTag in Element. How did you do that?")}function n(n){if("Element"===n.node.name)return t(n.node.cursor);if("Comment"===n.node.name)return null;if("Text"!==n.node.name)throw Error(`Invalid DoenetML at positions ${n.node.from} to ${n.node.to}. Found ${e.substring(n.node.from,n.node.to)}`);{let t=e.substring(n.node.from,n.node.to);if(""!==t)return t}}if(!e)return[];let r=parse(e),a=[];if(!r.firstChild())return a;let i=n(r);for(null!=i&&a.push(i);r.nextSibling();){let e=n(r);null!=e&&a.push(e)}return a}var base32$1={exports:{}};!function(e){!function(){var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof browser$1&&browser$1.versions&&browser$1.versions.node&&(t=commonjsGlobal);var n=!t.HI_BASE32_NO_COMMON_JS&&e.exports,r="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},i=[0,0,0,0,0,0,0,0],s=function(e,t){t.length>10&&(t="..."+t.substr(-10));var n=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw n.position=e,n},o=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,n,r,i,s,o,l,u,c=[],p=0,d=(e=e.replace(/=/g,"")).length,m=0,h=d>>3<<3;m>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3),c[p++]=255&(l<<5|u);var f=d-h;return 2===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2)):4===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4)):5===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1)):7===f&&(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],o=a[e.charAt(m++)],l=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3)),c},l=function(e,t){if(!t)return function(e){for(var t,n,r="",a=e.length,i=0,o=0;i191&&t<=223?(n=31&t,o=1):t<=239?(n=15&t,o=2):t<=247?(n=7&t,o=3):s(i,r);for(var l=0;l191)&&s(i,r),n<<=6,n+=63&t;n>=55296&&n<=57343&&s(i,r),n>1114111&&s(i,r),n<=65535?r+=String.fromCharCode(n):(n-=65536,r+=String.fromCharCode(55296+(n>>10)),r+=String.fromCharCode(56320+(1023&n)))}return r}(o(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var n,r,i,l,u,c,p,d,m="",h=e.indexOf("=");-1===h&&(h=e.length);for(var f=0,y=h>>3<<3;f>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))+String.fromCharCode(255&(p<<5|d));var g=h-y;return 2===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))):4===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))):5===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))):7===g&&(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],c=a[e.charAt(f++)],p=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))),m},u={encode:function(e,t){var n="string"!=typeof e;return n&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),n?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e[u],o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e[u++],n=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e[u++],n=e[u++],a=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e[u++],n=e[u++],a=e[u++],i=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):t?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e.charCodeAt(u),o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u++),i=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):function(e){var t,n,a,s,o,l,u,c=!1,p="",d=0,m=0,h=e.length;if(""===e)return p;do{for(i[0]=i[5],i[1]=i[6],i[2]=i[7],u=m;d>6,i[u++]=128|63&l):l<55296||l>=57344?(i[u++]=224|l>>12,i[u++]=128|l>>6&63,i[u++]=128|63&l):(l=65536+((1023&l)<<10|1023&e.charCodeAt(++d)),i[u++]=240|l>>18,i[u++]=128|l>>12&63,i[u++]=128|l>>6&63,i[u++]=128|63&l);m=u-5,d===h&&++d,d>h&&u<6&&(c=!0),t=i[0],u>4?(n=i[1],a=i[2],s=i[3],o=i[4],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[31&(s<<3|o>>>5)]+r[31&o]):1===u?p+=r[t>>>3]+r[t<<2&31]+"======":2===u?(n=i[1],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===u?(n=i[1],a=i[2],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):(n=i[1],a=i[2],s=i[3],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[s<<3&31]+"=")}while(!c);return p}(e)},decode:l};l.asBytes=o,n?e.exports=u:t.base32=u}()}(base32$1);var base32=base32$1.exports;async function cidFromText(e){let t=(new TextEncoder).encode(e);return await cidFromArrayBuffer(t)}async function cidFromArrayBuffer(e){let t=await crypto.subtle.digest("SHA-256",e),n=new Uint8Array(36);return n.set([1,85,18,32]),n.set(new Uint8Array(t),4),"b"+base32.encode(n).toLowerCase().replace(/=+/,"")}const textByCid={};function retrieveTextFileForCid(e,t="doenet"){return void 0!==textByCid[e]?Promise.resolve(textByCid[e]):new Promise(((n,r)=>{let a,i,s=retrieveTextFileFromIPFS(e),o=s.promise,l=s.controller,u=!1,c=!1;o.then((t=>{clearTimeout(i),a&&!c&&a.abort(),textByCid[e]=t,n(t)})).catch((e=>{u=!0,c&&(clearTimeout(i),r(e))})),i=setTimeout((()=>{let s=retrieveTextFileFromServer(e,t),o=s.promise;a=s.controller,o.then((t=>{u||l.abort(),textByCid[e]=t,n(t)})).catch((e=>{c=!0,u?r(e):i=setTimeout((()=>{l.abort(),r(e)}),5e3)}))}),100)}))}function retrieveTextFileFromIPFS(e){let t=new AbortController,n=t.signal;return{promise:async function(){try{let t=await fetch(`https://${e}.ipfs.dweb.link/`,{signal:n});if(t.ok){let n=await t.text();return await cidFromText(n)===e?n:Promise.reject(new Error("cid mismatch"))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:t}}function retrieveTextFileFromServer(e,t){let n=new AbortController,r=n.signal;return{promise:async function(){try{let n=await fetch(`/media/${e}.${t}`,{signal:r});if(n.ok){let t=await n.text(),r=await cidFromText(t);return r===e?t:(console.warn(`cid mismatch, ${e}, ${r}`),Promise.reject(new Error("cid mismatch")))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:n}}async function expandDoenetMLsToFullSerializedComponents({cids:e,doenetMLs:t,componentInfoObjects:n}){let r=[],a={};for(let e of t){let t=parseAndCompile(e);t=cleanIfHaveJustDocument(t),substituteDeprecations(t),temporarilyRenameSourceBackToTarget(t),correctComponentTypeCapitalization(t,n.componentTypeLowerCaseMapping),copyTargetOrFromURIAttributeCreatesCopyComponent(t,n.isCompositeComponent),createAttributesFromProps(t,n),breakUpTargetIntoPropsAndIndices(t,n),applyMacros(t,n),removeBlankStringChildren(t,n),decodeXMLEntities(t),applySugar({serializedComponents:t,componentInfoObjects:n}),r.push(t);let i=findContentCopies({serializedComponents:t});for(let e in i.cidComponents)void 0===a[e]&&(a[e]=[]),a[e].push(...i.cidComponents[e])}let i=Object.keys(a);if(i.length>0){let{newDoenetMLs:e,newCids:t}=await cidsToDoenetMLs(i);for(let[e,n]of i.entries())if(t[e]&&t[e].substring(0,n.length)!==n)return Promise.reject(new Error(`Requested cid ${n} but got back ${t[e]}!`));let r=i.length;for(let n=0;n"string"!=typeof e||e.trim())),r=1===t.length&&"object"==typeof t[0],a=e.doenetAttributes?.fromCopyFromURI;if(a||r)if(a&&!r)console.warn("ignoring copyFromURI as it was not a single component");else{let n=t[0];n.attributes||(n.attributes={}),e.doenetAttributes||(e.doenetAttributes={}),e.doenetAttributes.keptNewNamespaceOfLastChild=Boolean(n.attributes.newNamespace?.primitive),n.attributes.newNamespace={primitive:!0},e.children=[n,...e.children],e.doenetAttributes.nameFirstChildIndependently=!0}else{let t={componentType:"externalContent",children:JSON.parse(JSON.stringify(n)),attributes:{newNamespace:{primitive:!0}},doenetAttributes:{createUniqueName:!0}};e.children=[t,...e.children]}}}}return{cids:e,fullSerializedComponents:r}}function cidsToDoenetMLs(e){let t=[],n=e;for(let n of e)t.push(retrieveTextFileForCid(n,"doenet"));return Promise.all(t).then((e=>Promise.resolve({newDoenetMLs:e,newCids:n}))).catch((e=>{let t;return t=1===n.length?`Could not retrieve cid ${n[0]}`:`Could not retrieve cids ${n.join(",")}`,t+=": "+e.message,console.error(t),Promise.reject(new Error(t))}))}function removeBlankStringChildren(e,t){for(let n of e){if(n.children){let e=t.allComponentClasses[n.componentType];e&&!e.includeBlankStringChildren&&(n.children=n.children.filter((e=>"string"!=typeof e||""!==e.trim()))),removeBlankStringChildren(n.children,t)}for(let e in n.attributes){let r=n.attributes[e].component;r&&r.children&&removeBlankStringChildren([r],t)}}}function findContentCopies({serializedComponents:e}){let t={};for(let n of e)if("copy"===n.componentType){if(n.attributes&&n.attributes.uri){let e=n.attributes.uri.primitive;if(e&&"doenet:"===e.substring(0,7).toLowerCase()){let r=e.match(/[:&]cid=([^&]+)/i);if(r){let e=r[1];void 0===t[e]&&(t[e]=[]),t[e].push(n)}}}}else if(void 0!==n.children){let e=findContentCopies({serializedComponents:n.children});for(let n in e.cidComponents)void 0===t[n]&&(t[n]=[]),t[n].push(...e.cidComponents[n])}return{cidComponents:t}}function addDocumentIfItsMissing(e){if(1!==e.length||"document"!==e[0].componentType){let t=e.splice(0);e.push({componentType:"document",children:t})}}function substituteDeprecations(e){let t={tname:"target",triggerwithtnames:"triggerWith",updatewithtname:"updateWith",paginatortname:"paginator",randomizeorder:"shuffleOrder",copytarget:"copySource",triggerwithtargets:"triggerWith",triggerwhentargetsclicked:"triggerWhenObjectsClicked",fortarget:"forObject",targetattributestoignore:"sourceAttributesToIgnore",targetattributestoignorerecursively:"sourceAttributesToIgnoreRecursively",targetsareresponses:"sourcesAreResponses",updatewithtarget:"updateWith",targetsarefunctionsymbols:"sourcesAreFunctionSymbols",selectforvariantnames:"selectForVariants"},n={copy:{target:"source",tname:"source"},collect:{target:"source",tname:"source"},summarystatistics:{target:"source"}};for(let r of e)if("object"==typeof r){if(r.props){let e=r.componentType,a=n[e.toLowerCase()];a||(a={});let i=!0;for(;i;){i=!1;for(let n in r.props){let s=n.toLowerCase();if(s in a){let t=a[s];console.warn(`Attribute ${n} of component type ${e} is deprecated. Use ${t} instead.`),r.props[t]=r.props[n],delete r.props[n],i=!0;break}if(s in t){let e=t[s];console.warn(`Attribute ${n} is deprecated. Use ${e} instead.`),r.props[e]=r.props[n],delete r.props[n],i=!0;break}}}}r.children&&substituteDeprecations(r.children)}}function temporarilyRenameSourceBackToTarget(e){let t={copysource:"copyTarget"},n={copy:{source:"target"},collect:{source:"target"}};for(let r of e)if("object"==typeof r){if(r.props){let e=n[r.componentType.toLowerCase()];e||(e={});let a=!0;for(;a;){a=!1;for(let n in r.props){let i=n.toLowerCase();if(i in e){let t=e[i];r.props[t]=r.props[n],delete r.props[n],a=!0;break}if(i in t){let e=t[i];r.props[e]=r.props[n],delete r.props[n],a=!0;break}}}}r.children&&temporarilyRenameSourceBackToTarget(r.children)}}function cleanIfHaveJustDocument(e){let t=e.filter((e=>"string"!=typeof e||""!==e.trim()));return 1===t.length&&"document"===t[0].componentType?t:e}function correctComponentTypeCapitalization(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t[n.componentType.toLowerCase()];if(!e)throw Error(`Invalid component type${indexRangeString(n)}: ${n.componentType}`);n.componentType=e,n.children&&correctComponentTypeCapitalization(n.children,t)}}function copyTargetOrFromURIAttributeCreatesCopyComponent(e,t){for(let n of e){if(n.props){let e=!1,r=!1,a=!1,i=n.componentType,s=t({componentType:i,includeNonStandard:!1}),o=t({componentType:i,includeNonStandard:!0});for(let t of Object.keys(n.props)){let l=t.toLowerCase();if("copytarget"===l){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(r)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(e=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.target=n.props[t],"string"!=typeof n.props.target)throw Error(`Must specify value for copyTarget. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyTarget=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("copyfromuri"===l){if(r)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(e)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyFromURI. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(r=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.uri=n.props[t],"string"!=typeof n.props.uri)throw Error(`Must specify value for copyFromURI. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyFromURI=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("assignnames"===l&&!s){if(e||r)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);a=!0}}if(e){for(let e of Object.keys(n.props)){if("prop"===e.toLowerCase())throw Error(`Invalid attribute prop for component of type ${i}${indexRangeString(n)}`)}let e=!1;for(let t of Object.keys(n.props)){if("copyprop"===t.toLowerCase()){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);n.props.prop=n.props[t],delete n.props[t],e=!0}}}}n.children&©TargetOrFromURIAttributeCreatesCopyComponent(n.children,t)}}function breakUpTargetIntoPropsAndIndices(e,t,n=""){for(let[r,a]of e.entries()){if(a.props&&["copy","updateValue","animateFromSequence"].includes(a.componentType)){let i,s,o,l,u,c,p;for(let e of Object.keys(a.props)){if("target"===e.toLowerCase()){if(i)throw Error(`Cannot repeat attribute ${e}. Found in component type ${a.componentType}${indexRangeString(a)}`);i=e,p=a.props[e];let t=buildSourcePieces(p,!0);t.success&&t.matchLength===p.length&&(s=t.sourceName,o=t.componentIndex,l=t.componentAttributes,u=t.propArray,c=t.subNames)}}if(i&&s)if(o||l||u.length>0){if(a.attributes.prop)throw Error(`Cannot combine the prop attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.propIndex)throw Error(`Cannot combine the propIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.componentIndex)throw Error(`Cannot combine the componentIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);let d=createComponentFromExtendedSource({sourceName:s,componentIndex:o,subNames:c,componentAttributes:l,propArray:u,componentInfoObjects:t});if(d.success){let t=d.newComponent;if("copy"===a.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes),a.doenetAttributes.createNameFromComponentType||(a.doenetAttributes.createNameFromComponentType=a.componentType),a.componentType=t.componentType,0!==u.length||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes.isPlainCopy=!0),t.children&&(a.children=t.children);else if("copy"===t.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes);else{let s=createUniqueName("extract","fromExtendedSource"+n+"|"+r);t.doenetAttributes.prescribedName=s,t.doenetAttributes.createdFromMacro=!0;let o={componentType:"setup",children:[t],doenetAttributes:{createdFromMacro:!0}};e.push(o),delete a.props[i],a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.target=s,a.doenetAttributes.allowDoubleUnderscoreTarget=!0}}else"copy"===a.componentType?console.warn(`invalid copy source: ${p}`):console.warn(`invalid target: ${p}`)}else"copy"!==a.componentType||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isPlainCopy=!0)}a.children&&breakUpTargetIntoPropsAndIndices(a.children,t,n+"|"+r)}}function createAttributesFromProps(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t.allComponentClasses[n.componentType],r=e.createAttributesObject(),a={};for(let e in r)a[e.toLowerCase()]=e;let i={},s=Object.assign({},n.props);if(n.props)for(let o in n.props){let l=a[o.toLowerCase()],u=r[l];if(u){if(l in i)throw Error(`Cannot repeat attribute ${l}. Found in component type ${n.componentType}${indexRangeString(n)}`);i[l]=componentFromAttribute({attrObj:u,value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}else if(!["name","assignnames","target"].includes(o.toLowerCase())){if(!e.acceptAnyAttribute)throw Error(`Invalid attribute ${o} for component of type ${n.componentType}${indexRangeString(n)}`);i[o]=componentFromAttribute({value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}}for(let e in r){let n=r[e];n.createPrimitiveOfType&&"defaultPrimitiveValue"in n&&!(e in i)&&(i[e]=componentFromAttribute({attrObj:n,originalComponentProps:s,value:n.defaultPrimitiveValue.toString(),componentInfoObjects:t}))}n.attributes=i,void 0!==n.children&&createAttributesFromProps(n.children,t)}}function componentFromAttribute({attrObj:e,value:t,originalComponentProps:n,componentInfoObjects:r}){if("object"!=typeof t?t={rawString:t.toString()}:null===t&&(t={rawString:""}),e&&e.createComponentOfType){let a,i=t.rawString.trim().toLowerCase();if("true"===i&&void 0!==e.valueForTrue)a={componentType:e.createComponentOfType,state:{value:e.valueForTrue}};else if("false"===i&&void 0!==e.valueForFalse)a={componentType:e.createComponentOfType,state:{value:e.valueForFalse}};else if(r.isInheritedComponentType({inheritedComponentType:e.createComponentOfType,baseComponentType:"boolean"})&&["true","false"].includes(i))a={componentType:e.createComponentOfType,state:{value:"true"===i}};else{let n=t.childrenForComponent;n=n?JSON.parse(JSON.stringify(n)):[t.rawString],a={componentType:e.createComponentOfType,children:n},removeBlankStringChildren([a],r)}if(e.attributesForCreatedComponent||e.copyComponentAttributesForCreatedComponent){if(e.attributesForCreatedComponent?a.props=e.attributesForCreatedComponent:a.props={},e.copyComponentAttributesForCreatedComponent)for(let t of e.copyComponentAttributesForCreatedComponent)n[t]&&(a.props[t]=JSON.parse(JSON.stringify(n[t])));createAttributesFromProps([a],r)}let s={component:a};return e.ignoreFixed&&(s.ignoreFixed=!0),s}if(e&&e.createPrimitiveOfType){let n;if("boolean"===e.createPrimitiveOfType){n="true"===t.rawString.trim().toLowerCase()}else n="number"===e.createPrimitiveOfType?Number(t.rawString):"integer"===e.createPrimitiveOfType?Math.round(Number(t.rawString)):"stringArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/):"numberArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/).map(Number):t.rawString;return e.validationFunction&&(n=e.validationFunction(n)),{primitive:n}}if(e&&e.createTargetComponentNames){return{targetComponentNames:t.rawString.trim().split(/\s+/).map((e=>("$"===e[0]&&"$"!==e[1]&&"("===(e=e.slice(1))[0]&&")"===e[e.length-1]&&(e=e.slice(1,e.length-1)),{relativeName:e})))}}return t.childrenForComponent||(t.childrenForComponent=[t.rawString]),t}function findPreSugarIndsAndMarkFromSugar(e){let t=[];for(let n of e)if("object"==typeof n)if(void 0!==n.preSugarInd)t.push(n.preSugarInd);else if(n.doenetAttributes||(n.doenetAttributes={}),n.doenetAttributes.createdFromSugar=!0,n.children){let e=findPreSugarIndsAndMarkFromSugar(n.children);t.push(...e)}return t}function applyMacros(e,t){for(let n of e)if(n.children&&applyMacros(n.children,t),n.attributes)for(let e in n.attributes){let r=n.attributes[e];r.component?applyMacros([r.component],t):r.childrenForComponent&&applyMacros(r.childrenForComponent,t)}substituteMacros(e,t)}function substituteMacros(e,t){for(let n=0;n0&&e[n-1].range){let t=e[n-1].range;t.closeEnd?r+=t.closeEnd:t.selfCloseEnd&&(r+=t.selfCloseBegin)}throw Error(`${d.message}. At indices ${r}-${r+c}. Found: ${t}`)}l=d.newComponent,markCreatedFromMacro([l]),0===s.propArray.length&&(l.doenetAttributes.isPlainMacro=!0),o=[l];let m=1,h=i.substring(u+c);if(2===p){let r=i.slice(u+c).match(/^\s*\(/);if(!r){a=u+2;continue}let s=c+r[0].length,l=[],p=!1;i.length>u+s&&(p=!0,l.push(i.substring(u+s))),l.push(...e.slice(n+1));let d=createEvaluateIfFindMatchedClosingParens({componentsFromMacro:o,remainingComponents:l,includeFirstInRemaining:p,componentInfoObjects:t});if(!d.success){a=u+2;continue}o=d.componentsFromMacro,m=d.lastComponentIndMatched+1,p||m++,h=""}let f=[];u>0&&f.push(i.substring(0,u)),f.push(...o),h.length>0&&f.push(h),e.splice(n,m,...f),u>0&&n++;break}}}}function createComponentFromExtendedSource({sourceName:e,componentIndex:t,componentAttributes:n,propArray:r,subNames:a,componentInfoObjects:i}){let s={componentType:"copy",doenetAttributes:{target:e},attributes:{}};if(t){let e=[t];applyMacros(e,i),s.attributes.componentIndex={component:{componentType:"integer",children:e}}}if(a?.length>0){let e=[],t=[];for(let n of a)e.push(n.subName),void 0!==n.subNameComponentIndex&&(t.length0){let e=[t.join(" ")];applyMacros(e,i),s.attributes.sourceSubnamesComponentIndex={component:{componentType:"numberList",children:e}}}}let o=!1;if(n){o=!0;let e=createAttributesFromString(n,i);if(!e.success)return e;Object.assign(s.attributes,e.newAttributes),e.assignNames&&(s.props={assignNames:e.assignNames})}for(let e of r){if(o&&(s.doenetAttributes.createdFromMacro=!0,s={componentType:"extract",attributes:{},doenetAttributes:{},children:[s]}),s.attributes.prop={primitive:e.prop},e.propIndex){let t=[e.propIndex.join(" ")];applyMacros(t,i),s.attributes.propIndex={component:{componentType:"numberList",children:t}}}if(e.attributes){let t=createAttributesFromString(e.attributes,i);if(!t.success)return t;Object.assign(s.attributes,t.newAttributes),t.assignNames&&(s.props={assignNames:t.assignNames})}o=!0}return{success:!0,newComponent:s}}function createAttributesFromString(e,t){let n,r=``;try{n=parseAndCompile(r)}catch(e){return{success:!1,message:"Error in macro"}}createAttributesFromProps(n,t),markCreatedFromMacro(n),applyMacros(n,t);let a,i=n[0].attributes;if(i.prop||i.propIndex||i.componentIndex)return{success:!1,message:"Error in macro: macro cannot directly add attributes prop, propIndex, or componentIndex"};if(n[0].props)for(let e in n[0].props)if("assignnames"===e.toLowerCase()){if(a)return{success:!1,message:"Error in macro: cannot repeat assignNames"};a=n[0].props[e]}return{success:!0,newAttributes:i,assignNames:a}}function findFirstFullMacroInString(e){let t,n=0;for(;;){let r=e.substring(n).match(/(\$+)(.?)/);if(!r)return{success:!1};if(t=r[1].length,n+=r.index+t,t<=2){let r=!1,a=e.substring(n),i=0,s=findWordOrDelimitedGroup(a,r);"("===s.startDelim&&(r=!0,a=s.group,i=s.group.length);let o=buildSourcePieces(a,r);if(o.success){if(r){if(o.matchLength!==i)return{success:!1};o.matchLength+=2}return o.nDollarSigns=t,o.firstIndMatched=n-t,o.matchLength+=t,o}}}}function buildSourcePieces(e,t){let n=findWordOrDelimitedGroup(e,t),r=0;if(n.withPeriod||!n.word)return{success:!1};let a={sourceName:(n.withSlash?"/":"")+n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.componentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let i=[];for(;n.withSlash;){let a={subName:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.subNameComponentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),i.push(a)}a.subNames=i,"{"===n.startDelim&&(a.componentAttributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let s=[];for(;n.withPeriod;){let a={prop:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);let i=[];for(;"["===n.startDelim;)i.push(n.group),r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);i.length>0&&(a.propIndex=i),"{"===n.startDelim&&(a.attributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),s.push(a)}return a.propArray=s,a.matchLength=r,a.success=!0,a}function findWordOrDelimitedGroup(e,t=!1){let n,r=!1,a=!1;"."===e[0]&&"."!==e[1]&&(r=!0,e=e.substring(1)),t?r?n=/^[\w-]+/:("/"===e[0]&&e[1].match(/\w/)&&(a=!0,e=e.substring(1)),n=/^([\w\/-]|\.\.\/)+/):n=/^[a-zA-Z_]\w*/;let i=e.match(n);if(i)return{success:!0,withPeriod:r,withSlash:a,word:i[0],matchLength:i[0].length+(r?1:0)+(a?1:0)};if(r||a)return{success:!1};let s=[],o={"(":")","{":"}","[":"]"},l=Object.values(o),u=e[0],c=o[u];if(!c)return{success:!1};s.push(c);for(let t=1;t0?t[i]=s.substring(0,a.charInd):t=t.slice(0,i);let l=breakEmbeddedStringByCommas({childrenList:t});l.pieces.forEach((e=>applyMacros(e,r)));let u=l.pieces.map((e=>1===e.length&&"string"!=typeof e[0]?e[0]:{componentType:"math",doenetAttributes:{createdFromMacro:!0},children:e})),c=[{componentType:"evaluate",doenetAttributes:{createdFromMacro:!0},attributes:{function:{component:{componentType:"function",doenetAttributes:{createdFromMacro:!0},children:e}},input:{component:{componentType:"mathList",doenetAttributes:{createdFromMacro:!0},children:u}}}}];return o.length>0&&c.push(o),{success:!0,componentsFromMacro:c,lastComponentIndMatched:i}}function findFirstUnmatchedClosingParens(e){let t=0;for(let[n,r]of e.entries())if("string"==typeof r){let e=r;for(let r=0;r").replace(/</g,"<").replace(/$/g,"$").replace(/&/g,"&")}for(let[n,r]of e.entries())if("string"==typeof r)e[n]=t(r);else if(r.children&&decodeXMLEntities(r.children),r.attributes)for(let e in r.attributes){let n=r.attributes[e];n.component?decodeXMLEntities([n.component]):n.primitive?"string"==typeof n.primitive&&(n.primitive=t(n.primitive)):(n.childrenForComponent&&decodeXMLEntities(n.childrenForComponent),n.rawString&&(n.rawString=t(n.rawString)))}}function applySugar({serializedComponents:e,parentParametersFromSugar:t={},parentAttributes:n={},componentInfoObjects:r,parentUniqueId:a="",isAttributeComponent:i=!1}){for(let[s,o]of e.entries()){if("object"!=typeof o)continue;let e=o.componentType,l=r.allComponentClasses[e];if(!l)throw Error(`Unrecognized component type ${e}`);let u=a+"|"+e+s,c={};for(let e in o.attributes){let t=o.attributes[e];void 0!==t.primitive&&(c[e]=t.primitive)}if(o.children){let a={};if(!o.skipSugar)for(let[s,p]of l.returnSugarInstructions().entries()){let l=o.children.map((e=>"string"==typeof e?"s":"n")).join("");if(p.childrenRegex){let e=l.match(p.childrenRegex);if(!e||e[0].length!==o.children.length)continue}let d=deepClone(o.children),m=0;for(let e of d)"string"!=typeof e&&(e.preSugarInd=m,m++);let h=!1;o.doenetAttributes&&o.doenetAttributes.createdFromMacro&&(h=!0);let f=p.replacementFunction({matchedChildren:d,parentParametersFromSugar:t,parentAttributes:n,componentAttributes:c,uniqueId:u+"|sugar"+s,componentInfoObjects:r,isAttributeComponent:i,createdFromMacro:h});if(f.success){let t=f.newChildren,n=f.newAttributes,r=[],i=[];if(t&&(r=findPreSugarIndsAndMarkFromSugar(t)),n)for(let e in n){let t=n[e].component;t&&i.push(...findPreSugarIndsAndMarkFromSugar(t.children))}let s=[...r,...i];if(s.length!==m||!s.sort(((e,t)=>e-t)).every(((e,t)=>e===t)))throw Error(`Invalid sugar for ${e} as didn't return set of original components`);if(r.length>0){let t=[...r].sort(((e,t)=>e-t));if(!t.every(((e,t)=>e===r[t])))throw Error(`Invalid sugar for ${e} as didn't return original components in order`)}f.parametersForChildrenSugar&&Object.assign(a,f.parametersForChildrenSugar),o.children=t||[],n&&(o.attributes||(o.attributes={}),Object.assign(o.attributes,n))}}l.removeBlankStringChildrenPostSugar&&(o.children=o.children.filter((e=>"string"!=typeof e||/\S/.test(e)))),applySugar({serializedComponents:o.children,parentParametersFromSugar:a,parentAttributes:c,componentInfoObjects:r,parentUniqueId:u})}if(o.attributes)for(let e in o.attributes){let t=o.attributes[e];t.component&&applySugar({serializedComponents:[t.component],parentAttributes:c,componentInfoObjects:r,parentUniqueId:u,isAttributeComponent:!0})}}}function breakStringInPiecesBySpacesOrParens(e){if("string"!=typeof e)return{success:!1};let t=0,n=[];e=e.trim();let r=0;for(let a=0;a0&&n.push(t),r=a}t++}else if(")"===i){if(0===t)return{success:!1};if(1===t){let t=e.substring(r+1,a).trim();if(t.length>0){let e=breakStringInPiecesBySpacesOrParens(t);!0===e.success?n.push(e.pieces):n.push(t)}r=a+1}t--}else if(0===t&&i.match(/\s/)){let t=e.substring(r,a).trim();t.length>0&&n.push(t),r=a}}if(0!==t)return{success:!1};let a=e.substring(r,e.length).trim();return a.length>0&&n.push(a),{success:!0,pieces:n}}function countRegularComponentTypesInNamespace(e,t={}){for(let n of e)if("object"==typeof n){let e=n.componentType,r=t[e];void 0===r&&(r=0);let a=n.doenetAttributes;a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro||(t[e]=++r),n.children&&!n.attributes?.newNamespace?.primitive&&(t=countRegularComponentTypesInNamespace(n.children,t))}return t}function renameAutonameBasedOnNewCounts(e,t={}){let n={...t};for(let t of e)if("object"==typeof t){let e=t.componentType,r=n[e];void 0===r&&(r=0);let a=t.doenetAttributes;if(!(a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro)&&(n[e]=++r,t.componentName)){let n=t.componentName.lastIndexOf("/"),a=t.componentName.substring(n+1),i="_"+e.toLowerCase();a.substring(0,i.length)===i&&(t.componentName=t.componentName.substring(0,n+1)+i+r)}t.children&&!t.attributes?.newNamespace?.primitive&&(n=renameAutonameBasedOnNewCounts(t.children,n))}return n}function createComponentNames({serializedComponents:e,namespaceStack:t=[],componentInfoObjects:n,parentDoenetAttributes:r={},parentName:a,useOriginalNames:i=!1,attributesByTargetComponentName:s,indOffset:o=0,createNameContext:l="",initWithoutShadowingComposite:u=!1}){0===t.length&&t.push({namespace:"",componentCounts:{},namesUsed:{}});let c=t.length-1,p=t[c];for(let[r,d]of e.entries()){if("object"!=typeof d)continue;let e=d.componentType,m=n.allComponentClasses[e],h=d.doenetAttributes;void 0===h&&(h=d.doenetAttributes={});let f=d.attributes;f||(f=d.attributes={}),h.createNameFromComponentType&&(e=h.createNameFromComponentType);let y,g=h.prescribedName,b=h.assignNames,v=h.target,N=h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||h.createUniqueName;(f.newNamespace?.primitive||i&&d.originalAttributes&&d.originalAttributes.newNamespace)&&(y=!0);let T=void 0!==g,C=d.props;if(void 0===C)C=d.props={};else for(let t in C){let n=t.toLowerCase();if("name"===n){if(void 0!==g)throw Error(`Cannot define name twice. Found in component of type ${e}${indexRangeString(d)}`);g=C[t],delete C[t]}else if("assignnames"===n){if(void 0!==b)throw Error(`Cannot define assignNames twice for a component. Found in component of type ${e}${indexRangeString(d)}`);{let n=breakStringInPiecesBySpacesOrParens(C[t]);if(!n.success)throw Error(`Invalid format for assignnames. Found in component of type ${e}${indexRangeString(d)}`);b=n.pieces,delete C[t]}}else if("target"===n){if(void 0!==v)throw Error(`Cannot define target twice for a component. Found in component of type ${e}${indexRangeString(d)}`);if("string"!=typeof C[t])throw Error(`Must specify value for target. Found in component of type ${e}${indexRangeString(d)}`);v=C[t].trim(),delete C[t]}}if(g){if(!T&&!h.createdFromSugar){if(!/[a-zA-Z]/.test(g.substring(0,1)))throw Error(`Invalid component name: ${g}. Component name must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(g))throw Error(`Invalid component name: ${g}. Component name can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}h.prescribedName=g}else if(N){let t=a+"|createUniqueName|";d.downstreamDependencies?t+=JSON.stringify(d.downstreamDependencies):t+=r+"|"+o+"|"+l,g=createUniqueName(e.toLowerCase(),t)}if(!b&&i&&d.originalDoenetAttributes&&d.originalDoenetAttributes.assignNames&&(b=d.originalDoenetAttributes.assignNames),b){if(!m.assignNamesToReplacements)throw Error(`Cannot assign names for component type ${e}${indexRangeString(d)}`);if(h.assignNames=b,!h.createUniqueAssignNames){let t=flattenDeep(b);if(!h.fromCopyTarget&&!h.fromCopyFromURI)for(let n of t){if(!/[a-zA-Z]/.test(n.substring(0,1)))throw Error(`All assigned names must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(n))throw Error(`Assigned names can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}if(t.length!==new Set(t).size)throw Error(`Duplicate assigned names. Found in component of type ${e}${indexRangeString(d)}`)}}y&&(f.newNamespace={primitive:y});let A=p.componentCounts[e];void 0===A&&(A=0),h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||(p.componentCounts[e]=++A);let V="";for(let e=0;e<=c;e++)V+=t[e].namespace+"/";if(!g){if(i&&d.originalName){let e=d.originalName.lastIndexOf("/");g=d.originalName.substring(e+1)}g||(g="_"+e.toLowerCase()+A)}if(h.nameBecomesAssignNames){y&&(f.assignNewNamespaces={primitive:!0},delete f.newNamespace,y=!1),b=h.assignNames=[g],delete h.nameBecomesAssignNames;let e=a+"|createUniqueName|";h.createUniqueName=!0,delete h.prescribedName,d.downstreamDependencies?e+=JSON.stringify(d.downstreamDependencies):e+=r+"|"+o+"|"+l,g=createUniqueName("copy",e)}if(V+=g,d.componentName=V,g){if(g in p.namesUsed)throw Error(`Duplicate component name ${V}. Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[g]=!0}if(!y&&b)for(let t of flattenDeep(b)){if(t in p.namesUsed)throw Error(`Duplicate component name ${t} (from assignNames of ${V}). Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[t]=!0}if(d.doenetAttributes.createUniqueAssignNames&&d.originalName){let e=d.doenetAttributes.assignNames;e||(e=d.doenetAttributes.originalAssignNames);let n,r=V+"|createUniqueName|assignNames|",a="";if(y)a=V+"/",n=d.originalName+"/";else{for(let e=0;e<=c;e++)a+=t[e].namespace+"/";let e=d.originalName.lastIndexOf("/");n=d.originalName.slice(0,e+1)}let i=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:r,namespace:a,oldNamespace:n,attributesByTargetComponentName:s});b=d.doenetAttributes.assignNames=i}if(renameMatchingTargetNames(d,s),v){if(!m.acceptTarget)throw Error(`Component type ${e} does not accept a target attribute. Found in component ${V}${indexRangeString(d)}`);if(v.includes("|"))throw Error(`target cannot include |. Found in component of type ${e}${indexRangeString(d)}`);h.target=v,h.targetComponentName=convertComponentTarget({relativeName:v,oldAbsoluteName:h.targetComponentName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}for(let e in f){let n=f[e];if(n.targetComponentNames)for(let e of n.targetComponentNames)e.absoluteName=convertComponentTarget({relativeName:e.relativeName,oldAbsoluteName:e.absoluteName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}if(d.children)if(y||f.assignNewNamespaces?.primitive){let e={};b&&flattenDeep(b).forEach((t=>e[t]=!0));let r=d.children;if(h.nameFirstChildIndependently&&d.children.length>0){r=r.slice(1);let e={namespace:g,componentCounts:{},namesUsed:{}};t.push(e),createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}let a={namespace:g,componentCounts:{},namesUsed:e};if(h.haveNewNamespaceOnlyFromShadow){let e=!0,o=[...r];for(;o.length>0;){let r=[];for(let t of o){if(Boolean(t.doenetAttributes?.ignoreParentNewNamespace)===e)break;r.push(t)}o.splice(0,r.length),e?t.push(a):u&&r.forEach((e=>e.doenetAttributes.createUniqueName=!0)),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),e&&t.pop(),e=!e}}else t.push(a),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}else{let e=d.children;if(h.nameFirstChildIndependently&&e.length>0){e=e.slice(1);let r=p.namesUsed,a=p.componentCounts;p.namesUsed={},p.componentCounts={},createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),p.namesUsed=r,p.componentCounts=a}createComponentNames({serializedComponents:e,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s})}if(d.attributes)for(let e in d.attributes){let r=d.attributes[e];if(r.component){let a=r.component;a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isAttributeChild=!0,r.ignoreFixed&&(a.doenetAttributes.ignoreParentFixed=!0),createComponentNames({serializedComponents:[a],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}else r.childrenForComponent&&createComponentNames({serializedComponents:r.childrenForComponent,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}}return e}function createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:t,namespace:n,oldNamespace:r,attributesByTargetComponentName:a}){let i=[];for(let[s,o]of e.entries())if(Array.isArray(o)){let e=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:o,longNameIdBase:t+s+"_",namespace:n,oldNamespace:r,attributesByTargetComponentName:a});i.push(e)}else{let e=createUniqueName("fromAssignNames",t+s);i.push(e),renameMatchingTargetNames({componentName:n+e,originalName:r+o},a,!0)}return i}function convertComponentTarget({relativeName:e,oldAbsoluteName:t,namespaceStack:n,acceptDoubleUnderscore:r}){if(!t&&/__/.test(e)&&!r)throw Error("Invalid reference target: "+e);let a;if("/"===e.substring(0,1))a=e;else{let t=n.length-1;for(;"../"===e.substring(0,3);)e=e.substring(3),t--;t<0&&(t=0),a="";for(let e=0;e<=t;e++)a+=n[e].namespace+"/";a+=e}return a}function serializedComponentsReplacer(e,t){return t!=t?{objectType:"special-numeric",stringValue:"NaN"}:t===1/0?{objectType:"special-numeric",stringValue:"Infinity"}:t===-1/0?{objectType:"special-numeric",stringValue:"-Infinity"}:t}let nanInfinityReviver=function(e,t){if(t&&"special-numeric"===t.objectType){if("NaN"===t.stringValue)return NaN;if("Infinity"===t.stringValue)return 1/0;if("-Infinity"===t.stringValue)return-1/0}return t};function serializedComponentsReviver(e,t){return me$3.reviver(e,theModule.Subset.reviver(e,nanInfinityReviver(e,t)))}function processAssignNames({assignNames:e=[],assignNewNamespaces:t=!1,serializedComponents:n,parentName:r,parentCreatesNewNamespace:a,componentInfoObjects:i,indOffset:s=0,originalNamesAreConsistent:o=!1,shadowingComposite:l=!1}){let u=n.length;moveComponentNamesToOriginalNames(n);let c={},p=null;if(o){if(u>0){let e=n.filter((e=>"object"==typeof e))[0];if(e&&e.originalName){let t=e.originalName.lastIndexOf("/");p=e.originalName.substring(0,t)}}if(null!==p)for(let e of n)setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[e],attributesByTargetComponentName:c})}else for(let e=0;e0&&t.originalName){let e=t.originalName.lastIndexOf("/");p=t.originalName.substring(0,e)}null!==p&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[t],attributesByTargetComponentName:c})}}let d=[],m=0;for(let h=0;h0&&y.originalName)){let e=y.originalName.lastIndexOf("/");p=y.originalName.substring(0,e)}if(g)if(i.allComponentClasses[y.componentType].assignNamesSkipOver)g=[g];else if(y.attributes?.assignNamesSkip){let e=y.attributes.assignNamesSkip.primitive;if(e>0)for(let t=0;t({namespace:e,componentCounts:{},namesUsed:{}})));"/"!==e[0]&&c.splice(0,0,{componentCounts:{},namesUsed:{},namespace:""}),t.doenetAttributes||(t.doenetAttributes={}),t.attributes||(t.attributes={}),t.attributes.newNamespace?.primitive||s?u=!0:(u=!1,t.children&&markToCreateAllUniqueNames(t.children));for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}createComponentNames({serializedComponents:[t],namespaceStack:c,componentInfoObjects:a,parentName:e,useOriginalNames:u,attributesByTargetComponentName:i,indOffset:n,initWithoutShadowingComposite:!o})}function setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:t,attributesByTargetComponentName:n}){let r=e.length;for(let a of t)if("object"==typeof a){if(a.doenetAttributes&&a.doenetAttributes.target){let t=a.doenetAttributes.targetComponentName;void 0!==t&&(t.substring(0,r)!==e&&(a.doenetAttributes.target=t),n[t]||(n[t]=[]),n[t].push(a.doenetAttributes))}for(let t in a.attributes){let i=a.attributes[t];if(i.targetComponentNames)for(let t of i.targetComponentNames){let a=t.absoluteName;void 0!==a&&(a.substring(0,r)!==e&&(t.relativeName=a),n[a]||(n[a]=[]),n[a].push(t))}}if(a.children&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:a.children,attributesByTargetComponentName:n}),a.attributes)for(let t in a.attributes){let r=a.attributes[t];r.component?setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:[r.component],attributesByTargetComponentName:n}):r.childrenForComponent&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:r.childrenForComponent,attributesByTargetComponentName:n})}}}function renameMatchingTargetNames(e,t,n=!1){if(e.originalName&&t&&e.componentName!==e.originalName){if(t[e.originalName])for(let n of t[e.originalName])n.relativeName?(n.relativeName=e.componentName,n.absoluteName=e.componentName):(n.target=e.componentName,n.targetComponentName=e.componentName);if(n){let n=e.originalName+"/",r=n.length;for(let a in t)if(a.substring(0,r)===n){let n=a.substring(r);for(let r of t[a])r.relativeName?(r.relativeName=e.componentName+"/"+n,r.absoluteName=e.componentName+"/"+n):(r.target=e.componentName+"/"+n,r.targetComponentName=e.componentName+"/"+n)}}}}function moveComponentNamesToOriginalNames(e){for(let t of e)if(t.componentName&&(t.originalName=t.componentName,delete t.componentName),t.children&&moveComponentNamesToOriginalNames(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?moveComponentNamesToOriginalNames([n.component]):n.childrenForComponent&&moveComponentNamesToOriginalNames(n.childrenForComponent)}}function markToCreateAllUniqueNames(e){for(let t of e)if("object"==typeof t&&(t.doenetAttributes||(t.doenetAttributes={}),t.doenetAttributes.createUniqueName=!0,delete t.doenetAttributes.prescribedName,t.attributes?.newNamespace?.primitive||(t.doenetAttributes.assignNames?(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.doenetAttributes.assignNames,delete t.doenetAttributes.assignNames):t.originalDoenetAttributes&&t.originalDoenetAttributes.assignNames&&(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.originalDoenetAttributes.assignNames),t.children&&markToCreateAllUniqueNames(t.children)),t.attributes))for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}}function setTNamesToAbsolute(e){for(let t of e){if(t.doenetAttributes&&t.doenetAttributes.target){let e=t.doenetAttributes.targetComponentName;void 0!==e&&(t.doenetAttributes.target=e)}if(t.children&&setTNamesToAbsolute(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}}}function restrictTNamesToNamespace({components:e,namespace:t,parentNamespace:n,parentIsCopy:r=!1,invalidateReferencesToBaseNamespace:a=!1}){void 0===n&&(n=t);let i=t.length;for(let s of e){if(s.doenetAttributes&&s.doenetAttributes.target){let e=s.doenetAttributes.target;if("/"===e[0]){if(e.substring(0,i)!==t){let n=t.split("/").slice(1),r=e.split("/").slice(1),a=!1,i=t+e.slice(1);for(;n.length>0&&n[0]===r[0];)n=n.slice(1),r=r.slice(1),a=!0;if(a)i=t+r.join("/");else{let n=t.split("/").slice(1);for(let t=1;tn){r&&t<=n&&a.push({begin:t,end:n,componentName:r}),s=!0;break}r&&o.indBegin>t&&a.push({begin:t,end:o.indBegin-1,componentName:r});let l=extractRangeIndexPieces({componentArray:e.slice(i+1),lastInd:o.indBegin,stopInd:o.indEnd,enclosingComponentName:o.componentName});i+=l.componentsConsumed+1,a.push(...l.rangePieces),t=o.indEnd+1}return!s&&Number.isFinite(n)&&n>=t&&a.push({begin:t,end:n,componentName:r}),{componentsConsumed:i,rangePieces:a}}function createStateProxyHandler(){return{get:function(e,t){let n=e[t];return void 0!==n&&(n=n.isArray&&(n.public||n.trackChanges)?new Proxy(n.value,createArrayProxyHandler({variable:t,nDimensions:n.nDimensions})):n.value),n},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function createArrayProxyHandler({variable:e,nDimensions:t,indicesSoFar:n=[]}){return{variable:e,nDimensions:t,indicesSoFar:n,get:function(e,n){if("then"===n&&e instanceof Promise)return t=>e.then.bind(e)((e=>t(null!==e&&"object"==typeof e?new Proxy(e,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions,indicesSoFar:this.indicesSoFar})):e)));let r=e[n];return null!==r&&"object"==typeof r&&t>1&&(r=new Proxy(r,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions-1,indicesSoFar:[...this.indicesSoFar,n]}))),r},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function postProcessCopy({serializedComponents:e,componentName:t,addShadowDependencies:n=!0,markAsPrimaryShadow:r=!1,uniqueIdentifiersUsed:a=[],identifierPrefix:i="",unlinkExternalCopies:s=!1,copiesByTargetComponentName:o={},componentNamesFound:l=[],assignNamesFound:u=[],activeAliases:c=[],init:p=!0}){for(let d in e){let m,h=e[d];if("object"==typeof h){if(h.originalName){if(s){if(l.push(h.originalName),h.originalDoenetAttributes&&h.originalDoenetAttributes.assignNames){let e;if(h.attributes.newNamespace?.primitive)e=h.originalName;else{let t=h.originalName.lastIndexOf("/");e=h.originalName.substring(0,t)}for(let t of h.originalDoenetAttributes.assignNames)l.push(e+"/"+t),u.push(e+"/"+t)}h.attributes&&(h.attributes.alias&&c.push(h.attributes.alias.primitive),h.attributes.indexAlias&&c.push(h.attributes.indexAlias.primitive))}if(m=i+h.originalName+"|shadow",!h.originalNameFromSerializedComponent)if(n){let e={[h.originalName]:[{dependencyType:"referenceShadow",compositeName:t}]};if(p&&(e[h.originalName][0].firstLevelReplacement=!0),r&&(e[h.originalName][0].isPrimaryShadow=!0),h.state){let t=Object.keys(h.state);e[h.originalName].downstreamStateVariables=t,e[h.originalName].upstreamStateVariables=t}h.downstreamDependencies=e}else h.unlinkedCopySource=h.originalName}else m=i+h.componentType+"|shadowUnnamed";if("copy"===h.componentType&&s){let e=h.doenetAttributes.targetComponentName;if(e)c.includes(h.doenetAttributes.target)?h.doenetAttributes.targetComponentName=h.doenetAttributes.target:(void 0===o[e]&&(o[e]=[]),o[e].push(h));else if(!h.attributes.uri)throw Error("we need to create a targetComponentName here, then.")}h.uniqueIdentifier=getUniqueIdentifierFromBase(m,a)}}for(let p in e){let d=e[p];if("object"==typeof d){postProcessCopy({serializedComponents:d.children,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1});for(let e in d.attributes){let p=d.attributes[e];p.component&&(p.component=postProcessCopy({serializedComponents:[p.component],componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})[0])}d.replacements&&postProcessCopy({serializedComponents:d.replacements,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})}}if(p&&s)for(let e in o)if(!l.includes(e)){let t=!1;for(let n of u){let r=n+"/",a=r.length;if(e.substring(0,a)===r){t=!0;break}}if(!t)for(let t of o[e])t.attributes||(t.attributes={}),t.attributes.link={primitive:!1},t.doenetAttributes.target=t.doenetAttributes.targetComponentName}return e}function convertAttributesForComponentType({attributes:e,componentType:t,componentInfoObjects:n,compositeAttributesObj:r={},compositeCreatesNewNamespace:a,flags:i}){let s=n.allComponentClasses[t],o=s.createAttributesObject(),l={};for(let e in o)l[e.toLowerCase()]=e;let u={};for(let t in e){if(t in r&&!r[t].leaveRaw)continue;let i=l[t.toLowerCase()],c=o[i];if(c){if(i in u)throw Error(`Cannot repeat prop ${i}`);if(u[i]=componentFromAttribute({attrObj:c,value:JSON.parse(JSON.stringify(e[t])),componentInfoObjects:n}),u[i].component?.children){let e=[u[i].component];if(applyMacros(e,n),removeBlankStringChildren(e,n),applySugar({serializedComponents:e,componentInfoObjects:n,isAttributeComponent:!0}),a)for(let e of u[i].component.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}}}else s.acceptAnyAttribute&&(u[t]=JSON.parse(JSON.stringify(e[t])))}return u}async function verifyReplacementsMatchSpecifiedType({component:e,replacements:t,replacementChanges:n,assignNames:r,workspace:a={},componentInfoObjects:i,compositeAttributesObj:s,flags:o}){if(!e.attributes.createComponentOfType?.primitive&&!e.sharedParameters.compositesMustHaveAReplacement)return{replacements:t,replacementChanges:n};let l,u=e.replacementsToWithhold;if(n){l=e.replacements.map((e=>e.componentType));for(let e of n)if("add"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),!e.changeTopLevelReplacements)continue;if(e.serializedReplacements){let t=e.numberReplacementsToReplace;t>0||(t=0);let n=e.firstReplacementInd,r=e.serializedReplacements.map((e=>e.componentType));l.splice(n,t,...r)}}else if("delete"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),e.changeTopLevelReplacements){let t=e.firstReplacementInd,n=e.numberReplacementsToDelete;l.splice(t,n)}}else"changeReplacementsToWithhold"===e.changeType&&void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold)}else i.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"template"})&&(t=t.filter((e=>e.componentType||e.trim().length>0))),l=t.map((e=>e.componentType)),1===l.length&&"externalContent"===l[0]&&(l=t[0].children.filter((e=>e.componentType||e.trim().length>0)).map((e=>e.componentType)));if(u>0&&(l=l.slice(0,l.length-u)),!e.attributes.createComponentOfType?.primitive&&e.sharedParameters.compositesMustHaveAReplacement&&l.length>0)return{replacements:t,replacementChanges:n};let c=e.attributes.createComponentOfType?.primitive,p=await e.stateValues.nComponentsSpecified;if(!c){if(c=e.sharedParameters.compositesDefaultReplacementType,!c)throw Error("A component class specified descendantCompositesMustHaveAReplacement but didn't specify descendantCompositesDefaultReplacementType");p=1}if(c=i.componentTypeLowerCaseMapping[c.toLowerCase()],l.length!==p||!l.every((e=>e===c))){if(1===t?.length&&i.isInheritedComponentType({inheritedComponentType:t[0].componentType,baseComponentType:"template"}))return t[0].attributes||(t[0].attributes={}),t[0].attributes.createComponentOfType={primitive:c},t[0].attributes.nComponents={primitive:p},{replacements:t,replacementChanges:n};let d,m=l.length===p&&!(u>0)&&a.sourceNames?.length===p;m&&n&&(1===n.length&&n[0].numberReplacementsToReplace===p?d=n[0].serializedReplacements:m=!1),m?d||(d=t):(a.numReplacementsBySource=[],a.numNonStringReplacementsBySource=[],a.propVariablesCopiedBySource=[],a.sourceNames=[],a.uniqueIdentifiersUsedBySource={},a.uniqueIdentifiersUsedBySource[0]=[]);let h=e.attributes.newNamespace?.primitive;t=[];for(let n=0;n"string"!=typeof e)).length),n){n=[],e.replacementsToWithhold>0&&n.push({changeType:"changeReplacementsToWithhold",replacementsToWithhold:0});let r=0;e.replacements&&(r=e.replacements.length),n.push({changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:r,serializedReplacements:t})}}return{replacements:t,replacementChanges:n}}function gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n=!0,useReplacementsForComposites:r=!1,includeNonActiveChildren:a=!1,skipOverAdapters:i=!1,ignoreReplacementsOfMatchedComposites:s=!1,ignoreReplacementsOfEncounteredComposites:o=!1,init:l=!0,componentInfoObjects:u}){let c=e=>t.some((t=>u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:t}))),p=[];if(r&&u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"}))l&&p.push(...replacementsForComposites({composite:e,componentInfoObjects:u,includeComposites:a}).filter((e=>"object"==typeof e)));else for(let t of e.allChildrenOrdered){let n,r=e.allChildren[t],s=!1,o=!1;if(r)n=r.component,n.adaptedFrom&&(o=!0),e.activeChildren.includes(n)&&(s=!0);else for(let r of e.activeChildren){if(r.placeholderInd===t){n=r,s=!0,"string"==typeof t&&"adapt"===t.substring(t.length-5,t.length)&&(o=!0);break}if(r.adaptedFrom&&achild.adaptedFrom.placeholderInd===t){n=r.adaptedFrom;break}}n&&(o&&i?p.includes(n.adaptedFrom)||p.push(n.adaptedFrom):(s||a)&&p.push(n))}if(s||o){let e=[];for(let t of p){let n=c(t);o&&!n&&(n=!("copy"===t.componentType&&t.doenetAttributes.copiedURI)),n&&u.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&(e=[...e,...replacementsForComposites({composite:t,componentInfoObjects:u,includeComposites:!0}).filter((e=>"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))])}e.length>0&&(p=p.filter((t=>!(e.includes(t.componentName)||e.includes(t.placeholderInd)))))}let d=[];for(let e of p){let l=c(e);if(l&&d.push({componentName:e.componentName?e.componentName:e.placeholderInd,componentType:e.componentType}),(!l||n)&&void 0===e.placeholderInd){let l=gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n,useReplacementsForComposites:r,includeNonActiveChildren:a,skipOverAdapters:i,ignoreReplacementsOfMatchedComposites:s,ignoreReplacementsOfEncounteredComposites:o,init:!1,componentInfoObjects:u});d.push(...l)}}return d}function replacementsForComposites({composite:e,includeComposites:t=!1,componentInfoObjects:n}){let r=[];if(e.replacements){let a;if(e.replacementsToWithhold){let t=e.replacements.length-e.replacementsToWithhold;a=e.replacements.slice(0,t)}else a=e.replacements;for(let e of a)n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})?(t&&r.push(e),r.push(...replacementsForComposites({composite:e,componentInfoObjects:n,includeComposites:t}))):r.push(e)}return r}function ancestorsIncludingComposites(e,t){if(void 0===e.ancestors||0===e.ancestors.length)return[];let n=[e.ancestors[0].componentName],r=t[e.ancestors[0].componentName];if(r&&n.push(...ancestorsIncludingComposites(r,t)),e.replacementOf){n.push(e.replacementOf.componentName);let r=ancestorsIncludingComposites(e.replacementOf,t);for(let e of r)n.includes(e)||n.push(e)}return n}const dependencyTypeArray=[];class DependencyHandler{constructor({_components:e,componentInfoObjects:t,core:n}){this.upstreamDependencies={},this.downstreamDependencies={},this.switchDependencies={},this.circularCheckPassed={},this.circularResolveBlockedCheckPassed={},this.dependencyTypes={},dependencyTypeArray.forEach((e=>this.dependencyTypes[e.dependencyType]=e)),this.core=n,this._components=e,this.componentInfoObjects=t,this.updateTriggers={descendantDependenciesByAncestor:{},ancestorDependenciesByPotentialAncestor:{},replacementDependenciesByComposite:{},childDependenciesByParent:{},parentDependenciesByParent:{},dependenciesMissingComponentBySpecifiedName:{},dependenciesBasedOnDependenciesOfStateVariables:{},primaryShadowDependencies:{}},this.resolveBlockers={neededToResolve:{},resolveBlockedBy:{}}}async setUpComponentDependencies(e){this.downstreamDependencies[e.componentName]&&this.deleteAllDownstreamDependencies({component:e}),this.downstreamDependencies[e.componentName]={},this.upstreamDependencies[e.componentName]||(this.upstreamDependencies[e.componentName]={});let t=[],n=[];for(let r in e.state)e.state[r].isArrayEntry||e.state[r].isAlias||n.includes(r)||(t.push(r),e.state[r].additionalStateVariablesDefined&&n.push(...e.state[r].additionalStateVariablesDefined));for(let n of t){let t=[n];e.state[n].additionalStateVariablesDefined&&t.push(...e.state[n].additionalStateVariablesDefined),await this.setUpStateVariableDependencies({component:e,stateVariable:n,allStateVariablesAffected:t})}}async setUpStateVariableDependencies({component:e,stateVariable:t,allStateVariablesAffected:n}){let r,a=e.state[t];a.stateVariablesDeterminingDependencies?(r={},a.stateVariablesDeterminingDependencies&&(r.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies})):r=await a.returnDependencies({componentInfoObjects:this.componentInfoObjects,sharedParameters:e.sharedParameters});for(let a in r){let i=r[a];if(!(i.dependencyType in this.dependencyTypes))throw Error(`Unrecognized dependency type ${i.dependencyType} for ${a} of ${t} of ${e.componentName}`);let s=new this.dependencyTypes[i.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:a,dependencyDefinition:i,dependencyHandler:this,expandComposites:!1,forceExpandComposites:!1});await s.initialize(),s.checkForCircular()}}deleteAllDownstreamDependencies({component:e,stateVariables:t="__all__"}){let n,r=e.componentName;n="__all__"===t?Object.keys(this.downstreamDependencies[r]):t;for(let e of n){let t=this.downstreamDependencies[r][e];for(let e in t)t[e].deleteDependency();delete this.downstreamDependencies[r][e]}0!==Object.keys(this.downstreamDependencies[r]).length||this.components[r]||delete this.downstreamDependencies[r]}async deleteAllUpstreamDependencies({component:e,stateVariables:t="__all__",completelyDelete:n=!1}){let r,a=e.componentName;r="__all__"===t?Object.keys(this.upstreamDependencies[a]):t;for(let e of r){if(this.upstreamDependencies[a][e])for(let t of[...this.upstreamDependencies[a][e]])if(n){for(let e of t.upstreamVariableNames)this._components[t.upstreamComponentName].state[e].initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:this.components[t.upstreamComponentName],varName:e});t.deleteDependency()}else await t.removeDownstreamComponent({indexToRemove:t.downstreamComponentNames.indexOf(a)});delete this.upstreamDependencies[a][e]}0!==Object.keys(this.upstreamDependencies[a]).length||this._components[a]||delete this.upstreamDependencies[a]}async addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:t}){let n=this.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];if(n)for(let r of t){let t=n[r];if(t)for(let n of t)if(n.gettingValue){let t=n.varsWithUpdatedDeps[e];t||(t=n.varsWithUpdatedDeps[e]=[]),t.includes(r)||t.push(r)}else for(let e of n.upstreamVariableNames)await this.addBlocker({blockerComponentName:n.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:n.dependencyName,componentNameBlocked:n.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}async addBlockersFromChangedActiveChildren({parent:e}){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let t of this.updateTriggers.childDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let t of this.updateTriggers.parentDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let t of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}}async resolveBlockersFromChangedActiveChildren(e,t=!1){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let n of this.updateTriggers.childDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let n of this.updateTriggers.parentDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});for(let n of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.resolveDescendantBlockersToAncestor(n,t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let n of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}}async addDescendantBlockersToAncestor(e){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let t of this.updateTriggers.descendantDependenciesByAncestor[e]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}async resolveDescendantBlockersToAncestor(e,t=!1){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let n of this.updateTriggers.descendantDependenciesByAncestor[e])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}async addBlockersFromChangedReplacements(e){if(this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let t of this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t)}checkForCircularDependency({componentName:e,varName:t,previouslyVisited:n=[]}){let r=e+":"+t;if(n.includes(r)){console.log("found circular",r,n);let e,t=/^(.*):/,a=n.map((e=>e.match(t)[1])),i=a.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);throw 0===i.length&&(i=[a[0]]),1===i.length?e=i[0]:2===i.length?e=i.join(" and "):(i[i.length-2]=i.slice(i.length-2).join(", and "),i.pop(),e=i.join(", ")),Error(`Circular dependency involving ${e}`)}if(n=[...n,r],!this.circularCheckPassed[r]&&(this.circularCheckPassed[r]=!0,e in this.downstreamDependencies)){let r=this.downstreamDependencies[e][t];for(let e in r){let t=r[e],a=t.downstreamComponentNames;if(!a)continue;let i=t.mappedDownstreamVariableNamesByComponent;if(i)for(let[e,t]of a.entries()){let r=i[e];for(let e of r)this.checkForCircularDependency({componentName:t,varName:e,previouslyVisited:n})}}}}resetCircularCheckPassed(e,t){let n=e+":"+t;if(this.circularCheckPassed[n]){delete this.circularCheckPassed[n];let r=this.upstreamDependencies[e][t];if(r)for(let e of r)for(let t of e.upstreamVariableNames)"__identity"!==t&&this.resetCircularCheckPassed(e.upstreamComponentName,t)}}async updateDependencies({componentName:e,stateVariable:t,dependency:n}){let r=this._components[e],a=r.state[t],i=[t];a.additionalStateVariablesDefined&&i.push(...a.additionalStateVariablesDefined);let s,o=this.downstreamDependencies[e][t].__determine_dependencies;if(o){let t=!0;if(o.originalDownstreamVariableNames.length>0)for(let[r,a]of o.downstreamComponentNames.entries()){let s=this._components[a];for(let l of o.mappedDownstreamVariableNamesByComponent[r]){let r=s.state[l].isResolved;if(!r){r=(await this.resolveItem({componentName:a,type:"stateVariable",stateVariable:l})).success}if(!r){t=!1;for(let t of i)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:l,componentNameBlocked:e,typeBlocked:"determineDependencies",stateVariableBlocked:t,dependencyBlocked:n})}}}if(!t)return{success:!1};s=await o.getValue()}else s={changes:{},value:{stateValues:{}}};if(0===Object.keys(s.changes).length&&void 0!==a._previousValue)return{success:!0};let l={stateValues:Object.assign({},s.value.stateValues),componentInfoObjects:this.componentInfoObjects,sharedParameters:r.sharedParameters},u=await a.returnDependencies(l);a.stateVariablesDeterminingDependencies&&(u.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies});let c=await this.replaceDependenciesIfChanged({component:r,stateVariable:t,newDependencies:u,allStateVariablesAffected:i});if(!c.changedDependency&&!l.changedDependency)return{success:!0};for(let e of c.newlyCreatedDependencies)e.checkForCircular();for(let e of i)this.checkForCircularDependency({componentName:r.componentName,varName:e}),r.state[e].forceRecalculation=!0;a.initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:r,varName:t});for(let e of i)r.state[e].initiallyResolved&&this.recordActualChangeInUpstreamDependencies({component:r,varName:e});return await this.addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:i}),{success:!0}}async replaceDependenciesIfChanged({component:e,stateVariable:t,newDependencies:n,allStateVariablesAffected:r}){let a=this.downstreamDependencies[e.componentName][t],i=!1,s=[];for(let e in a)e in n||(i=!0,a[e].deleteDependency());for(let o in n)if(o in a){if(!deepCompare(n[o],a[o].definition)){i=!0,a[o].deleteDependency();let l=n[o],u=new this.dependencyTypes[l.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:l,dependencyHandler:this});await u.initialize(),s.push(u)}}else{i=!0;let a=n[o],l=new this.dependencyTypes[a.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:a,dependencyHandler:this});await l.initialize(),s.push(l)}return{changedDependency:i,newlyCreatedDependencies:s}}async checkForDependenciesOnNewComponent(e){let t=[],n={};if(this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){for(let r of this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){let a=this._components[r.upstreamComponentName];if(!a)continue;let i=!0;for(let e of r.upstreamVariableNames)if(!(e in a.state)){i=!1;break}if(i){for(let e of r.upstreamVariableNames){a.state[e].initiallyResolved&&(n[r.upstreamComponentName]&&n[r.upstreamComponentName][e]||t.push({componentName:r.upstreamComponentName,varName:e}))}for(let t of r.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:r.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:r.dependencyName,blockerComponentName:e,blockerType:"componentIdentity"});if((await this.resolveIfReady({componentName:r.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:r.representativeStateVariable,dependency:r.dependencyName,expandComposites:!1,recurseUpstream:!0})).success)for(let e of r.upstreamVariableNames)a.state[e].initiallyResolved||(n[r.upstreamComponentName]||(n[r.upstreamComponentName]={}),n[r.upstreamComponentName][e]=!0);else for(let e of r.upstreamVariableNames)await this.addBlocker({blockerComponentName:r.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:r.dependencyName,componentNameBlocked:r.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}delete this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]}return t}async getStateVariableDependencyValues({component:e,stateVariable:t}){let n={},r={},a={},i=this.downstreamDependencies[e.componentName][t];for(let e in i){let{value:t,changes:s,usedDefault:o}=await i[e].getValue();n[e]=t,Object.keys(s).length>0&&(r[e]=s),o&&(a[e]=o)}return{dependencyValues:n,changes:r,usedDefault:a}}recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:n}){let r=e.componentName,a=this.upstreamDependencies[r][t];if(a)for(let i of a)if(i.valuesChanged){let a=i.downstreamComponentNames.indexOf(r),s=i.valuesChanged[a][t];if(!s&&e.stateVarAliases)for(let n in e.stateVarAliases)e.stateVarAliases[n]===t&&n in upValuesChangedSub&&(s=upValuesChangedSub[n]);if(!s){if(!e.state[t].isArrayEntry)throw Error(`Something is wrong, as a variable ${t} of ${e.componentName} actually changed, but wasn't marked with a potential change`);s=upValuesChangedSub[t]={changed:{}}}e.state[t]&&e.state[t].isArray?(void 0===s.changed?s.changed={arrayKeysChanged:{}}:!0===s.changed&&(s.changed={allArrayKeysChanged:!0,arraySizeChanged:!0,arrayKeysChanged:{}}),n&&(n.allArrayKeysChanged&&(s.changed.allArrayKeysChanged=!0),n.arraySizeChanged&&(s.changed.arraySizeChanged=!0),Object.assign(s.changed.arrayKeysChanged,n.arrayKeysChanged))):s.changed=!0}}async collateCountersAndPropagateToAncestors(e){let t=Object.keys(e.counters);for(let n of e.allChildrenOrdered){let e=this._components[n];if(e)for(let n in e.counters)t.includes(n)||t.push(n)}let n=!1;for(let r of t){let t=e.counters[r];t||(t=e.counters[r]={dependencies:[],componentList:[]});let a=[];t.dependencies.length>0&&a.push(e.componentName);for(let t of e.allChildrenOrdered){let e=this._components[t];if(e){let t=e.counters[r];t&&a.push(...t.componentList)}}(a.length!==t.componentList.length||t.componentList.some(((e,t)=>e!=a[t])))&&(n=!0,t.componentList=a)}if(!n)return{foundChange:!1};if(!e.ancestors[0]){for(let n of t){let t=e.counters[n];for(let[e,r]of t.componentList.entries()){let t=this._components[r],a=t.counters[n];a.value=e+1;for(let e of a.dependencies)if(t.state[e.representativeStateVariable].initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:t,varName:e.representativeStateVariable});for(let n of e.upstreamVariableNames)t.state[n].forceRecalculation=!0,this.recordActualChangeInUpstreamDependencies({component:t,varName:n})}}}return{foundChange:!0,finishedPropagation:!0}}let r=this._components[e.ancestors[0].componentName];if(!r||!r.allChildrenOrdered.includes(e.componentName))return{foundChange:!0,finishedPropagation:!1};let a=await this.collateCountersAndPropagateToAncestors(r);return a.foundChange||console.error(`we found a change in propagating counters for ${e.componentName}, but no change for ancestors!`),{foundChange:!0,finishedPropagation:a.finishedPropagation}}getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];a||(a=this.resolveBlockers.neededToResolve[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r,blockerType:a,blockerCode:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:n,blockerDependency:r,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:r,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:n,blockerStateVariable:a,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.neededToResolve[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.neededToResolve[e]}}checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];if(!a)return!1;let i=a[t];if(!i)return!1;if(n){if(i=i[n],!i)return!1;if(r){if(i=i[r],!i)return!1}}return Object.keys(i).length>0}getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.resolveBlockedBy[e];a||(a=this.resolveBlockers.resolveBlockedBy[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:a,codeBlocked:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:n,dependencyBlocked:r,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:r,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:n,stateVariableBlocked:a,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.resolveBlockedBy[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.resolveBlockedBy[e]}}async addBlocker({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,componentNameBlocked:a,typeBlocked:i,stateVariableBlocked:s,dependencyBlocked:o}){let l=e;n&&(l+="|"+n,r&&(l+="|"+r));let u=a;s&&(u+="|"+s,o&&(u+="|"+o));let c=this.getNeededToResolve({componentName:a,type:i,stateVariable:s,dependency:o}),p=c[t];if(p||(p=c[t]=[]),p.includes(l))return;if(p.push(l),"stateVariable"===i){let e=this._components[a];if(e){let t=e.state[s];if(t.isResolved=!1,t.initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:e,varName:s});let t=this.upstreamDependencies[a][s];if(t)for(let e of t)if(this._components[e.upstreamComponentName])for(let t of e.upstreamVariableNames)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:s,componentNameBlocked:e.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t})}}}let d=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}),m=d[i];m||(m=d[i]=[]),m.includes(u)||m.push(u),this.resetCircularResolveBlockerCheckPassed({componentName:a,type:i,stateVariable:s,dependency:o}),this.checkForCircularResolveBlocker({componentName:a,type:i,stateVariable:s,dependency:o})}async processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){if("stateVariable"===t){let t=this._components[e];if(t){t.state[n]&&(t.state[n].isResolved=!0,t.state[n].initiallyResolved=!0)}}else if("componentIdentity"===t){if(!(e in this._components)&&!i)return{success:!1}}else if("recalculateDownstreamComponents"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let e=await t.recalculateDownstreamComponents({force:i});if(!e.success&&!i)return e;for(let e of t.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"recalculateDownstreamComponents",blockerCode:t.upstreamComponentName+"|"+e+"|"+r});for(let e of t.upstreamVariableNames)await this.resolveIfReady({componentName:t.upstreamComponentName,type:"stateVariable",stateVariable:e,expandComposites:a,force:i,recurseUpstream:s});return{success:!0}}}else if("determineDependencies"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let o=this.getNeededToResolve({componentName:e,type:"stateVariable",stateVariable:n}),l=!1,u=[];if(o.determineDependencies)for(let t of o.determineDependencies){let[r,a,i]=t.split("|");if(this.checkIfHaveNeededToResolve({componentName:e,type:"determineDependency",stateVariable:n,dependency:i})){l=!0;break}u.push(i)}if(l)return{success:!0};if(!(await this.updateDependencies({componentName:e,stateVariable:n,dependency:r})).success)return{success:!1};for(let n of t.upstreamVariableNames){for(let e of u)this.deleteFromResolveBlockedBy({blockerComponentName:t.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:n,blockerDependency:e});await this.resolveIfReady({componentName:e,type:"stateVariable",stateVariable:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}}else if("childMatches"===t){let t=this._components[e];if(t&&!t.childrenMatched){if(!(await this.core.deriveChildResultsFromDefiningChildren({parent:t,expandComposites:a,forceExpandComposites:i})).skipping&&!t.childrenMatchedWithPlaceholders&&!i)return{success:!1}}}else{if("expandComposite"!==t)throw Error(`Unrecognized type newly resolved: ${t}`);if(!this._components[e].isExpanded){if(this.core.updateInfo.compositesBeingExpanded.includes(e))return{success:!1};await this.core.expandCompositeComponent(this._components[e])}}let o=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});o=Object.assign({},o);for(let l in o)for(let u of[...o[l]])if(this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:l,codeBlocked:u}),s){let[e,t,n]=u.split("|");await this.resolveIfReady({componentName:e,type:l,stateVariable:t,dependency:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}async resolveStateVariablesIfReady({component:e,stateVariables:t}){let n=e.componentName;t||(await this.resolveIfReady({componentName:n,type:"componentIdentity",expandComposites:!1}),t=Object.keys(e.state));for(let r of t){let t=e.state[r];if(t&&t.determineDependenciesImmediately){let e=this.getNeededToResolve({componentName:n,type:"stateVariable",stateVariable:r}).determineDependencies;if(e)for(let t of e){let[e,n,r]=t.split("|");await this.resolveIfReady({componentName:e,type:"determineDependencies",stateVariable:n,dependency:r,expandComposites:!0})}}await this.resolveIfReady({componentName:n,type:"stateVariable",stateVariable:r,expandComposites:!1})}}async resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){return this.checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})?{success:!1}:(this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r}),await this.processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a,force:i,recurseUpstream:s}))}async resolveItem({componentName:e,type:t,stateVariable:n,dependency:r,force:a=!1,recurseUpstream:i=!1,expandComposites:s=!0,numPreviouslyNeeded:o}){let l,u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),c=u.determineDependencies;if(c&&c.length>0)for(let e of[...c]){let[t,n,r]=e.split("|"),i=await this.resolveItem({componentName:t,type:"determineDependencies",stateVariable:n,dependency:r,force:a,expandComposites:s});if(!i.success)return i}"stateVariable"===t&&this._components[e]&&(l=this._components[e].state[n],l&&(l.currentlyResolving=!0));let p=1/0,d=1/0;for(;(Object.keys(u).length>0||d>0)&&!(Number.isFinite(d)&&d>=p);){d>0&&(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})),p=d,d=0;for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,expandComposites:s});if(!o.success){if(!a)return o;d++}}}}if(d>0)for(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});Object.keys(u).length>0;)for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,force:a,expandComposites:s});if(!o.success)return o}}l&&(l.currentlyResolving=!1);let m=await this.resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,force:a,recurseUpstream:i,expandComposites:s});if(!m.success){let l=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),u=Object.keys(l).length;u>0&&(void 0===o||ue.match(t)[1])),r=n.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);0===r.length&&(r=[n[0]]),1===r.length?e=r[0]:2===r.length?e=r.join(" and "):(r[r.length-2]=r.slice(r.length-2).join(", and "),r.pop(),e=r.join(", "));let i=[],o=[];for(let e of a){let[t,n]=e.split("|"),r=this._components[t];if(r){this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&!r.attributes.createComponentOfType?.primitive&&("readyToExpandWhenResolved"===n?i.push(t):n===r.constructor.stateVariableToEvaluateAfterReplacements&&o.push(t))}}let l=!1;for(let e of i)if(o.includes(e)){l=!0;break}let u=`Circular dependency involving ${e}.`;throw l&&(u+=" Specifying the type of a composite component may address this circular dependency."),Error(u)}if(a=[...a,s],!this.circularResolveBlockedCheckPassed[s]){this.circularResolveBlockedCheckPassed[s]=!0;let i=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in i)for(let t of i[e]){let[n,r,i]=t.split("|");this.checkForCircularResolveBlocker({componentName:n,type:e,stateVariable:r,dependency:i,previouslyVisited:a})}}}resetCircularResolveBlockerCheckPassed({componentName:e,type:t,stateVariable:n,dependency:r}){let a=e;n&&(a+="|"+n,r&&(a+="|"+r));let i=a+"|"+t;if(this.circularResolveBlockedCheckPassed[i]){delete this.circularResolveBlockedCheckPassed[i];let a=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in a)for(let t of a[e]){let[n,r,a]=t.split("|");this.resetCircularResolveBlockerCheckPassed({componentName:n,type:e,stateVariable:r,dependency:a})}}}get components(){return this._components}set components(e){return null}}class Dependency{constructor({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:r,dependencyDefinition:a,dependencyHandler:i}){this.dependencyName=r,this.dependencyHandler=i,this.upstreamComponentName=e.componentName,this.upstreamVariableNames=n,this.definition=Object.assign({},a),this.representativeStateVariable=t,a.doNotProxy&&(this.doNotProxy=!0),a.variablesOptional&&(this.variablesOptional=!0),a.publicStateVariablesOnly&&(this.publicStateVariablesOnly=!0),a.caseInsensitiveVariableMatch&&(this.caseInsensitiveVariableMatch=!0),a.useMappedVariableNames&&(this.useMappedVariableNames=!0),a.propIndex&&(a.propIndex.every(Number.isFinite)?this.propIndex=a.propIndex.map(Math.round):this.propIndex=[]),this.returnSingleVariableValue=!1,this.returnSingleComponent=!1,this.originalDownstreamVariableNames=[]}static dependencyType="_base";downstreamVariableNameIfNoVariables="__identity";static get rendererType(){return this.componentType}get dependencyType(){return this.constructor.dependencyType}setUpParameters(){}async determineDownstreamComponents(){return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async initialize(){this.setUpParameters();let e=await this.determineDownstreamComponents(),t=e.downstreamComponentNames,n=e.downstreamComponentTypes;this.componentIdentitiesChanged=!0;let r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];r||(r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName]={});for(let e of this.upstreamVariableNames)r[e]||(r[e]={}),r[e][this.dependencyName]=this;0!==this.originalDownstreamVariableNames.length||this.originalVariablesByComponent?(this.mappedDownstreamVariableNamesByComponent=[],this.valuesChanged=[]):(delete this.mappedDownstreamVariableNamesByComponent,delete this.upValuesChanged),this.downstreamComponentNames=[],this.downstreamComponentTypes=[];for(let[e,r]of t.entries())await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:n[e],index:e})}async addDownstreamComponent({downstreamComponentName:e,downstreamComponentType:t,index:n}){this.componentIdentitiesChanged=!0,this.downstreamComponentNames.splice(n,0,e),this.downstreamComponentTypes.splice(n,0,t);let r=this.dependencyHandler._components[e];if(r){let t;t=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[n]:this.originalDownstreamVariableNames,this.caseInsensitiveVariableMatch&&(t=this.dependencyHandler.core.findCaseInsensitiveMatches({stateVariables:t,componentClass:r.constructor})),this.publicStateVariablesOnly&&(t=this.dependencyHandler.core.matchPublicStateVariables({stateVariables:t,componentClass:r.constructor}));let a=this.dependencyHandler.core.substituteAliases({stateVariables:t,componentClass:r.constructor});this.constructor.convertToArraySize&&(a=a.map((function(e){let t=r.state[e];if(t)return t.arraySizeStateVariable?t.arraySizeStateVariable:`__${e}_is_not_an_array`;if(r.arrayEntryPrefixes){let t=Object.keys(r.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let n of t)if(e.substring(0,n.length)===n){let t=r.arrayEntryPrefixes[n],a=r.state[t];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return r.state[t].arraySizeStateVariable}}return`__${e}_is_not_an_array`}))),void 0!==this.propIndex&&(a=await this.dependencyHandler.core.arrayEntryNamesFromPropIndex({stateVariables:a,component:r,propIndex:this.propIndex}));let i=a;if(t.length>0||this.originalVariablesByComponent){this.mappedDownstreamVariableNamesByComponent.splice(n,0,a);let t={};for(let e of a)t[e]={changed:!0};this.valuesChanged.splice(n,0,t),this.variablesOptional&&(i=i.filter((e=>e in r.state||this.dependencyHandler.core.checkIfArrayEntry({stateVariable:e,component:r}))));for(let t of i)if(r.state[t]||await this.dependencyHandler.core.createFromArrayEntry({component:r,stateVariable:t}),!r.state[t].isResolved)for(let n of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:n}),"determineDependencies"===this.dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"determineDependencies",stateVariableBlocked:n,dependencyBlocked:this.dependencyName})}0===i.length&&(i=[this.downstreamVariableNameIfNoVariables]);let s=this.dependencyHandler.upstreamDependencies[e];s||(s=this.dependencyHandler.upstreamDependencies[e]={});for(let e of i)if(void 0===s[e]&&(s[e]=[]),s[e].push(this),e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async removeDownstreamComponent({indexToRemove:e,recordChange:t=!0}){t&&(this.componentIdentitiesChanged=!0);let n=this.downstreamComponentNames[e];if(this.downstreamComponentNames.splice(e,1),this.downstreamComponentTypes.splice(e,1),n in this.dependencyHandler._components){let t;this.mappedDownstreamVariableNamesByComponent?(t=this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent.splice(e,1),this.valuesChanged.splice(e,1),this.variablesOptional&&t.push(this.downstreamVariableNameIfNoVariables)):t=[this.downstreamVariableNameIfNoVariables];for(let e of t){let t=this.dependencyHandler.upstreamDependencies[n][e];if(t){let r=t.indexOf(this);-1!==r&&(1===t.length?delete this.dependencyHandler.upstreamDependencies[n][e]:t.splice(r,1))}if(e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}}if(t)for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async swapDownstreamComponents(e,t){this.componentIdentitiesChanged=!0,[this.downstreamComponentNames[e],this.downstreamComponentNames[t]]=[this.downstreamComponentNames[t],this.downstreamComponentNames[e]],[this.downstreamComponentTypes[e],this.downstreamComponentTypes[t]]=[this.downstreamComponentTypes[t],this.downstreamComponentTypes[e]],(this.originalDownstreamVariableNames.length>0||this.originalVariablesByComponent)&&([this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent[t]]=[this.mappedDownstreamVariableNamesByComponent[t],this.mappedDownstreamVariableNamesByComponent[e]],[this.valuesChanged[e],this.valuesChanged[t]]=[this.valuesChanged[t],this.valuesChanged[e]]);for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}deleteDependency(){let e=[];if(this.mappedDownstreamVariableNamesByComponent){if(e=this.mappedDownstreamVariableNamesByComponent,this.variablesOptional){let t=[];for(let[n,r]of this.downstreamComponentNames.entries()){let a=[];for(let t of e[n])this.dependencyHandler.components[r].state[t]&&a.push(t);a.length>0?t.push(a):t.push([this.downstreamVariableNameIfNoVariables])}e=t}}else e=Array(this.downstreamComponentNames.length).fill([this.downstreamVariableNameIfNoVariables]);for(let[t,n]of this.downstreamComponentNames.entries())for(let r of e[t]){let e=this.dependencyHandler.upstreamDependencies[n][r];if(e){let t=e.indexOf(this);-1!==t&&(1===e.length?delete this.dependencyHandler.upstreamDependencies[n][r]:e.splice(t,1))}for(let e of this.upstreamVariableNames)this.dependencyHandler.deleteFromNeededToResolve({componentNameBlocked:this.componentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"stateVariable",blockerCode:n+"|"+r});if(r!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}this.deleteFromUpdateTriggers();let t=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];for(let e of this.upstreamVariableNames)delete t[e][this.dependencyName]}deleteFromUpdateTriggers(){}async getValue({verbose:e=!1,skipProxy:t=!1}={}){let n=[],r={},a=[];this.componentIdentitiesChanged&&(r.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1);for(let[e,t]of this.downstreamComponentNames.entries()){let i=this.dependencyHandler._components[t];if(a[e]=!1,i){let s,o={componentType:i.componentType};if(this.skipComponentNames||(o.componentName=t),s=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[e]:this.originalDownstreamVariableNames,s.length>0){o.stateValues={};let t={},n=!1;for(let[a,l]of s.entries()){let s=this.mappedDownstreamVariableNamesByComponent[e][a],u=this.useMappedVariableNames?s:l;if(!this.variablesOptional||s in i.state){let a=i.state[s];if(!a.deferred)if(o.stateValues[u]=await a.value,this.valuesChanged[e][s].changed&&(r.valuesChanged||(r.valuesChanged={}),r.valuesChanged[e]||(r.valuesChanged[e]={}),r.valuesChanged[e][u]=this.valuesChanged[e][s]),this.valuesChanged[e][s]={},a.usedDefault)t[u]=!0,n=!0;else if(a.isArrayEntry&&1===a.arrayKeys.length){i.state[a.arrayStateVariable].usedDefaultByArrayKey[a.arrayKeys[0]]&&(t[u]=!0,n=!0)}}}n&&(a[e]=t)}n.push(o)}else n.push({componentType:this.downstreamComponentTypes[e]})}if(!e)if(this.returnSingleVariableValue)if(1===n.length){n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0];let e=Object.keys(n.stateValues);if(1===e.length){let t=e[0];n=n.stateValues[t],r.valuesChanged&&r.valuesChanged[t]&&(r.valuesChanged=r.valuesChanged[t]),a&&(a=a[t])}else n=null,r={},a=!1}else n=null,r={},a=!1;else this.returnSingleComponent&&(1===n.length?(n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0]):(n=null,a=!1));return{value:n,changes:r,usedDefault:a}}checkForCircular(){for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e);for(let e of this.upstreamVariableNames)this.dependencyHandler.checkForCircularDependency({componentName:this.upstreamComponentName,varName:e})}async recalculateDownstreamComponents({force:e=!1}={}){let t=await this.determineDownstreamComponents({force:e}),n=t.downstreamComponentNames,r=n.length!==this.downstreamComponentNames.length||this.downstreamComponentNames.some(((e,t)=>e!=n[t]));if(r){this.componentIdentitiesChanged=!0;let e=0;for(let[t,r]of[...this.downstreamComponentNames].entries())n.includes(r)||(await this.removeDownstreamComponent({indexToRemove:t-e}),e++);for(let[e,r]of n.entries()){let n=this.downstreamComponentNames.indexOf(r);-1!==n?n!==e&&await this.swapDownstreamComponents(n,e):await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:t.downstreamComponentTypes[e],index:e})}}if(this.originalVariablesByComponent)for(let[e,n]of[...this.downstreamComponentNames].entries())(this.mappedDownstreamVariableNamesByComponent[e].length!==this.originalDownstreamVariableNamesByComponent[e].length||this.mappedDownstreamVariableNamesByComponent[e].some(((t,n)=>this.originalDownstreamVariableNamesByComponent[e][n]!==t)))&&(await this.removeDownstreamComponent({indexToRemove:e}),await this.addDownstreamComponent({downstreamComponentName:n,downstreamComponentType:t.downstreamComponentTypes[e],index:e}));return{success:t.success}}}class StateVariableDependency extends Dependency{static dependencyType="stateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableName is not defined`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.returnAsComponentObject?this.returnSingleComponent=!0:this.returnSingleVariableValue=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(StateVariableDependency);class MultipleStateVariablesDependency extends Dependency{static dependencyType="multipleStateVariables";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(MultipleStateVariablesDependency);class StateVariableComponentTypeDependency extends StateVariableDependency{static dependencyType="stateVariableComponentType";async getValue({verbose:e=!1}={}){let t=[],n={};if(this.staticValue)t=[this.staticValue];else if(this.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let e=this.downstreamComponentNames[0],r=this.dependencyHandler.components[e],a={componentName:r.componentName,componentType:r.componentType,stateValues:{}},i=this.originalDownstreamVariableNames[0],s=this.mappedDownstreamVariableNamesByComponent[0][0],o=this.useMappedVariableNames?s:i;if((!this.variablesOptional||s in r.state)&&!r.state[s].deferred){let e=r.state[s];if(await e.value,a.stateValues[o]=e.componentType,e.isArray&&e.wrappingComponents?.length>0){let t=e.wrappingComponents[e.wrappingComponents.length-1][0];"object"==typeof t&&(t=t.componentType),a.stateValues[o]=t}this.valuesChanged[0][s].changed&&(n.valuesChanged||(n.valuesChanged={}),n.valuesChanged[0]||(n.valuesChanged[0]={}),n.valuesChanged[0][o]=this.valuesChanged[0][s]),this.valuesChanged[0][s]={};let t=e.shadowingInstructions?.hasVariableComponentType;if(!t&&e.isArrayEntry){t=r.state[e.arrayStateVariable].shadowingInstructions?.hasVariableComponentType}t||(this.staticValue=a,await this.removeDownstreamComponent({indexToRemove:0,recordChange:!1}))}t=[a]}if(!e)if(this.returnSingleVariableValue)if(1===t.length){t=t[0];let e=Object.keys(t.stateValues);n.valuesChanged&&n.valuesChanged[0]&&n.valuesChanged[0][0]&&(n.valuesChanged=n.valuesChanged[0][0]),t=1===e.length?t.stateValues[e[0]]:null}else t=null;else this.returnSingleComponent&&(1===t.length?(t=t[0],n.valuesChanged&&n.valuesChanged[0]&&(n.valuesChanged=n.valuesChanged[0])):t=null);return{value:t,changes:n,usedDefault:!1}}}dependencyTypeArray.push(StateVariableComponentTypeDependency);class StateVariableArraySizeDependency extends StateVariableDependency{static dependencyType="stateVariableArraySize";static convertToArraySize=!0}dependencyTypeArray.push(StateVariableArraySizeDependency);class RecursiveDependencyValuesDependency extends Dependency{static dependencyType="recursiveDependencyValues";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.startingVariableNames=this.definition.variableNames,this.originalVariablesByComponent=!0,this.includeImmediateValueWithValue=this.definition.includeImmediateValueWithValue,this.includeRawValueWithImmediateValue=this.definition.includeRawValueWithImmediateValue,this.includeOnlyEssentialValues=this.definition.includeOnlyEssentialValues,this.variablesOptional=!0}async determineDownstreamComponents({force:e=!1}={}){this.missingComponents=[],this.originalDownstreamVariableNamesByComponent=[];let t=await this.getRecursiveDependencyVariables({componentName:this.componentName,variableNames:this.startingVariableNames,force:e});if(!t.success)return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=[],r=[];for(let e in t.components)if(this.includeOnlyEssentialValues){let a=[],i=this.dependencyHandler._components[e];for(let n of t.components[e].variableNames)(i.state[n]?.hasEssential||i.state[n]?.isArrayEntry&&i.state[i.state[n].arrayStateVariable].hasEssential)&&a.push(n);a.length>0&&(n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(a))}else n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(t.components[e].variableNames);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getRecursiveDependencyVariables({componentName:e,variableNames:t,force:n,components:r={}}){let a=this.dependencyHandler._components[e];if(!a){if(!this.missingComponents.includes(e)){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(this)||t.push(this)}for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}this.includeImmediateValueWithValue&&t.includes("value")&&!t.includes("immediateValue")&&"immediateValue"in a.state&&(t=[...t,"immediateValue"]),this.includeRawValueWithImmediateValue&&t.includes("immediateValue")&&!t.includes("rawRendererValue")&&"rawRendererValue"in a.state&&(t=[...t,"rawRendererValue"]);let i=r[e];i||(i=r[e]={componentName:e,componentType:a.componentType,variableNames:[]});let s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];s||(s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e]={});for(let o of t)if(!i.variableNames.includes(o)){i.variableNames.push(o);let t=s[o];t||(t=s[o]=[]),t.includes(this)||t.push(this);let l=a.state[o];if(l){if(!l.isResolved){if(!n){for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:o,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}await l.value}let t=this.dependencyHandler.downstreamDependencies[a.componentName][o];for(let e in t){let a=t[e];for(let[e,t]of a.downstreamComponentNames.entries()){let i=[];if((a.originalDownstreamVariableNames.length>0||a.originalVariablesByComponent)&&(i=a.mappedDownstreamVariableNamesByComponent[e]),!(await this.getRecursiveDependencyVariables({componentName:t,variableNames:i,force:n,components:r})).success)return{success:!1}}}}}return{success:!0,components:r}}async getValue(){let e;this.gettingValue=!0,this.varsWithUpdatedDeps={};let t={},n=!0,r={};for(;n;){if(n=!1,e=await super.getValue(),e.changes.valuesChanged)if(r.valuesChanged)for(let t in e.changes.valuesChanged){let n=e.changes.valuesChanged[t];if(r.valuesChanged[t])for(let e in n)r.valuesChanged[t][e]=n[e];else r.valuesChanged[t]=n}else r.valuesChanged=e.changes.valuesChanged;for(let e in this.varsWithUpdatedDeps){let r=t[e];r||(r=t[e]=[]);for(let t of this.varsWithUpdatedDeps[e])r.includes(t)||(r.push(t),n=!0)}n&&await this.recalculateDownstreamComponents()}return this.gettingValue=!1,e.changes=r,e}deleteFromUpdateTriggers(){for(let e of this.missingComponents){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}}dependencyTypeArray.push(RecursiveDependencyValuesDependency);class ComponentIdentityDependency extends Dependency{static dependencyType="componentIdentity";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ComponentIdentityDependency);class AttributeComponentDependency extends Dependency{static dependencyType="attributeComponent";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.attributeName=this.definition.attributeName,this.returnSingleComponent=!0,this.shadowDepth=0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=e.attributes[this.attributeName];if(this.shadowDepth=0,t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]};let n=e;for(;n.shadows;){let e=n.shadows,r=n.shadows.propVariable;if(n=this.dependencyHandler._components[e.componentName],!n)break;if(r){if(!n.state[r]?.shadowingInstructions?.attributesToShadow?.includes(this.attributeName)&&!n.constructor.createAttributesObject()[this.attributeName]?.propagateToProps)break}else{let t=this.dependencyHandler._components[e.compositeName];if("sourceAttributesToIgnoreRecursively"in t.state){if((await t.stateValues.sourceAttributesToIgnoreRecursively).includes(this.attributeName))break}if(e.firstLevelReplacement&&"sourceAttributesToIgnore"in t.state){if((await t.stateValues.sourceAttributesToIgnore).includes(this.attributeName))break}}if(this.shadowDepth++,t=n.attributes[this.attributeName],t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0});return t.value&&(t.value.shadowDepth=this.shadowDepth),t}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AttributeComponentDependency);class ChildDependency extends Dependency{static dependencyType="child";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];if(this.childGroups=this.definition.childGroups,!Array.isArray(this.childGroups))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups must be an array`);void 0!==this.definition.childIndices&&(this.childIndices=this.definition.childIndices.map((e=>Number(e)))),this.skipComponentNames=this.definition.skipComponentNames,this.skipPlaceholders=this.definition.skipPlaceholders,this.proceedIfAllChildrenNotMatched=this.definition.proceedIfAllChildrenNotMatched}async determineDownstreamComponents(){this.downstreamPrimitives?this.previousDownstreamPrimitives=[...this.downstreamPrimitives]:this.previousDownstreamPrimitives=[],this.downstreamPrimitives=[];let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];t||(t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),t.includes(this)||t.push(this);let n=e.returnMatchedChildIndices(this.childGroups);if(void 0===n)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups ${this.childGroups} does not exist.`);if(this.childIndices&&(n=n.filter(((e,t)=>this.childIndices.includes(t)))),!e.childrenMatched&&!this.proceedIfAllChildrenNotMatched){let t=!1;if(e.childrenMatchedWithPlaceholders&&(this.skipPlaceholders&&(n=n.filter((t=>!e.placeholderActiveChildrenIndices.includes(t)))),t=!(!this.skipComponentNames||0!==this.originalDownstreamVariableNames.length)||n.every((t=>!e.placeholderActiveChildrenIndices.includes(t)))),!t){let t=e.unexpandedCompositesNotReady.length>0;if(!t&&e.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(t){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});let t=[],r=[];for(let a of e.unexpandedCompositesNotReady){if(e.childrenMatchedWithPlaceholders){if(e.placeholderActiveChildrenIndicesByComposite[a].every((e=>!n.includes(e))))continue}this.dependencyHandler._components[a].attributes.createComponentOfType?.primitive?t.push(a):r.push(a)}let a=r;0===a.length&&(a=t);for(let e of a)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}let r=n.map((t=>e.activeChildren[t]));if(this.compositeReplacementRange=[],e.compositeReplacementActiveRange&&r.length>0){let t=0;for(;t=r){let e=t,i=t;for(;a.lastInd>r&&t=r);)i=t;if(this.compositeReplacementRange.push({compositeName:a.compositeName,target:a.target,firstInd:e,lastInd:i}),t++,t===n.length)break;r=n[t]}t++}}this.shadowDepthByChild=[];for(let t of r){let n=0,r=t,a=e;for(;r?.shadows&&r.shadows.compositeName===a?.shadows?.compositeName;)n++,a=this.dependencyHandler._components[a.shadows.componentName],r=this.dependencyHandler._components[r.shadows.componentName];this.shadowDepthByChild.push(n)}this.activeChildrenIndices=n;let a=[],i=[];for(let[e,t]of r.entries())"object"==typeof t?(this.downstreamPrimitives.push(null),a.push(t.componentName?t.componentName:`__placeholder_${e}`),i.push(t.componentType)):this.downstreamPrimitives.push(t);return{success:!0,downstreamComponentNames:a,downstreamComponentTypes:i}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let[e,a]of this.downstreamPrimitives.entries())if(null===a){t.value[r].shadowDepth=this.shadowDepthByChild[e],n.push(t.value[r]),r++}else n.push(a);return n.compositeReplacementRange=this.compositeReplacementRange,t.value=n,(this.downstreamPrimitives.length!==this.previousDownstreamPrimitives.length||this.downstreamPrimitives.some(((e,t)=>e!==this.previousDownstreamPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousDownstreamPrimitives=[...this.downstreamPrimitives]),t}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ChildDependency);class DescendantDependency extends Dependency{static dependencyType="descendant";setUpParameters(){if(this.definition.ancestorName?(this.ancestorName=this.definition.ancestorName,this.specifiedComponentName=this.ancestorName):this.ancestorName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.componentTypes=this.definition.componentTypes,this.recurseToMatchedChildren=this.definition.recurseToMatchedChildren,this.useReplacementsForComposites=this.definition.useReplacementsForComposites,this.includeNonActiveChildren=this.definition.includeNonActiveChildren,this.includeAttributeChildren=this.definition.includeAttributeChildren,this.skipOverAdapters=this.definition.skipOverAdapters,this.ignoreReplacementsOfMatchedComposites=this.definition.ignoreReplacementsOfMatchedComposites,this.ignoreReplacementsOfEncounteredComposites=this.definition.ignoreReplacementsOfEncounteredComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.ancestorName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.ancestorName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];t||(t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName]=[]),t.includes(this)||t.push(this);let n=this.gatherUnexpandedComposites(e);if(n.haveCompositesNotReady||n.haveUnexpandedCompositeReady){for(let e of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t in n.unexpandedCompositesReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});for(let t in n.unexpandedCompositesNotReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName})}return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let r=gatherDescendants({ancestor:e,descendantTypes:this.componentTypes,recurseToMatchedChildren:this.recurseToMatchedChildren,useReplacementsForComposites:this.useReplacementsForComposites,includeNonActiveChildren:this.includeNonActiveChildren,skipOverAdapters:this.skipOverAdapters,ignoreReplacementsOfMatchedComposites:this.ignoreReplacementsOfMatchedComposites,ignoreReplacementsOfEncounteredComposites:this.ignoreReplacementsOfEncounteredComposites,componentInfoObjects:this.dependencyHandler.componentInfoObjects});if(void 0!==this.componentIndex){let e=r[this.componentIndex-1];r=e?[e]:[]}return{success:!0,downstreamComponentNames:r.map((e=>e.componentName)),downstreamComponentTypes:r.map((e=>e.componentType))}}gatherUnexpandedComposites(e){let t={},n={},r=!1,a=!1,i=this.skipComponentNames&&0===this.originalDownstreamVariableNames.length;if(!e.childrenMatched)if(e.childrenMatchedWithPlaceholders){if(e.unexpandedCompositesReady.length>0){let n=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesReady,i);n.length>0&&(t[e.componentName]=n,r=!0)}if(e.unexpandedCompositesNotReady.length>0){let t=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesNotReady,i);t.length>0&&(n[e.componentName]=t,a=!0)}}else e.unexpandedCompositesReady.length>0&&(t[e.componentName]=e.unexpandedCompositesReady,r=!0),e.unexpandedCompositesNotReady.length>0&&(n[e.componentName]=e.unexpandedCompositesNotReady,a=!0);for(let i in e.allChildren){let s=e.allChildren[i].component;if("object"==typeof s){let e=this.gatherUnexpandedComposites(s);e.haveUnexpandedCompositeReady&&(Object.assign(t,e.unexpandedCompositesReadyByParentName),r=!0),e.haveCompositesNotReady&&(Object.assign(n,e.unexpandedCompositesNotReadyByParentName),a=!0)}}return{unexpandedCompositesReadyByParentName:t,haveUnexpandedCompositeReady:r,unexpandedCompositesNotReadyByParentName:n,haveCompositesNotReady:a}}unexpandedCompositesAdjustedForPlacedholders(e,t){let n=[];for(let r of e){let e=this.dependencyHandler._components[r];if(e.attributes.createComponentOfType){let a=this.dependencyHandler.componentInfoObjects.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],i=this.componentTypes.some((e=>this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:a,baseComponentType:e})));i&&t||n.push(r)}else n.push(r)}return n}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DescendantDependency);class ParentDependency extends Dependency{static dependencyType="parentStateVariable";setUpParameters(){if(this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentDependency);class ParentIdentityDependency extends Dependency{static dependencyType="parentIdentity";setUpParameters(){this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentIdentityDependency);class AncestorDependency extends Dependency{static dependencyType="ancestor";setUpParameters(){if(this.definition.descendantName?(this.descendantName=this.definition.descendantName,this.specifiedComponentName=this.descendantName):this.descendantName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.definition.componentType&&(this.componentType=this.definition.componentType)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.descendantName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.descendantName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!(this.dependencyHandler.core.documentName in this.dependencyHandler._components)){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e}),await this.dependencyHandler.addBlocker({blockerComponentName:this.dependencyHandler.core.documentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.findMatchingAncestor(e);if(t.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:t.missingComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of t.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];t||(t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e]=[]),t.includes(this)||t.push(this)}return this.ancestorResults=t,t.ancestorFound?{success:!0,downstreamComponentNames:[t.ancestorFound.componentName],downstreamComponentTypes:[t.ancestorFound.componentClass.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}findMatchingAncestor(e){let t=[];if(this.componentType){for(let n of e.ancestors){let e=this.dependencyHandler._components[n.componentName];if(!e)return{missingComponentName:n.componentName};if(t.push(n.componentName),this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:this.componentType}))return{ancestorsExamined:t,ancestorFound:n}}return{ancestorsExamined:t}}if(0===this.originalDownstreamVariableNames.length)return console.warn(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must specify componentType or variableNames to find ancestor`),{ancestorsExamined:t};let n=this.originalDownstreamVariableNames;for(let r of e.ancestors){let e=this.dependencyHandler._components[r.componentName];if(!e)return{missingComponentName:r.componentName};t.push(r.componentName);let a=!0;for(let t of n)if(!(t in e.state)&&!this.dependencyHandler.core.checkIfArrayEntry({stateVariable:t,component:e})){a=!1;break}if(a)return{ancestorsExamined:t,ancestorFound:r}}return{ancestorsExamined:t}}deleteFromUpdateTriggers(){for(let e of this.ancestorResults.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}if(this.ancestorResults&&this.ancestorResults.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorResults.missingComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AncestorDependency);class ReplacementDependency extends Dependency{static dependencyType="replacement";setUpParameters(){if(this.definition.compositeName?(this.compositeName=this.definition.compositeName,this.specifiedComponentName=this.compositeName):this.compositeName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.recursive=this.definition.recursive,this.recurseNonStandardComposites=this.definition.recurseNonStandardComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN),this.definition.targetSubnames&&(this.targetSubnames=this.definition.targetSubnames),this.definition.targetSubnamesComponentIndex&&(this.definition.targetSubnamesComponentIndex.every(Number.isInteger)?this.targetSubnamesComponentIndex=this.definition.targetSubnamesComponentIndex:this.targetSubnamesComponentIndex=[NaN]),this.includeWithheldReplacements=this.definition.includeWithheldReplacements,this.expandReplacements=!0}async determineDownstreamComponents(){this.replacementPrimitives?this.previousReplacementPrimitives=[...this.replacementPrimitives]:this.previousReplacementPrimitives=[],this.replacementPrimitives=[];let e=this.dependencyHandler._components[this.compositeName];if(!e){let a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName];a||(a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName]=[]),a.includes(this)||a.push(this);for(let i of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:i,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:i,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:i});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.isExpanded){for(let s of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:s,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:s}),await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:s,dependencyBlocked:this.dependencyName});return e.state.readyToExpandWhenResolved.isResolved||await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.compositeName,typeBlocked:"expandComposite"}),{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}this.compositesFound=[this.compositeName];let t=e.replacements;if(!this.includeWithheldReplacements&&e.replacementsToWithhold>0&&(t=t.slice(0,-e.replacementsToWithhold)),this.recursive){let o=this.dependencyHandler.core.recursivelyReplaceCompositesWithReplacements({replacements:t,recurseNonStandardComposites:this.recurseNonStandardComposites,includeWithheldReplacements:this.includeWithheldReplacements});if(o.unexpandedCompositesNotReady.length>0||o.unexpandedCompositesReady.length>0){for(let l of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:l,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:l});for(let u of[...o.unexpandedCompositesReady,...o.unexpandedCompositesNotReady])await this.dependencyHandler.addBlocker({blockerComponentName:u,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:l,dependencyBlocked:this.dependencyName})}for(let c of o.unexpandedCompositesNotReady)await this.dependencyHandler.addBlocker({blockerComponentName:c,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:c,typeBlocked:"expandComposite"});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}t=o.newReplacements,this.compositesFound.push(...o.compositesFound)}for(let p of this.compositesFound){let d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p];d||(d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p]=[]),d.includes(this)||d.push(this)}if(void 0!==this.componentIndex){let m=t[this.componentIndex-1];t=m?[m]:[]}if(this.targetSubnames){function h({components:e,subNames:t,subNamesComponentIndex:n,dep:r}){if(0===t.length)return e;let a=t.slice(1),i=[];for(let s of e){let e=s.componentName+"/"+t[0],o=r.dependencyHandler._components[e];if(o)r.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"_composite"})?console.warn("Have not yet implemented recursing subnames to multiple levels of composites"):0===a.length&&(n?.length,1)&&i.push(o);else{let t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(r)||t.push(r)}}return i}t=h({components:t,subNames:this.targetSubnames,subNamesComponentIndex:this.targetSubnamesComponentIndex,dep:this})}let n=[],r=[];for(let f of t)"object"==typeof f?(this.replacementPrimitives.push(null),n.push(f.componentName),r.push(f.componentType)):this.replacementPrimitives.push(f);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let e of this.replacementPrimitives)null===e?(n.push(t.value[r]),r++):n.push(e);return t.value=n,(this.replacementPrimitives.length!==this.previousReplacementPrimitives.length||this.replacementPrimitives.some(((e,t)=>e!==this.previousReplacementPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousReplacementPrimitives=[...this.replacementPrimitives]),t}deleteFromUpdateTriggers(){if(this.compositesFound)for(let e of this.compositesFound){let t=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ReplacementDependency);class SourceCompositeStateVariableDependency extends Dependency{static dependencyType="sourceCompositeStateVariable";setUpParameters(){if(this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.compositeComponentType&&(this.compositeComponentType=this.definition.compositeComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;if(this.compositeComponentType)for(;!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.compositeComponentType});){if(!t.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};t=t.replacementOf}return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeStateVariableDependency);class SourceCompositeIdentityDependency extends Dependency{static dependencyType="sourceCompositeIdentity";setUpParameters(){this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeIdentityDependency);class ShadowSourceDependency extends Dependency{static dependencyType="shadowSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.shadows)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.shadows.componentName,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ShadowSourceDependency);class UnlinkedCopySourceDependency extends Dependency{static dependencyType="unlinkedCopySource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.unlinkedCopySource)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.unlinkedCopySource,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(UnlinkedCopySourceDependency);class PrimaryShadowDependency extends Dependency{static dependencyType="primaryShadow";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName];if(t||(t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName]=[]),t.includes(this)||t.push(this),!e.primaryShadow)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=e.primaryShadow,r=this.dependencyHandler._components[n];return r?{success:!0,downstreamComponentNames:[r.componentName],downstreamComponentTypes:[r.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(PrimaryShadowDependency);class AdapterSourceStateVariableDependency extends Dependency{static dependencyType="adapterSourceStateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceStateVariableDependency);class AdapterSourceDependency extends Dependency{static dependencyType="adapterSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceDependency);class CountAmongSiblingsDependency extends Dependency{static dependencyType="countAmongSiblingsOfSameType";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return console.warn(`component ${this.componentName} does not have a parent for state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}.`),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(n||(n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),!t.childrenMatched){if(!t.childrenMatchedWithPlaceholders){let e=t.unexpandedCompositesNotReady.length>0;if(!e&&t.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(e){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let e of t.unexpandedCompositesNotReady)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}async getValue(){let e=this.dependencyHandler.components[this.upstreamComponentName].componentType,t=this.dependencyHandler.components[this.parentName].activeChildren.filter((t=>t.componentType===e)),n=t.map((e=>e.componentName)).indexOf(this.upstreamComponentName)+1;if(this.parentName===this.dependencyHandler.core.documentName){let t=this.dependencyHandler.core.previousComponentTypeCounts[e];t&&(n+=t)}return{value:n,changes:{}}}}dependencyTypeArray.push(CountAmongSiblingsDependency);class AttributeTargetComponentNamesDependency extends StateVariableDependency{static dependencyType="attributeTargetComponentNames";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.targetComponentNames:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributeTargetComponentNamesDependency);class TargetComponentDependency extends Dependency{static dependencyType="targetComponent";setUpParameters(){let e=this.dependencyHandler._components[this.upstreamComponentName];if(this.target=e.doenetAttributes.target,this.target&&(this.targetComponentName=this.specifiedComponentName=e.doenetAttributes.targetComponentName),this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0}async determineDownstreamComponents(){if(!this.target)return{downstreamComponentNames:[],downstreamComponentTypes:[]};let e=this.dependencyHandler._components[this.targetComponentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.targetComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.targetComponentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}dependencyTypeArray.push(TargetComponentDependency);class ValueDependency extends Dependency{static dependencyType="value";setUpParameters(){this.value=this.definition.value}async getValue(){return{value:this.value,changes:{}}}}dependencyTypeArray.push(ValueDependency);class FlagDependency extends ValueDependency{static dependencyType="flag";setUpParameters(){this.flagName=this.definition.flagName,this.value=this.dependencyHandler.core.flags[this.flagName]}}dependencyTypeArray.push(FlagDependency);class DoenetAttributeDependency extends StateVariableDependency{static dependencyType="doenetAttribute";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){e=this.dependencyHandler.components[this.downstreamComponentNames[0]].doenetAttributes[this.attributeName]}return{value:e,changes:t}}}dependencyTypeArray.push(DoenetAttributeDependency);class AttributePrimitiveDependency extends StateVariableDependency{static dependencyType="attributePrimitive";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.primitive:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributePrimitiveDependency);class SerializedChildrenDependency extends Dependency{static dependencyType="serializedChildren";setUpParameters(){this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.parentName].serializedChildren,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SerializedChildrenDependency);class DoenetMLDependency extends Dependency{static dependencyType="doenetML";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.displayOnlyChildren=this.definition.displayOnlyChildren}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler.core.requestComponentDoenetML(this.componentName,this.displayOnlyChildren),changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DoenetMLDependency);class VariantsDependency extends Dependency{static dependencyType="variants";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].variants,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(VariantsDependency);class CounterDependency extends Dependency{static dependencyType="counter";setUpParameters(){this.counterName=this.definition.counterName,this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName],t=e.counters[this.counterName];return t||(t=e.counters[this.counterName]={dependencies:[],componentList:[],value:null}),t.dependencies.includes(this)||t.dependencies.push(this),await this.dependencyHandler.collateCountersAndPropagateToAncestors(e),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].counters[this.counterName].value,changes:{}}}}dependencyTypeArray.push(CounterDependency);class DetermineDependenciesDependency extends Dependency{static dependencyType="determineDependencies";setUpParameters(){if(this.recalculateDependencies=!0,this.definition.componentName?this.componentName=this.definition.componentName:this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}async markStale(){let e=this.dependencyHandler._components[this.upstreamComponentName];for(let t of this.upstreamVariableNames)if(!(e&&e.state[t]&&e.state[t].currentlyResolving)){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});for(let e in this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t]){"determineDependencies"!==this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t][e].dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:e})}}}}dependencyTypeArray.push(DetermineDependenciesDependency);class FileDependency extends Dependency{static dependencyType="file";setUpParameters(){this.cid=this.definition.cid,this.uri=this.definition.uri,this.fileType=this.definition.fileType}async getValue(){let e;if(this.cid){if("csv"!==this.fileType.toLowerCase())return{value:null,changes:{}};return e="csv",{value:await retrieveTextFileForCid(this.cid,e),changes:{}}}{let e=await fetch(this.uri);if(e.ok){return{value:await e.text(),changes:{}}}return{value:null,changes:{}}}}}dependencyTypeArray.push(FileDependency);var appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","re","im","det","trace","nPr","nCr"],appliedFunctionSymbolsDefaultLatex=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","Re","Im","det","trace","nPr","nCr"];let allowedLatexSymbols=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","varnothing","emptyset","angle","circ","$","%"];var textToAst$1=new me$3.converters.textToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefault});function getFromText({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefault,splitSymbols:n=!0,parseScientificNotation:r=!1}){return a=>me$3.fromAst(new me$3.converters.textToAstObj({appliedFunctionSymbols:t,functionSymbols:e,splitSymbols:n,parseScientificNotation:r}).convert(a))}var latexToAst=new me$3.converters.latexToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefaultLatex,allowedLatexSymbols:allowedLatexSymbols});function getFromLatex({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefaultLatex,splitSymbols:n=!0,parseScientificNotation:r=!1}){return n?n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordIncludingNumberWithVar(n,r))):n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordWithVar(n,r)))}function normalizeMathExpression({value:e,simplify:t,expand:n=!1,createVectors:r=!1,createIntervals:a=!1}){return r&&(e=e.tuples_to_vectors()),a&&(e=e.to_intervals()),n&&(e=e.expand()),"full"===t?e.simplify():"numbers"===t?e.evaluate_numbers():"numberspreserveorder"===t?e.evaluate_numbers({skip_ordering:!0}):e}function findFiniteNumericalValue(e){if(void 0!==e)return Number.isFinite(e)||void 0!==e.evaluate_to_constant&&(e=e.evaluate_to_constant(),Number.isFinite(e))?e:null}function convertValueToMathExpression(e){return e instanceof me$3.class?e:"number"==typeof e||"string"==typeof e||Array.isArray(e)?me$3.fromAst(e):me$3.fromAst("_")}function returnNVariables(e,t){if(!Number.isInteger(e)||e<1)return[];let n=t.length;if(0===n){if(1===e)return[me$3.fromAst("x")];if(2===e)return[me$3.fromAst("x"),me$3.fromAst("y")];if(3===e)return[me$3.fromAst("x"),me$3.fromAst("y"),me$3.fromAst("z")];{let t=[];for(let n=1;n<=e;n++)t.push(me$3.fromAst(textToAst$1.convert(`x_${n}`)));return t}}if(new Set(t.map((e=>e.toString()))).sizee.toString()))],a=[...t];for(let t=n+1;t<=e;t++){let n;n=1==t?e>3?["x_1"]:["x"]:2==t?e>3?["x_2","y_2"]:["y","x_2"]:3==t?e>3?["x_3","y_3","z_3"]:["z","x_3","z_3"]:["x","y","z","u","v","w","X","Y","Z"].map((e=>`${e}_${t}`));let i=!1;for(let e of n)if(!r.includes(e)){a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),i=!0;break}if(!i){let e=n[0];a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),console.warn("Variables added were not unique")}}return a}async function preprocessMathInverseDefinition({desiredValue:e,stateValues:t,variableName:n="value",arrayKey:r,workspace:a}){if(!vectorOperators.includes(e.tree[0])||!e.tree.includes())return{desiredValue:e};let i,s=n+"Ast";if(void 0!==r&&(s+=`_${r}`),a[s])i=a[s].slice(0,e.tree.length);else{let a=await t[n];a&&void 0!==r&&(a=a[r]),a&&vectorOperators.includes(a.tree[0])&&(i=a.tree.slice(0,e.tree.length))}if(i){let t=[],n=!1;for(let[r,a]of e.tree.entries())void 0===a?(n=!0,t.push(r)):i[r]=a;return e=me$3.fromAst(i),a[s]=i,n?{desiredValue:e,vectorComponentsNotAffected:t}:{desiredValue:e}}{let t=[];for(let n of e.tree.slice(1))void 0===n?t.push("_"):t.push(n);return{desiredValue:e=me$3.fromAst([e.tree[0],...t])}}}function normalizeLatexString(e,{unionFromU:t=!1}={}){let n=[["α","\\alpha "],["β","\\beta "],["ϐ","\\beta "],["Γ","\\Gamma "],["γ","\\gamma "],["Δ","\\Delta "],["δ","\\delta "],["ε","\\epsilon "],["ϵ","\\epsilon "],["ζ","\\zeta "],["η","\\eta "],["Θ","\\Theta "],["ϴ","\\Theta "],["θ","\\theta "],["ᶿ","\\theta "],["ϑ","\\theta "],["ι","\\iota "],["κ","\\kappa "],["Λ","\\Lambda "],["λ","\\lambda "],["μ","\\mu "],["µ","\\mu "],["ν","\\nu "],["Ξ","\\Xi "],["ξ","\\xi "],["Π","\\Pi "],["π","\\pi "],["ϖ","\\pi "],["ρ","\\rho "],["ϱ","\\rho "],["Σ","\\Sigma "],["σ","\\sigma "],["ς","\\sigma "],["τ","\\tau "],["Υ","\\Upsilon "],["υ","\\upsilon "],["Φ","\\Phi "],["φ","\\phi "],["ϕ","\\phi "],["Ψ","\\Psi "],["ψ","\\psi "],["Ω","\\Omega "],["ω","\\omega "],["−","-"],["⋅"," \\cdot "],["·"," \\cdot "],["∪"," \\cup "],["∩"," \\cap "],["∞"," \\infty "],["∅"," \\emptyset "]];for(let t of n)e=e.replaceAll(t[0],t[1]);let r=e.match(/^(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*(.*)$/);if(r){let t=r[6];e=","!==t[0]?"\\ldots,"+t:"\\ldots"+t}let a=e.match(/^(.*?)(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*$/);if(a){let t=a[1];e=","!==t[t.length-1]?t+",\\ldots":t+"\\ldots"}return e=(e=e.replaceAll(/(\b|\\ )or(\b|\\ )/g,"$1\\lor$2")).replaceAll(/(\b|\\ )and(\b|\\ )/g,"$1\\land$2"),t&&(e=e.replaceAll(/(\b|\\ )U(\b|\\ )/g,"$1\\cup$2")),e}function isValidVariable(e){let t=e.tree,n=!0;return"string"==typeof t?"_"===t&&(n=!1):(!Array.isArray(t)||"_"!==t[0]||"string"!=typeof t[1]||"string"!=typeof t[2]&&"number"!=typeof t[2])&&(n=!1),n}function mathStateVariableFromNumberStateVariable({numberVariableName:e="number",mathVariableName:t="math",isPublic:n=!1}={}){let r={returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:e}}),definition:function({dependencyValues:e}){return{setValue:{[t]:numberToMathExpression(e.number)}}},inverseDefinition:function({desiredStateVariableValues:e}){let n=e[t].evaluate_to_constant();return null===n&&(n=NaN),{success:!0,instructions:[{setDependency:"number",desiredValue:n}]}}};return n&&(r.public=!0,r.shadowingInstructions={createComponentOfType:"math"}),r}function numberToMathExpression(e){let t;if("number"==typeof e?.re&&"number"==typeof e?.im)if(0===e.im)t=e.re;else{let n;n=1===e.im?"i":-1===e.im?["-","i"]:["*",e.im,"i"],t=0===e.re?n:["+",e.re,n]}else t=e;return me$3.fromAst(t)}function roundForDisplay({value:e,dependencyValues:t,usedDefault:n}){let r;return!n.displayDigits&&t.displayDigits>=1||n.displayDecimals||!Number.isFinite(t.displayDecimals)?(r=t.displayDigits>=1?me$3.round_numbers_to_precision(e,t.displayDigits):me$3.round_numbers_to_precision(e,10),t.displaySmallAsZero>0&&(r=me$3.evaluate_numbers(r,{skip_ordering:!0,set_small_zero:t.displaySmallAsZero}))):r=me$3.round_numbers_to_decimals(e,t.displayDecimals),r}function mergeListsWithOtherContainers(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);return[...vectorOperators,"list","set"].includes(t)&&(n=n.reduce(((e,t)=>Array.isArray(t)&&"list"===t[0]?[...e,...t.slice(1)]:[...e,t]),[])),n=n.map((e=>mergeListsWithOtherContainers(e))),[t,...n]}function wrapWordWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordWithVarSub(e,t),n}function wrapWordWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9]?)([a-zA-Z][a-zA-Z0-9]+)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function wrapWordIncludingNumberWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordIncludingNumberWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordIncludingNumberWithVarSub(e,t),n}function wrapWordIncludingNumberWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9\s]?\s*)([a-zA-Z][a-zA-Z0-9]*[0-9][a-zA-Z0-9]*)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1]||"^"===i[1][0]||"_"===i[1][0])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function stripLatex(e){return e.replaceAll("\\,","").replaceAll(/\\operatorname{([^{}]*)}/g,"$1")}function superSubscriptsToUnicode(e){let t={0:"₀",1:"₁",2:"₂",3:"₃",4:"₄",5:"₅",6:"₆",7:"₇",8:"₈",9:"₉","+":"₊","-":"₋"," ":""},n={0:"⁰",1:"¹",2:"²",3:"³",4:"⁴",5:"⁵",6:"⁶",7:"⁷",8:"⁸",9:"⁹","+":"⁺","-":"⁻"," ":""};function r(e,n){let r="";for(let e of n)r+=t[e];return r}function a(e,t){let r="";for(let e of t)r+=n[e];return r}return e=(e=(e=(e=e.replaceAll(/_(\d+)/g,r)).replaceAll(/_\(([\d +-]+)\)/g,r)).replaceAll(/\^(\d+)/g,a)).replaceAll(/\^\(([\d +-]+)\)/g,a)}function unicodeToSuperSubscripts(e){let t={"₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9","₊":"+","₋":"-"},n={"⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","⁺":"+","⁻":"-"};return e=(e=e.replaceAll(/([\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208A\u208B]+)/g,(function(e,n){let r="";for(let e of n)r+=t[e];return"_("+r+")"}))).replaceAll(/([\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079\u207A\u207B]+)/g,(function(e,t){let r="";for(let e of t)r+=n[e];return"^("+r+")"}))}const vectorOperators=["vector","altvector","tuple"];function renameStateVariable({stateVariableDefinitions:e,oldName:t,newName:n}){let r=e[n]=e[t];if(delete e[t],r.additionalStateVariablesDefined){let e=r.additionalStateVariablesDefined.indexOf(t);-1!==e&&(r.additionalStateVariablesDefined[e]=n)}let a=r.definition,i=["setValue","useEssentialOrDefaultValue","setEssentialValue"],s=["noChanges"];r.definition=function(e){let r=a(e);for(let e of i)r[e]&&t in r[e]&&(r[e][n]=r[e][t],delete r[e][t]);for(let e of s)if(r[e]){let a=r[e].indexOf(t);-1!==a&&(r[e][a]=n)}return r};let o=r.inverseDefinition;o&&(r.inverseDefinition=async function(e){let r=e.desiredStateVariableValues;r[t]=r[n],delete r[n];let a=await o(e);if(a.success)for(let e of a.instructions)e.setEssentialValue===t&&(e.setEssentialValue=n);return a})}function returnDefaultGetArrayKeysFromVarName(e){return e>1?function({arrayEntryPrefix:e,varEnding:t,arraySize:n,nDimensions:r}){let a=t.split("_").map((e=>Number(e)-1));return a.length===r&&a.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?a.every(((e,t)=>e=0?n?rcrypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),""),core,queuedRequestActions=[];async function createCore(e){core=new Core(e),core.getInitializedPromise().then((()=>{for(let e of queuedRequestActions)core.requestAction(e);queuedRequestActions=[]}))}async function returnAllStateVariables(e){if(!e.components)return{};let t={};for(let n in e.components){let r=e.components[n],a=t[n]={componentName:n,componentType:r.componentType,stateValues:{}};for(let e in r.state)a.stateValues[e]=removeFunctionsMathExpressionClass(await r.state[e].value);a.activeChildren=r.activeChildren.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),r.replacements&&(a.replacements=r.replacements.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),void 0!==r.replacementsToWithhold&&(a.replacementsToWithhold=r.replacementsToWithhold)),a.sharedParameters=removeFunctionsMathExpressionClass(r.sharedParameters)}return t}function removeFunctionsMathExpressionClass(e){if(e instanceof me$3.class)e=e.tree;else if("function"==typeof e)e=void 0;else if(Array.isArray(e))e=e.map((e=>removeFunctionsMathExpressionClass(e)));else if("object"==typeof e&&null!==e){let t={};for(let n in e)t[n]=removeFunctionsMathExpressionClass(e[n]);e=t}return e}onmessage=function(e){"createCore"===e.data.messageType?createCore(e.data.args):"requestAction"===e.data.messageType?core?.initialized?core.requestAction(e.data.args):queuedRequestActions.push(e.data.args):"returnAllStateVariables"===e.data.messageType?(console.log("all components"),console.log(core._components),returnAllStateVariables(core).then((e=>{postMessage({messageType:"returnAllStateVariables",args:e})}))):"visibilityChange"===e.data.messageType?core.handleVisibilityChange(e.data.args):"terminate"===e.data.messageType?core.terminate().then((()=>{postMessage({messageType:"terminated"})})):"navigatingToComponent"===e.data.messageType?core.handleNavigatingToComponent(e.data.args.componentName):"submitAllAnswers"===e.data.messageType&&core.requestAction({componentName:core.documentName,actionName:"submitAllAnswers",args:e.data.args})};let styleAttributes={lineColor:{componentType:"text"},lineColorWord:{componentType:"text"},lineOpacity:{componentType:"number"},lineWidth:{componentType:"number"},lineWidthWord:{componentType:"text"},lineStyle:{componentType:"text"},lineStyleWord:{componentType:"text"},markerColor:{componentType:"text"},markerColorWord:{componentType:"text"},markerStyle:{componentType:"text"},markerStyleWord:{componentType:"text"},markerSize:{componentType:"number"},fillColor:{componentType:"text"},fillColorWord:{componentType:"text"},fillOpacity:{componentType:"number"}},defaultStyle={lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3};function returnDefaultStyleDefinitions(){return{1:{lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3},2:{lineColor:"#D4042D",lineColorWord:"red",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#D4042D",markerColorWord:"red",markerStyle:"square",markerStyleWord:"square",markerSize:5,fillColor:"#D4042D",fillColorWord:"red",fillOpacity:.3},3:{lineColor:"#F19143",lineColorWord:"orange",lineOpacity:.7,lineWidth:3,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#F19143",markerColorWord:"orange",markerStyle:"triangle",markerStyleWord:"triangle",markerSize:5,fillColor:"#F19143",fillColorWord:"orange",fillOpacity:.3},4:{lineColor:"#644CD6",lineColorWord:"purple",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#644CD6",markerColorWord:"purple",markerStyle:"diamond",markerStyleWord:"diamond",markerSize:5,fillColor:"#644CD6",fillColorWord:"purple",fillOpacity:.3},5:{lineColor:"black",lineColorWord:"black",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"solid",lineStyleWord:"",markerColor:"black",markerColorWord:"black",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"black",fillColorWord:"black",fillOpacity:.3},6:{lineColor:"gray",lineColorWord:"gray",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"dotted",lineStyleWord:"dotted",markerColor:"gray",markerColorWord:"gray",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"gray",fillColorWord:"gray",fillOpacity:.3}}}function returnStyleDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.styleDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`styleDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["styleDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithStyle&&(t=e.ancestorWithStyle.stateValues.styleDefinitions),t||(t=returnDefaultStyleDefinitions());for(let e in t)n[e]=Object.assign({},t[e]);let r=[];for(let t of e.setupChildren)r.push(...e[`styleDefinitionsOf${t.componentName}`]);for(let e of r){let t=e.stateValues.value;for(let e in t){let r=n[e];r||(r=n[e]=Object.assign({},defaultStyle));let a=Object.assign({},t[e]);"markerColor"in a&&!("markerColorWord"in a)&&(a.markerColorWord=a.markerColor),"markerStyle"in a&&!("markerStyleWord"in a)&&(a.markerStyleWord=a.markerStyle,"circle"===a.markerStyleWord?a.markerStyleWord="point":"triangle"===a.markerStyleWord.slice(0,8)&&(a.markerStyleWord="triangle")),"lineColor"in a&&!("lineColorWord"in a)&&(a.lineColorWord=a.lineColor),"fillColor"in a&&!("fillColorWord"in a)&&(a.fillColorWord=a.fillColor),"lineWidth"in a&&!("lineWidthWord"in a)&&(a.lineWidth>=4?a.lineWidthWord="thick":a.lineWidth<=1?a.lineWidthWord="thin":a.lineWidthWord=""),"lineStyle"in a&&!("lineStyleWord"in a)&&("dashed"===a.lineStyle?a.lineStyleWord="dashed":"dotted"===a.lineStyle?a.lineStyleWord="dotted":a.lineStyleWord=""),Object.assign(r,a)}}return{setValue:{styleDefinitions:n}}}},e}function returnSelectedStyleStateVariableDefinition(){return{selectedStyle:{forRenderer:!0,willNeverBeEssential:!0,returnDependencies:()=>({styleNumber:{dependencyType:"stateVariable",variableName:"styleNumber"},ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]}}),definition:function({dependencyValues:e}){let t=e.ancestorWithStyle.stateValues.styleDefinitions;t||(t=returnDefaultStyleDefinitions());let n=t[e.styleNumber];return void 0===n&&(n=defaultStyle),{setValue:{selectedStyle:n}}}}}}function enumerateSelectionCombinations({numberOfIndices:e,numberOfOptions:t,maxNumber:n=1/0,withReplacement:r=!1,skipZero:a=!1}){if(1===e){let e=[...Array(t).keys()];return e=e.slice(1),a||(e=[...e,0]),e=e.slice(0,n),e=e.map((e=>[e])),e}let i=enumerateSelectionCombinations({numberOfIndices:e-1,numberOfOptions:t,maxNumber:n,withReplacement:r,skipZero:!r}),s=[],o=0;for(let e of i)for(let r=1;r<=t;r++){let i=[r%t,...e.map((e=>(r+e)%t))];if((!a||!i.includes(0))&&(s.push(i),o++,o>=n))return s}return s}function enumerateCombinations({numberOfOptionsByIndex:e,maxNumber:t=1/0}){let n=e.length;if(0===n)return[];let r=[];for(let t=0;t[...t,...e]),[]).reduce(((e,t)=>Math.max(e,t)),1);if(1===a){let n=e.reduce(((e,t)=>e*t));n=Math.min(n,t);let r=[];for(let t=0;tt%e));r.push(n)}return r}if(2===n){let n=a,r=me$3.math.lcm(...e),i=[],s=0;for(let a=0;a=t)return i}return i}let i=[];for(let t=0;t1?n.push(me$3.math.lcm(e[t],e[a])):n.push(null);i.push(n)}let s,o=i.reduce(((e,t)=>[...t,...e]),[]).filter((e=>null!==e)).reduce(((e,t)=>Math.min(e,t)),1/0);for(let e=0;e{if(0===e.length)n.push(a);else for(let i=0;i=t)return}};return r(e),n}function returnStandardSequenceAttributes(){return{type:{createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"number",toLowerCase:!0,validValues:["number","math","letters"]},from:{createComponentOfType:"_componentWithSelectableType"},to:{createComponentOfType:"_componentWithSelectableType"},step:{createComponentOfType:"math"},length:{createComponentOfType:"number"},exclude:{createComponentOfType:"_componentListWithSelectableType"}}}function returnStandardSequenceStateVariableDefinitions(){let e={specifiedFrom:{returnDependencies:()=>({fromAttr:{dependencyType:"attributeComponent",attributeName:"from",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"from",definition:function({dependencyValues:e}){return null===e.fromAttr?{useEssentialOrDefaultValue:{specifiedFrom:!0}}:null===e.fromAttr.stateValues.value?{setValue:{specifiedFrom:NaN}}:{setValue:{specifiedFrom:e.fromAttr.stateValues.value}}}},specifiedTo:{returnDependencies:()=>({toAttr:{dependencyType:"attributeComponent",attributeName:"to",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"to",definition:function({dependencyValues:e}){return null===e.toAttr?{useEssentialOrDefaultValue:{specifiedTo:!0}}:null===e.toAttr.stateValues.value?{setValue:{specifiedTo:NaN}}:{setValue:{specifiedTo:e.toAttr.stateValues.value}}}},specifiedLength:{returnDependencies:()=>({lengthAttr:{dependencyType:"attributeComponent",attributeName:"length",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"length",definition:function({dependencyValues:e}){return null===e.lengthAttr?{useEssentialOrDefaultValue:{specifiedLength:!0}}:null===e.lengthAttr.stateValues.value?{setValue:{specifiedLength:NaN}}:{setValue:{specifiedLength:e.lengthAttr.stateValues.value}}}},specifiedStep:{returnDependencies:()=>({stepAttr:{dependencyType:"attributeComponent",attributeName:"step",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),defaultValue:null,hasEssential:!0,essentialVarName:"step",definition:function({dependencyValues:e}){if(null===e.stepAttr)return{useEssentialOrDefaultValue:{specifiedStep:!0}};let t=e.stepAttr.stateValues.value;return null===t?{setValue:{specifiedStep:NaN}}:{setValue:{specifiedStep:t}}}},specifiedExclude:{returnDependencies:()=>({excludeAttr:{dependencyType:"attributeComponent",attributeName:"exclude",variableNames:["values"]}}),defaultValue:[],hasEssential:!0,essentialVarName:"exclude",definition:function({dependencyValues:e}){return null===e.excludeAttr?{useEssentialOrDefaultValue:{specifiedExclude:!0}}:{setValue:{specifiedExclude:e.excludeAttr.stateValues.values}}}},lowercase:{returnDependencies:()=>({specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"}}),definition:function({dependencyValues:e}){let t=/^[A-Z]*$/,n=!0;return null!==e.specifiedFrom?t.test(e.specifiedFrom)&&(n=!1):null!==e.specifiedTo&&t.test(e.specifiedTo)&&(n=!1),{setValue:{lowercase:n}}}}};return e.validSequence={returnDependencies:()=>({specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition:function({dependencyValues:e}){let t=!0;if(null!==e.specifiedLength&&(!Number.isInteger(e.specifiedLength)||e.specifiedLength<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),t=!1),null!==e.specifiedStep&&"math"!==e.type){let n=findFiniteNumericalValue(e.specifiedStep);Number.isFinite(n)||(console.warn("Invalid step of sequence. Must be a number for sequence of type "+e.type+"."),t=!1)}if(null!==e.specifiedFrom)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedFrom);Number.isFinite(n)||(console.warn("Invalid from of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedFrom)&&(console.warn("Invalid from of sequence"),t=!1);if(null!==e.specifiedTo)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedTo);Number.isFinite(n)||(console.warn("Invalid to of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedTo)&&(console.warn("Invalid to of sequence"),t=!1);return{setValue:{validSequence:t}}}},e.from={additionalStateVariablesDefined:["step","length","exclude"],returnDependencies:()=>({specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},type:{dependencyType:"stateVariable",variableName:"type"},specifiedExclude:{dependencyType:"stateVariable",variableName:"specifiedExclude"},validSequence:{dependencyType:"stateVariable",variableName:"validSequence"}}),definition:function({dependencyValues:e}){let t=e.specifiedFrom,n=e.specifiedTo,r=e.specifiedStep,a=e.specifiedLength,i=[...e.specifiedExclude],s=e.type;if("math"===e.type)null!==n&&(n instanceof me$3.class||(n=me$3.fromAst(n))),null!==t&&(t instanceof me$3.class||(t=me$3.fromAst(t))),null!==r&&(r instanceof me$3.class||(r=me$3.fromAst(r)));else if(null!==r&&r instanceof me$3.class&&(r=r.evaluate_to_constant()),"letters"===e.type)null!==t&&(t=lettersToNumber$1(t)),null!==n&&(n=lettersToNumber$1(n)),i=i.map(lettersToNumber$1);else if("number"===e.type){null!==n&&(n=n instanceof me$3.class?n.evaluate_to_constant():Number(n)),null!==t&&(t=t instanceof me$3.class?t.evaluate_to_constant():Number(t));for(let[e,t]of i.entries())t instanceof me$3.class?i[e]=t.evaluate_to_constant():i[e]=Number(t)}if(e.validSequence){let e=calculateSequenceParameters({from:t,to:n,step:r,length:a,type:s});return e.exclude=i,{setValue:e}}return(!Number.isInteger(a)||a<0)&&(a=0),{setValue:{from:t,step:r,length:a,exclude:i}}}},e}function calculateSequenceParameters({from:e,to:t,step:n,length:r,type:a}){if(null===e)null===t?(e="math"===a?me$3.fromAst(1):1,null===n?(n="math"===a?me$3.fromAst(1):1,null===r&&(r=10)):null===r&&(r=10)):(null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r="math"===a?Math.floor((t.subtract(1).divide(n).evaluate_to_constant()+1)*(1+1e-14)):Math.floor(((t-1)/n+1)*(1+1e-14))),"math"===a?e=t.subtract(n.multiply(r-1)).simplify():(e=t-n*(r-1),"letters"===a&&e<1&&(e=t-n*((r=Math.floor(((t-1)/n+1)*(1+1e-14)))-1))));else if(null===t)null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r=10);else if(null===n)null===r?"math"===a?(n=me$3.fromAst(1),r=Math.floor(t.subtract(e).add(1).evaluate_to_constant()*(1+1e-14))):(n=1,r=Math.floor((t-e+1)*(1+1e-14))):"math"===a?n=t.subtract(e).divide(r-1):(n=(t-e)/(r-1),"letters"===a&&(n=Math.floor(n)));else{if(null!==r)throw Error("Can't define from, to, step, and length for sequence");r="math"===a?Math.floor(t.subtract(e).divide(n).add(1).evaluate_to_constant()*(1+1e-14)):Math.floor(((t-e)/n+1)*(1+1e-14))}return(!Number.isInteger(r)||r<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),r=0),{from:e,step:n,length:r}}function returnSequenceValues({from:e,step:t,length:n,exclude:r,type:a,lowercase:i,maxNum:s},o=!1){let l=[],u=0;for(let c=0;c0&&("math"===a?n=n.add(t.multiply(me$3.fromAst(c))).expand().simplify():n+=t*c),"math"===a){if(r.some((e=>e&&e.equals(n))))continue}else if("number"===a){if(r.some((e=>Math.abs(e-n)<=1e-14*Math.max(Math.abs(e),Math.abs(n)))))continue}else if(r.includes(n))continue;if("letters"===a&&(n=numberToLetters(n,i)),o?l.push({value:n,originalIndex:c}):l.push(n),u++,u===s)break}return l}function returnSequenceValueForIndex({index:e,from:t,step:n,length:r,exclude:a,type:i,lowercase:s}){if(!(e>=0&&(void 0===r||e0&&("math"===i?o=o.add(n.multiply(me$3.fromAst(e))).expand().simplify():o+=n*e),"math"===i){if(a.some((e=>e&&e.equals(o))))return null}else if("number"===i){if(a.some((e=>Math.abs(e-o)<=1e-14*Math.max(Math.abs(e),Math.abs(o)))))return null}else if(a.includes(o))return null;return"letters"===i&&(o=numberToLetters(o,s)),o}function lettersToNumber$1(e){try{e=e.toUpperCase()}catch(t){return void console.warn("Cannot convert "+e+" to a number")}let t=0,n=e.length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t}function numberToLetters(e,t){e--;let n=65;t&&(n=97);let r="";for(;;){let t=e%26;if(r=String.fromCharCode(n+t)+r,e<26)break;e=Math.floor(e/26)-1}return r}function getVariantsForDescendantsForUniqueVariants({variantIndex:e,serializedComponent:t,componentInfoObjects:n}){let r=t.variants?.descendantVariantComponents;if(void 0===r)return{success:!1};let a=r.map((e=>e.variants.numberOfVariants)),i=enumerateCombinations({numberOfOptionsByIndex:a,maxNumber:e})[e-1],s=[];for(let[e,t]of r.entries()){let r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:i[e]+1,componentInfoObjects:n});if(!r.success)return{succss:!1};s.push(r.desiredVariant)}return{success:!0,desiredVariants:s}}function setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:r=!1}){let a,i;if(e.variants&&(i=e.variants.desiredVariant),a=void 0!==i?.seed?i.seed.toString():r?t.subpartVariantRng().toString().slice(2):t.variantRng().toString().slice(2),t.variantSeed=a,t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}function gatherVariantComponents({serializedComponents:e,componentInfoObjects:t}){let n=[];for(let r of e){if("object"!=typeof r)continue;if(r.variants||(r.variants={}),r.variants.isVariantComponent){n.push(r);continue}if(r.componentType in t.componentTypesCreatingVariants){r.variants.isVariantComponent=!0,n.push(r);continue}if(!r.children)continue;if(r.children.some((e=>"variantControl"===e.componentType))){r.variants.isVariantComponent=!0,n.push(r);continue}let e=gatherVariantComponents({serializedComponents:r.children,componentInfoObjects:t});e.length>0&&(r.variants.descendantVariantComponents=e,n.push(...e))}return n}function getNumberOfVariants({serializedComponent:e,componentInfoObjects:t}){let n;e.variants||(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){n=t;break}let r="document"===e.componentType;if(!n){if(!r)return{success:!1};let n=e.children.filter((e=>e.componentType||""!==e.trim()));if(1===n.length&&t.isInheritedComponentType({inheritedComponentType:n[0].componentType,baseComponentType:"_sectioningComponent"})){let r=n[0],a=getNumberOfVariants({serializedComponent:r,componentInfoObjects:t});if(a.success)return e.variants.descendantVariantComponents=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t}),e.variants.uniqueVariants=!0,e.variants.numberOfVariants=r.variants.numberOfVariants,e.variants.allPossibleVariants=r.variants.allPossibleVariants,e.variants.allVariantNames=r.variants.allVariantNames,e.variants.allPossibleVariantUniqueIndices=[...r.variants.allPossibleVariants.keys()].map((e=>e+1)),e.variants.allPossibleVariantSeeds=[...r.variants.allPossibleVariants.keys()].map((e=>(e+1).toString())),a}}return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:r})}function determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:n=!1}){let r;void 0===e.variants&&(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){r=t;break}if(!r&&!n){return t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t})}let a=[];if(r?.attributes.variantNames&&(a=r.attributes.variantNames.component.children.map((e=>e.toLowerCase()))),a.length!==[...new Set(a)].length)throw Error("Duplicate variant names specified");let i=r?.attributes.nVariants?.primitive;Number.isFinite(i)||(i=100),i=Math.min(Math.max(i,1),1e3);let s=[...a];if(s.lengthe.toLowerCase())),o=[...new Set(o)];for(let e of o)if(!s.includes(e))throw Error(`Cannot include variant ${e} as ${e} is a not variant name`)}let l=r?.attributes.variantsToExclude?.component.children;if(l){l=l.map((e=>e.toLowerCase()));for(let e of l)if(!s.includes(e))throw Error(`Cannot exclude variant ${e} as ${e} is not a variant name`)}else l=[];o=o?o.filter((e=>!l.includes(e))):[...s].filter((e=>!l.includes(e)));let u=o.map((e=>s.indexOf(e)+1)),c=[];r?.attributes.seeds&&(c=r.attributes.seeds.component.children);let p=[...c];if(p.lengthp[e-1])),h=void 0!==r?.attributes.uniqueVariants,f=r?.attributes.uniqueVariants?.primitive;if(f||!h){d=t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}),f=!!d.success&&(f||d.numberOfVariants<=i)}let y=[],g=[],b=[];if(f)for(let[e,t]of u.entries())t<=d.numberOfVariants&&(g.push(t),y.push(o[e]),b.push(m[e]));else y=o,g=u,b=m;let v=y.length;if(0===v)throw Error("No variants selected based on variantsToInclude, variantsToExclude, and the number of variants available");return e.variants.uniqueVariants=f,e.variants.numberOfVariants=v,e.variants.allPossibleVariants=y,e.variants.allVariantNames=s,e.variants.allPossibleVariantUniqueIndices=g,e.variants.allPossibleVariantSeeds=b,{success:!0,numberOfVariants:v}}function indexToLowercaseLetters(e){return numberToLetters(e,!0)}class BaseComponent{constructor({componentName:e,ancestors:t,serializedComponent:n,definingChildren:r,serializedChildren:a,attributes:i,stateVariableDefinitions:s,componentInfoObjects:o,coreFunctions:l,flags:u,shadow:c,numerics:p,parentSharedParameters:d,sharedParameters:m}){this.numerics=p,this.parentSharedParameters=d,this.sharedParameters=m,this.componentName=e,this.ancestors=t,this.counters={},this.componentInfoObjects=o,this.coreFunctions=l,this.flags=u,!0===c&&(this.isShadow=!0),this.definingChildren=r,void 0===this.definingChildren&&(this.definingChildren=[]),this.serializedChildren=a,this.attributes=i,this.state={};for(let e in s)this.state[e]=Object.assign({},s[e]);this.stateValues=new Proxy(this.state,createStateProxyHandler()),this.essentialState={},n.state&&(this.essentialState=deepClone(n.state)),this.doenetAttributes={},void 0!==n.doenetAttributes&&Object.assign(this.doenetAttributes,n.doenetAttributes),void 0!==n.variants&&(this.variants=n.variants),n.range&&(this.doenetMLrange=n.range),this.actions={copyDoenetMLToClipboard:this.copyDoenetMLToClipboard.bind(this)}}static componentType="_base";static get rendererType(){return this.componentType}get componentType(){return this.constructor.componentType}get componentOrAdaptedName(){return this.adaptedFrom?this.adaptedFrom.componentOrAdaptedName:this.componentName}get rendererType(){return this.constructor.rendererType}get allPotentialRendererTypes(){let e=[];this.rendererType&&e.push(this.rendererType);for(let t in this.state){let n=this.state[t];if(n.public){let t=n.componentType;Array.isArray(t)||(t=[t]),n.wrappingComponents&&t.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let n of t){let t=this.componentInfoObjects.allComponentClasses[n];if(t){let n=t.rendererType;n&&!e.includes(n)&&e.push(n)}}}}if(this.constructor.adapters)for(let t of this.constructor.adapters){let n;n="string"==typeof t?t:t.componentType;let r=this.componentInfoObjects.allComponentClasses[n];if(r){let t=r.rendererType;t&&!e.includes(t)&&e.push(t)}}if(!this.rendererType)return e;for(let t in this.allChildren){let n=this.allChildren[t].component;if("object"==typeof n)for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}return e}potentialRendererTypesFromSerializedComponents(e){let t=[];for(let n of e){let e=this.componentInfoObjects.allComponentClasses[n.componentType];if(e){let n=e.rendererType;n&&!t.includes(n)&&t.push(n);let r=e.returnStateVariableInfo({onlyPublic:!0}).stateVariableDescriptions;for(let e in r){let n=r[e],a=n.shadowingInstructions?.createComponentOfType;Array.isArray(a)||(a=[a]),n.wrappingComponents&&a.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let e of a){let n=this.componentInfoObjects.allComponentClasses[e];if(n){let e=n.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(e.adapters)for(let n of e.adapters){let e;e="string"==typeof n?n:n.componentType;let r=this.componentInfoObjects.allComponentClasses[e];if(r){let e=r.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(n.children){let e=this.potentialRendererTypesFromSerializedComponents(n.children);for(let n of e)t.includes(n)||t.push(n)}}return t}get childrenMatched(){return this.childrenMatchedWithPlaceholders&&!this.placeholderActiveChildrenIndices}static createAttributesObject(){return{hide:{createComponentOfType:"boolean",createStateVariable:"hide",defaultValue:!1,public:!0},disabled:{createComponentOfType:"boolean"},fixed:{createComponentOfType:"boolean",ignoreFixed:!0},modifyIndirectly:{createComponentOfType:"boolean",createStateVariable:"modifyIndirectly",defaultValue:!0,public:!0,propagateToProps:!0},styleNumber:{createComponentOfType:"number",createStateVariable:"styleNumber",defaultValue:1,public:!0,fallBackToParentStateVariable:"styleNumber"},isResponse:{createPrimitiveOfType:"boolean",createStateVariable:"isResponse",defaultValue:!1,public:!0},newNamespace:{createPrimitiveOfType:"boolean",createStateVariable:"newNamespace",defaultValue:!1,public:!0}}}static returnSugarInstructions(){return[]}static returnChildGroups(){return[]}static get childGroups(){return this.hasOwnProperty("childGroupsData")||(this.childGroupsData=this.returnChildGroups()),this.childGroupsData}static childGroupOfComponentTypeData;static get childGroupOfComponentType(){return this.hasOwnProperty("childGroupOfComponentTypeData")||(this.childGroupOfComponentTypeData={}),this.childGroupOfComponentTypeData}static childGroupIndsByNameData;static get childGroupIndsByName(){if(this.hasOwnProperty("childGroupIndsByNameData"))return Object.assign({},this.childGroupIndsByNameData);this.childGroupIndsByNameData={};for(let[e,t]of this.childGroups.entries()){if(t.group in this.childGroupIndsByNameData)throw Error(`Invalid childGroups for componentClass ${this.componentType}: ${t} is repeated`);this.childGroupIndsByNameData[t.group]=e}return Object.assign({},this.childGroupIndsByNameData)}returnMatchedChildIndices(e){let t=[];for(let n of e){let e=this.childMatchesByGroup[n];if(!e)return;t.push(...e)}return t.sort(((e,t)=>e-t))}static returnStateVariableDefinitions(){let e={};return e.hidden={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide",variablesOptional:!0},parentHidden:{dependencyType:"parentStateVariable",variableName:"hidden"},sourceCompositeHidden:{dependencyType:"sourceCompositeStateVariable",variableName:"hidden"},adapterSourceHidden:{dependencyType:"adapterSourceStateVariable",variableName:"hidden"}}),definition:({dependencyValues:e})=>({setValue:{hidden:Boolean(e.parentHidden||e.sourceCompositeHidden||e.adapterSourceHidden||e.hide)}}),markStale:()=>({updateParentRenderedChildren:!0}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"hide",desiredValue:e.hidden}]})},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,doNotShadowEssential:!0,defaultValue:!1,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({disabledAttr:{dependencyType:"attributeComponent",attributeName:"disabled",variableNames:["value"]},readOnly:{dependencyType:"flag",flagName:"readOnly"},parentDisabled:{dependencyType:"parentStateVariable",variableName:"disabled"},sourceCompositeDisabled:{dependencyType:"sourceCompositeStateVariable",variableName:"disabled"},adapterSourceDisabled:{dependencyType:"adapterSourceStateVariable",variableName:"disabled"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(e.readOnly)return{setValue:{disabled:!0}};if(null!==e.disabledAttr)return{setValue:{disabled:e.disabledAttr.stateValues.value}};if(void 0!==n.disabled)return{useEssentialOrDefaultValue:{disabled:!0}};let r=!1,a=!0;return null===e.parentDisabled||t.parentDisabled||(r=r||e.parentDisabled,a=!1),null===e.sourceCompositeDisabled||t.sourceCompositeDisabled||(r=r||e.sourceCompositeDisabled,a=!1),null===e.adapterSourceDisabled||t.adapterSourceDisabled||(r=r||e.adapterSourceDisabled,a=!1),a?{useEssentialOrDefaultValue:{disabled:!0}}:{setValue:{disabled:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.disabledAttr?{success:!0,instructions:[{setDependency:"disabledAttr",desiredValue:t.disabled,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"disabled",value:t.disabled}]}},e.fixed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,ignoreFixed:!0,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({fixedAttr:{dependencyType:"attributeComponent",attributeName:"fixed",variableNames:["value"]},parentFixed:{dependencyType:"parentStateVariable",variableName:"fixed"},sourceCompositeFixed:{dependencyType:"sourceCompositeStateVariable",variableName:"fixed"},adapterSourceFixed:{dependencyType:"adapterSourceStateVariable",variableName:"fixed"},ignoreParentFixed:{dependencyType:"doenetAttribute",attributeName:"ignoreParentFixed"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(null!==e.fixedAttr)return{setValue:{fixed:e.fixedAttr.stateValues.value}};if(void 0!==n.fixed)return{useEssentialOrDefaultValue:{fixed:!0}};let r=!1,a=!0;return null===e.parentFixed||t.parentFixed||e.ignoreParentFixed||(r=r||e.parentFixed,a=!1),null===e.sourceCompositeFixed||t.sourceCompositeFixed||(r=r||e.sourceCompositeFixed,a=!1),null===e.adapterSourceFixed||t.adapterSourceFixed||(r=r||e.adapterSourceFixed,a=!1),a?{useEssentialOrDefaultValue:{fixed:!0}}:{setValue:{fixed:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.fixedAttr?{success:!0,instructions:[{setDependency:"fixedAttr",desiredValue:t.fixed,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"fixed",value:t.fixed}]}},e.isInactiveCompositeReplacement={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{isInactiveCompositeReplacement:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:{variableName:"isInactiveCompositeReplacement",value:e.isInactiveCompositeReplacement}}]})},e.doenetML={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({doenetML:{dependencyType:"doenetML"}}),definition({dependencyValues:e}){let t=e.doenetML;return t||(t=""),{setValue:{doenetML:t}}}},e}static returnNormalizedStateVariableDefinitions({attributeNames:e,numerics:t}){let n=this.returnStateVariableDefinitions({attributeNames:e,numerics:t});if(!n)throw Error(`Error in state variable definitions of ${this.componentType}: returnStateVariableDefinitions did not return anything`);let r=function(e){for(let[t,n]of e.entries())"object"==typeof n&&(e[t]=n.variableName)},a=["returnDependencies","definition","inverseDefinition","stateVariablesDeterminingDependencies","stateVariablesDeterminingArraySizeDependencies","isArray","nDimensions","returnArraySizeDependencies","returnArraySize","returnArrayDependenciesByKey","arrayDefinitionByKey","inverseArrayDefinitionByKey","basedOnArrayKeyStateVariables","markStale","getPreviousDependencyValuesForMarkStale","determineDependenciesImmediately","createWorkspace","workspace","provideEssentialValuesInDefinition","providePreviousValuesInDefinition"],i={};for(let e in n){let t=n[e];if(i[e]=t,t.createWorkspace&&(t.workspace={}),t.additionalStateVariablesDefined){for(let[n,s]of t.additionalStateVariablesDefined.entries()){let o={};for(let e of a)e in t&&(o[e]=t[e]);o.additionalStateVariablesDefined=[...t.additionalStateVariablesDefined],o.additionalStateVariablesDefined[n]=e,r(o.additionalStateVariablesDefined);let l=s;"object"==typeof s&&(l=s.variableName,s=Object.assign({},s),delete s.variableName,Object.assign(o,s)),i[l]=o}r(t.additionalStateVariablesDefined)}}return i}static returnStateVariableInfo({onlyPublic:e=!1,onlyForRenderer:t=!1}={}){let n=this.createAttributesObject(),r={},a={},i={};for(let a in n){let i=n[a],s=i.createStateVariable;if(s&&(!e||i.public)&&(!t||i.forRenderer))if(i.public){let e;!i.createComponentOfType?(e=i.createPrimitiveOfType,"string"===e&&(e="text")):e=i.createComponentOfType,r[s]={createComponentOfType:e,public:!0}}else r[s]={}}let s=this.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(r)});for(let n in s){let o=s[n];if(o.isAlias)i[n]=o.targetVariableName;else if((!e||o.public)&&(!t||o.forRenderer)&&(o.public?r[n]={createComponentOfType:o.shadowingInstructions.createComponentOfType,public:!0}:r[n]={},o.isArray)){let e;r[n].isArray=!0,r[n].nDimensions=void 0===o.nDimensions?1:o.nDimensions,r[n].wrappingComponents=o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents():[],e=o.entryPrefixes?o.entryPrefixes:[n];for(let t of e)a[t]={arrayVariableName:n,nDimensions:o.returnEntryDimensions?o.returnEntryDimensions(t):1,wrappingComponents:o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents(t):[]};o.getArrayKeysFromVarName?r[n].getArrayKeysFromVarName=o.getArrayKeysFromVarName:r[n].getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(r[n].nDimensions)}}return{stateVariableDescriptions:r,arrayEntryPrefixes:a,aliases:i}}get parentName(){if(void 0!==this.ancestors&&0!==this.ancestors.length)return this.ancestors[0].componentName}getAllChildrenDownstreamComponentNames(e=!1){const t=Object.keys(this.allChildren);let n=Object.keys(this.downstreamDependencies);return!0!==e&&(n=n.filter((e=>!0!==this.downstreamDependencies[e].inactive))),[...t,...n]}get allDescendants(){let e=[];for(let t in this.allChildren){let n=this.allChildren[t].component;e=[...e,t,...n.allDescendants]}return e}async serialize(e={}){let t,n={componentType:this.componentType},r=[],a={...e};t=e.sourceAttributesToIgnoreRecursively?[...e.sourceAttributesToIgnoreRecursively]:[],e.sourceAttributesToIgnore&&(t.push(...e.sourceAttributesToIgnore),delete a.sourceAttributesToIgnore);for(let e of this.definingChildren)"object"!=typeof e?r.push(e):r.push(await e.serialize(a));if(void 0!==this.serializedChildren)for(let e of this.serializedChildren)r.push(this.copySerializedComponent(e));r.length>0&&(n.children=r),n.attributes={};for(let r in this.attributes){let i=this.attributes[r];i.component?e.copyAll&&(n.attributes[r]={component:await i.component.serialize(a)}):t.includes(r)&&!e.copyAll||(n.attributes[r]=JSON.parse(JSON.stringify(i)))}return this.essentialState&&Object.keys(this.essentialState).length>0&&(n.state=deepClone(this.essentialState)),e.copyVariants&&this.state.generatedVariantInfo&&(n.variants={desiredVariant:await this.stateValues.generatedVariantInfo}),n.originalName=this.componentName,n.originalDoenetAttributes=deepClone(this.doenetAttributes),n.doenetAttributes=deepClone(this.doenetAttributes),n.originalAttributes=deepClone(n.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames,n}copySerializedComponent(e){if("object"!=typeof e)return e;let t=[];if(void 0!==e.children)for(let n of e.children)t.push(this.copySerializedComponent(n));let n={componentType:e.componentType,originalName:e.componentName,originalNameFromSerializedComponent:!0,children:t,state:{},doenetAttributes:{}};return void 0!==e.doenetAttributes&&(n.originalDoenetAttributes=deepClone(e.doenetAttributes),n.doenetAttributes=deepClone(e.doenetAttributes),n.originalAttributes=deepClone(e.attributes),n.attributes=deepClone(e.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames),void 0!==e.state&&Object.assign(n.state,e.state),n}static adapters=[];static get nAdapters(){return this.adapters.length}getAdapter(e){if(e>=this.constructor.adapters.length)return;let t,n,r,a,i=this.constructor.adapters[e];"string"==typeof i?t=i:(t=i.stateVariable,n=i.componentType,r=i.substituteForPrimaryStateVariable,a=i.stateVariablesToShadow);let s=this.state[t];if(void 0===s||!s.public&&!n)throw Error("Invalid adapter "+t+" in "+this.componentType);return void 0===n&&(n=s.shadowingInstructions.createComponentOfType),{componentType:n,downstreamDependencies:{[this.componentName]:[{dependencyType:"adapter",adapterVariable:t,adapterTargetIdentity:{componentName:this.componentName,componentType:this.componentType},substituteForPrimaryStateVariable:r,stateVariablesToShadow:a}]}}}static getAdapterComponentType(e,t){if(e>=this.adapters.length)return;let n,r,a=this.adapters[e];if("string"==typeof a?n=a:(n=a.stateVariable,r=a.componentType),void 0===r){let e=t[this.componentType].stateVariableDescriptions[n];if(!e)throw Error("Invalid adapter "+n+" in "+this.componentType);if(r=e.createComponentOfType,!r)throw Error(`Couldn't get adapter component type for ${n} of componentType ${this.componentType}`)}return r}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=[];e.children&&(r=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t})),void 0===e.variants&&(e.variants={}),e.variants.descendantVariantComponents=r,n=1;let a=[];for(let e of r){let r=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!r.success)return{success:!1};a.push(r.numberOfVariants),n*=r.numberOfVariants}return e.variants.numberOfVariants=n,e.variants.uniqueVariantData={numberOfVariantsByDescendant:a},{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=!1,i=e.variants.uniqueVariantData.numberOfVariantsByDescendant,s=e.variants.descendantVariantComponents,o=[];if(s.length>0){let e=enumerateCombinations({numberOfOptionsByIndex:i,maxNumber:t})[t-1].map((e=>e+1));for(let t=0;t1){let r=s[t],i=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:e[t],componentInfoObjects:n});if(!i.success)return{success:!1};o.push(i.desiredVariant),a=!0}else o.push({})}let l={index:t};return a&&(l.subvariants=o),{success:!0,desiredVariant:l}}async copyDoenetMLToClipboard({actionId:e}){let t=await this.stateValues.doenetML;t?this.coreFunctions.copyToClipboard(t,e):this.coreFunctions.resolveAction({actionId:e})}}class InlineComponent extends BaseComponent{static componentType="_inline"}class Text extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveText:this.moveText.bind(this)})}static componentType="text";static includeBlankStringChildren=!0;static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"textLike",componentTypes:["string","text","_singleCharacterInline","_inlineRenderInlineChildren"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,returnDependencies:()=>({textLikeChildren:{dependencyType:"child",childGroups:["textLike"],variableNames:["text"]}}),defaultValue:"",set:e=>null===e?"":String(e),definition:function({dependencyValues:e}){if(0===e.textLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.textLikeChildren)t+="string"==typeof n?n:n.stateValues.text;return{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.textLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveText({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class TextOrInline extends InlineComponent{static componentType="_textOrInline";static renderChildren=!0;static rendererType="containerInline";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}class CompositeComponent extends BaseComponent{constructor(e){super(e),this.replacementsWorkspace={}}static componentType="_composite";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.replacements={returnDependencies:()=>({replacements:{dependencyType:"replacement"}}),definition:({dependencyValues:e})=>({setValue:{replacements:e.replacements}})},e.recursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0}}),definition:({dependencyValues:e})=>({setValue:{recursiveReplacements:e.recursiveReplacements}})},e.fullRecursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0,recurseNonStandardComposites:!0}}),definition:({dependencyValues:e})=>({setValue:{fullRecursiveReplacements:e.recursiveReplacements}})},e}static createSerializedReplacements(){return{replacements:[]}}static calculateReplacementChanges(){return[]}replacements=[];replacementsToWithhold=0;get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;for(let t in this.allChildren){let n=this.allChildren[t].component;for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}if(this.replacements)for(let t of this.replacements)if("object"==typeof t)for(let n of t.allPotentialRendererTypes)e.includes(n)||e.push(n);return e}}class Template extends CompositeComponent{static componentType="template";static treatAsComponentForRecursiveReplacements=!0;static includeBlankStringChildren=!0;static renderedDefault=!1;static assignNamesToReplacements=!0;static createsVariants=!0;static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static createAttributesObject(){let e=super.createAttributesObject();return e.rendered={createComponentOfType:"boolean",createStateVariable:"rendered",defaultValue:this.renderedDefault,public:!0},e.isResponse={leaveRaw:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.serializedChildren={returnDependencies:()=>({serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return{setValue:{serializedChildren:e.serializedChildren}}}},e.newNamespace={returnDependencies:()=>({newNamespace:{dependencyType:"attributePrimitive",attributeName:"newNamespace"}}),definition:({dependencyValues:e})=>({setValue:{newNamespace:e.newNamespace}})},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:n}){let r;if(e.typeAttr){if(!(n.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in n.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);r=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error(`You must specify createComponentOfType when specifying nComponents for a ${t.componentType}.`);r=null}return{setValue:{nComponentsSpecified:r}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,alwaysCreateReplacements:n,flags:r}){if(await e.stateValues.nComponentsSpecified,await e.stateValues.rendered||n){let n=deepClone(await e.state.serializedChildren.value),a=e.attributes.newNamespace?.primitive;if("isResponse"in e.attributes)for(let i of n){if("object"!=typeof i)continue;let n=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:i.componentType,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r});i.attributes||(i.attributes={}),Object.assign(i.attributes,n)}let i=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:n,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t,originalNamesAreConsistent:!0});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:i.serializedComponents,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:t,compositeAttributesObj:this.createAttributesObject(),flags:r})).replacements}}return{replacements:[]}}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n);return e}}const vectorAndListOperators=["list",...vectorOperators];class MathComponent extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="math";static primaryStateVariableForDefinition="unnormalizedValue";static primaryEssentialStateVariable="value";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0,toLowerCase:!0,validValues:["text","latex"]},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full",false:"none"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expand",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"inline",public:!0,forRenderer:!0},e.unordered={createComponentOfType:"boolean"},e.createVectors={createComponentOfType:"boolean",createStateVariable:"createVectors",defaultValue:!1,public:!0},e.createIntervals={createComponentOfType:"boolean",createStateVariable:"createIntervals",defaultValue:!1,public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.sourcesAreFunctionSymbols={createComponentOfType:"textList",createStateVariable:"sourcesAreFunctionSymbols",defaultValue:[]},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.groupCompositeReplacements={createPrimitiveOfType:"boolean",createStateVariable:"groupCompositeReplacements",defaultValue:!0},e.displayBlanks={createComponentOfType:"boolean",createStateVariable:"displayBlanks",defaultValue:!0,public:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]},{group:"displayedMaths",componentTypes:["m","me","men"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDigits"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDecimals"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.mathChildren[0].stateValues.displayDecimals}};r=!0,n=e.mathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displaySmallAsZero"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.mathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["padZeros"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.mathChildren.length&&0==e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].padZeros)return{setValue:{padZeros:e.mathChildren[0].stateValues.padZeros}};r=!0,n=e.mathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.valueShadow={defaultValue:me$3.fromAst("_"),hasEssential:!0,essentialVarName:"value",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]}}},e.unordered={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,returnDependencies:()=>({unorderedAttr:{dependencyType:"attributeComponent",attributeName:"unordered",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["unordered"]}}),definition({dependencyValues:e}){if(null===e.unorderedAttr){if(e.mathChildren.length>0){let t=e.mathChildren.every((e=>e.stateValues.unordered));return{setValue:{unordered:t}}}return{useEssentialOrDefaultValue:{unordered:!0}}}return{setValue:{unordered:e.unorderedAttr.stateValues.value}}}},e.codePre={returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e}){let t="math",n=!1;do{n=!1;for(let r of e.stringChildren)if(!0===r.includes(t)){n=!0,t+="m";break}}while(n);return{setValue:{codePre:t}}}},e.mathChildrenFunctionSymbols={returnDependencies:()=>({sourcesAreFunctionSymbols:{dependencyType:"stateVariable",variableName:"sourcesAreFunctionSymbols"},mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition({dependencyValues:e}){let t=[];if(e.mathChildren.compositeReplacementRange)for(let n of e.mathChildren.compositeReplacementRange)if(e.sourcesAreFunctionSymbols.includes(n.target))for(let e=n.firstInd;e<=n.lastInd;e++)t.push(e);return{setValue:{mathChildrenFunctionSymbols:t}}}},e.expressionWithCodes={hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"],variableNames:["latex"]},format:{dependencyType:"stateVariable",variableName:"format"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},mathChildrenFunctionSymbols:{dependencyType:"stateVariable",variableName:"mathChildrenFunctionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"},groupCompositeReplacements:{dependencyType:"stateVariable",variableName:"groupCompositeReplacements"}}),set:e=>null===e?null:convertValueToMathExpression(e),definition:calculateExpressionWithCodes,async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,componentName:r}){let a=e.expressionWithCodes,i=[{setEssentialValue:"expressionWithCodes",value:a}],s=t.stringChildren.length;if(0===s)return{success:!1};if(0===t.mathChildren.length){let e;e="latex"===await n.format?a.toLatex():a.toString(),i.push({setDependency:"stringChildren",desiredValue:e,childIndex:0,variableIndex:0,ignoreChildChangeForComponent:!0});for(let e=1;e({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value","canBeModified"]}}),definition:({dependencyValues:e})=>({setValue:{mathChildrenWithCanBeModified:e.mathChildren}})},e.unnormalizedValue={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),set:convertValueToMathExpression,defaultValue:me$3.fromAst("_"),definition:calculateMathValue,inverseDefinition:invertMath},e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,attributesToShadow:["unordered","displayDigits","displayDecimals","displaySmallAsZero","padZeros","simplify","expand"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},returnDependencies:()=>({unnormalizedValue:{dependencyType:"stateVariable",variableName:"unnormalizedValue"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},createVectors:{dependencyType:"stateVariable",variableName:"createVectors"},createIntervals:{dependencyType:"stateVariable",variableName:"createIntervals"}}),definition:function({dependencyValues:e}){let t=e.unnormalizedValue,{simplify:n,expand:r,createVectors:a,createIntervals:i}=e;return t=normalizeMathExpression({value:t,simplify:n,expand:r,createVectors:a,createIntervals:i}),{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"unnormalizedValue",desiredValue:e.value}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=e.value.evaluate_to_constant();return null===t&&(t=NaN),{setValue:{number:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"value",desiredValue:me$3.fromAst(e.number)}]}}},e.isNumber={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{isNumber:Number.isFinite(e.value.tree)}}}},e.isNumeric={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:"number"}}),definition:function({dependencyValues:e}){return{setValue:{isNumeric:Number.isFinite(e.number)}}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:normalizeMathExpression({value:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}),simplify:e.simplify,expand:e.expand})}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.valueForDisplay}]})},e.latex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toLatex(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{latex:n}}},inverseDefinition({desiredStateVariableValues:e}){let t;try{t=me$3.fromLatex(e.latex)}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"valueForDisplay",desiredValue:t}]}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toString(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{text:superSubscriptsToUnicode(n.toString())}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n,r=getFromText({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(unicodeToSuperSubscripts(e.text))}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}}},e.codesAdjacentToStrings={returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},codePre:{dependencyType:"stateVariable",variableName:"codePre"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:calculateCodesAdjacentToStrings},e.canBeModified={additionalStateVariablesDefined:["constantChildIndices","codeForExpression","inverseMaps","template","mathChildrenMapped"],returnDependencies:()=>({mathChildrenModifiable:{dependencyType:"child",childGroups:["maths"],variableNames:["canBeModified"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition:determineCanBeModified},e.mathChildrenByVectorComponent={returnDependencies:()=>({codePre:{dependencyType:"stateVariable",variableName:"codePre"},mathChildren:{dependencyType:"child",childGroups:["maths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"}}),definition:function({dependencyValues:e}){if(null===e.expressionWithCodes)return{setValue:{mathChildrenByVectorComponent:null}};let t=e.expressionWithCodes.tree,n=e.mathChildren.length;if(0===n||!Array.isArray(t)||!vectorOperators.includes(t[0]))return{setValue:{mathChildrenByVectorComponent:null}};let r={},a=0,i=e.codePre+a;for(let s=1;s=n)break}return{setValue:{mathChildrenByVectorComponent:r}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=1,n=e.value.tree;if(Array.isArray(n))if(vectorAndListOperators.includes(n[0]))t=n.length-1;else if("matrix"===n[0]){let e=n[1].slice(1);1===e[0]?t=e[1]:1===e[1]&&(t=e[0])}else vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=n[1].length-1);return{setValue:{nDimensions:t}}}},e.vector={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;ee.tree))]);else if("matrix"===s[0]){let e=s[1].slice(1);if(1===e[0]){let e=["tuple"];for(let t=0;te.tree))]],s[2]&&i.push(s[2]),i=me$3.fromAst(i));return i||(i=r.desiredVector[0]),{success:!0,instructions:[{setDependency:"value",desiredValue:i}]}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.matrixSize={public:!0,shadowingInstructions:{createComponentOfType:"numberList"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=[1,1],n=e.value.tree;return Array.isArray(n)&&(vectorAndListOperators.includes(n[0])?t=[n.length-1,1]:"matrix"===n[0]?t=n[1].slice(1):vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=[1,n[1].length-1])),{setValue:{matrixSize:t}}}},e.nRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nRows:e.matrixSize[0]}})},e.nColumns={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nColumns:e.matrixSize[1]}})},e.matrix={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"matrixEntry"===e?[]:"row"===e?[["matrix","matrixRow"]]:"column"===e?[["matrix","matrixColumn"]]:[["matrixRow"],["matrix"]]},isArray:!0,nDimensions:2,entryPrefixes:["matrixEntry","row","column","rows","columns"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("matrixEntry"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}if("column"===e){let e=Number(t)-1;return Number.isInteger(e)&&e>=0?n?en+","+e)):[]:["0,"+e]:[]}if("rows"===e||"columns"===e){if(!n)return["0,0"];let e=[];for(let t=0;tt+","+n)));return e}},arrayVarNameFromPropIndex(e,t){if("matrix"===t||"rows"===t)return 1===e.length?"row"+e[0]:`matrixEntry${e[0]}_${e[1]}`;if("columns"===t)return 1===e.length?"column"+e[0]:`matrixEntry${e[1]}_${e[0]}`;if("row"===t.slice(0,3)){let n=Number(t.slice(3));if(Number.isInteger(n)&&n>0)return`matrixEntry${n}_${e[0]}`}if("column"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`matrixEntry${e[0]}_${n}`}return null},returnArraySizeDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),returnArraySize:({dependencyValues:e})=>e.matrixSize,returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;e({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=[{stateVariable:"number",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text",{componentType:"subsetOfReals",stateVariable:"value",substituteForPrimaryStateVariable:"subsetValue"}];async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function calculateExpressionWithCodes({dependencyValues:e,changes:t}){if(!("stringMathChildren"in t&&t.stringMathChildren.componentIdentitiesChanged||"displayedMathChildren"in t||"format"in t||"splitSymbols"in t||"parseScientificNotation"in t||"functionSymbols"in t||"mathChildrenFunctionSymbols"in t))return{useEssentialOrDefaultValue:{expressionWithCodes:!0}};if(0===e.stringMathChildren.length){if(e.displayedMathChildren.length>0){let t;try{t=me$3.fromLatex(e.displayedMathChildren[0].stateValues.latex)}catch(e){t=me$3.fromAst("_")}return{setValue:{expressionWithCodes:t},setEssentialValue:{expressionWithCodes:t}}}return{setValue:{expressionWithCodes:null},setEssentialValue:{expressionWithCodes:null}}}let n,r,a,i,s="",o=0,l="",u=e.stringMathChildren.compositeReplacementRange;e.groupCompositeReplacements&&u.length>0&&(a=0,i=u[a].firstInd);for(let[t,c]of e.stringMathChildren.entries()){if(void 0===n&&t===i){n=a,r=u[a].lastInd,l="";let s=r===t;if(!s)for(let n=t;n<=r;n++)if("string"==typeof e.stringMathChildren[n]){s=!0;break}s&&(u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0)}if("string"==typeof c)s+=" "+c+" ";else{let t,r=e.codePre+o;o++,t="latex"===e.format?"\\operatorname{"+r+"}":" "+r+" ",void 0!==n?(l&&(l+=","),l+=t):s+=t}if(t===r){let o=s.trimEnd(),c=!1;if(0===o.length)c=!0;else{let n=o[o.length-1];if(["{","[","(","|",","].includes(n)){let n=e.stringMathChildren[t+1];if("string"!=typeof n)c=!0;else{let t=n.trimStart();if(0===t.length)c=!0;else{let n=t[0];"latex"===e.format&&"\\"===n&&t.length>1&&(n=t[1]),["}","]",")","|",","].includes(n)||(c=!0)}}}else c=!0}c&&(l="("+l+")"),s+=l,l="",u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0}}let c=null,p=[...e.functionSymbols];if(p.push(...e.mathChildrenFunctionSymbols.map((t=>e.codePre+t))),""===s)c=me$3.fromAst("_");else if("text"===e.format){let t=getFromText({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of text format: "+s)}}else if("latex"===e.format){let t=getFromLatex({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of latex format: "+s)}}return{setValue:{expressionWithCodes:c},setEssentialValue:{expressionWithCodes:c}}}function calculateMathValue({dependencyValues:e}={}){if(null===e.expressionWithCodes)return{setValue:{unnormalizedValue:e.valueShadow}};let t={};for(let[n,r]of e.mathChildren.entries())t[e.codePre+n]=r.stateValues.value;let n=e.expressionWithCodes;return e.mathChildren.length>0&&(n=n.substitute(t)),n=me$3.fromAst(mergeListsWithOtherContainers(n.tree)),{setValue:{unnormalizedValue:n}}}function calculateCodesAdjacentToStrings({dependencyValues:e}){let t,n=[];for(let[r,a]of e.stringMathChildren.entries())if("string"==typeof a){let a=e.stringMathChildren[r+1];if(void 0!==a&&"string"==typeof a)continue;let i={};if(void 0!==t&&("latex"===e.format?i.prevCode="\\operatorname{"+e.codePre+t+"}":i.prevCode=e.codePre+t),void 0!==a){let n=0;void 0!==t&&(n=t+1),"latex"===e.format?i.nextCode="\\operatorname{"+e.codePre+n+"}":i.nextCode=e.codePre+n}n.push(i)}else void 0===t?t=0:t++;return{setValue:{codesAdjacentToStrings:n}}}function determineCanBeModified({dependencyValues:e}){if(!e.modifyIndirectly||e.fixed)return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};if(0===e.mathChildrenModifiable.length)return e.displayedMathChildren.length>0?{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}:{setValue:{canBeModified:!0,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};let t=[],n=[],r=[],a={};for(let[i,s]of e.mathChildrenModifiable.entries()){let o=e.codePre+i;!0===s.stateValues.canBeModified?(t.push(i),n.push(o)):(r.push(o),a[o]=i)}let i=e.codePre+"expr",s=checkForLinearExpression(me$3.utils.unflattenLeft(e.expressionWithCodes.tree),n,i,r);if(s.foundLinear){let e={},r=s.template,o=new Set;for(let r in s.mappings){e[r]=s.mappings[r];let a=e[r].mathChildSub;if(a){let i=t[n.indexOf(a)];e[r].mathChildInd=i,o.add(Number(i))}}return o.has=o.has.bind(o),{setValue:{canBeModified:!0,constantChildIndices:a,codeForExpression:i,inverseMaps:e,template:r,mathChildrenMapped:o}}}return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}}function checkForLinearExpression(e,t,n,r=[],a=[]){let i=me$3.variables(e);if(i.every((e=>!t.includes(e)))&&i.every((e=>!r.includes(e)))){let e={},t="x"+a.join("_");return e[t]={result:me$3.fromAst(n).simplify(),components:a},{foundLinear:!0,mappings:e,template:t}}if(!Array.isArray(e))return checkForScalarLinearExpression(e,t,n,a);let s=e[0],o=e.slice(1);if(vectorAndListOperators.includes(s)){let e={mappings:{},template:[s]},i=0;for(let s=0;s!t.includes(e)))?(n=["+",n,["-",i[0]]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["+",n,["-",i[1]]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"*"===a?me$3.variables(i[0]).every((e=>!t.includes(e)))?(n=["/",n,i[0]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["/",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"/"===a&&me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["*",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}}async function invertMath({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r,overrideFixed:a,componentName:i}){if(!await n.canBeModified&&!a)return{success:!1};let s=t.mathChildren,o=t.stringChildren.length;if(1===s.length&&0===o)return{success:!0,instructions:[{setDependency:"mathChildren",desiredValue:e.unnormalizedValue,childIndex:0,variableIndex:0}]};let l=convertValueToMathExpression(e.unnormalizedValue),u=await preprocessMathInverseDefinition({desiredValue:l,stateValues:n,variableName:"value",workspace:r}),c=u.vectorComponentsNotAffected;if(l=u.desiredValue,0===s.length){let f=[];return o>0?f.push({setDependency:"expressionWithCodes",desiredValue:l}):f.push({setDependency:"valueShadow",desiredValue:l}),{success:!0,instructions:f}}let p=await getExpressionPieces({expression:l,stateValues:n});if(!p)return{success:!1};let d=[],m=[];if(c&&await n.mathChildrenByVectorComponent){let y=await n.mathChildrenByVectorComponent;for(let g of c)y[g]&&m.push(...y[g])}let h=await n.mathChildrenWithCanBeModified;for(let[b,v]of s.entries())if(n.mathChildrenMapped.has(b)&&h[b].stateValues.canBeModified){if(!m.includes(b)){let N=p[b],T={},C=!1,A=await n.constantChildIndices;for(let V in A){let x=A[V];T[V]=s[x].stateValues.value,C=!0}C&&(N=N.substitute(T)),N=N.simplify(),d.push({setDependency:"mathChildren",desiredValue:N,childIndex:b,variableIndex:0})}delete p[b]}if(o>0){let S=t.expressionWithCodes,w=t.codePre,E=w.length;function D(e){return"string"==typeof e&&e.substring(0,E)===w}function O(e){return Array.isArray(e)?flattenDeep(e.slice(1)).some(D):D(e)}if(vectorAndListOperators.includes(S.tree[0])&&!S.tree.slice(1).every(O)){let I=await n.inverseMaps;for(let R in p){let _=I[R];if(void 0!==_.mathChildInd)continue;let M=_.components;S=S.substitute_component(M,p[R])}d.push({setDependency:"expressionWithCodes",desiredValue:S})}}return{success:!0,instructions:d}}async function getExpressionPieces({expression:e,stateValues:t}){let n=await t.template,r=me$3.utils.match(e.tree,n);if(!(r||(r=me$3.utils.match(e.tuples_to_vectors().tree,me$3.fromAst(n).tuples_to_vectors().tree),r||(r=me$3.utils.match(e.to_intervals().tree,me$3.fromAst(n).to_intervals().tree),r||(r=me$3.utils.match(e.tuples_to_vectors().to_intervals().tree,me$3.fromAst(n).tuples_to_vectors().to_intervals().tree),r)))))return!1;let a={};for(let e in r){let n={};n[await t.codeForExpression]=r[e];let i=(await t.inverseMaps)[e];if(void 0!==i){let r=e;void 0!==i.mathChildInd&&(r=i.mathChildInd),a[r]=i.result.substitute(n),a[r]=normalizeMathExpression({value:a[r],simplify:await t.simplify,expand:await t.expand,createVectors:await t.createVectors,createIntervals:await t.createIntervals})}}return a}class Label extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveLabel:this.moveLabel.bind(this)})}static componentType="label";static renderChildren=!0;static rendererType="label";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="valueShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.forObject={createTargetComponentNames:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.valueShadow={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]})},e.hasLatex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow;return{setValue:{hasLatex:Boolean(/\\\(.*\\\)/.exec(t))}}}for(let t of e.inlineChildren)if("object"!=typeof t);else if("boolean"==typeof t.stateValues.hasLatex&&"string"==typeof t.stateValues.value&&"string"==typeof t.stateValues.text){if(t.stateValues.hasLatex)return{setValue:{hasLatex:!0}}}else if("boolean"==typeof t.stateValues.renderAsMath&&"string"==typeof t.stateValues.latex&&"string"==typeof t.stateValues.text){if(t.stateValues.renderAsMath)return{setValue:{hasLatex:!0}}}else if("string"==typeof t.stateValues.latex)return{setValue:{hasLatex:!0}};return{setValue:{hasLatex:!1}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"latex",public:!0,shadowingInstructions:{createComponentOfType:"text"}},{variableName:"value",public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"hasLatex"}}}}],returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"},hasLatex:{dependencyType:"stateVariable",variableName:"hasLatex"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow,n=t;return e.hasLatex&&(n=n.replace(/\\\(/g,""),n=n.replace(/\\\)/g,"")),{setValue:{text:n,latex:n,value:t}}}let t="",n="";for(let r of e.inlineChildren)if("object"!=typeof r){let e=r.toString();t+=e,n+=e}else"boolean"==typeof r.stateValues.hasLatex&&"string"==typeof r.stateValues.value&&"string"==typeof r.stateValues.text?(t+=r.stateValues.text,n+=r.stateValues.value):"boolean"==typeof r.stateValues.renderAsMath&&"string"==typeof r.stateValues.latex&&"string"==typeof r.stateValues.text?r.stateValues.renderAsMath?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):(t+=r.stateValues.text,n+=r.stateValues.text):"string"==typeof r.stateValues.latex?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):"string"==typeof r.stateValues.text&&(t+=r.stateValues.text,n+=r.stateValues.text);return{setValue:{text:t,latex:t,value:n}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n;if("string"==typeof e.value)n=e.value;else if("string"==typeof e.text)n=e.text;else{if("string"!=typeof e.latex)return{success:!1};n=e.latex}if(0===t.inlineChildren.length&&null!==t.valueShadow)return{success:!0,instructions:[{setDependency:"valueShadow",desiredValue:n}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0],r=e.value;if("object"!=typeof n)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0}]};if("boolean"==typeof n.stateValues.hasLatex&&"string"==typeof n.stateValues.value&&"string"==typeof n.stateValues.text)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:2}]};if("boolean"==typeof n.stateValues.renderAsMath&&"string"==typeof n.stateValues.latex&&"string"==typeof n.stateValues.text){if(n.stateValues.renderAsMath){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}}if("string"==typeof n.stateValues.latex){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}:{success:!1}}return{success:!1}}},e.forObjectComponentName={returnDependencies:()=>({forObject:{dependencyType:"attributeTargetComponentNames",attributeName:"forObject"}}),definition({dependencyValues:e}){let t;return t=1===e.forObject?.length?e.forObject[0].absoluteName:null,{setValue:{forObjectComponentName:t}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=["text"];async moveLabel({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function returnGroupIntoComponentTypeSeparatedBySpaces({componentType:e,forceComponentType:t=!1}){return function({matchedChildren:n,componentInfoObjects:r}){let a=[],i=[];function s(){let n=!1;if(t){if(1===i.length){let t=i[0],s=t.componentType;"copy"===s&&t.attributes?.createComponentOfType&&(t.attributes.nComponents&&1!==t.attributes.nComponents.primitive||(s=t.attributes.createComponentOfType.primitive)),r.isInheritedComponentType({inheritedComponentType:s,baseComponentType:e})&&(a.push(t),n=!0)}}else 1===i.length&&"string"!=typeof i[0]&&(a.push(i[0]),n=!0);!n&&i.length>0&&a.push({componentType:e,children:i}),i=[]}for(let e of n)if("string"!=typeof e)i.push(e);else{let t=e.split(/\s+/),n=t[0];""===n?s():i.push(n);for(let e of t.slice(1))s(),""!==e&&i.push(e)}return s(),{success:!0,newChildren:a}}}function returnBreakStringsIntoComponentTypeBySpaces({componentType:e}){return function({matchedChildren:t}){let n=t.reduce((function(t,n){return"string"==typeof n?[...t,...n.split(/\s+/).filter((e=>e)).map((t=>({componentType:e,children:[t]})))]:[...t,n]}),[]);return{success:!0,newChildren:n}}}class MathList extends InlineComponent{static componentType="mathList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="maths";static primaryStateVariableForDefinition="mathsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.mergeMathLists={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"math"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"math"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"mathLists",componentTypes:["mathList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{mathsShadow:!0}})},e.mergeMathLists={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({mergeMathListsAttr:{dependencyType:"attributeComponent",attributeName:"mergeMathLists",variableNames:["value"]},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],skipComponentNames:!0},mathChildren:{dependencyType:"child",childGroups:["maths"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{mergeMathLists:e.mergeMathListsAttr?.stateValues.value||0===e.mathListChildren.length&&1===e.mathChildren.length}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["mergeMathLists"],additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies({stateValues:e}){let t={maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}};return e.mergeMathLists?t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","nComponents"],variablesOptional:!0}:(t.mathListChildren={dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0}),t},definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.mathAndMathListChildren.length>0)if(e.mergeMathLists)for(let[a,i]of e.mathAndMathListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})){for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.maths={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["math"],stateVariablesDeterminingDependencies:["mergeMathLists","childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","math"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].mathAndMathListChildren[0];if(n)if(void 0!==n.stateValues.value){let t=n.stateValues.value;if(e.mergeMathLists&&Array.isArray(t.tree)&&"list"===t.tree[0]){let n=e.childIndexByArrayKey[a][1];r[a]=t.get_component(n)}else r[a]=t}else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["math"+t]}else null!==e.mathsShadow&&(r[a]=e.mathsShadow[a])}return{setValue:{maths:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.mergeMathLists){let t=[],s=await a.childIndexByArrayKey,o=[];for(let l in e.maths){if(!n[l])continue;if(o.includes(l))continue;let u;if(void 0!==s[l][2]){let t=Number(l)-s[l][1],n=t+s[l][2]-1;i.desiredMaths||(i.desiredMaths=[]);let r=["list"];for(let s=t;s<=n;s++)void 0!==e.maths[s]?i.desiredMaths[s]=convertValueToMathExpression(e.maths[s]):void 0===i.desiredMaths[s]&&(i.desiredMaths[s]=(await a.maths)[s]),r.push(i.desiredMaths[s].tree),o.push(s.toString());u=me$3.fromAst(r)}else u=e.maths[l];let c=n[l].mathAndMathListChildren[0];c&&(void 0!==c.stateValues.value?t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:0}):t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:1}))}return{success:!0,instructions:t}}let s=[];for(let t in e.maths){if(!n[t])continue;let a=n[t].mathAndMathListChildren[0];a&&(void 0!==a.stateValues.value?s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:0}):s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:s}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({maths:{dependencyType:"stateVariable",variableName:"maths"}}),definition({dependencyValues:e}){let t;return t=0===e.maths.length?me$3.fromAst("_"):1===e.maths.length?e.maths[0]:me$3.fromAst(["list",...e.maths.map((e=>e.tree))]),{setValue:{math:t}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"maths"},e.latex={additionalStateVariablesDefined:["latexs"],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","latex","latexs"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.mathAndMathListChildren.length>0)for(let t of e.mathAndMathListChildren)if(t.stateValues.valueForDisplay){let a=t.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(a.tree)&&"list"===a.tree[0])for(let e=0;eroundForDisplay({value:n,dependencyValues:e,usedDefault:t}).toLatex(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{latex:n.join(", "),latexs:n}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}}),definition:function({dependencyValues:e}){let t=[];if(e.mathAndMathListChildren.length>0)for(let n of e.mathAndMathListChildren)if(n.stateValues.valueForDisplay){let r=n.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(r.tree)&&"list"===r.tree[0])for(let e=0;ee.toString())));let n=e.maximumNumber;return null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),{setValue:{text:t.join(", "),texts:t}}}},e.componentNamesInList={returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.mathAndMathListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"mathList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.mathAndMathListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"mathList"})){let t=e.mathListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Columns extends Text{static componentType="columns";static rendererType="text"}class Title extends TextOrInline{static componentType="title"}class RightHandSide extends MathComponent{static componentType="rightHandSide";static rendererType="math"}class Description extends TextOrInline{static componentType="description";static rendererType=void 0}class Else extends Template{static componentType="else"}class Xlabel extends Label{static componentType="xlabel";static rendererType="label"}class Ylabel extends Label{static componentType="ylabel";static rendererType="label"}class MatrixRow extends MathList{static componentType="matrixRow";static rendererType="mathList"}class MatrixColumn extends MathList{static componentType="matrixColumn";static rendererType="mathList"}var Aliases=Object.freeze({__proto__:null,Columns:Columns,Title:Title,RightHandSide:RightHandSide,Description:Description,Else:Else,Xlabel:Xlabel,Ylabel:Ylabel,MatrixRow:MatrixRow,MatrixColumn:MatrixColumn});class M$3 extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="m";static rendererType="math";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length)return{useEssentialOrDefaultValue:{latex:!0}};let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n:"string"==typeof n.stateValues.latex?t+=n.stateValues.latex:"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{latex:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.latex)return{success:!1};if(0===t.inlineChildren.length)return{success:!0,instructions:[{setEssentialValue:"latex",value:e.latex}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0];return"object"!=typeof n?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0}]}:"string"==typeof n.stateValues.latex?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:0}]}:"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:1}]}:{success:!1}}return{success:!1}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.inlineChildren.length)return{setValue:{latexWithInputChildren:[e.latex]}};let n=[],r="",a=0;for(let i of e.inlineChildren)"object"!=typeof i?r+=i:t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"input"})?(r.length>0&&(n.push(r),r=""),n.push(a),a++):"string"==typeof i.stateValues.latex?r+=i.stateValues.latex:"string"==typeof i.stateValues.text&&(r+=i.stateValues.text);return r.length>0&&n.push(r),{setValue:{latexWithInputChildren:n}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"inline"}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=me$3.fromAst(latexToAst.convert(e.latex))}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Me$2 extends M$3{static componentType="me";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e}}class Men extends M$3{static componentType="men";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"numbered"}}),e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({equationCounter:{dependencyType:"counter",counterName:"equation"}}),definition:({dependencyValues:e})=>({setValue:{equationTag:String(e.equationCounter)}})},e}}var MMeMen=Object.freeze({__proto__:null,M:M$3,Me:Me$2,Men:Men});class Md extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="md";static rendererType="math";static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"mrows",componentTypes:["mrow"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.mrowChildNames={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"]}}),definition:({dependencyValues:e})=>({setValue:{mrowChildNames:e.mrowChildren.map((e=>e.componentName))}})},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,shadowVariable:!0,forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latex","hide","equationTag","numbered"]}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t="";for(let n of e.mrowChildren)n.stateValues.hide||(t.length>0&&(t+="\\\\"),n.stateValues.numbered?t+=`\\tag{${n.stateValues.equationTag}}`:t+="\\notag ",t+=n.stateValues.latex);return{setValue:{latex:t}}}return{useEssentialOrDefaultValue:{latex:!0}}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latexWithInputChildren","hide","equationTag","numbered"]},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t=[],n=0,r="";for(let a of e.mrowChildren)if(!a.stateValues.hide){r.length>0&&(r+="\\\\"),a.stateValues.numbered?r+=`\\tag{${a.stateValues.equationTag}}`:r+="\\notag ";for(let e of a.stateValues.latexWithInputChildren)"number"==typeof e?(r.length>0&&(t.push(r),r=""),t.push(n),n++):r+=e}return r.length>0&&t.push(r),{setValue:{latexWithInputChildren:t}}}return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=e.latex.replaceAll("\\notag","").replaceAll("\\amp","").split("\\\\").map((e=>me$3.fromAst(latexToAst.convert(e)).toString())).join("\\\\\n")}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"align"}})},e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Mdn extends Md{static componentType="mdn";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e}}class Mrow extends M$3{static componentType="mrow";static createAttributesObject(){let e=super.createAttributesObject();return e.number={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e.numbered={forRenderer:!0,returnDependencies:()=>({parentNumbered:{dependencyType:"parentStateVariable",variableName:"numbered"},numberAttr:{dependencyType:"attributeComponent",attributeName:"number",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=null!==e.numberAttr?e.numberAttr.stateValues.value:e.parentNumbered,{setValue:{numbered:t}}}},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["numbered"],returnDependencies:({stateValues:e})=>e.numbered?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e}}var MdMdnMrow=Object.freeze({__proto__:null,Md:Md,Mdn:Mdn,Mrow:Mrow});function periodicSetEquality(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_periodic_set(e))return!1;if(is_periodic_set(t)){if(r){let n=contained_in(e.tree,t.tree,r);if(!1===n)return 0;let a=contained_in(t.tree,e.tree,r);return!1===a?0:!0===n?!0===a?1:a:!0===a?n:Math.min(n,a)}return contained_in(e.tree,t.tree,r)&&contained_in(t.tree,e.tree,r)}{let a=e.tree.slice(1);if(a.length>1)return!1;let i=me$3.fromAst(a[0][1]).evaluate_to_constant(),s=me$3.fromAst(["apply","abs",a[0][2]]).evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return!1;let o=a[0][3],l=a[0][4];if(o!==-1/0||l!==1/0)return!1;if("list"!==t.tree[0])return!1;let u=t.tree.slice(1),c=0;if("ldots"===u[0][0])c++,u=u.slice(1);else if(!r)return!1;if("ldots"===u[u.length-1][0])c++,u=u.slice(0,u.length-1);else if(!r)return!1;let p=u.length;if(0===p)return!1;if(!r&&pme$3.fromAst(e).evaluate_to_constant())).map((e=>Number.isFinite(e)?e:NaN));let d=me$3.math.mod(u[0]-i,s);if(!(me$3.math.min(d,s-d)<1e-10*s))return!1;let m=1;for(let e=1;e=n)return!0;let h=m/Math.max(p,n);return h*=(9+c/2)/10,h}}function is_periodic_set(e){var t=e.tree;if(!Array.isArray(t))return!1;if("periodic_set"!==t[0])return!1;var n=t.slice(1);for(var r of n){if(!Array.isArray(r))return!1;if("tuple"!==r[0])return!1;if(5!==r.length)return!1}return!0}function contained_in(e,t,n){if("periodic_set"===e[0]){if(n){let r=0;for(let a of e.slice(1)){let e=contained_in(a,t,n);!0===e?r++:!1!==e&&(r+=e)}let a=e.length-1;return r===a||0!==r&&r/a}return e.slice(1).every((e=>contained_in(e,t)))}var r=e[1],a=e[2],i=e[3],s=e[4];if(i!==-1/0||s!==1/0)return!1;r=me$3.fromAst(["/",r,a]).evaluate_to_constant();var o=t.slice(1),l=[];for(let e=0;e1e3)return!1;let c=s.d;l.push([u,c,r,i])}for(l.sort();;){if(1!==l[0][0])break;let e=l[0][2],t=l[0][3],n=me$3.fromAst(["+",e,["-",r]]).evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t)&&(n=me$3.math.mod(n,t),me$3.math.min(n,t-n)<1e-10*t))return!0;if(l.splice(0,1),0===l.length)return!1}var u=[...new Set(l.map((e=>e[0])))];let c=0;for(let e of u){let t=l.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),a=[];for(let n of t){let t=n[0],i=n[1],s=n[2],o=l[s][2],u=l[s][3];for(let n=0;nc&&(c=t)}}return!!(n&&c>0)&&c}const nonTupleVectorOperators=["vector","altvector"];function checkEquality({object1:e,object2:t,isUnordered:n=!1,partialMatches:r=!1,matchByExactPositions:a=!1,symbolicEquality:i=!1,simplify:s="none",expand:o=!1,allowedErrorInNumbers:l=0,includeErrorInNumberExponents:u=!1,allowedErrorIsAbsolute:c=!1,nSignErrorsMatched:p=0,nPeriodicSetMatchesRequired:d=3,caseInsensitiveMatch:m=!1,matchBlanks:h=!1}){let f=!1;if(e instanceof me$3.class){if(f=!0,!(t instanceof me$3.class)){if("number"!=typeof t&&"string"!=typeof t)return{fraction_equal:0};t=me$3.fromAst(t)}}else if(t instanceof me$3.class){if(f=!0,"number"!=typeof e&&"string"!=typeof e)return{fraction_equal:0};e=me$3.fromAst(e)}let y,g=function(e,t=!1){e instanceof me$3.class||(e=me$3.fromAst(e)),e=e.normalize_function_names().normalize_applied_functions(),m&&(e=me$3.fromAst(setStringsInTreeToLowerCase(e.tree)));let n=s,r=o;return t&&(n="full",r=!0),"none"===n?l>0&&(e=e.constants_to_floats()):e="numberspreserveorder"===n?e.evaluate_numbers({max_digits:1/0,skip_ordering:!0}):"number"===n?e.evaluate_numbers({max_digits:1/0}):e.evaluate_numbers({max_digits:1/0,evaluate_functions:!0}),normalizeMathExpression({value:e,simplify:n,expand:r})};y=f?i?function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return!e.variables().includes("_")&&!t.variables().includes("_")&&(e=g(e)).equalsViaSyntax(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.variables().includes("_")||r.variables().includes("_"))return{fraction_equal:0};if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equalsViaSyntax(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),m&&(n=me$3.fromAst(setStringsInTreeToLowerCase(n.tree)),r=me$3.fromAst(setStringsInTreeToLowerCase(r.tree))),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return e.equals(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equals(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:(e,t)=>(m&&(e=convertStringsToLowerCase(e),t=convertStringsToLowerCase(t)),{fraction_equal:deepCompare(e,t)?1:0});let b=!1,v=!1;if(f){e=g(e,!i),t=g(t,!i);let s=e.tree[0],o=t.tree[0];if("periodic_set"===s||"periodic_set"===o){let n=e,a=t;"periodic_set"!==s&&(n=t,a=e);let i=periodicSetEquality(n,a,{match_partial:r,min_elements_match:d});return!0===i?{fraction_equal:1}:!1===i?{fraction_equal:0}:{fraction_equal:i}}if("list"===s)e=e.tree.slice(1),t="list"===o?t.tree.slice(1):[t.tree];else if("list"===o)t=t.tree.slice(1),e=[e.tree];else if(nonTupleVectorOperators.includes(s)){if(e=e.tree.slice(1),"interval"===o||"matrix"===o||"array"===o||"set"===o)return{fraction_equal:0};t=vectorOperators.includes(o)?t.tree.slice(1):[t.tree]}else if(nonTupleVectorOperators.includes(o)){if(t=t.tree.slice(1),"interval"===s||"matrix"===s||"array"===s||"set"===s)return{fraction_equal:0};e="tuple"===s?e.tree.slice(1):[e.tree]}else if("interval"===s){a=!0;let n=e.tree[2],r=n[1],i=n[2];if(e=e.tree[1].slice(1),"matrix"===o||"set"===o)return{fraction_equal:0};if("tuple"===o){let e=t.tree.slice(1);if(2!==e.length||!1!==r||!1!==i)return{fraction_equal:0};t=e}else if("array"===o){let e=t.tree.slice(1);if(2!==e.length||!0!==r||!0!==i)return{fraction_equal:0};t=e}else{if("interval"!==o)return{fraction_equal:0};{let e=t.tree[2];if(e[1]!==r||e[2]!==i)return{fraction_equal:0};t=t.tree[1].slice(1)}}}else if("interval"===o){a=!0;let n=t.tree[2],r=n[1],i=n[2];if(t=t.tree[1].slice(1),"matrix"===s||"set"===s)return{fraction_equal:0};if("tuple"===s){let t=e.tree.slice(1);if(2!==t.length||!1!==r||!1!==i)return{fraction_equal:0};e=t}else{if("array"!==s)return{fraction_equal:0};{let t=e.tree.slice(1);if(2!==t.length||!0!==r||!0!==i)return{fraction_equal:0};e=t}}}else if("matrix"===s){if("matrix"!==o)return{fraction_equal:0};e=convertMatrixToArrayOfTuples(e.tree.slice(1)),t=convertMatrixToArrayOfTuples(t.tree.slice(1)),a=!0,v=!0,b=!0}else{if("matrix"===o)return{fraction_equal:0};if("set"===s){let r=[];for(let t of e.tree.slice(1))r.some((e=>1===y(e,t).fraction_equal))||r.push(t);if(e=r,n=!0,"tuple"===o||"array"===o)return{fraction_equal:0};if("set"===o){r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);t=r}else t=[t.tree]}else if("set"===o){let r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);if(t=r,n=!0,"tuple"===s||"array"===s)return{fraction_equal:0};e=[e.tree]}else if("tuple"===s){if(e=e.tree.slice(1),"array"===o)return{fraction_equal:0};t="tuple"===o?t.tree.slice(1):[t.tree]}else if("tuple"===o){if(t=t.tree.slice(1),"array"===s)return{fraction_equal:0};e=[e.tree]}else if("array"===s)e=e.tree.slice(1),t="array"===o?t.tree.slice(1):[t.tree];else{if("array"!==o)return y(e.tree,t.tree);t=t.tree.slice(1),e=[e.tree]}}}else if(Array.isArray(e))Array.isArray(t)||(t="string"==typeof t&&e.every((e=>"string"==typeof e&&!e.includes(",")))?t.split(",").map((e=>e.trim())):[t]);else{if(!Array.isArray(t))return y(e,t);e="string"==typeof e&&t.every((e=>"string"==typeof e&&!e.includes(",")))?e.split(",").map((e=>e.trim())):[e]}let N=e.length,T=t.length,C={fraction_equal:0};if(a&&(n=!1),!n){let n=0,u=Math.min(N,T);for(let r=0;rArray(T+1).fill(0)));for(let n=0;nr&&(r=t.fraction_equal,e=a)}-1!==e&&(V+=r,A.add(e))}return N===T&&N===V?(C.fraction_equal=1,C):r?(C.fraction_equal=V/Math.max(N,T),C):C}function setStringsInTreeToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?[e[0],...e.slice(1).map(setStringsInTreeToLowerCase)]:e}function convertStringsToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?e.map(convertStringsToLowerCase):e}function convertMatrixToArrayOfTuples(e){let t=e[0][1],n=e[0][2];if(!Number.isInteger(t)||!Number.isInteger(n))return e;let r=[];for(let a=0;aevaluateLogic({logicTree:e,canOverrideUnorderedCompare:t,dependencyValues:n,valueOnInvalid:r});if(!Array.isArray(e)){if("string"==typeof e){let t=n.booleanChildrenByCode[e];if(t)return n.matchPartial&&void 0!==t.stateValues.fractionSatisfied?t.stateValues.fractionSatisfied:t.stateValues.value?1:0;{let t=n.mathChildrenByCode[e];if(t){let e=t.stateValues.value.simplify().evaluate_to_constant();return Number.isFinite(e)&&0!==e?1:0}{let t=n.numberChildrenByCode[e];if(t){let e=t.stateValues.value;return Number.isFinite(e)&&0!==e?1:0}if("true"===e.toLowerCase())return 1;if("false"===e.toLowerCase())return 0}}}else if("number"==typeof e)return 0===e?0:1;return console.warn("Invalid format for boolean condition"),r}let i=e[0],s=e.slice(1);if("not"===i)return 1!==s.length?(console.warn("Invalid format for boolean condition"),r):0===a(s[0])?1:0;if("and"===i)return n.matchPartial?s.reduce(((e,t)=>e+a(t)),0)/s.length:s.every((e=>1===a(e)))?1:0;if("or"===i)return n.matchPartial?s.reduce(((e,t)=>Math.max(a(t),e)),0):s.some((e=>1===a(e)))?1:0;let o=!1,l=!1,u=!1,c=!1;s.forEach((function(e){"string"==typeof e&&(e in n.mathChildrenByCode||e in n.mathListChildrenByCode||e in n.numberChildrenByCode||e in n.numberListChildrenByCode?o=!0:e in n.textChildrenByCode||e in n.textListChildrenByCode?l=!0:e in n.booleanChildrenByCode||e in n.booleanListChildrenByCode?u=!0:e in n.otherChildrenByCode&&(c=!0))}));let p,d=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?t.stateValues.value.tree:(t=n.mathListChildrenByCode[e],void 0!==t?["list",...t.stateValues.maths.map((e=>e.tree))]:(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?["list",...t.stateValues.numbers]:e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(d)]:e};if("apply"===i&&["isnumber","isinteger"].includes(s[0])){if(l||u||c)return 0;let e=me$3.fromAst(d(s[1])).simplify().evaluate_to_constant();if(!Number.isFinite(e))return 0;if("isnumber"===s[0])return 1;{let t=Math.round(e);return Math.abs(t-e)<=1e-15*Math.abs(e)?1:0}}if(!["=","ne","<",">","le","ge","lts","gts","in","notin"].includes(i)){if(l||u||c)return console.warn("Invalid format for boolean condition"),r;let t=me$3.fromAst(d(e)).simplify().evaluate_to_constant();return Number.isFinite(t)&&0!==t?1:0}if(u){if(o||l||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1;if(s=s.map((function(t){if("string"==typeof t){let i=n.booleanChildrenByCode[t];return void 0!==i?i.stateValues.value:(i=n.booleanListChildrenByCode[t],void 0!==i?(i.stateValues.unordered&&(a=!0),i.stateValues.booleans):"true"===(t=t.toLowerCase().trim())||"t"===t||"false"!==t&&"f"!==t&&(console.warn("Invalid format for boolean condition"),e=!0,r))}return console.warn("Invalid format for boolean condition"),e=!0,r})),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),r;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(l){if(o||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1,l=function(t,r=!1){if("string"==typeof t){let e=n.textChildrenByCode[t];return void 0!==e?e.stateValues.value.trim().replace(/\s+/," "):(e=n.textListChildrenByCode[t],void 0!==e?(e.stateValues.unordered&&(a=!0),e.stateValues.texts.map((e=>e.trim().replace(/\s+/," ")))):t.trim())}return"number"==typeof t?t.toString():r&&Array.isArray(t)&&"*"===t[0]?t.slice(1).map(l).join(" "):(console.warn("Invalid format for boolean condition"),e=!0,"")};if(s=s.map((e=>l(e,!0))),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),0;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(c){if(o)return console.warn("Invalid format for boolean condition"),r;let e=!1;return s=s.map((function(t){if("string"==typeof t){let e=n.otherChildrenByCode[t];if(void 0!==e)return e.stateValues.value}return console.warn("Invalid format for boolean condition"),e=!0,null})),e?r:"="===i?s.slice(1).every((e=>deepCompare(e,s[0])))?1:0:"ne"===i?2!==s.length?(console.warn("Invalid format for boolean condition"),0):deepCompare(s[0],s[1])?0:1:(console.warn("Invalid format for boolean condition"),0)}"lts"!==i&&"gts"!==i||(p=s[1].slice(1),s=s[0].slice(1));let m=!1,h=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?(t.stateValues.unordered&&(m=!0),t.stateValues.value.tree):(t=n.mathListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.maths.map((e=>e.tree))]):(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.numbers]):e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(h)]:e},f=s.map((function(e){return me$3.fromAst(h(e))})),y=n.unorderedCompare;if(t&&m&&(y=!0),"="===i){let e=f[0];if(Number.isNaN(e.tree))return f.slice(1).every((e=>Number.isNaN(e.tree)))?1:0;if(n.matchPartial){let t=f.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return f.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal))?1:0}if("ne"===i){return 0===checkEquality({object1:f[0],object2:f[1],isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal?1:0}if("in"===i||"notin"===i){let e=f[0],t=f[1].tree;if(!Array.isArray(t)||"set"!==t[0])return console.warn("Invalid format for boolean condition"),r;if(n.matchPartial){let r=t.slice(1).map((t=>checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),a=r.reduce(((e,t)=>Math.max(e,t.fraction_equal)),0);return"in"===i?a:1-a}{let r=t.slice(1).some((t=>1===checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal));return"in"===i?r?1:0:r?0:1}}let g=f.map((e=>e.simplify().evaluate_to_constant()));if(g.some((e=>null===e||Number.isNaN(e))))return 0;if("<"===i)return g[0]"===i)return g[0]>g[1]?1:0;if("le"===i)return g[0]<=g[1]?1:0;if("ge"===i)return g[0]>=g[1]?1:0;for(let e=0;eg[e+1]))return 0}else if(!(g[e]>=g[e+1]))return 0;return 1}function splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n=!1,init:r=!0}){if(!Array.isArray(e))return"string"!=typeof e||n||r?e:fromTextSplit(e).tree;let a=e[0],i=e.slice(1);if(["and","not","or"].includes(a))return[a,...i.map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:r})))];if(i.some((e=>t.includes(e)))&&(n=!0),"apply"===a){i=[i[0],...i.slice(1).map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))];let e=!1;if("int"===i[0]?e=!0:Array.isArray(i[0])&&("^"===i[0][0]?("int"===i[0][1]||Array.isArray(i[0][1])&&"_"===i[0][1][0]&&"int"===i[0][1][1])&&(e=!0):"_"===i[0][0]&&"int"===i[0][1]&&(e=!0)),e){i=me$3.fromAst([a,...i]).tree.slice(1);let e=i[1];if(Array.isArray(e)&&"*"===e[0]){let t=[];for(let n=0;nsplitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))]}class BooleanComponent extends InlineComponent{static componentType="boolean";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numbersepreserveorder"],public:!0},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"comparableTypes",componentTypes:["math","mathList","number","numberList","text","textList","boolean","booleanList","orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["mathListChildrenByCode","numberChildrenByCode","numberListChildrenByCode","textChildrenByCode","textListChildrenByCode","booleanChildrenByCode","booleanListChildrenByCode","otherChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value","texts","maths","numbers","booleans","fractionSatisfied","unordered"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s={},o={},l={},u={},c={},p=0,d=e.codePre;for(let m of e.allChildren)if("string"!=typeof m){let e=d+p;t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"math"})?n[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"mathList"})?r[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"number"})?a[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"numberList"})?i[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"text"})?s[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"textList"})?o[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"boolean"})?l[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"booleanList"})?u[e]=m:c[e]=m,p+=1}return{setValue:{mathChildrenByCode:n,mathListChildrenByCode:r,numberChildrenByCode:a,numberListChildrenByCode:i,textChildrenByCode:s,textListChildrenByCode:o,booleanChildrenByCode:l,booleanListChildrenByCode:u,otherChildrenByCode:c}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean",attributesToShadow:["fixed"]},forRenderer:!0,hasEssential:!0,defaultValue:!1,set:Boolean,returnDependencies:()=>({symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(0===e.allChildren.length)return{useEssentialOrDefaultValue:{value:!0}};if(null===e.parsedExpression)return{setValue:{value:!1}};let n=t.unorderedCompare;return{setValue:{value:1===evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e})}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.allChildren.length)return{success:!0,instructions:[{setEssentialValue:"value",value:Boolean(e.value)}]};if(1===t.allChildren.length){let r=t.allChildren[0];if("string"==typeof r)return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value.toString(),childIndex:0,variableIndex:0}]};if(n.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"boolean"}))return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}}return{success:!1}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=String(e.text).toLowerCase();return"true"===n?t=!0:"false"===n&&(t=!1),void 0!==t?{success:!0,instructions:[{setDependency:"value",desiredValue:t}]}:{success:!1}}},e}static adapters=["text"]}class BooleanOperator extends BooleanComponent{static componentType="_booleanOperator";static rendererType="boolean";static descendantCompositesMustHaveAReplacement=!1;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"boolean",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();delete e.parsedExpression,delete e.mathChildrenByCode;let t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({booleanChildren:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.booleanChildren.map((e=>e.stateValues.value)))}}}},e}}class BooleanOperatorOneInput extends BooleanComponent{static componentType="_booleanOperatorOneInput";static rendererType="boolean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreOperator"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"valuePreOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.value)}}}},e}}class Not extends BooleanOperatorOneInput{static componentType="not";static applyBooleanOperator(e){return!e}}class And extends BooleanOperator{static componentType="and";static applyBooleanOperator(e){return e.every((e=>e))}}class Or$1 extends BooleanOperator{static componentType="or";static applyBooleanOperator(e){return e.some((e=>e))}}class Xor extends BooleanOperator{static componentType="xor";static applyBooleanOperator(e){return 1===e.reduce(((e,t)=>e+t),0)}}var BooleanOperators=Object.freeze({__proto__:null,Not:Not,And:And,Or:Or$1,Xor:Xor});class BooleanBaseOperatorOfMath extends BooleanComponent{static componentType="_booleanOperatorOfMath";static rendererType="boolean";static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.booleanOperator={returnDependencies:()=>({}),definition:()=>({setValue:{booleanOperator:e=>!1}})},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},booleanOperator:{dependencyType:"stateVariable",variableName:"booleanOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:e.booleanOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class IsInteger extends BooleanBaseOperatorOfMath{static componentType="isInteger";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsInteger requires exactly one math child"),null;let t=e[0].evaluate_to_constant();if(!Number.isFinite(t))return!1;let n=Math.round(t);return Math.abs(n-t)<=1e-15*Math.abs(t)}}}),e}}class IsNumber extends BooleanBaseOperatorOfMath{static componentType="isNumber";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsNumber requires exactly one math child"),null;let t=e[0].evaluate_to_constant();return Number.isFinite(t)}}}),e}}class IsBetween extends BooleanBaseOperatorOfMath{static componentType="isBetween";static createAttributesObject(){let e=super.createAttributesObject();return e.limits={createComponentOfType:"numberList",createStateVariable:"limits",defaultValue:[],public:!0},e.strict={createComponentOfType:"boolean",createStateVariable:"strict",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator={returnDependencies:()=>({limits:{dependencyType:"stateVariable",variableName:"limits"},strict:{dependencyType:"stateVariable",variableName:"strict"}}),definition({dependencyValues:e}){let t,n,r=e.limits[0],a=e.limits[1];if(r!1}};n=a,t=r}let i=e.strict;return{setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsBetween requires exactly one math child"),null;let r=e[0].evaluate_to_constant();return i?r>n&&r=n&&r<=t}}}}},e}}var BooleanOperatorsOfMath=Object.freeze({__proto__:null,IsInteger:IsInteger,IsNumber:IsNumber,IsBetween:IsBetween});class MathOperator extends MathComponent{static componentType="_mathOperator";static rendererType="math";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:Number.isFinite(Number(e))?"number":"math",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDigits"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDigitsAttr?{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}}:null!==e.displayDecimalsAttr||1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDigits?{useEssentialOrDefaultValue:{displayDigits:!0}}:{setValue:{displayDigits:e.mathLikeChildren[0].stateValues.displayDigits}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.mathLikeChildren[0].stateValues.displayDecimals}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.mathLikeChildren[0].stateValues.displaySmallAsZero}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.mathLikeChildren[0].stateValues.padZeros}}},e.isNumericOperator={returnDependencies:()=>({forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["isNumber"],variablesOptional:!0},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths"]}}),definition({dependencyValues:e}){let t;return t=!!e.forceNumeric||!e.forceSymbolic&&(0===e.mathChildren.length&&0===e.mathListChildren.length||e.mathChildren.every((e=>e.stateValues.isNumber))&&e.mathListChildren.every((e=>e.stateValues.maths.every((e=>Number.isFinite(e.tree)))))),{setValue:{isNumericOperator:t}}}},delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me$3.fromAst("_")}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:e=>me$3.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:null}})},e.unnormalizedValue={returnDependencies:()=>({mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["value","maths","numbers","canBeModified"],variablesOptional:!0},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},numericOperator:{dependencyType:"stateVariable",variableName:"numericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.mathNumberChildren.length)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};if(e.isNumericOperator){let n=[];for(let r of e.mathNumberChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})){let e=r.stateValues.value.evaluate_to_constant();Number.isFinite(e)||(e=NaN),n.push(e)}else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"}))n.push(...r.stateValues.numbers);else{let e=r.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));n.push(...e)}return{setValue:{unnormalizedValue:me$3.fromAst(e.numericOperator(n))}}}{let n=[];for(let r of e.mathNumberChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"})?n.push(me$3.fromAst(r.stateValues.value)):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})?n.push(r.stateValues.value):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.numbers.map((e=>me$3.fromAst(e)))):n.push(...r.stateValues.maths);return{setValue:{unnormalizedValue:e.mathOperator(n)}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.mathNumberChildren.length)return{success:!1};if(t.isNumericOperator){if(t.inverseNumericOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"}))r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e);else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})){let t=s.stateValues.value.evaluate_to_constant();Number.isFinite(t)||(t=NaN),r.push(t),a.push(s.stateValues.canBeModified),i.push(e)}else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"}))r.push(...s.stateValues.numbers),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN));else{let t=s.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));r.push(...t),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN))}let s=t.inverseNumericOperator({desiredValue:e.unnormalizedValue.evaluate_to_constant(),inputs:r,canBeModified:a,desiredMathValue:e.unnormalizedValue});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}if(t.inverseMathOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"})?(r.push(me$3.fromAst(s.stateValues.value)),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})?(r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})?(r.push(...s.stateValues.numbers.map((e=>me$3.fromAst(e)))),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN))):(r.push(...s.stateValues.maths),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN)));let s=t.inverseMathOperator({desiredValue:e.unnormalizedValue,inputs:r,canBeModified:a});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}},e.canBeModified={returnDependencies:()=>({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers"],variableNames:["canBeModified"]},mathNumberListChildren:{dependencyType:"child",childGroups:["mathLists","numberLists"],variableNames:["nComponents"]},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e}){let t=e.modifyIndirectly&&!e.fixed&&Boolean(e.isNumericOperator?e.inverseNumericOperator:e.inverseMathOperator);if(t&&e.mathNumberChildren.length+e.mathNumberListChildren.length>0){let n=e.mathNumberChildren.filter((e=>e.stateValues.canBeModified)).length+e.mathNumberListChildren.reduce(((e,t)=>e+t.stateValues.nComponents),0);1!==n&&(t=!1)}return{setValue:{canBeModified:t}}}},e}}class MathOperatorOneInput extends MathComponent{static componentType="_mathOperatorOneInput";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreOperator"}),e.unnormalizedValue={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"unnormalizedValuePreOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"}}),definition:function({dependencyValues:e}){return{setValue:{unnormalizedValue:e.mathOperator(e.value)}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentName:n}){if(t.inverseMathOperator){return{success:!0,instructions:[{setDependency:"value",desiredValue:t.inverseMathOperator(e.unnormalizedValue)}]}}return{success:!1}}},renameStateVariable({stateVariableDefinitions:e,oldName:"canBeModified",newName:"canBeModifiedPreOperator"}),e.canBeModified={returnDependencies:()=>({canBeModifiedPreOperator:{dependencyType:"stateVariable",variableName:"canBeModifiedPreOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"}}),definition:function({dependencyValues:e}){let t=e.canBeModifiedPreOperator;return e.inverseMathOperator||(t=!1),{setValue:{canBeModified:t}}}},e}}class Sum extends MathOperator{static componentType="sum";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e+t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t)))}}})},e}}class Product extends MathOperator{static componentType="product";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e*t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.multiply(t)))}}})},e}}class ClampNumber extends MathOperatorOneInput{static componentType="clampNumber";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function clamp({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?me$3.fromAst(Math.max(t,Math.min(n,r))):me$3.fromAst(NaN)}class WrapNumberPeriodic extends MathOperatorOneInput{static componentType="wrapNumberPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function makePeriodic({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?t===n?me$3.fromAst(t):(t>n&&([n,t]=[t,n]),me$3.fromAst(t+me$3.math.mod(r-t,n-t))):me$3.fromAst(NaN)}class Round extends MathOperatorOneInput{static componentType="round";static createAttributesObject(){let e=super.createAttributesObject();return e.numberDecimals={createComponentOfType:"number",createStateVariable:"numberDecimals",defaultValue:0,public:!0},e.numberDigits={createComponentOfType:"number",createStateVariable:"numberDigits",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({numberDecimals:{dependencyType:"stateVariable",variableName:"numberDecimals"},numberDigits:{dependencyType:"stateVariable",variableName:"numberDigits"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){let n=t.evaluate_numbers({max_digits:1/0,evaluate_functions:!0});return null!==e.numberDigits?n.round_numbers_to_precision(e.numberDigits):n.round_numbers_to_decimals(e.numberDecimals)}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class setSmallToZero extends MathOperatorOneInput{static componentType="setSmallToZero";static createAttributesObject(){let e=super.createAttributesObject();return e.threshold={createComponentOfType:"number",createStateVariable:"threshold",defaultValue:1e-14,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return t.evaluate_numbers({skip_ordering:!0,set_small_zero:e.threshold})}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class ConvertSetToList extends MathOperatorOneInput{static componentType="convertSetToList";static createAttributesObject(){let e=super.createAttributesObject();return delete e.unordered,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.unordered={returnDependencies:()=>({}),definition:()=>({setValue:{unordered:!0}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){if(void 0!==e&&Array.isArray(e.tree)&&"set"===e.tree[0]){let t=[];for(let n of e.tree.slice(1))t.some((t=>e.context.equalsViaSyntax(e.context.fromAst(t),e.context.fromAst(n))))||t.push(n);return e.context.fromAst(["list",...t])}return e}}})},e}}class Ceil extends MathOperatorOneInput{static componentType="ceil";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","ceil",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.ceil(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Floor extends MathOperatorOneInput{static componentType="floor";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","floor",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.floor(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Abs extends MathOperatorOneInput{static componentType="abs";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.abs(t)):me$3.fromAst(["apply","abs",e.tree])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function(e){let t=e,n=e.evaluate_to_constant();return Number.isFinite(n)?n<0&&(t=me$3.fromAst(0)):Array.isArray(e.tree)&&"apply"===e.tree[0]&&"abs"===e.tree[1]&&(t=me$3.fromAst(e.tree[2])),t}}})},e}}class Sign extends MathOperatorOneInput{static componentType="sign";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.sign(t)):me$3.fromAst(["apply","sign",e.tree])}}})},e}}class Mean extends MathOperator{static componentType="mean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){let t=e.reduce(((e,t)=>e+t));return t/=e.length,t}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t))).divide(e.length)}}})},e}}class Variance extends MathOperator{static componentType="variance";static createAttributesObject(){let e=super.createAttributesObject();return e.population={createComponentOfType:"boolean",createStateVariable:"population",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{numericOperator:function(t){return calculateNumericVariance(t,e.population)}}})},e.mathOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return calculateSymbolicVariance(t,e.population)}}})},e}}function calculateNumericVariance(e,t){let n=0,r=0;for(let t of e)n+=t,r+=t*t;let a=e.length;return r-=n**2/a,r/=t?a:a-1,r}function calculateSymbolicVariance(e,t){let n=e.length,r=e.reduce(((e,t)=>e.add(t))),a=e.slice(1).reduce(((e,t)=>e.add(t.pow(2))),e[0].pow(2)).subtract(r.pow(2).divide(n));return a=t?a.divide(n):a.divide(n-1),a}class StandardDeviation extends Variance{static componentType="standardDeviation";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator.definition=({dependencyValues:e})=>({setValue:{numericOperator:function(t){return Math.sqrt(calculateNumericVariance(t,e.population))}}}),e.mathOperator.definition=({dependencyValues:e})=>({setValue:{mathOperator:function(t){return me$3.fromAst(["apply","sqrt",calculateSymbolicVariance(t,e.population).tree])}}}),e}}class Count extends MathOperator{static componentType="count";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.length}}})},e}}class Min extends MathOperator{static componentType="min";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.min(e,t)),1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","min",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Max extends MathOperator{static componentType="max";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.max(e,t)),-1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","max",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Mod extends MathOperator{static componentType="mod";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return 2!==e.length?NaN:me$3.math.mod(e[0],e[1])}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return 2!==e.length?me$3.fromAst("_"):me$3.fromAst(["apply","mod",["tuple",...e.map((e=>e.tree))]])}}})},e}}class Gcd extends MathOperator{static componentType="gcd";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.every(Number.isInteger)?gcd(...e):NaN}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","gcd",["tuple",...e.map((e=>e.tree))]])}}})},e}}class ExtractMath extends MathOperatorOneInput{static componentType="extractMath";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:null,toLowerCase:!0,validValues:["operand","function","functionargument","numberofoperands"]},e.operandNumber={createComponentOfType:"number",createStateVariable:"operandNumber",defaultValue:null,public:!0},e.argumentNumber={createComponentOfType:"number",createStateVariable:"argumentNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},operandNumber:{dependencyType:"stateVariable",variableName:"operandNumber"},argumentNumber:{dependencyType:"stateVariable",variableName:"argumentNumber"}}),definition:({dependencyValues:e})=>"operand"===e.type?null===e.operandNumber?(console.warn("Must specify a operandNumber when extracting a math operand"),{setValue:{mathOperator:e=>me$3.fromAst("_")}}):{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return 1===e.operandNumber?t:me$3.fromAst("_");if("apply"===n[0])return 1===e.operandNumber?t:me$3.fromAst("_");let r=n[e.operandNumber];return void 0===r?me$3.fromAst("_"):me$3.fromAst(r)}}}:"function"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"!==t[0]?me$3.fromAst("_"):me$3.fromAst(t[1]):me$3.fromAst("_")}}}:"functionargument"===e.type?{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return me$3.fromAst("_");if("apply"!==n[0])return me$3.fromAst("_");let r=n[2];if(null===e.argumentNumber)return me$3.fromAst(r);if(1===e.argumentNumber)return Array.isArray(r)&&"tuple"===r[0]?me$3.fromAst(r[1]):me$3.fromAst(r);if(Array.isArray(r)&&"tuple"===r[0]){let t=r[e.argumentNumber];return void 0===t?me$3.fromAst("_"):me$3.fromAst(t)}return me$3.fromAst("_")}}}:"numberofoperands"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"===t[0]?me$3.fromAst(1):me$3.fromAst(t.length-1):me$3.fromAst(1)}}}:{setValue:{mathOperator:e=>me$3.fromAst("_")}}},e}}function gcd(e,t,...n){return!t&&n.length>0?gcd(e,...n):t?gcd(t,e%t,...n):e}var MathOperators=Object.freeze({__proto__:null,Sum:Sum,Product:Product,ClampNumber:ClampNumber,WrapNumberPeriodic:WrapNumberPeriodic,Round:Round,setSmallToZero:setSmallToZero,ConvertSetToList:ConvertSetToList,Ceil:Ceil,Floor:Floor,Abs:Abs,Sign:Sign,Mean:Mean,Variance:Variance,StandardDeviation:StandardDeviation,Count:Count,Min:Min,Max:Max,Mod:Mod,Gcd:Gcd,ExtractMath:ExtractMath});function returnLabelStateVariableDefinitions(){let e={};return e.componentNameAndShadowSourceNames={returnDependencies:()=>({shadowSource:{dependencyType:"shadowSource",variableNames:["componentNameAndShadowSourceNames"]},unlinkedCopySource:{dependencyType:"unlinkedCopySource",variableNames:["componentNameAndShadowSourceNames"]}}),definition({dependencyValues:e,componentName:t}){let n=[t];return e.shadowSource?.stateValues.componentNameAndShadowSourceNames?n.push(...e.shadowSource.stateValues.componentNameAndShadowSourceNames):e.unlinkedCopySource?.stateValues.componentNameAndShadowSourceNames&&n.push(...e.unlinkedCopySource.stateValues.componentNameAndShadowSourceNames),{setValue:{componentNameAndShadowSourceNames:n}}}},e.label={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"labelHasLatex"}}},hasEssential:!0,doNotShadowEssential:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,additionalStateVariablesDefined:[{variableName:"labelHasLatex",forRenderer:!0}],returnDependencies:()=>({labelChild:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex"]},labelIsName:{dependencyType:"stateVariable",variableName:"labelIsName"},labelIsNameAttr:{dependencyType:"attributeComponent",attributeName:"labelIsName"},componentNameAndShadowSourceNames:{dependencyType:"stateVariable",variableName:"componentNameAndShadowSourceNames"},shadowSource:{dependencyType:"shadowSource",variableNames:["label","labelHasLatex"]}}),definition({dependencyValues:e,essentialValues:t}){let n=e.labelChild[e.labelChild.length-1];if(n&&!n.shadowDepth)return{setValue:{label:n.stateValues.value,labelHasLatex:n.stateValues.hasLatex}};if(void 0!==t.label)return{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}};if(e.labelIsName&&!e.labelIsNameAttr.shadowDepth){let t="__",n=e.componentNameAndShadowSourceNames;for(let e of n){let n=e.lastIndexOf("/");if(t=e.substring(n+1),"__"!==t.slice(0,2))break}return"__"===t.slice(0,2)?{setValue:{label:"",labelHasLatex:!1}}:("_"!==t[0]&&(t.includes("_")||t.includes("-")?t=t.replace(/[_\-]/g," "):t.match(/^[a-z]/)?t.match(/[A-Z]/)&&(t=t.replace(/([A-Z])/g," $1").toLowerCase()):t.match(/^[A-Z]/)&&t.match(/[a-z]/)&&(t=t.replace(/([A-Z])/g," $1"),t=t.slice(1))),{setValue:{label:t,labelHasLatex:!1}})}return"string"==typeof e.shadowSource?.stateValues.label?{setValue:{label:e.shadowSource.stateValues.label,labelHasLatex:Boolean(e.shadowSource.stateValues.labelHasLatex)}}:{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.label)return{success:!1};let n=t.labelChild.length-1,r=t.labelChild[n];return r&&!r.shadowDepth?{success:!0,instructions:[{setDependency:"labelChild",desiredValue:e.label,childIndex:n,variableIndex:0}]}:t.labelIsName&&!t.labelIsNameAttr.shadowDepth?{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}:"string"==typeof t.shadowSource?.stateValues.label?{success:!0,instructions:[{setDependency:"shadowSource",desiredValue:e.label,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}}},e.labelForGraph={forRenderer:!0,returnDependencies:()=>({label:{dependencyType:"stateVariable",variableName:"label"},labelHasLatex:{dependencyType:"stateVariable",variableName:"labelHasLatex"}}),definition({dependencyValues:e}){let t;if(e.labelHasLatex){let n=0;t="";for(let r of e.label)"("===r?n++:")"===r?n--:0===n&&("_"===r?r="_":"^"===r&&(r="^")),t+=r}else t=e.label.replaceAll("_","_").replaceAll("^","^");return{setValue:{labelForGraph:t}}}},e}class GraphicalComponent extends BaseComponent{static componentType="_graphical";static createAttributesObject(){let e=super.createAttributesObject();return e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.layer={createComponentOfType:"integer",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();Object.assign(e,t);let n=returnLabelStateVariableDefinitions();return Object.assign(e,n),e}}function returnNumericalFunctionFromFormula({formula:e,nInputs:t,variables:n,domain:r,component:a=0}){let i;if(a=Number(a),Array.isArray(e.tree)&&vectorOperators.includes(e.tree[0]))try{e=e.get_component(Number(a))}catch(e){return()=>NaN}else if(0!==a)return()=>NaN;try{i=e.subscripts_to_strings().f()}catch(e){return()=>NaN}if(1===t){let e=n[0].subscripts_to_strings().tree,t=-1/0,a=1/0,s=!1,o=!1;if(null!==r){let e=r[0];if(void 0!==e)try{t=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)?s=!e.tree[2][1]:t=-1/0,a=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(a)?o=!e.tree[2][2]:a=1/0}catch(e){}}return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=t)||!(n<=a)||s&&n===t||o&&n===a)return NaN;try{return i({[e]:n})}catch(e){return NaN}}}let s=[];for(let e=0;eme$3.fromAst("_")}else if("0"!==t)return e=>me$3.fromAst("_");let r=e.simplify,a=e.expand,i=n.subscripts_to_strings();if(1===e.nInputs){let t=e.variables[0].subscripts_to_strings().tree;return e=>normalizeMathExpression({value:i.substitute({[t]:e}).strings_to_subscripts(),simplify:r,expand:a})}let s=[];for(let t=0;tNaN;let l=e-1;t[0][o];let u,c,p=t[l][o],d=n.map((e=>e[o]));return i&&(u=s[o]),r&&(c=a[o]),function(e){if(isNaN(e))return NaN;if(e<0)return i?(u[2]*e+u[1])*e+u[0]:NaN;if(e>=l)return r?(e-=l,(c[2]*e+c[1])*e+c[0]):e===l?p:NaN;let t=Math.floor(e);e-=t;let n=d[t];return((n[3]*e+n[2])*e+n[1])*e+n[0]}}function returnInterpolatedFunction({xs:e,coeffs:t,interpolationPoints:n,domain:r}){let a=[];if(n&&(a=n.map((e=>e.y))),null===e)return e=>NaN;let i=-1/0,s=1/0,o=!1,l=!1;if(null!==r){let e=r[0];if(void 0!==e)try{i=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(i)?o=!e.tree[2][1]:i=-1/0,s=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(s)?l=!e.tree[2][2]:s=1/0}catch(e){}}let u=e[0],c=e[e.length-1];return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=i)||!(n<=s)||o&&n===i||l&&n===s)return NaN;if(n<=u){n-=u;let e=t[0];return((e[3]*n+e[2])*n+e[1])*n+e[0]}if(n>=c){let r=e.length-2;n-=e[r];let a=t[r];return((a[3]*n+a[2])*n+a[1])*n+a[0]}for(var p,d=0,m=e.length-1;d<=m;){p=Math.floor(.5*(d+m));let t=e[p];if(tn))return a[p];m=p-1}}let h=Math.max(0,m);n-=e[h];let f=t[h];return((f[3]*n+f[2])*n+f[1])*n+f[0]}}function returnReturnDerivativesOfInterpolatedFunction({xs:e,coeffs:t,variables:n}){if(!e)return e=>NaN;let r=n[0].subscripts_to_strings().tree,a=e[0],i=e[e.length-1];return function(n){let s=n.map((e=>e.subscripts_to_strings().tree)),o=s.length;return o>3||!s.every((e=>e===r))||s.includes("_")?e=>0:0===o||null===e?e=>NaN:function(n){if(isNaN(n))return NaN;if(n<=a){n-=a;let e=t[0];return 1===o?(3*e[3]*n+2*e[2])*n+e[1]:2===o?6*e[3]*n+2*e[2]:6*e[3]}if(n>=i){let r=e.length-2;n-=e[r];let a=t[r];return 1===o?(3*a[3]*n+2*a[2])*n+a[1]:2===o?6*a[3]*n+2*a[2]:6*a[3]}for(var r,s=0,l=e.length-1;s<=l;){r=Math.floor(.5*(s+l));let a=e[r];if(an))return 1===o?t[r][1]:2===o?2*t[r][2]:6*t[r][3];l=r-1}}let u=Math.max(0,l);n-=e[u];let c=t[u];return 1===o?(3*c[3]*n+2*c[2])*n+c[1]:2===o?6*c[3]*n+2*c[2]:6*c[3]}}}var functionOperatorDefinitions={clampFunction:function(e,t){return function(n){return Number.isFinite(n)?Math.max(e,Math.min(t,n)):NaN}},wrapFunctionPeriodic:function(e,t){return function(n){if(!Number.isFinite(n))return NaN;let r=e,a=t;return r===a?r:(r>a&&([a,r]=[r,a]),r+me$3.math.mod(n-r,a-r))}},derivative:function(e,t){if("interpolatedFunction"===e.derivativeType){let n=returnReturnDerivativesOfInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,variables:e.variables.map(convertValueToMathExpression)}),r=t.map(convertValueToMathExpression);if(e.additionalDerivVariables){r=[...e.additionalDerivVariables.map(convertValueToMathExpression),...r]}if(e.variableMappings)for(let t of e.variableMappings){let e=[];for(let n of r){let r=t[n.subscripts_to_strings().tree];r?e.push(convertValueToMathExpression(r)):e.push(me$3.fromAst("_"))}r=e}return n(r)}return e=>NaN}};class Function$1 extends InlineComponent{static componentType="function";static rendererType="math";static primaryStateVariableForDefinition="numericalfShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.simplify={createComponentOfType:"text",createStateVariable:"simplifySpecified",defaultValue:"none",toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expandSpecified",defaultValue:!1,public:!0},e.xscale={createComponentOfType:"number",createStateVariable:"xscale",defaultValue:1,public:!0},e.yscale={createComponentOfType:"number",createStateVariable:"yscale",defaultValue:1,public:!0},e.nInputs={createComponentOfType:"integer"},e.nOutputs={createComponentOfType:"integer"},e.domain={createComponentOfType:"_intervalListComponent"},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.minima={createComponentOfType:"extrema"},e.maxima={createComponentOfType:"extrema"},e.extrema={createComponentOfType:"extrema"},e.through={createComponentOfType:"_pointListComponent"},e.throughSlopes={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.symbolic={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurve",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[],i=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a=e.slice(0,t),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),i=e.slice(t))}return 1===r.length&&"string"!=typeof r[0]||0===r.length?{success:!1}:{success:!0,newChildren:[...a,{componentType:"math",children:r},...i]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"functions",componentTypes:["function"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions({numerics:e}){let t=GraphicalComponent.returnStateVariableDefinitions();return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" function"}}}},t.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDigits"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth0){let n=t.functionChild[0],r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;return n||r||(n=!0),n?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:e.functionChild[0].stateValues.displayDigits}}}:{setValue:{displayDigits:e.functionChild[0].stateValues.displayDigits}}}return{useEssentialOrDefaultValue:{displayDigits:!0}}}},t.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:null,hasEssential:!0,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displayDecimals:e.functionChild[0].stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},t.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displaySmallAsZero:e.functionChild[0].stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},t.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{padZeros:e.functionChild[0].stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},t.isInterpolatedFunction={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through"},minima:{dependencyType:"attributeComponent",attributeName:"minima"},maxima:{dependencyType:"attributeComponent",attributeName:"maxima"},extrema:{dependencyType:"attributeComponent",attributeName:"extrema"}}),definition:({dependencyValues:e})=>({setValue:{isInterpolatedFunction:e.through||e.minima||e.maxima||e.extrema}})},t.nInputs={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{nInputs:1}};if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}return null!==e.variablesAttr?{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}}:e.functionChild.length>0?{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}}:{setValue:{nInputs:1}}}},t.nOutputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nOutputsAttr:{dependencyType:"attributeComponent",attributeName:"nOutputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nOutputs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(e.functionChild.length>0)return{setValue:{nOutputs:e.functionChild[0].stateValues.nOutputs}};if(null!==e.nOutputsAttr){let t=e.nOutputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nOutputs:t}}}if(e.mathChild.length>0){let t=e.mathChild[0].stateValues.value,n=1;return Array.isArray(t.tree)&&vectorOperators.includes(t.tree[0])&&(n=t.tree.length-1),{setValue:{nOutputs:n}}}return{useEssentialOrDefaultValue:{nOutputs:!0}}}},t.domain={returnDependencies:()=>({domainAttr:{dependencyType:"attributeComponent",attributeName:"domain",variableNames:["intervals"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),definition({dependencyValues:e}){if(null!==e.domainAttr){let t=e.nInputs,n=e.domainAttr.stateValues.intervals.slice(0,t);return n.length!==t?{setValue:{domain:null}}:n.every((e=>Array.isArray(e.tree)&&"interval"===e.tree[0]))?{setValue:{domain:n}}:{setValue:{domain:null}}}return e.functionChild.length>0?{setValue:{domain:e.functionChild[0].stateValues.domain}}:{setValue:{domain:null}}}},t.simplify={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({simplifySpecified:{dependencyType:"stateVariable",variableName:"simplifySpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["simplify"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.simplifySpecified&&e.functionChild.length>0?{setValue:{simplify:e.functionChild[0].stateValues.simplify}}:{setValue:{simplify:e.simplifySpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.simplifySpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.simplify,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"simplifySpecified",desiredValue:e.simplify}]}},t.expand={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({expandSpecified:{dependencyType:"stateVariable",variableName:"expandSpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["expand"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.expandSpecified&&e.functionChild.length>0?{setValue:{expand:e.functionChild[0].stateValues.expand}}:{setValue:{expand:e.expandSpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.expandSpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.expand,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"expandSpecified",desiredValue:e.expand}]}},t.numericalfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{numericalfShadow:!0}})},t.symbolicfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{symbolicfShadow:!0}})},t.symbolic={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({symbolicAttr:{dependencyType:"attributeComponent",attributeName:"symbolic",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolic"]},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"}}),definition:({dependencyValues:e})=>null!==e.symbolicAttr?{setValue:{symbolic:e.symbolicAttr.stateValues.value}}:e.functionChild.length>0?{setValue:{symbolic:e.functionChild[0].stateValues.symbolic}}:e.numericalfShadow?{setValue:{symbolic:!1}}:e.symbolicfShadow?{setValue:{symbolic:!0}}:{useEssentialOrDefaultValue:{symbolic:!0}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(n)+1)]}};return{globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},functionChild:{dependencyType:"child",childGroups:["functions"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.functionChild.length>0){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.unnormalizedFormula={defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition:function({dependencyValues:e,usedDefault:t}){return e.isInterpolatedFunction?{setValue:{unnormalizedFormula:me$3.fromAst("_")}}:e.mathChild.length>0?{setValue:{unnormalizedFormula:e.mathChild[0].stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0].formula?{setValue:{unnormalizedFormula:e.functionChild[0].stateValues.formula}}:{useEssentialOrDefaultValue:{unnormalizedFormula:!0}}}},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({unnormalizedFormula:{dependencyType:"stateVariable",variableName:"unnormalizedFormula"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){if(t.unnormalizedFormula)return{useEssentialOrDefaultValue:{formula:!0}};return{setValue:{formula:normalizeMathExpression({value:e.unnormalizedFormula,simplify:e.simplify,expand:e.expand})}}}},t.nPrescribedPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nPrescribedPoints:t}}}},t.prescribedPoints={isArray:!0,entryPrefixes:["prescribedPoint"],returnArraySizeDependencies:()=>({nPrescribedPoints:{dependencyType:"stateVariable",variableName:"nPrescribedPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nPrescribedPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["point"+e]},throughSlopes:{dependencyType:"attributeComponent",attributeName:"throughSlopes",variableNames:["math"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].through;if(null!==t){let a=Number(r)+1,i=t.stateValues["point"+a],s=null,o=e[r].throughSlopes;null!==o&&(s=o.stateValues["math"+a],void 0===s&&(s=null)),n[r]={x:i[0],y:i[1],slope:s}}}return{setValue:{prescribedPoints:n}}}},t.prescribedMinima={returnDependencies:()=>({minima:{dependencyType:"attributeComponent",attributeName:"minima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.minima&&(t=e.minima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMinima:t}}}},t.prescribedMaxima={returnDependencies:()=>({maxima:{dependencyType:"attributeComponent",attributeName:"maxima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.maxima&&(t=e.maxima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMaxima:t}}}},t.prescribedExtrema={returnDependencies:()=>({extrema:{dependencyType:"attributeComponent",attributeName:"extrema",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.extrema&&(t=e.extrema.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedExtrema:t}}}},t.interpolationPoints={returnDependencies:()=>({xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"},prescribedPoints:{dependencyType:"stateVariable",variableName:"prescribedPoints"},prescribedMinima:{dependencyType:"stateVariable",variableName:"prescribedMinima"},prescribedMaxima:{dependencyType:"stateVariable",variableName:"prescribedMaxima"},prescribedExtrema:{dependencyType:"stateVariable",variableName:"prescribedExtrema"}}),definition:({dependencyValues:t})=>calculateInterpolationPoints({dependencyValues:t,numerics:e})},t.xs={additionalStateVariablesDefined:["coeffs"],returnDependencies:()=>({interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"}}),definition:computeSplineParamCoeffs},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)if("0"===r){let n=returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain});t[r]=function(e){me$3.fromAst(n(e.evaluate_to_constant()))}}else t[r]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.symbolicfs[r];return{setValue:{symbolicfs:t}}}if(e.symbolicfShadow){let t={};for(let r of n)t[r]="0"===r?e.symbolicfShadow:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?function(t){let n=t.evaluate_to_constant();return null===n?NaN:me$3.fromAst(e.numericalfShadow(n))}:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}},t.symbolicf={isAlias:!0,targetVariableName:"symbolicf1"},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}):e=>me$3.fromAst("_");return{setValue:{numericalfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.numericalfs[r];return{setValue:{numericalfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?e.numericalfShadow:()=>NaN;return{setValue:{numericalfs:t}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]="0"===t?function(e){let t=dependencyValues.symbolicfShadow(me$3.fromAst(e)).evaluate_to_constant();return null===t&&(t=NaN),t}:()=>NaN;return{setValue:{numericalfs:e}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}},t.numericalf={returnDependencies:()=>({numericalf1:{dependencyType:"stateVariable",variableName:"numericalf1"}}),definition:({dependencyValues:e})=>({setValue:{numericalf:e.numericalf1}})},t.fDefinitions={isArray:!0,entryPrefixes:["fDefinition"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinitions"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?{functionType:"interpolated",xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}:{};return{setValue:{fDefinitions:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.fDefinitions[r];return{setValue:{fDefinitions:t}}}if(e.numericalfShadow){let e={};for(let t of n)e[t]={};return{setValue:{fDefinitions:e}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]={};return{setValue:{fDefinitions:e}}}{let t={};for(let r of n)t[r]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:r};return{setValue:{fDefinitions:t}}}}{let t={};for(let r of n)t[r]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:r};return{setValue:{fDefinitions:t}}}}},t.fDefinition={isAlias:!0,targetVariableName:"fDefinition1"},t.fs={isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={symbolicf:{dependencyType:"stateVariable",variableName:"symbolicf"+e},numericalf:{dependencyType:"stateVariable",variableName:"numericalf"+e}}}return{globalDependencies:{symbolic:{dependencyType:"stateVariable",variableName:"symbolic"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};if(e.symbolic)for(let e of n)r[e]=t[e].symbolicf;else for(let e of n)r[e]=t[e].numericalf;return{setValue:{fs:r}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({formula:{dependencyType:"stateVariable",variableName:"formula"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.formula,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},t.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},t.allMinima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMinima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMinima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]>0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)0){let t=-d[1]/(2*d[2]);if(t+n[e]>=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]+r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)0){let e=-d[1]/(2*d[2]);e+n[n.length-2]>=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMinima:t.functionChild[0].stateValues.allMinima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMinima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}),definition:({dependencyValues:e})=>({setValue:{numberMinima:e.allMinima.length},checkForActualChange:{numberMinima:!0}})},t.minima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"minimum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["minimum","minimumLocations","minimumLocation","minimumValues","minimumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["minimum","minimumLocation","minimumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"minimumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"minimumLocation"+(Number(t)+1):"minimumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("minima"===t){if(1===e.length)return"minimum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"minimumLocation"+t;if(2===e[1])return"minimumValue"+t}return null}}if("minimumLocations"===t)return"minimumLocation"+e[0];if("minimumValues"===t)return"minimumValue"+e[0];if("minimum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"minimumLocation"+n;if(2===e[0])return"minimumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMinima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMaxima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMaxima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]<0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]-r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMaxima:t.functionChild[0].stateValues.allMaxima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMaxima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>-t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&r(t+i)<0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition:({dependencyValues:e})=>({setValue:{numberMaxima:e.allMaxima.length},checkForActualChange:{numberMaxima:!0}})},t.maxima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"maximum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["maximum","maximumLocations","maximumLocation","maximumValues","maximumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["maximum","maximumLocation","maximumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"maximumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"maximumLocation"+(Number(t)+1):"maximumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("maxima"===t){if(1===e.length)return"maximum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"maximumLocation"+t;if(2===e[1])return"maximumValue"+t}return null}}if("maximumLocations"===t)return"maximumLocation"+e[0];if("maximumValues"===t)return"maximumValue"+e[0];if("maximum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"maximumLocation"+n;if(2===e[0])return"maximumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMaxima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"},numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),definition:function({dependencyValues:e}){return{setValue:{numberExtrema:e.numberMinima+e.numberMaxima},checkForActualChange:{numberExtrema:!0}}}},t.allExtrema={returnDependencies:()=>({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"},allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition({dependencyValues:e}){let t=[...e.allMinima,...e.allMaxima].sort(((e,t)=>e[0]-t[0]));return{setValue:{allExtrema:t}}}},t.extrema={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"extremum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["extremum","extremumLocations","extremumLocation","extremumValues","extremumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["extremum","extremumLocation","extremumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"extremumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"extremumLocation"+(Number(t)+1):"extremumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("extrema"===t){if(1===e.length)return"extremum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"extremumLocation"+t;if(2===e[1])return"extremumValue"+t}return null}}if("extremumLocations"===t)return"extremumLocation"+e[0];if("extremumValues"===t)return"extremumValue"+e[0];if("extremum"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0){if(1===e[0])return"extremumLocation"+n;if(2===e[0])return"extremumValue"+n}}return null},returnArraySizeDependencies:()=>({numberExtrema:{dependencyType:"stateVariable",variableName:"numberExtrema"}}),returnArraySize:({dependencyValues:e})=>[e.numberExtrema,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allExtrema:{dependencyType:"stateVariable",variableName:"allExtrema"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{returnNumericalDerivatives:returnReturnDerivativesOfInterpolatedFunction(e)}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.returnNumericalDerivatives){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{returnNumericalDerivatives:e.functionChild[0].stateValues.returnNumericalDerivatives}};return{setValue:{returnNumericalDerivatives:function(t){let n=[];for(let e of t){let t=a[e.subscripts_to_strings().tree];t?n.push(t):n.push(me$3.fromAst("_"))}return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}return{setValue:{returnNumericalDerivatives:null}}}},t.numericalDerivativesDefinition={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{numericalDerivativesDefinition:{derivativeType:"interpolatedFunction",xs:e.xs,coeffs:e.coeffs,variables:e.variables}}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.numericalDerivativesDefinition){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{numericalDerivativesDefinition:e.functionChild[0].stateValues.numericalDerivativesDefinition}};{let t={...e.functionChild[0].stateValues.numericalDerivativesDefinition};return t.variableMappings?t.variableMappings=[a,...t.variableMappings]:t.variableMappings=[a],{setValue:{numericalDerivativesDefinition:t}}}}return{setValue:{numericalDerivativesDefinition:{}}}}},t}static adapters=[{stateVariable:"numericalf",componentType:"curve",stateVariablesToShadow:["label","labelHasLatex"]},{stateVariable:"formula",componentType:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}]}function calculateInterpolationPoints({dependencyValues:e,numerics:t}){let n=[],r=[],a={maximum:e.prescribedMaxima,minimum:e.prescribedMinima,extremum:e.prescribedExtrema,point:e.prescribedPoints};for(let e in a)for(let t of a[e]){let a=null,i=null,s=null;if(null===t.x||(a=t.x.evaluate_to_constant(),Number.isFinite(a)))if(null===t.y||(i=t.y.evaluate_to_constant(),Number.isFinite(i)))if(null!==t.slope&&void 0!==t.slope&&(s=t.slope.evaluate_to_constant(),Number.isFinite(s)||(console.warn("Ignoring non-numerical slope"),s=null)),null===a){if(null===i){console.warn(`Ignoring empty ${e}`);continue}r.push({type:e,y:i,slope:s})}else n.push({type:e,x:a,y:i,slope:s});else console.warn(`Ignoring non-numerical ${e}`);else console.warn(`Ignoring non-numerical ${e}`)}n.sort(((e,t)=>e.x-t.x)),r.sort(((e,t)=>e.y-t.y));let i=-1/0,s=t.eps;for(let e=0;e0;){let e,t;void 0===l?e=v({allowedTypes:["maximum","minimum","extremum"],comparison:"atLeast",value:-1/0}):"maximum"===l?e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}):"minimum"===l?e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}):"point"===l&&(e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}),!0!==e.success&&(e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}))),!0===e.success?(t=e.point,r.splice(e.ind,1),m?(t.x=0,m=!1):t.x=i+u):(t=r.pop(),m?(t.x=0,m=!1):t.x=i+2*u);let n=y({p:t,typePrev:l,xPrev:i,yPrev:o});l=n.type,i=n.x,o=n.y}if(0===p.length&&p.push({type:"point",x:0,y:0,slope:0}),m=p[0],"maximum"===m.type){let e={type:"point",x:m.x-u,y:m.y-c,slope:2*c/u};p.splice(0,0,e)}else if("minimum"===m.type){let e={type:"point",x:m.x-u,y:m.y+c,slope:-2*c/u};p.splice(0,0,e)}else if("point"===m.type)if(1===p.length)null===m.slope&&(m.slope=0);else{let e=p[1],t=(e.y-m.y)/(e.x-m.x);if("maximum"===e.type||"minimum"===e.type)null===m.slope&&(m.slope=2*t);else{2===p.length?null===m.slope&&(m.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:m,nextPoint:p[2]})),null===m.slope&&(m.slope=2*(m.y-e.y)/(m.x-e.x)-e.slope));let n={x:m.x-u,y:m.y-u*m.slope,slope:m.slope};p.splice(0,0,n)}}let h=p[p.length-1];if("maximum"===h.type){let e={type:"point",x:h.x+u,y:h.y-c,slope:-2*c/u};p.push(e)}else if("minimum"===h.type){let e={type:"point",x:h.x+u,y:h.y+c,slope:2*c/u};p.push(e)}else if("point"===h.type)if(1===p.length){let e={type:"point",x:h.x+u,y:h.y+m.slope*u,slope:m.slope};p.push(e)}else{let e=p[p.length-2],t=(e.y-h.y)/(e.x-h.x);if("maximum"===e.type||"minimum"===e.type)null===h.slope&&(h.slope=2*t);else{2===p.length?null===h.slope&&(h.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:p[p.length-3],nextPoint:h})),null===h.slope&&(h.slope=2*(e.y-h.y)/(e.x-h.x)-e.slope));let n={x:h.x+u,y:h.y+u*h.slope,slope:h.slope};p.push(n)}}for(let e=1;ei-c||void 0!==r&&null!==e.y&&e.y>t.y-c?g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("minimum"===n||"minimum"===r)return null!==e.y&&e.yt.y+c?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("point"===n||"point"===r){let o="maximum";return(null===e.y&&void 0!==t&&t.type===maximum||null!==e.y&&e.y<=i-c||void 0!==r&&null!==e.y&&e.y>=t.y-c)&&(o="minimum"),"minimum"===o?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t})}return null!==e.y&&e.ys-c){let n,a,o=(e+i)/2,l=null,u=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:Math.min(s,t)-c});!0===u.success?(a="minimum",n=u.point.y,r.splice(u.ind,1),l=0):(a="point",n=s-c),p.push({type:a,x:o,y:n,slope:l})}}else if("minimum"===a&&ti-c){let n=[(2*a+e)/3,(a+2*e)/3],s=[i-c,t+c],o=["atMost","atLeast"],l=[["minimum","extremum"],["maximum","extremum"]];for(let e=0;e<2;e++){let t,a,i=n[e],u=null,c=v({allowedTypes:l[e],comparison:o[e],value:s[e]});!0===c.success?(a=l[e][0],t=c.point.y,r.splice(c.ind,1),u=0):(a="point",t=s[e],u=null),p.push({type:a,x:i,y:t,slope:u})}}}else if("minimum"===n){null===t&&(t=void 0===s?i:"minimum"===o.type?Math.min(i,s):Math.min(i,s-c));let n,l,u=Math.max(i,t)+c,d=(e+a)/2,m=null,h=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:u});!0===h.success?(l="maximum",n=h.point.y,r.splice(h.ind,1),m=0):(l="point",n=u),p.push({type:l,x:d,y:n,slope:m})}else if("point"===n)if(null===t)t=void 0===s?i-c:"minimum"===o.type?Math.min(i-c,s):Math.min(i,s)-c;else if(t>i-c){let n,i,s=(e+a)/2,o=null,l=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:t+c});!0===l.success?(i="maximum",n=l.point.y,r.splice(l.ind,1),o=0):(i="point",n=t+c),p.push({type:i,x:s,y:n,slope:o})}let l={type:"minimum",x:e,y:t,slope:0};return p.push(l),l}function v({allowedTypes:e,comparison:t,value:n}){let a=[];if("atMost"===t)a=Object.keys(r).reverse();else{if("atLeast"!==t)return{success:!1};a=Object.keys(r)}for(let i of e)for(let e of a){let a=r[e];if(a.type===i)if("atMost"===t){if(a.y<=n)return{success:!0,ind:e,point:a}}else if(a.y>=n)return{success:!0,ind:e,point:a}}return{success:!1}}}function computeSplineParamCoeffs({dependencyValues:e}){let t=e.interpolationPoints;if(null===t)return{setValue:{xs:null,coeffs:null}};let n,r=[],a=[],i=t[0];a.push(i.x);for(let e=1;et.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}return 0===a.length||1===a.length&&"string"!=typeof a[0]?{success:!1}:{success:!0,newChildren:[...i,{componentType:"math",children:a},...s]}}}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this.componentType;t.isInterpolatedFunction={returnDependencies:()=>({}),definition:()=>({setValue:{isInterpolatedFunction:!1}})},delete t.nPrescribedPoints,delete t.prescribedPoints,delete t.prescribedMinima,delete t.prescribedMaxima,delete t.prescribedExtrema,delete t.interpolationPoints,delete t.xs,t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!1}})},t.formula.returnDependencies=()=>({}),t.formula.definition=()=>({setValue:{formula:me$3.fromAst("_")}}),t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!0}})},t.symbolicFunctionOperator={returnDependencies:()=>({}),definition:()=>({setValue:{symbolicFunctionOperator:e=>me$3.fromAst("_")}})},t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperator:e=>NaN,numericalFunctionOperatorArguments:[]}})},t.numericalFunctionOperatorArguments={returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperatorArguments:{}}})},t.formulaOperator={returnDependencies:()=>({}),definition:()=>({setValue:{formulaOperator:e=>me$3.fromAst("_")}})},t.returnNumericalDerivatives={returnDependencies:()=>({}),definition:()=>({setValue:{returnNumericalDerivatives:null}})},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalStateVariablesDefined:["operatorBasedOnFormula"],returnDependencies:()=>({operatorBasedOnFormulaIfAvailable:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormulaIfAvailable"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},formulaOperator:{dependencyType:"stateVariable",variableName:"formulaOperator"}}),definition:function({dependencyValues:e}){if(!e.operatorBasedOnFormulaIfAvailable||(0===e.functionChild.length||"_"===e.functionChild[0].stateValues.formula.tree)&&(0===e.mathChild.length||"_"===e.mathChild[0].stateValues.value.tree))return{setValue:{formula:me$3.fromAst("_"),operatorBasedOnFormula:!1}};let t;return t=0===e.functionChild.length?e.mathChild[0].stateValues.value:e.functionChild[0].stateValues.formula,{setValue:{formula:e.formulaOperator(t),operatorBasedOnFormula:!0}}}},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},symbolicFunctionOperator:{dependencyType:"stateVariable",variableName:"symbolicFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:e}}}{let t=Object.assign({},e);t.formula=e.mathChild[0].stateValues.value;let a=[];for(let e=0;ee.symbolicFunctionOperator(...a.map((e=>e(...t))));return{setValue:{symbolicfs:i}}}}{let t=[];for(let n=0;ne.symbolicFunctionOperator(...t.map((e=>e(...n))));return{setValue:{symbolicfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.symbolicFunctionOperator(...t);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)return t[r]=returnSymbolicFunctionFromFormula(e,r),{setValue:{symbolicfs:t}}}}},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>NaN;return{setValue:{numericalfs:e}}}{Object.assign({},e).formula=e.mathChild[0].stateValues.value;let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.numericalFunctionOperator(...t);return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)return t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r}),{setValue:{numericalfs:t}}}}},t.fDefinitions={isArray:!0,entryPrefixes:["fDefinition"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinitions"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},numericalFunctionOperatorArguments:{dependencyType:"stateVariable",variableName:"numericalFunctionOperatorArguments"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:r,arraySize:a}){if(e.operatorBasedOnFormula){let t={};for(let n of r)t[n]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:n};return{setValue:{fDefinitions:t}}}if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let t={};for(let n of r)t[n]={functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain};return{setValue:{fDefinitions:t}}}throw Error("function operator with math child not implemented yet")}{let t={};for(let a of r)t[a]={functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!0,originalFDefinition:e.functionChild[0].stateValues.fDefinitions[a]};return{setValue:{fDefinitions:t}}}}if(0===e.functionChild.length){if(0===e.mathChild.length){let t={};for(let n of r)t[n]={functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain};return{setValue:{fDefinitions:t}}}throw Error("function operator with math child not implemented yet")}{let t={};for(let a of r)t[a]={functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!1,originalFDefinition:e.functionChild[0].stateValues.fDefinitions[a]};return{setValue:{fDefinitions:t}}}}};let r=t.allMinima.returnDependencies;t.allMinima.returnDependencies=function(e){let t=r(e);return delete t.functionChild,t};let a=t.allMaxima.returnDependencies;return t.allMaxima.returnDependencies=function(e){let t=a(e);return delete t.functionChild,t},t}}class ClampFunction extends FunctionOperator{static componentType="clampFunction";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.clampFunction(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class WrapFunctionPeriodic extends FunctionOperator{static componentType="wrapFunctionPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.wrapFunctionPeriodic(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class Derivative extends FunctionOperator{static componentType="derivative";static createAttributesObject(){let e=super.createAttributesObject();return e.derivVariables={createComponentOfType:"variables"},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!0}})},t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!1}})},t.haveFunctionChild={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"]}}),definition:({dependencyValues:e})=>({setValue:{haveFunctionChild:e.functionChild.length>0}})},t.nInputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},stateVariablesDeterminingDependencies:["haveFunctionChild"],returnDependencies({stateValues:e}){let t={nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]}};return e.haveFunctionChild||(t.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]}),t},definition({dependencyValues:e}){if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}if(null!==e.variablesAttr)return{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}};if(e.functionChild.length>0)return{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}};if(null!==e.derivVariablesAttr){let t=[...new Set(e.derivVariablesAttr.stateValues.variables.map((e=>e.subscripts_to_strings().tree)))].length;return{setValue:{nInputs:t}}}return{useEssentialOrDefaultValue:{nInputs:!0}}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],stateVariablesDeterminingDependencies:["haveFunctionChild"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},haveFunctionChild:{dependencyType:"stateVariable",variableName:"haveFunctionChild"}},r={};if(t.haveFunctionChild)for(let t of e)r[t]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(t)+1)]}};else n.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]};return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.haveFunctionChild){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}if(null!==e.derivVariablesAttr){let t=[],r=[];for(let n of e.derivVariablesAttr.stateValues.variables){let e=n.subscripts_to_strings().tree;r.includes(e)||(t.push(n),r.push(e))}return{setValue:{variables:returnNVariables(n[0],t)}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.nDerivatives={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["nComponents"]}}),definition:({dependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{nDerivatives:e.derivVariablesAttr.stateValues.nComponents}}:{setValue:{nDerivatives:1}}},t.derivVariables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["derivVariable"],returnArraySizeDependencies:()=>({nDerivatives:{dependencyType:"stateVariable",variableName:"nDerivatives"}}),returnArraySize:({dependencyValues:e})=>[e.nDerivatives],returnArrayDependenciesByKey:()=>({globalDependencies:{derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]},variable1:{dependencyType:"stateVariable",variableName:"variable1"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{derivVariables:e.derivVariablesAttr.stateValues.variables}}:{setValue:{derivVariables:{0:e.variable1}}}},t.formulaOperator={returnDependencies:()=>({derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),definition:({dependencyValues:e})=>({setValue:{formulaOperator:function(t){let n=t.subscripts_to_strings();for(let t of e.derivVariables)n=n.derivative(t.subscripts_to_strings().tree);return n.strings_to_subscripts()}}})},t.numericalFunctionOperator={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["returnNumericalDerivatives"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.returnNumericalDerivatives)return{setValue:{numericalFunctionOperator:e=>NaN,returnNumericalDerivatives:null}};return{setValue:{numericalFunctionOperator:e.functionChild[0].stateValues.returnNumericalDerivatives(e.derivVariables),returnNumericalDerivatives:function(t){let n=[...e.derivVariables,...t];return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}},t.numericalFunctionOperatorArguments={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["numericalDerivativesDefinition"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.numericalDerivativesDefinition)return{setValue:{numericalFunctionOperatorArguments:[],numericalDerivativesDefinition:{}}};let t=e.functionChild[0].stateValues.numericalDerivativesDefinition,n={...t};return n.additionalDerivVariables?n.additionalDerivVariables=[...e.derivVariables,...n.additionalDerivVariables]:n.additionalDerivVariables=[...e.derivVariables],{setValue:{numericalFunctionOperatorArguments:[t,e.derivVariables],numericalDerivativesDefinition:n}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}var FunctionOperators=Object.freeze({__proto__:null,ClampFunction:ClampFunction,WrapFunctionPeriodic:WrapFunctionPeriodic,Derivative:Derivative});class TextBaseOperatorOfMath extends Text{static componentType="_textOperatorOfMath";static rendererType="text";static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyTextOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class ExtractMathOperator extends TextBaseOperatorOfMath{static componentType="extractMathOperator";static applyTextOperator(e){return 0===e.length?"":1!==e.length?(console.warn("MathOperator requires exactly one math child"),""):Array.isArray(e[0].tree)?e[0].tree[0]:""}}var TextOperatorsOfMath=Object.freeze({__proto__:null,ExtractMathOperator:ExtractMathOperator});class Extremum extends BaseComponent{static componentType="extremum";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.location={createComponentOfType:"math"},e.value={createComponentOfType:"math"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/s+(.*s)?/,replacementFunction:function({matchedChildren:e}){let t=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),n=t({matchedChildren:e});if(!n.success&&1===e.length)return{success:!0,newAttributes:{value:{component:{componentType:"math",children:e}}}};if(n.success){if(1===n.newChildren.length)return{success:!0,newAttributes:{value:{component:n.newChildren[0]}}};if(2===n.newChildren.length){let e=n.newChildren[0],t=n.newChildren[1],r={location:{component:e},value:{component:t}};return(0===e.children.length||1===e.children.length&&"string"==typeof e.children[0]&&""===e.children[0].trim())&&delete r.location,(0===t.children.length||1===t.children.length&&"string"==typeof t.children[0]&&""===t.children[0].trim())&&delete r.value,{success:!0,newAttributes:r}}return{success:!1}}return n}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this;return t.value={public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"location",public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0}],returnDependencies:()=>({extremumChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions","xs"]},location:{dependencyType:"attributeComponent",attributeName:"location",variableNames:["value"]},value:{dependencyType:"attributeComponent",attributeName:"value",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t,r;if(e.extremumChild.length>0){let a=e.extremumChild[0];2!==a.stateValues.nDimensions?(console.log("Cannot determine "+n.componentType+" from a point that isn't 2D"),t=null,r=null):(t=a.stateValues.xs[0],r=a.stateValues.xs[1])}else null!==e.location&&(t=e.location.stateValues.value),null!==e.value&&(r=e.value.stateValues.value);let a={},i={},s=!1,o=!1;void 0===t?(i.location=!0,o=!0):(a.location=t,s=!0),void 0===r?(i.value=!0,o=!0):(a.value=r,s=!0);let l={};return s&&(l.setValue=a),o&&(l.useEssentialOrDefaultValue=i),l}},t}}class Extrema extends BaseComponent{static componentType="extrema";static rendererType=void 0;static componentTypeSingular="extremum";static get componentTypeCapitalized(){return this.componentType.charAt(0).toUpperCase()+this.componentType.slice(1)}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=this;return e.push({replacementFunction:function({matchedChildren:e}){let n=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==n.success?{success:!1}:{success:!0,newChildren:n.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:t.componentTypeSingular,children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"extrema",componentTypes:[this.componentTypeSingular]},{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e["n"+t.componentTypeCapitalized]={additionalStateVariablesDefined:["childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["extrema","points"]}}),definition:function({dependencyValues:e}){return{setValue:{["n"+t.componentTypeCapitalized]:e.children.length,childIdentities:e.children}}}},e[t.componentType]={isArray:!0,nDimensions:2,entryPrefixes:[t.componentTypeSingular,t.componentTypeSingular+"Locations",t.componentTypeSingular+"Location",t.componentTypeSingular+"Values",t.componentTypeSingular+"Value"],stateVariablesDeterminingDependencies:["childIdentities"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:n,arraySize:r}){if([t.componentTypeSingular,t.componentTypeSingular+"Location",t.componentTypeSingular+"Value"].includes(e)){let a=Number(n)-1;return Number.isInteger(a)&&a>=0&&(!r||at+",0")):["0,0"]:e===t.componentTypeSingular+"Values"?""!==n?[]:r?Array.from(Array(r[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[n,r]=e.split(",");return"0"===r?t.componentTypeSingular+"Location"+(Number(n)+1):t.componentTypeSingular+"Value"+(Number(n)+1)},arrayVarNameFromPropIndex(e,n){if(n===t.componentType){if(1===e.length)return t.componentTypeSingular+e[0];{let n=Number(e[0]);if(Number.isInteger(n)&&n>0){if(1===e[1])return t.componentTypeSingular+"Location"+n;if(2===e[1])return t.componentTypeSingular+"Value"+n}return null}}if(n===t.componentTypeSingular+"Locations")return t.componentTypeSingular+"Location"+e[0];if(n===t.componentTypeSingular+"Values")return t.componentTypeSingular+"Value"+e[0];let r=t.componentTypeSingular.length;if(n.slice(0,r)===t.componentTypeSingular){let a=Number(n.slice(r));if(Number.isInteger(a)&&a>0){if(1===e[0])return t.componentTypeSingular+"Location"+a;if(2===e[0])return t.componentTypeSingular+"Value"+a}}return null},returnArraySizeDependencies:()=>({nChildren:{dependencyType:"stateVariable",variableName:"n"+t.componentTypeCapitalized}}),returnArraySize:({dependencyValues:e})=>[e.nChildren,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:n}){let r={};for(let a of e){let e,[i,s]=a.split(",");e=n.childIdentities[i].componentType===t.componentTypeSingular?0===Number(s)?"location":"value":"x"+(Number(s)+1),r[a]={child:{dependencyType:"child",childGroups:["extrema","points"],variableNames:[e],childIndices:[i]}}}return{dependenciesByKey:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:n}){let r={};for(let t of n){let n=e[t].child[0];if(n){let e=t.split(",")[1],a=0===Number(e)?"location":"value";a in n.stateValues?r[t]=n.stateValues[a]:r[t]=n.stateValues["x"+(Number(e)+1)]}}return{setValue:{[t.componentType]:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:n}){let r=[];for(let a in e[t.componentType])r.push({setDependency:n[a].extremumChild,desiredValue:e[t.componentType][a],childIndex:0,variableIndex:0});return{success:!0,instructions:r}}},e}}var Extrema$1=Object.freeze({__proto__:null,Extremum:Extremum,Extrema:Extrema});class InlineRenderInlineChildren extends InlineComponent{static componentType="_inlineRenderInlineChildren";static renderChildren=!0;static includeBlankStringChildren=!0;static beginTextDelimiter="";static endTextDelimiter="";static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let n="";for(let t of e.inlineChildren)"object"!=typeof t?n+=t.toString():"string"==typeof t.stateValues.text?n+=t.stateValues.text:n+=" ";return n=t.beginTextDelimiter+n+t.endTextDelimiter,{setValue:{text:n}}}},e}}class Em extends InlineRenderInlineChildren{static componentType="em"}class Alert extends InlineRenderInlineChildren{static componentType="alert"}class Q$2 extends InlineRenderInlineChildren{static componentType="q";static beginTextDelimiter='"';static endTextDelimiter='"'}class SQ extends InlineRenderInlineChildren{static componentType="sq";static beginTextDelimiter="'";static endTextDelimiter="'"}class Term extends InlineRenderInlineChildren{static componentType="term";static rendererType="alert"}class C$2 extends InlineRenderInlineChildren{static componentType="c"}class Tag extends InlineRenderInlineChildren{static componentType="tag";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter=">"}class Tage extends InlineRenderInlineChildren{static componentType="tage";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter="/>";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.selfClosed={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{selfClosed:!0}})},e}}class Attr extends InlineRenderInlineChildren{static componentType="attr";static rendererType="c"}var ParagraphMarkup=Object.freeze({__proto__:null,Em:Em,Alert:Alert,Q:Q$2,SQ:SQ,Term:Term,C:C$2,Tag:Tag,Tage:Tage,Attr:Attr});class SingleCharacter extends InlineComponent{static componentType="_singleCharacterInline";static unicodeCharacter="";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({}),definition:()=>({setValue:{text:this.unicodeCharacter}})},e}}class Ndash extends SingleCharacter{static componentType="ndash";static unicodeCharacter="–"}class Mdash extends SingleCharacter{static componentType="mdash";static unicodeCharacter="—"}class NBSP extends SingleCharacter{static componentType="nbsp";static unicodeCharacter=" "}class Ellipsis extends SingleCharacter{static componentType="ellipsis";static unicodeCharacter="…"}var SingleCharacterComponents=Object.freeze({__proto__:null,Ndash:Ndash,Mdash:Mdash,NBSP:NBSP,Ellipsis:Ellipsis});class BlockComponent extends BaseComponent{static componentType="_block"}function returnDefaultFeedbackDefinitions(){return{numericalerror:"Credit reduced because numbers in your answer weren't quite right. Did you round too much?",goodjob:"Good job!",onesignerror:"Credit reduced because it appears that you made a sign error.",twosignerrors:"Credit reduced because it appears that you made two sign errors."}}function returnFeedbackDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.feedbackDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithFeedback:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`feedbackDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["feedbackDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithFeedback&&(t=e.ancestorWithFeedback.stateValues.feedbackDefinitions),t||(t=returnDefaultFeedbackDefinitions()),Object.assign(n,t);let r=[];for(let t of e.setupChildren)r.push(...e[`feedbackDefinitionsOf${t.componentName}`]);for(let e of r)Object.assign(n,e.stateValues.value);return{setValue:{feedbackDefinitions:n}}}},e}class SectioningComponent extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),revealSection:this.revealSection.bind(this),closeSection:this.closeSection.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="_sectioningComponent";static renderChildren=!0;static includeBlankStringChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores={createComponentOfType:"boolean",createStateVariable:"aggregateScores",defaultValue:!1,public:!0},e.weight={createComponentOfType:"number",createStateVariable:"weight",defaultValue:1,public:!0},e.sectionWideCheckWork={createComponentOfType:"boolean",createStateVariable:"sectionWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.boxed={createComponentOfType:"boolean",createStateVariable:"boxed",defaultValue:!1,public:!0,forRenderer:!0},e.suppressAutoName={createComponentOfType:"boolean",createStateVariable:"suppressAutoName",defaultValue:!1,public:!0},e.suppressAutoNumber={createComponentOfType:"boolean",createStateVariable:"suppressAutoNumber",defaultValue:!1,public:!0},e.includeAutoName={createComponentOfType:"boolean",createStateVariable:"includeAutoName",defaultValue:!1,public:!0},e.includeAutoNumber={createComponentOfType:"boolean",createStateVariable:"includeAutoNumber",defaultValue:!1,public:!0},e.includeAutoNameNumberIfNoTitle={createComponentOfType:"boolean",createStateVariable:"includeAutoNameNumberIfNoTitle",defaultValue:!0,public:!0},e.includeParentNumber={createComponentOfType:"boolean",createStateVariable:"includeParentNumber",defaultValue:!1,public:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"variantControls",componentTypes:["variantControl"]},{group:"titles",componentTypes:["title"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.enumeration={additionalStateVariablesDefined:[{variableName:"sectionNumber",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["enumeration"]},includeParentNumber:{dependencyType:"stateVariable",variableName:"includeParentNumber"}}),definition({dependencyValues:e}){let t=[];return e.includeParentNumber&&e.sectionAncestor&&t.push(...e.sectionAncestor.stateValues.enumeration),t.push(e.countAmongSiblings),{setValue:{enumeration:t,sectionNumber:t.join(".")}}}},e.sectionName={returnDependencies:()=>({}),definition:()=>({setValue:{sectionName:"Section"}})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","variantControls","titles","setups"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={additionalStateVariablesDefined:[{variableName:"titlePrefix",forRenderer:!0,alwaysUpdateRenderer:!0}],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,alwaysUpdateRenderer:!0,returnDependencies:({sharedParameters:e})=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]},sectionName:{dependencyType:"stateVariable",variableName:"sectionName"},sectionNumber:{dependencyType:"stateVariable",variableName:"sectionNumber"},includeAutoName:{dependencyType:"stateVariable",variableName:"includeAutoName"},includeAutoNumber:{dependencyType:"stateVariable",variableName:"includeAutoNumber"},prerender:{dependencyType:"value",value:e.prerender},includeAutoNameNumberIfNoTitle:{dependencyType:"stateVariable",variableName:"includeAutoNameNumberIfNoTitle"}}),definition({dependencyValues:e}){let t="",n="";const r=e.titleChild.length>0;let a=(e.includeAutoNumber||!r&&e.includeAutoNameNumberIfNoTitle)&&!e.prerender,i=e.includeAutoName||!r&&e.includeAutoNameNumberIfNoTitle;return a?(i&&(t=e.sectionName+" "),t+=e.sectionNumber):i&&(t=e.sectionName),r?(t&&(e.includeAutoName?t+=": ":t+=". "),n=e.titleChild[e.titleChild.length-1].stateValues.text):n=t,{setValue:{title:n,titlePrefix:t}}}},e.containerTag={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{containerTag:"section"}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.displayDigitsForCreditAchieved={returnDependencies:()=>({}),definition:()=>({setValue:{displayDigitsForCreditAchieved:3}})},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},forRenderer:!0,defaultValue:0,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},defaultValue:0,hasEssential:!0}],stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchieved"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchieved"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchieved:0,percentCreditAchieved:0}};let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e["creditAchieved"+t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchievedIfSubmit:0}};let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={};e.variantName?(n.index=e.variantIndex,n.name=e.variantName):n.seed=e.variantSeed,n.meta={createdBy:t};let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.collapsible={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{collapsible:!1}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({sectionWideCheckWork:{dependencyType:"stateVariable",variableName:"sectionWideCheckWork"},aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor&&e.sectionAncestor.stateValues.suppressAnswerSubmitButtons?r=!0:e.sectionWideCheckWork&&(e.aggregateScores?(n=!0,r=!0):console.warn(`Cannot create submit all button for ${t} because it doesn't aggegrate scores`)),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{creditAchieved:await this.stateValues.creditAchievedIfSubmit}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}async revealSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){if(!e.variants?.allPossibleVariants)return void setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0});let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r){let e=t.variantRng();r=Math.floor(e*a)+1}if(t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){if(!e.variants.allPossibleVariants)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};if(!e.variants.uniqueVariants)return{success:!0,desiredVariant:{index:t}};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?(e.variants.selectedUniqueVariant=!0,{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}):(console.log("Failed to get unique variant for section."),{success:!1})}}class Section extends SectioningComponent{static componentType="section";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeParentNumber.defaultValue=!0,e}}class Subsection extends Section{static componentType="subsection"}class Subsubsection extends Section{static componentType="subsubsection"}class Paragraphs extends SectioningComponent{static componentType="paragraphs";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:4}}),e.sectionName.definition=()=>({setValue:{sectionName:"Paragraphs"}}),e}}class Aside extends SectioningComponent{static componentType="aside";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.collapsible={createComponentOfType:"boolean",createStateVariable:"collapsible",defaultValue:!0,public:!0,forRenderer:!0},e.startOpen={createComponentOfType:"boolean",createStateVariable:"startOpen",defaultValue:!1},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.collapsible,e.open.returnDependencies=()=>({startOpen:{dependencyType:"stateVariable",variableName:"startOpen"}}),e.open.definition=({dependencyValues:e})=>({useEssentialOrDefaultValue:{open:{defaultValue:e.startOpen}}}),e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e.sectionName.definition=()=>({setValue:{sectionName:"Aside"}}),e}}class Problem extends SectioningComponent{static componentType="problem";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores.defaultValue=!0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Problem"}}),e}}class Exercise extends Problem{static componentType="exercise";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Exercise"}}),e}}class Example extends SectioningComponent{static componentType="example";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Example"}}),e}}class StandinForFutureLayoutTag extends SectioningComponent{static componentType="standinForFutureLayoutTag";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e}}class externalContent extends SectioningComponent{static componentType="externalContent";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeAutoNameNumberIfNoTitle.defaultValue=!1,e}}var Sectioning=Object.freeze({__proto__:null,Section:Section,Subsection:Subsection,Subsubsection:Subsubsection,Paragraphs:Paragraphs,Aside:Aside,Problem:Problem,Exercise:Exercise,Example:Example,StandinForFutureLayoutTag:StandinForFutureLayoutTag,externalContent:externalContent});class Ol extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="ol";static rendererType="list";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.label={createComponentOfType:"text",createStateVariable:"label",defaultValue:null,public:!0,forRenderer:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"lis",componentTypes:["li"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"ol",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Ul extends Ol{static componentType="ul";static rendererType="list";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e}}class Li$1 extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="li";static rendererType="list";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.item={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{item:!0}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Lists=Object.freeze({__proto__:null,Ol:Ol,Ul:Ul,Li:Li$1});class ODESystem extends InlineComponent{static componentType="odesystem";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.independentVariable={createComponentOfType:"variable",createStateVariable:"independentVariable",defaultValue:me$3.fromAst("t"),public:!0},e.initialIndependentVariableValue={createComponentOfType:"math",createStateVariable:"initialIndependentVariableValue",defaultValue:me$3.fromAst(0),public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"align",public:!0,forRenderer:!0},e.chunkSize={createComponentOfType:"number",createStateVariable:"chunkSize",defaultValue:10,public:!0},e.tolerance={createComponentOfType:"number",createStateVariable:"tolerance",defaultValue:1e-6,public:!0},e.maxIterations={createComponentOfType:"number",createStateVariable:"maxIterations",defaultValue:1e3,public:!0},e.hideInitialCondition={createComponentOfType:"boolean",createStateVariable:"hideInitialCondition",defaultValue:!1,public:!0},e.initialConditions={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"rightHandSides",componentTypes:["rightHandSide"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validIndependentVariable={returnDependencies:()=>({independentVarAttr:{dependencyType:"attributeComponent",attributeName:"independentVariable",variableNames:["validVariable"]}}),definition({dependencyValues:e}){let t=!0;return e.independentVarAttr&&(t=e.independentVarAttr.stateValues.validVariable),{setValue:{validIndependentVariable:t}}}},e.nDimensions={returnDependencies:()=>({rhsChildren:{dependencyType:"child",childGroups:["rightHandSides"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:e.rhsChildren.length},checkForActualChange:{nDimensions:!0}}}},e.variables={additionalStateVariablesDefined:[{variableName:"validVariables",isArray:!0,entryPrefixes:["validVar"]}],isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables","validVariables"]},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[],n=[],r=e.nDimensions;null!==e.variables&&(t=e.variables.stateValues.variables,n=[...e.variables.stateValues.validVariables].slice(0,r));let a=returnNVariables(r,t);return a.some((t=>t.equals(e.independentVariable)))&&console.warn("Variables of odesystem must be different than independent variable."),n.length({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={rhsChild:{dependencyType:"child",childGroups:["rightHandSides"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].rhsChild[0].stateValues.value;return{setValue:{rhss:n}}}},e.rhs={isAlias:!0,targetVariableName:"rhs1"},e.righthandside={isAlias:!0,targetVariableName:"rhs1"},e.righthandsides={isAlias:!0,targetVariableName:"rhss"},e.initialConditions={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["initialCondition"],defaultValueByArrayKey:()=>me$3.fromAst(0),returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={initialConditionAttr:{dependencyType:"attributeComponent",attributeName:"initialConditions",variableNames:[`math${Number(n)+1}`]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=!1;if(e[a].initialConditionAttr){let r=e[a].initialConditionAttr.stateValues[`math${Number(a)+1}`];void 0!==r&&(t=!0,n[a]=r)}t||(r[a]=!0)}let a={};return Object.keys(n).length>0&&(a.setValue={initialConditions:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialConditions:r}),a}},e.initialCondition={isAlias:!0,targetVariableName:"initialCondition1"},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],returnDependencies:({stateValues:e})=>e.number?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"stateVariable",variableName:"variables"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"},hideInitialCondition:{dependencyType:"stateVariable",variableName:"hideInitialCondition"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},rhss:{dependencyType:"stateVariable",variableName:"rhss"},number:{dependencyType:"stateVariable",variableName:"number"},equationTag:{dependencyType:"stateVariable",variableName:"equationTag"}}),definition({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=[],a=e.independentVariable.toLatex();for(let i=0;i({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.numericalRHSf={additionalStateVariablesDefined:["numericalRHSfDefinitions"],returnDependencies:()=>({validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},rhss:{dependencyType:"stateVariable",variableName:"rhss"}}),definition({dependencyValues:e}){let t=!0;e.validIndependentVariable||(console.warn("Can't define ODE RHS functions with invalid independent variable."),t=!1),e.validVariables.every((e=>e))||(console.warn("Can't define ODE RHS functions with an invalid variable."),t=!1);let n,r=e.independentVariable.subscripts_to_strings().tree,a=e.variables.map((e=>e.subscripts_to_strings().tree));a.includes(r)&&(console.warn("Can't define ODE RHS functions when independent variable is a dependent variable"),t=!1),[...new Set(a)].length!==a.length&&(console.warn("Can't define ODE RHS functions with duplicate dependent variable names"),t=!1);try{n=e.rhss.map((e=>e.subscripts_to_strings().f()))}catch(e){console.warn("Cannot define ODE RHS function. Error creating mathjs function"),t=!1}if(!t){let t=e.rhss.length;return{setValue:{numericalRHSf:()=>NaN,numericalRHSfDefinitions:Array(t).fill({})}}}return{setValue:{numericalRHSf:function(e,t){let i={[r]:e};Array.isArray(t)?t.forEach(((e,t)=>i[a[t]]=e)):i[a[0]]=t;try{return n.map((e=>e(i)))}catch(e){return NaN}},numericalRHSfDefinitions:e.rhss.map((e=>({functionType:"formula",formula:e,nInputs:a.length+1,variables:[r,...a]})))}}}},e.haveNumericalInitialConditions={additionalStateVariablesDefined:["t0","x0s"],returnDependencies:()=>({initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"}}),definition({dependencyValues:e}){let t=e.initialIndependentVariableValue.evaluate_to_constant(),n=e.initialConditions.map((e=>e.evaluate_to_constant())),r=Number.isFinite(t)&&n.every((e=>Number.isFinite(e)));return{setValue:{t0:t,x0s:n,haveNumericalInitialConditions:r}}}},e.numericalSolutions={isArray:!0,entryPrefixes:["numericalSolution"],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinitions:{stateVariableToShadow:"numericalSolutionFDefinitions"}}},createWorkspace:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSf:{dependencyType:"stateVariable",variableName:"numericalRHSf"}}}),arrayDefinitionByKey({globalDependencyValues:e,workspace:t,componentName:n}){let r={};if(t.calculatedNumericSolutions=[],t.endingNumericalValues=[],t.maxPossibleTime=void 0,!e.haveNumericalInitialConditions){for(let t=0;tNaN;return{setValue:{numericalSolutions:r}}}let a=e.t0,i=e.x0s,s=e.chunkSize,o=e.tolerance,l=e.numericalRHSf,u=e.maxIterations;for(let c=0;c=r)for(let e=r;e<=p;e++){let r=t.endingNumericalValues[e-1];void 0===r&&(r=i);let c=a+e*s,p=me$3.math.dopri(c,c+s,r,l,o,u);t.endingNumericalValues.push(p.y[p.y.length-1]),t.calculatedNumericSolutions.push(p.at.bind(p));let d=p.x[p.x.length-1];if(d<.999999*(c+s)){t.maxPossibleTime=d;let e="For chunksize "+s+" and tolerance "+o+", odesystem";void 0!==n&&(e+=" ("+n+")"),e+=" hit maxiterations ("+u+") at t = "+t.maxPossibleTime+". Will not calculate solution beyond that time. Decrease chunksize, increase maxiterations, or increase tolerance to calculate further.";break}}return e>t.maxPossibleTime?NaN:t.calculatedNumericSolutions[p](e)[c]};return{setValue:{numericalSolutions:r}}}},e.numericalSolution={isAlias:!0,targetVariableName:"numericalSolution1"},e.numericalSolutionFDefinitions={forRenderer:!0,isArray:!0,entryPrefixes:["numericalSolutionFDefinition"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSfDefinitions:{dependencyType:"stateVariable",variableName:"numericalRHSfDefinitions"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>e.haveNumericalInitialConditions?{setValue:{numericalSolutionFDefinitions:[...Array(e.nDimensions).keys()].map((t=>({functionType:"ODESolution",nDimensions:e.nDimensions,t0:e.t0,x0s:e.x0s,chunkSize:e.chunkSize,tolerance:e.tolerance,numericalRHSfDefinitions:e.numericalRHSfDefinitions,maxIterations:e.maxIterations,component:t})))}}:{setValue:{numericalSolutionFDefinitions:Array(e.nDimensions).fill({})}}},e}}class Polyline extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this),polylineClicked:this.polylineClicked.bind(this),mouseDownOnPolyline:this.mouseDownOnPolyline.bind(this)})}static componentType="polyline";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.verticesDraggable={createComponentOfType:"boolean"},e.vertices={createComponentOfType:"_pointListComponent"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.verticesDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({verticesDraggableAttr:{dependencyType:"attributeComponent",attributeName:"verticesDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.verticesDraggableAttr?{setValue:{verticesDraggable:e.verticesDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{verticesDraggable:{defaultValue:e.draggable}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.vertices?{setValue:{nVertices:e.vertices.stateValues.nPoints}}:{setValue:{nVertices:0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.vertices){return{setValue:{nDimensions:e.vertices.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].vertices;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{vertices:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].vertices||!t[r].vertices.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0})}return{success:!0,instructions:i}}},e.numericalVertices={isArray:!0,entryPrefixes:["numericalVertex"],forRenderer:!0,returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){if(1===Object.keys(e).length){if(!await this.stateValues.verticesDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}async polylineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPolyline({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class CobwebPolyline extends Polyline{static componentType="cobwebPolyline";static rendererType="cobwebPolyline";static createAttributesObject(){let e=super.createAttributesObject();return e.attractThreshold={createComponentOfType:"number",createStateVariable:"attractThreshold",defaultValue:.5,public:!0},e.nPoints={createComponentOfType:"number",createStateVariable:"nPoints",defaultValue:1,public:!0,clamp:[0,1/0],forRenderer:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0,forRenderer:!0},e.nIterationsRequired={createComponentOfType:"number",createStateVariable:"nIterationsRequired",defaultValue:0,public:!0},e.initialPoint={createComponentOfType:"point"},e.function={createComponentOfType:"function"},e.lockToSolution={createComponentOfType:"boolean",createStateVariable:"lockToSolution",defaultValue:!1},e.defaultPoint={createComponentOfType:"point"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions.returnDependencies=()=>({}),e.nDimensions.definition=()=>({setValue:{nDimensions:2}}),e.initialPoint={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"initialPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["initialPointX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={initialPointAttr:{dependencyType:"attributeComponent",attributeName:"initialPoint",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=Number(a)+1;e[a].initialPointAttr?n[a]=e[a].initialPointAttr.stateValues["x"+t]:r[a]=!0}let a={};return Object.keys(n).length>0&&(a.setValue={initialPoint:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialPoint:r}),a},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.initialPoint)t[a].initialPointAttr&&t[a].initialPointAttr.stateValues["x"+(Number(a)+1)]?r.push({setDependency:n[a].initialPointAttr,desiredValue:e.initialPoint[a],variableIndex:0}):r.push({setEssentialValue:"initialPoint",value:{[a]:e.initialPoint[a]}});return{success:!0,instructions:r}}},e.f={additionalStateVariablesDefined:[{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalf","fDefinition"]}}),definition:({dependencyValues:e})=>e.functionAttr?{setValue:{f:e.functionAttr.stateValues.numericalf,fDefinition:e.functionAttr.stateValues.fDefinition}}:{setValue:{f:null,fDefinition:null}}},e.nVertices={isAlias:!0,targetVariableName:"nPoints"},e.nOriginalVertices={providePreviousValuesInDefinition:!0,returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e,previousValues:t}){let n=e.nVertices;return t.nOriginalVertices>n&&(n=t.nOriginalVertices),{setValue:{nOriginalVertices:n}}}},e.originalVertices={isArray:!0,nDimensions:2,hasEssential:!0,entryPrefixes:["originalVertexX","originalVertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("originalVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("originalVertices"===t)return 1===e.length?"originalVertex"+e[0]:`originalVertexX${e[0]}_${e[1]}`;if("originalVertex"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`originalVertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nOriginalVertices:{dependencyType:"stateVariable",variableName:"nOriginalVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nOriginalVertices-1,e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},defaultPoint:{dependencyType:"attributeComponent",attributeName:"defaultPoint",variableNames:["xs"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",").map(Number);n[r]={get defaultValue(){if(e.defaultPoint){let n=e.defaultPoint.stateValues.xs;if(2===n.length&&t[1]<2)return n[t[1]]}if(e.graphAncestor){if(0===t[1]){let t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax;return me$3.fromAst((t+n)/2)}if(1===t[1]){let t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax;return me$3.fromAst((t+n)/2)}}return me$3.fromAst(0)}}}return{useEssentialOrDefaultValue:{originalVertices:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.originalVertices)t.push({setEssentialValue:"originalVertices",value:{[n]:e.originalVertices[n]}});return{success:!0,instructions:t}}},e.vertices.additionalStateVariablesDefined=[{variableName:"prelimCorrectVertices",entryPrefixes:["prelimCorrectVertexX","prelimCorrectVertex"],getArrayKeysFromVarName:function({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("prelimCorrectVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}}}],e.vertices.basedOnArrayKeyStateVariables=!0,e.vertices.returnArrayDependenciesByKey=function({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]="0"===e?{initialPoint:{dependencyType:"stateVariable",variableName:"initialPointX"+(Number(r)+1)}}:{originalVertexX1:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_1"},originalVertexX2:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_2"},previousVertexX1:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_1"},previousVertexX2:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_2"}}}return{globalDependencies:{f:{dependencyType:"stateVariable",variableName:"f"},attractThreshold:{dependencyType:"stateVariable",variableName:"attractThreshold"},lockToSolution:{dependencyType:"stateVariable",variableName:"lockToSolution"}},dependenciesByKey:t}},e.vertices.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let[n,s]=i.split(",");if("0"===n)r[i]=t[i].initialPoint,a[i]=null;else{let s,o,l;try{s=[t[i].originalVertexX1.evaluate_to_constant(),t[i].originalVertexX2.evaluate_to_constant()],o=[t[i].previousVertexX1.evaluate_to_constant(),t[i].previousVertexX2.evaluate_to_constant()]}catch(e){r[n+",0"]=me$3.fromAst(0),r[n+",1"]=me$3.fromAst(0),a[n+",0"]=!1;continue}if(Number(n)%2==1){let t=e.f(o[0]);l=[o[0],t]}else l=[o[1],o[1]];Math.pow(s[0]-l[0],2)+Math.pow(s[1]-l[1],2)({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={prelimCorrectVertex:{dependencyType:"stateVariable",variableName:"prelimCorrectVertexX"+(Number(n)+2)+"_1"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].prelimCorrectVertex;return{setValue:{correctVertices:n}}}},e.fractionCorrectVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nCorrectVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({correctVertices:{dependencyType:"stateVariable",variableName:"correctVertices"}}),definition({dependencyValues:e}){let t,n,r=e.correctVertices.length;return 0===r?(t=0,n=0):(n=e.correctVertices.reduce(((e,t)=>e+t),0),t=n/r),{setValue:{fractionCorrectVertices:t,nGradedVertices:r,nCorrectVertices:n}}}},e.fractionCorrectVerticesAdjusted={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVerticesAdjusted",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({nCorrectVertices:{dependencyType:"stateVariable",variableName:"nCorrectVertices"},nGradedVertices:{dependencyType:"stateVariable",variableName:"nGradedVertices"},nIterationsRequired:{dependencyType:"stateVariable",variableName:"nIterationsRequired"}}),definition({dependencyValues:e}){let t=0;e.nIterationsRequired>0&&(t=2*e.nIterationsRequired-1);let n,r=Math.max(e.nGradedVertices,t);return n=0===r?0:e.nCorrectVertices/r,{setValue:{fractionCorrectVerticesAdjusted:n,nGradedVerticesAdjusted:r}}}},e.nIterateValues={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition:({dependencyValues:e})=>({setValue:{nIterateValues:Math.ceil((e.nVertices+1)/2)}})},e.iterateValues={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterateValue"],returnArraySizeDependencies:()=>({nIterateValues:{dependencyType:"stateVariable",variableName:"nIterateValues"}}),returnArraySize:({dependencyValues:e})=>[e.nIterateValues],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]="0"===n?{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX1_1"}}:{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX"+2*Number(n)+"_2"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].iterateValue;return{setValue:{iterateValues:n}}}},e}}class Point extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePoint:this.movePoint.bind(this),switchPoint:this.switchPoint.bind(this),pointClicked:this.pointClicked.bind(this),mouseDownOnPoint:this.mouseDownOnPoint.bind(this)})}static componentType="point";static primaryStateVariableForDefinition="coordsShadow";static stateVariableForAttributeValue="coords";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.coords={createComponentOfType:"coords"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"constraints")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{coords:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:[{componentType:"math",children:e}]}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]},{group:"constraints",componentTypes:["constraints"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.markerColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.selectedStyle.markerColorWord+" "+e.selectedStyle.markerStyleWord}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{coordsShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,workspace:n}){return{success:!0,instructions:[{setEssentialValue:"coordsShadow",value:e.coordsShadow}]}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]},x:{dependencyType:"attributeComponent",attributeName:"x"},y:{dependencyType:"attributeComponent",attributeName:"y"},z:{dependencyType:"attributeComponent",attributeName:"z"},xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){let t,n,r=!1;if(n=null!==e.z?3:null!==e.y?2:0,null!==e.coords?(r=!0,t=e.coords.stateValues.value):e.coordsShadow&&(r=!0,t=e.coordsShadow),r){let e=t.tree;return n=Array.isArray(e)&&vectorOperators.includes(e[0])?Math.max(e.length-1,n):Math.max(1,n),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}}}return null!==e.xs?{setValue:{nDimensions:Math.max(e.xs.stateValues.nComponents,n)}}:e.pointChild.length>0?{setValue:{nDimensions:Math.max(e.pointChild[0].stateValues.nDimensions,n)}}:e.vectorChild.length>0?{setValue:{nDimensions:Math.max(e.vectorChild[0].stateValues.nDimensions,n)}}:(0===n&&(n=2),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}})}},e.arrayVariableForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayVariableForConstraints:"unconstrainedXs"}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayEntryPrefixForConstraints:"unconstrainedX"}})},e.nDimensionsForConstraints={isAlias:!0,targetVariableName:"nDimensions"},e.unconstrainedXs={isArray:!0,entryPrefixes:["unconstrainedX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===n&&(t[n].component={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]})}return{globalDependencies:{coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r,a={},i={},s=!1;if(null!==e.coords?(s=!0,r=e.coords.stateValues.value):e.coordsShadow&&(s=!0,r=e.coordsShadow),s){let e=r.tree;if(Array.isArray(e)&&vectorOperators.includes(e[0]))for(let t of n){let n=Number(t);(n>=0||n0)a[e]=r[0].stateValues["x"+n];else{let r=t[e].vectorChild;r.length>0&&(a[e]=r[0].stateValues["x"+n])}}}for(let e of n){let n=t[e].component;n?a[e]=n.stateValues.value.simplify():void 0===a[e]&&(i[e]=!0)}let o={};return Object.keys(a).length>0&&(o.setValue={unconstrainedXs:a}),Object.keys(i).length>0&&(o.useEssentialOrDefaultValue={unconstrainedXs:i}),o},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i,s,o=[],l=!1,u=!1;null!==t.coords?(l=!0,i="coords",s=Array(a[0]+1)):null!==t.coordsShadow&&(l=!0,i="coordsShadow",s=Array(a[0]+1));for(let t of Object.keys(e.unconstrainedXs).reverse()){let a=convertValueToMathExpression(e.unconstrainedXs[t]);if(null!==n[t].component)o.push({setDependency:r[t].component,desiredValue:a,childIndex:0,variableIndex:0});else if(l)s[Number(t)+1]=a.tree,u=!0;else{if(null!==n[t].xs)o.push({setDependency:r[t].xs,desiredValue:a,childIndex:0,variableIndex:0});else{if(n[t].pointChild.length>0)o.push({setDependency:r[t].pointChild,desiredValue:a,childIndex:0,variableIndex:0});else{n[t].vectorChild.length>0?o.push({setDependency:r[t].vectorChild,desiredValue:a,childIndex:0,variableIndex:0}):o.push({setEssentialValue:"unconstrainedXs",value:{[t]:a}})}}}}if(u){let e;1===a[0]?e=me$3.fromAst(s[1]):(s[0]="vector",e=me$3.fromAst(s));let t={setDependency:i,desiredValue:e};"coords"===i&&(t.childIndex=0,t.variableIndex=0),o.push(t)}return{success:!0,instructions:o}}},e.xs={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r={};r.unconstrainedX={dependencyType:"stateVariable",variableName:`unconstrainedX${e}`},r.constraintsChild={dependencyType:"child",childGroups:["constraints"],variableNames:[`constraintResult${e}`]},t[n]=r}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)if(e[r].constraintsChild.length>0){let t=Number(r)+1;n[r]=convertValueToMathExpression(e[r].constraintsChild[0].stateValues["constraintResult"+t])}else n[r]=convertValueToMathExpression(e[r].unconstrainedX);return t.length>0?{setValue:{xs:n}}:{}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r of Object.keys(e.xs).reverse())t[r]&&(t[r].constraintsChild.length>0?i.push({setDependency:n[r].constraintsChild,desiredValue:e.xs[r],childIndex:0,variableIndex:0}):i.push({setDependency:n[r].unconstrainedX,desiredValue:e.xs[r]}));return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.coords={public:!0,shadowingInstructions:{createComponentOfType:"coords",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({xs:{dependencyType:"stateVariable",variableName:"xs"}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.xs)n?t.push(n.tree):t.push("_");return t=t.length>1?["vector",...t]:1===t.length?t[0]:"_",{setValue:{coords:me$3.fromAst(t)}}},inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,initialChange:n}){if(n&&!await t.draggable)return{success:!1};let r=[],a={},i=e.coords.tree;if(Array.isArray(i)&&vectorOperators.includes(i[0]))for(let t=0;t({coords:{dependencyType:"stateVariable",variableName:"coords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.coords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.value={isAlias:!0,targetVariableName:"coords"},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintsChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["constraintUsed"]}}),definition:function({dependencyValues:e}){return 0===e.constraintsChild.length?{setValue:{constraintUsed:!1}}:{setValue:{constraintUsed:e.constraintsChild[0].stateValues.constraintUsed}}}},e.numericalXs={isArray:!0,entryPrefixes:["numericalX"],forRenderer:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={x:{dependencyType:"stateVariable",variableName:`x${e}`}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].x;t?(t=e[r].x.evaluate_to_constant(),Number.isFinite(t)?n[r]=t:n[r]=NaN):n[r]=NaN}return{setValue:{numericalXs:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,initialChange:n,stateValues:r}){if(n&&!await r.draggable)return{success:!1};let a=[];for(let n in e.numericalXs)dependencyValuesByKey[n]&&a.push({setDependency:t[n].xs,desiredValue:e.numericalXs[n]});return{success:!0,instructions:a}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalXs:{dependencyType:"stateVariable",variableName:"numericalXs"}}),definition:({dependencyValues:e})=>({setValue:{nearestPoint:function(){let t={};for(let n=1;n<=e.nDimensions;n++){let r=e.numericalXs[n-1];if(!Number.isFinite(r))return{};t["x"+n]=r}return t}}})},e}static adapters=[{stateVariable:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async movePoint({x:e,y:t,z:n,transient:r,actionId:a}){let i={};return void 0!==e&&(i[0]=me$3.fromAst(e)),void 0!==t&&(i[1]=me$3.fromAst(t)),void 0!==n&&(i[2]=me$3.fromAst(n)),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}switchPoint(){}async pointClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPoint({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class EquilibriumPoint extends Point{static componentType="equilibriumPoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.open={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{open:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.open}]})},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Line extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLine:this.moveLine.bind(this),switchLine:this.switchLine.bind(this),lineClicked:this.lineClicked.bind(this),mouseDownOnLine:this.mouseDownOnLine.bind(this)})}static componentType="line";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.equation={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.slope={createComponentOfType:"number"},e.variables={createComponentOfType:"variables"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){if(0===e.length)return{success:!1};let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{equation:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line"}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nPointsPrescribed:0}}:{setValue:{nPointsPrescribed:e.throughAttr.stateValues.nPoints}}}},e.basedOnSlope={returnDependencies:()=>({slopeAttr:{dependencyType:"attributeComponent",attributeName:"slope"},nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:({dependencyValues:e})=>({setValue:{basedOnSlope:e.nPointsPrescribed<2&&null!==e.slopeAttr&&2===e.nDimensions}})},e.dForSlope={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dForSlope:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dForSlope",value:e.dForSlope}]})},e.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];return null!==e.variables&&(n=e.variables.stateValues.variables),{setValue:{variables:returnNVariables(t[0],n)}}}},e.equationIdentity={returnDependencies:()=>({equation:{dependencyType:"attributeComponent",attributeName:"equation"}}),definition:function({dependencyValues:e}){return null!==e.equation?{setValue:{equationIdentity:e.equation}}:{setValue:{equationIdentity:null}}}},e.essentialPoints={isArray:!0,nDimensions:"2",hasEssential:!0,entryPrefixes:["essentialPointX","essentialPoint"],set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("essentialPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialPoints:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialPoints)t.push({setEssentialValue:"essentialPoints",value:{[n]:convertValueToMathExpression(e.essentialPoints[n])}});return{success:!0,instructions:t}}},e.points={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"pointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["equationIdentity","nPointsPrescribed","basedOnSlope"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){if(null===e.equationIdentity){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1);n[r]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+i]}},e.basedOnSlope?("1"===t&&(1===e.nPointsPrescribed&&n[r].through.variableNames.push("pointX1_"+(Number(a)+1)),n[r].dForSlope={dependencyType:"stateVariable",variableName:"dForSlope"},n[r].slopeAttr={dependencyType:"attributeComponent",attributeName:"slope",variableNames:["value"]}),0===e.nPointsPrescribed&&(n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX2_"+(Number(a)+1)})):n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX"+i}}return{dependenciesByKey:n,globalDependencies:{nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},basedOnSlope:{dependencyType:"stateVariable",variableName:"basedOnSlope"}}}}return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r,componentName:a}){if("coeff0"in e){let t=calculatePointsFromCoeffs(e);if(t.success)return{setValue:{points:t.points}};{let e={};for(let t=0;te.toString()))];for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){if(Number.isNaN(e.nDimensions))return{};let a={};for(let r of n){let n=t[r].point;Array.isArray(n)||(n=[n]);let i=[];for(let t=0;t({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){let t=e.coeff0.evaluate_to_constant();Number.isFinite(t)||(t=NaN);let n=e.coeffvar1.evaluate_to_constant();Number.isFinite(n)||(n=NaN);let r=e.coeffvar2.evaluate_to_constant();return Number.isFinite(r)||(r=NaN),{setValue:{numericalCoeff0:t,numericalCoeffvar1:n,numericalCoeffvar2:r}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){return{setValue:{slope:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeffvar1,b:e.coeffvar2}).simplify()}}}},e.xintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"}}),definition:({dependencyValues:e})=>({setValue:{xintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar1}).simplify()}})},e.yintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:({dependencyValues:e})=>({setValue:{yintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar2}).simplify()}})},e.lastPointsFromInverting={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{lastPointsFromInverting:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"lastPointsFromInverting",value:e.lastPointsFromInverting}]})},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({equation:{dependencyType:"stateVariable",variableName:"equation"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.equation,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalCoeff0:{dependencyType:"stateVariable",variableName:"numericalCoeff0"},numericalCoeffvar1:{dependencyType:"stateVariable",variableName:"numericalCoeffvar1"},numericalCoeffvar2:{dependencyType:"stateVariable",variableName:"numericalCoeffvar2"}}),definition({dependencyValues:e}){let t=e.numericalCoeffvar1,n=e.numericalCoeffvar2,r=e.numericalCoeff0,a=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r),i=2!==e.nDimensions||!a||0===t&&0===n;return{setValue:{nearestPoint:function({variables:e,scales:a=[1,1]}){if(i)return{};let s=a[0],o=a[1],l=t*s,u=n*o,c=l*l+u*u,p=e.x1?.evaluate_to_constant(),d=e.x2?.evaluate_to_constant();if(!Number.isFinite(p)||!Number.isFinite(d))return{};let m=p/s,h=d/o,f={};return f.x1=(u*(u*m-l*h)-l*r)*s/c,f.x2=(l*(-u*m+l*h)-u*r)*o/c,void 0!==e.x3&&(f.x3=0),f}}}}},e}static adapters=[{stateVariable:"equation",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveLine({point1coords:e,point2coords:t,transient:n,actionId:r}){let a={"0,0":me$3.fromAst(e[0]),"0,1":me$3.fromAst(e[1])};return await this.stateValues.basedOnSlope||(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{point1:e,point2:t}}})}switchLine(){}async lineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLine({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}function calculateCoeffsFromEquation({equation:e,variables:t}){let n=t[0],r=t[1],a=n.toString(),i=r.toString();if(e=e.expand().simplify(),!Array.isArray(e.tree)||"="!==e.tree[0]||3!==e.tree.length)return{success:!1};let s=me$3.fromAst(["+",e.tree[2],["-",e.tree[1]]]).expand().simplify(),o=[];o=Array.isArray(s.tree)&&"+"===s.tree[0]?s.tree.slice(1):[s.tree];let l=me$3.fromAst(0),u=me$3.fromAst(0),c=me$3.fromAst(0);for(let e of o){let t=p(e);if(!t.success)return{success:!1};l=l.add(t.coeffvar1),u=u.add(t.coeffvar2),c=c.add(t.coeff0)}return l=l.simplify(),u=u.simplify(),c=c.simplify(),{success:!0,coeff0:c,coeffvar1:l,coeffvar2:u};function p(e){let t=0,s=0,o=0;if("string"==typeof e)e===a?t=1:e===i?s=1:o=e;else if("number"==typeof e)o=e;else{if(!Array.isArray(e))return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};{let a=e[0],i=e.slice(1);if("-"===a){let e=p(i[0]);if(!e.success)return{success:!1};t=["-",e.coeffvar1.tree],s=["-",e.coeffvar2.tree],o=["-",e.coeff0.tree]}else{if("+"===a)return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};if("*"===a){let a=-1,l=-1;for(let e=0;e({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},e}async switchLine({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Curve extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveControlVector:this.moveControlVector.bind(this),moveThroughPoint:this.moveThroughPoint.bind(this),changeVectorControlDirection:this.changeVectorControlDirection.bind(this),switchCurve:this.switchCurve.bind(this),curveClicked:this.curveClicked.bind(this),mouseDownOnCurve:this.mouseDownOnCurve.bind(this)})}static componentType="curve";static rendererType="curve";static primaryStateVariableForDefinition="fShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.flipFunction={createComponentOfType:"boolean",createStateVariable:"flipFunction",defaultValue:!1,public:!0,forRenderer:!0},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:1e3,public:!0},e.periodic={createComponentOfType:"boolean",createStateVariable:"periodic",defaultValue:!1,public:!0},e.splineTension={createComponentOfType:"number",createStateVariable:"splineTension",defaultValue:.8,clamp:[0,1],public:!0},e.extrapolateBackward={createComponentOfType:"boolean",createStateVariable:"extrapolateBackward",defaultValue:!1,public:!0,forRenderer:!0},e.extrapolateForward={createComponentOfType:"boolean",createStateVariable:"extrapolateForward",defaultValue:!1,public:!0,forRenderer:!0},e.splineForm={createComponentOfType:"text",createStateVariable:"splineForm",defaultValue:"centripetal",public:!0,toLowerCase:!0,validValues:["centripetal","uniform"]},e.variable={createComponentOfType:"variable",createStateVariable:"variableForChild",defaultValue:me$3.fromAst("x")},e.through={createComponentOfType:"_pointListComponent"},e.parMin={createComponentOfType:"math"},e.parMax={createComponentOfType:"math"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurvePrelim",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e=>t.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}if(0===a.length)return{success:!1};let o=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"function",children:e}),mustStripOffOuterParentheses:!0}),l=o({matchedChildren:a}),u=[];return u=l.success?l.newChildren:[{componentType:"function",children:a}],{success:!0,newChildren:[...i,...u,...s]}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"functions",componentTypes:["function"]},{group:"bezierControls",componentTypes:["bezierControls"]}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" curve"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},through:{dependencyType:"attributeComponent",attributeName:"through"}}),definition({dependencyValues:e}){let t="function";return null!==e.through?t="bezier":e.functionChildren.length>1&&(t="parameterization"),{setValue:{curveType:t}}}},t.fShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fShadow:!0}})},t.graphXmin={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"graphXmax",forRenderer:!0},{variableName:"graphYmin",forRenderer:!0},{variableName:"graphYmax",forRenderer:!0}],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphXmin:e.graphAncestor.stateValues.xmin,graphXmax:e.graphAncestor.stateValues.xmax,graphYmin:e.graphAncestor.stateValues.ymin,graphYmax:e.graphAncestor.stateValues.ymax}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMaxAttr:{dependencyType:"attributeComponent",attributeName:"parMax",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=e.nThroughPoints-1,e.extrapolateForward&&(t*=2);else if(null!==e.parMaxAttr)t=e.parMaxAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][2]).evaluate_to_constant(),Number.isFinite(t)||t===1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?r+.1*(r-n):Math.min(t,r+.1*(r-n))),void 0===t&&(t=1/0)}else t=10;return{setValue:{parMax:t}}}},t.parMin={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMinAttr:{dependencyType:"attributeComponent",attributeName:"parMin",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=0,e.extrapolateBackward&&(t=-(e.nThroughPoints-1));else if(null!==e.parMinAttr)t=e.parMinAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)||t===-1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?n+.1*(n-r):Math.max(t,n+.1*(n-r))),void 0===t&&(t=-1/0)}else t=-10;return{setValue:{parMin:t}}}},t.domainForFunctions={returnDependencies:()=>({parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"}}),definition:({dependencyValues:e})=>({setValue:{domainForFunctions:[me$3.fromAst(["interval",["tuple",e.parMin,e.parMax],["tuple",!0,!0]])]}})},t.nThroughPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nThroughPoints:t}}}},t.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.through){return{setValue:{nDimensions:e.through.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].through;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst(0)}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].through||!t[r].through.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].through,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,entryPrefixes:["numericalThroughPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}}},t.haveBezierControls={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"]}}),definition:({dependencyValues:e})=>({setValue:{haveBezierControls:e.controlChild.length>0}})},t.bezierControlsAlwaysVisible={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["alwaysVisible"]}}),definition:({dependencyValues:e})=>({setValue:{bezierControlsAlwaysVisible:e.controlChild.length>0&&e.controlChild[0].stateValues.alwaysVisible}})},t.vectorControlDirections={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["vectorControlDirection"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["direction"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["direction"+(Number(r)+1)]:n[r]="none"}return{setValue:{vectorControlDirections:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.vectorControlDirections){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.vectorControlDirections[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.hiddenControls={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["hiddenControl"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["hiddenControl"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["hiddenControl"+(Number(r)+1)]:n[r]=!1}return{setValue:{hiddenControls:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.hiddenControls){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.hiddenControls[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.controlVectors={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlVectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlVectorX","controlVector"],nDimensions:3,stateVariablesDeterminingDependencies:["vectorControlDirections","nThroughPoints"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlVectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1)),i=a.join("_");n[r]={direction:{dependencyType:"stateVariable",variableName:"vectorControlDirection"+a[0]},controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["control"+i]}};let s=e[0],o=t.vectorControlDirections[s],l=[];"none"===o?l=[s-1,s,s+1]:"previous"===o?l=[s,s+1]:"next"===o&&(l=[s-1,s]);for(let e of l)e>=0&&eNumber(e))),s=r.map((e=>e+1)),o=s.join("_"),l=r[0],u=r[1],c=n[i].direction;if("none"===c){let r,s,o=n[i]["throughPoint"+(l+1)];l>0&&(r=n[i]["throughPoint"+l]),lNumber(e))),s=i.map((e=>e+1)),o=s.join("_"),l=n[r].controlChild;if(l.length>0){l[0].stateValues["control"+o]&&a.push({setDependency:t[r].controlChild,desiredValue:e.controlVectors[r],childIndex:0,variableIndex:0})}}return{success:!0,instructions:a}}},t.numericalControlVectors={isArray:!0,entryPrefixes:["numericalControlVector"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlVector:{dependencyType:"stateVariable",variableName:"controlVector"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlVector.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlVectors:n}}}},t.controlPoints={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlPointX","controlPoint"],nDimensions:3,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={throughPointX:{dependencyType:"stateVariable",variableName:"throughPointX"+r[0]+"_"+r[2]},controlVectorX:{dependencyType:"stateVariable",variableName:"controlVectorX"+a}}}return{globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(2!==e.nDimensions)r[a]=me$3.fromAst(NaN);else{let e=t[a].controlVectorX;if(e){let n=t[a].throughPointX.evaluate_to_constant();Number.isFinite(n)||(n=NaN),r[a]=me$3.fromAst(n+e.tree)}else r[a]=null}return{setValue:{controlPoints:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls||2!==r.nDimensions)return{success:!1};let a=[];for(let r in e.controlPoints){if(n[r].controlVectorX){let i=n[r].throughPointX,s=e.controlPoints[r];s.tree&&(s=s.tree);let o=me$3.fromAst(["+",s,["-",i.tree]]);a.push({setDependency:t[r].controlVectorX,desiredValue:o})}}return{success:!0,instructions:a}}},t.numericalControlPoints={isArray:!0,entryPrefixes:["numericalControlPoint"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlPoint:{dependencyType:"stateVariable",variableName:"controlPoint"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlPoint.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlPoints:n}}}},t.splineCoeffs={isArray:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r=e+1;t[n]={previousPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+e},nextPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+r},previousVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+e+"_2"},nextVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+r+"_1"}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].previousPoint,a=e[r].nextPoint,i=e[r].previousVector,s=e[r].nextVector,o=[];for(let e=0;e<2;e++)o.push(initCubicPoly(t[e],a[e],3*i[e],-3*s[e]));n[r]=o}return{setValue:{splineCoeffs:n}}}},t.extrapolateBackwardCoeffs={stateVariablesDeterminingDependencies:["extrapolateBackward"],additionalStateVariablesDefined:[{variableName:"extrapolateBackwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateBackward&&(t.firstSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs1"},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateBackward||!e.firstSplineCoeffs)return{setValue:{extrapolateBackwardCoeffs:null,extrapolateBackwardMode:""}};let t=e.firstSplineCoeffs[0],n=e.firstSplineCoeffs[1],r=t[0],a=t[1],i=2*t[2],s=n[0],o=n[1],l=a*a+o*o,u=(o*i-a*(2*n[2]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateBackwardCoeffs:[[r,t,0],[s,n,0]],extrapolateBackwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a>0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateBackwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateBackwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateBackwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateBackwardMode:"parabolaHorizontal"}}}}},t.extrapolateForwardCoeffs={stateVariablesDeterminingDependencies:["nThroughPoints","extrapolateForward"],additionalStateVariablesDefined:[{variableName:"extrapolateForwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateForward&&e.nThroughPoints>=2&&(t.lastSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs"+(e.nThroughPoints-1)},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateForward||!e.lastSplineCoeffs)return{setValue:{extrapolateForwardCoeffs:null,extrapolateForwardMode:""}};let t=e.lastSplineCoeffs[0],n=e.lastSplineCoeffs[1],r=t[0]+t[1]+t[2]+t[3],a=t[1]+2*t[2]+3*t[3],i=2*t[2]+6*t[3],s=n[0]+n[1]+n[2]+n[3],o=n[1]+2*n[2]+3*n[3],l=a*a+o*o,u=(o*i-a*(2*n[2]+6*n[3]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateForwardCoeffs:[[r,t,0],[s,n,0]],extrapolateForwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a<0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateForwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateForwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateForwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateForwardMode:"parabolaHorizontal"}}}}},t.fs={isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0,entryPrefixes:["fDefinition"]}],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinitions:{stateVariableToShadow:"fDefinitions"},domain:{stateVariableToShadow:"domainForFunctions"}}},returnArraySizeDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),returnArraySize:({dependencyValues:e})=>"bezier"===e.curveType?[2]:[Math.max(1,e.functionChildren.length)],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalf","fDefinition"],childIndices:[n]}},0===Number(n)&&(t[n].fShadow={dependencyType:"stateVariable",variableName:"fShadow"},t[n].fDefinitionAdapted={dependencyType:"adapterSourceStateVariable",variableName:"fDefinition"});return{globalDependencies:{curveType:{dependencyType:"stateVariable",variableName:"curveType"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},extrapolateBackwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateBackwardCoeffs"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},extrapolateForwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateForwardCoeffs"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if("bezier"===e.curveType){let t={functionType:"bezier",nThroughPoints:e.nThroughPoints,numericalThroughPoints:e.numericalThroughPoints,splineCoeffs:e.splineCoeffs,extrapolateForward:e.extrapolateForward,extrapolateForwardCoeffs:e.extrapolateForwardCoeffs,extrapolateBackward:e.extrapolateBackward,extrapolateBackwardCoeffs:e.extrapolateBackwardCoeffs},n={},r={};return t.component=0,n[0]=returnBezierFunctions(t),r[0]=t,t={...t},t.component=1,n[1]=returnBezierFunctions(t),r[1]=t,{setValue:{fs:n,fDefinitions:r}}}let r={},a={};for(let e of n){let n=t[e].functionChild;1===n.length?(r[e]=n[0].stateValues.numericalf,a[e]=n[0].stateValues.fDefinition):0===Number(e)&&t[e].fShadow?(r[e]=t[e].fShadow,a[e]=t[e].fDefinitionAdapted):(r[e]=()=>0,a[e]={functionType:"zero"})}return{setValue:{fs:r,fDefinitions:a}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.allXCriticalPoints={returnDependencies:()=>({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allXCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[0],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allXCriticalPoints:t}}}},t.nXCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nXCriticalPoints:e.allXCriticalPoints.length}})},t.xCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"xCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["xCriticalPointX","xCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("xCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("xCriticalPoints"===t)return 1===e.length?"xCriticalPoint"+e[0]:`xCriticalPointX${e[0]}_${e[1]}`;if("xCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`xCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nXCriticalPoints:{dependencyType:"stateVariable",variableName:"nXCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nXCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allYCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[1],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allYCriticalPoints:t}}}},t.nYCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nYCriticalPoints:e.allYCriticalPoints.length}})},t.yCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"yCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["yCriticalPointX","yCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("yCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("yCriticalPoints"===t)return 1===e.length?"yCriticalPoint"+e[0]:`yCriticalPointX${e[0]}_${e[1]}`;if("yCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`yCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nYCriticalPoints:{dependencyType:"stateVariable",variableName:"nYCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nYCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allCurvatureChangePoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let[e,r,s,o]=n[0],[l,u,c,p]=n[1],d=3*(s*p-c*o),m=3*(r*p-u*o),h=r*c-u*s;if(Math.abs(d)<1e-14){i=addTimePointBezier({t:-h/m,ind:t,ts:a,ignoreLeft:i})}else{let e=m*m-4*d*h;if(0==e){i=addTimePointBezier({t:-m/(2*d),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),r=[(-m-n)/(2*d),(-m+n)/(2*d)];d<0&&(r=[r[1],r[0]]);let s=!1;for(let e of r){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(s=!0)}i=s}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allCurvatureChangePoints:t}}}},t.nCurvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}),definition:({dependencyValues:e})=>({setValue:{nCurvatureChangePoints:e.allCurvatureChangePoints.length}})},t.curvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"curvatureChangePointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["curvatureChangePointX","curvatureChangePoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("curvatureChangePointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("curvatureChangePoints"===t)return 1===e.length?"curvatureChangePoint"+e[0]:`curvatureChangePointX${e[0]}_${e[1]}`;if("curvatureChangePoint"===t.slice(0,20)){let n=Number(t.slice(20));if(Number.isInteger(n)&&n>0)return`curvatureChangePointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"nCurvatureChangePoints"}}),returnArraySize:({dependencyValues:e})=>[e.nCurvatureChangePoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({nearestPointAsCurvePrelim:{dependencyType:"stateVariable",variableName:"nearestPointAsCurvePrelim"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nearestPointAsCurve"]},adapterSourceValue:{dependencyType:"adapterSourceStateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.nearestPointAsCurvePrelim;return t.nearestPointAsCurvePrelim&&(e.functionChild.length>0?n=e.functionChild[0].stateValues.nearestPointAsCurve:null!==e.adapterSourceValue&&(n=e.adapterSourceValue)),{setValue:{nearestPointAsCurve:n}}}},t.nearestPoint={returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},fs:{dependencyType:"stateVariable",variableName:"fs"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"},parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"},periodic:{dependencyType:"stateVariable",variableName:"periodic"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},nearestPointAsCurve:{dependencyType:"stateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:t}){let n=null;return"function"===t.curveType?n=getNearestPointFunctionCurve({dependencyValues:t,numerics:e}):["parameterization","bezier"].includes(t.curveType)&&(n=getNearestPointParametrizedCurve({dependencyValues:t,numerics:e})),{setValue:{nearestPoint:n}}}},t}async moveControlVector({controlVector:e,controlVectorInds:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["controlVector"+t.join("_")]:e}}})}async moveThroughPoint({throughPoint:e,throughPointInd:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["throughPoint"+t]:e}}})}async changeVectorControlDirection({direction:e,throughPointInd:t,actionId:n}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vectorControlDirection",value:{[t]:e}}],actionId:n})}switchCurve(){}async curveClicked({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnCurve({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}}function getNearestPointFunctionCurve({dependencyValues:e,numerics:t}){let n=e.flipFunction,r=e.fs[0],a=e.nDiscretizationPoints,i=e.parMax,s=e.parMin;return function({variables:o,scales:l}){let u,c,p,d,m=o.x1?.evaluate_to_constant(),h=o.x2?.evaluate_to_constant(),f=l[0],y=l[1];if(s!==-1/0){if(u=s,c=r(s),!Number.isFinite(c)){let e=.99999*s+1e-5*i,t=r(e);Number.isFinite(t)&&(u=e,c=t)}if(n){let e=u;u=c,c=e}}if(i!==1/0){if(p=i,d=r(i),!Number.isFinite(d)){let e=1e-5*s+.99999*i,t=r(e);Number.isFinite(t)&&(p=e,d=t)}if(n){let e=p;p=d,d=e}}if(!e.nearestPointAsCurve||!Number.isFinite(m)||!Number.isFinite(h)){let e,t;if(n?(t=h,e=r(t)):(e=m,t=r(e)),!Number.isFinite(e)||!Number.isFinite(t)){let r,a;n?(r=Math.abs(s-h),a=Math.abs(i-h)):(r=Math.abs(s-m),a=Math.abs(i-m)),re.evaluate_to_constant())),a)l=a.map((e=>e.evaluate_to_constant())),s=n?n.map((e=>e.evaluate_to_constant())):[2*o[0]-l[0],2*o[1]-l[1]];else{if(!n)return{coordsNumeric:[me$3.fromAst(NaN),me$3.fromAst(NaN)],numericEntries:!1};s=n.map((e=>e.evaluate_to_constant())),l=[2*o[0]-s[0],2*o[1]-s[1]]}let c=[];if("centripetal"===i){let n=u(s,o),r=u(o,l);n=Math.sqrt(n),r=Math.sqrt(r),rme$3.fromAst(e)));return{coordsNumeric:p,numericEntries:Number.isFinite(c[0])&&Number.isFinite(c[1])}}function initCubicPoly(e,t,n,r){return[e,n,-3*e+3*t-2*n-r,2*e-2*t+n+r]}function addTimePointBezier({t:e,ind:t,ts:n,ignoreLeft:r=!1}){const a=1e-14;let i=!1;return e>=a?e<=.99999999999999?n.push(t+e):e<1.00000000000001&&(n.push(t+1),i=!0):e>-a&&!r&&n.push(t),i}class EquilibriumCurve extends Curve{static componentType="equilibriumCurve";static rendererType="curve";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.dashed={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},t}async switchCurve({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}var DynamicalSystems=Object.freeze({__proto__:null,ODESystem:ODESystem,CobwebPolyline:CobwebPolyline,EquilibriumPoint:EquilibriumPoint,EquilibriumLine:EquilibriumLine,EquilibriumCurve:EquilibriumCurve});class Atom extends InlineComponent{static componentType="atom";static rendererType="math";static primaryStateVariableForDefinition="atomicNumberShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.atomicNumberShadow={defaultValue:null,hasEssential:!0,essentialVarName:"atomicNumber",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Name:null,{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.atomicMass={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Mass"]:null,{setValue:{atomicMass:t}}}},e.phaseAtSTP={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Phase at STP"]:null,{setValue:{phaseAtSTP:t}}}},e.chargeOfCommonIon={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Charge of Common Ion"]:null,{setValue:{chargeOfCommonIon:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.ionizationEnergy={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Ionization Energy"]:null,{setValue:{ionizationEnergy:t}}}},e.meltingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Melting Point"]:null,{setValue:{meltingPoint:t}}}},e.boilingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Boiling Point"]:null,{setValue:{boilingPoint:t}}}},e.atomicRadius={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Radius"]:null,{setValue:{atomicRadius:t}}}},e.density={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Density:null,{setValue:{density:t}}}},e.electronegativity={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Electronegativity:null,{setValue:{electronegativity:t}}}},e.electronConfiguration={public:!0,shadowingInstructions:{createComponentOfType:"electronConfiguration"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Electron Configuration"]:null,{setValue:{electronConfiguration:t}}}},e.orbitalDiagram={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({electronConfiguration:{dependencyType:"stateVariable",variableName:"electronConfiguration"}}),definition({dependencyValues:e}){let t;return t=e.electronConfiguration?electronConfigurationToOrbitalDiagram(e.electronConfiguration):null,{setValue:{orbitalDiagram:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?["^",e.symbol]:"_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?`\\text{${e.symbol}}`:"[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name",{stateVariable:"atomicNumber",componentType:"ion"}]}function electronConfigurationToOrbitalDiagram(e){let t=e.tree;if(!Array.isArray(t)||"*"!==t[0])return null;t=t.slice(1);let n=t.length/2;if(!Number.isInteger(n))return null;let r=[];for(let e=0;e0))return null;let a=t[2*e+1];if(!Array.isArray(a)||"^"!==a[0])return null;let i=a[1],s=a[2];if(!(["s","p","d","f"].includes(i)&&Number.isInteger(s)&&s>0))return null;let o,l=`${n}${i}`;o="s"===i?1:"p"===i?3:"d"===i?5:7;let u=Array(o).fill("");for(let e=0;e({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomChild:{dependencyType:"child",childGroups:["atoms"],variableNames:["atomicNumber"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.atomChild.length>0)n=e.atomChild[0].stateValues.atomicNumber;else if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.charge={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},chargeAttr:{dependencyType:"attributeComponent",attributeName:"charge",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return e.chargeAttr?(t=e.chargeAttr.stateValues.value,Number.isFinite(t)||(t=0)):t=e.dataForAtom&&e.dataForAtom["Charge of Common Ion"]||0,{setValue:{charge:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},charge:{dependencyType:"stateVariable",variableName:"charge"},group:{dependencyType:"stateVariable",variableName:"group"},atomicNumber:{dependencyType:"stateVariable",variableName:"atomicNumber"}}),definition({dependencyValues:e}){let t;if(e.dataForAtom){if(t=e.dataForAtom.Name,e.charge<0){let e={Hydrogen:"Hydride",Oxygen:"Oxide",Sulfur:"Sulfide",Nitrogen:"Nitride",Phosphorus:"Phosphide",Carbon:"Carbide"},n=t.length;"ine"===t.substring(n-3,n)?t=t.substring(0,n-3)+"ide":t in e&&(t=e[t])}else if(e.charge>0&&(e.group>=3&&e.group<=12||101===e.group||102===e.group||[13,31,49,50,81,82,83,84].includes(e.atomicNumber))){let n="";switch(e.charge){case 1:n=" (I)";break;case 2:n=" (II)";break;case 3:n=" (III)";break;case 4:n=" (IV)";break;case 5:n=" (V)";break;case 6:n=" (VI)";break;case 7:n=" (VII)";break;case 8:n=" (VIII)"}t+=n}}else t=null;return{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=["^",e.symbol],-1===e.charge?t.push("-"):1===e.charge?t.push("+"):e.charge<0?t.push(Math.abs(e.charge)+"-"):e.charge>0&&t.push(Math.abs(e.charge)+"+")):t="_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=`\\text{${e.symbol}}`,-1===e.charge?t+="^-":1===e.charge?t+="^+":e.charge<0?t+=`^{${Math.abs(e.charge)}-}`:e.charge>0&&(t+=`^{${Math.abs(e.charge)}+}`)):t="[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name"]}class IonicCompound extends InlineComponent{static componentType="ionicCompound";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e.charge={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"ions",componentTypes:["ion"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.ionicCompound={returnDependencies:()=>({ionChildren:{dependencyType:"child",childGroups:["ions"],variableNames:["symbol","charge","atomicNumber","name"]}}),definition({dependencyValues:e}){let t=e.ionChildren.map((e=>e.stateValues.charge));if(2!==t.length)return console.warn("have not implemented ionic compound for anything other than two ions"),{setValue:{ionicCompound:null}};if(!(t[0]*t[1]<0))return console.warn("ionic compound implemented only for one cation and one anion"),{setValue:{ionicCompound:null}};let n=Math.abs(t[1]),r=Math.abs(t[0]),a=me$3.math.gcd(n,r);return n/=a,r/=a,{setValue:{ionicCompound:[{symbol:e.ionChildren[0].stateValues.symbol,atomicNumber:e.ionChildren[0].stateValues.atomicNumber,name:e.ionChildren[0].stateValues.name,charge:t[0],count:n},{symbol:e.ionChildren[1].stateValues.symbol,atomicNumber:e.ionChildren[1].stateValues.atomicNumber,name:e.ionChildren[1].stateValues.name,charge:t[1],count:r}]}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t=[];for(let n of e.ionicCompound){let e=n.symbol;n.count>1&&(e=["_",e,n.count]),t.push(e)}t=t.length>1?["*",...t]:1===t.length?t[0]:"_"}else t="_";return{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t="";for(let n of e.ionicCompound)t+=`\\text{${n.symbol}}`,n.count>1&&(t+=`_{${n.count}}`)}else t="[\\text{Invalid Ionic Compound}]";return{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math"]}class ElectronConfiguration extends MathComponent{static componentType="electronConfiguration";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;try{n=e.valueForDisplay.toLatex()}catch(e){n="_"}return n=n.replaceAll("\\,",""),n=n.replaceAll("\\cdot","~"),{setValue:{latex:n}}}},e}}class OrbitalDiagram extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagram";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.labels={createComponentOfType:"textList",createStateVariable:"labels",defaultValue:[]},e}static returnSugarInstructions(){return[{replacementFunction:function({matchedChildren:e}){return 1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"tupleList",children:e}]}}}]}static returnChildGroups(){return[{group:"tupleLists",componentTypes:["tupleList"]},{group:"orbitalDiagrams",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({orbitalDiagramChildren:{dependencyType:"child",childGroups:["orbitalDiagrams"],variableNames:["value"]},tupleListChildren:{dependencyType:"child",childGroups:["tupleLists"],variableNames:["maths"]},labels:{dependencyType:"stateVariable",variableName:"labels"}}),definition:function({dependencyValues:e}){return{setValue:{value:function(){function t(e){if("u"===e||"U"===e)return"U";if("d"===e||"D"===e)return"D";if("e"===e||"E"===e)return"";if(Array.isArray(e)&&"*"===e[0]){let t="";for(let n of e.slice(1))if("u"===n||"U"===n)t+="U";else{if("d"!==n&&"D"!==n)return"";t+="D"}return t}return""}if(1===e.orbitalDiagramChildren.length)return e.orbitalDiagramChildren[0].stateValues.value;let n=[];if(e.tupleListChildren[0]?.stateValues.maths.length>0){let r=e.tupleListChildren[0].stateValues.maths;for(let[a,i]of r.entries()){let r="";e.labels[a]&&(r=e.labels[a]);let s=[];if(Array.isArray(i.tree)&&"tuple"===i.tree[0])for(let e of i.tree.slice(1))s.push(t(e));else s.push(t(i.tree));n.push({orbitalText:r,boxes:s})}return n}return[{orbitalText:"",boxes:[]}]}()}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class OrbitalDiagramInput extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{addRow:this.addRow.bind(this),removeRow:this.removeRow.bind(this),addBox:this.addBox.bind(this),removeBox:this.removeBox.bind(this),addUpArrow:this.addUpArrow.bind(this),addDownArrow:this.addDownArrow.bind(this),removeArrow:this.removeArrow.bind(this),updateRowText:this.updateRowText.bind(this),selectRow:this.selectRow.bind(this),selectBox:this.selectBox.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagramInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"orbitalDiagram",createStateVariable:"prefill",defaultValue:[]},e.prefillLabel={createComponentOfType:"textList",createStateVariable:"prefillLabel",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLabel:{dependencyType:"stateVariable",variableName:"prefillLabel"}}),definition:function({dependencyValues:e}){return{useEssentialOrDefaultValue:{value:{get defaultValue(){return function(){if(e.prefill?.length>0){let t=JSON.parse(JSON.stringify(e.prefill));for(let[n,r]of t.entries())e.prefillLabel[n]&&(r.orbitalText=e.prefillLabel[n]);return t}return[{orbitalText:"",boxes:[]}]}()}}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"value",value:e.value}]})},e.rows={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{rows:[...e.value].reverse()}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:[...e.rows].reverse()}]})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({rows:{dependencyType:"stateVariable",variableName:"rows"}}),definition:function({dependencyValues:e}){return{setValue:{numRows:e.rows.length}}}},e.selectedRowIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedRowIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=await t.numRows,r=e.selectedRowIndex;return r=Number.isFinite(r)?Math.min(n,Math.max(0,Math.round(r))):0,{success:!0,instructions:[{setEssentialValue:"selectedRowIndex",value:r}]}}},e.selectedBoxIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedBoxIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e}){let t=e.selectedBoxIndex;return t=Number.isFinite(t)?Math.max(0,Math.round(t)):0,{success:!0,instructions:[{setEssentialValue:"selectedBoxIndex",value:t}]}}},e}async addRow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t));t.length<20&&(n=[{orbitalText:"",boxes:[]},...t]);let r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==await this.stateValues.selectedRowIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0}),-1!==await this.stateValues.selectedBoxIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeRow({actionId:e}){let t=await this.stateValues.rows,n=await this.stateValues.selectedRowIndex-1,r=JSON.parse(JSON.stringify(t));if(t.length>1){let e=t.length-1-n;-1===n&&(e=0),r.splice(e,1)}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async addBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0),n[a].boxes.length<17&&n[a].boxes.push("");let i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];if(-1!==r){let e=0;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e})}return await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.splice(s,1);let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==i&&o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addUpArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"U");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addDownArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"D");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length>0&&(n[a].boxes[s]=n[a].boxes[s].slice(0,-1));let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async updateRowText({newValue:e,actionId:t}){let n=await this.stateValues.rows,r=JSON.parse(JSON.stringify(n)),a=await this.stateValues.selectedRowIndex-1,i=n.length-a-1;-1===a&&(i=0),r[i].orbitalText=e;let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r}];return await this.coreFunctions.performUpdate({updateInstructions:s,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async selectRow({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedRowIndex:e}}})}async selectBox({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedBoxIndex:e}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Chemistry=Object.freeze({__proto__:null,Atom:Atom,Ion:Ion,IonicCompound:IonicCompound,ElectronConfiguration:ElectronConfiguration,OrbitalDiagram:OrbitalDiagram,OrbitalDiagramInput:OrbitalDiagramInput});class FeedbackDefinition extends BaseComponent{static componentType="feedbackDefinition";static createAttributesObject(){let e=super.createAttributesObject();return e.code={createComponentOfType:"text"},e.text={createComponentOfType:"text"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.feedbackDefinition={returnDependencies:()=>({codeAttr:{dependencyType:"attributeComponent",attributeName:"code",variableNames:["value"]},textAttr:{dependencyType:"attributeComponent",attributeName:"text",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.codeAttr&&null!==e.textAttr){return{setValue:{feedbackDefinition:{[e.codeAttr.stateValues.value.toLowerCase()]:e.textAttr.stateValues.value}}}}return{setValue:{feedbackDefinition:null}}}},e}}class FeedbackDefinitions extends BaseComponent{static componentType="feedbackDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"feedbackDefinition",componentTypes:["feedbackDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({feedbackDefinitionChildren:{dependencyType:"child",childGroups:["feedbackDefinition"],variableNames:["feedbackDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.feedbackDefinitionChildren)n.stateValues.feedbackDefinition&&Object.assign(t,n.stateValues.feedbackDefinition);return{setValue:{value:t}}}},e}}var FeedbackDefinitions$1=Object.freeze({__proto__:null,FeedbackDefinition:FeedbackDefinition,FeedbackDefinitions:FeedbackDefinitions});class StyleDefinition extends BaseComponent{static componentType="styleDefinition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();e.styleNumber={createPrimitiveOfType:"number",createStateVariable:"styleNumber",defaultValue:1};for(let t in styleAttributes)e[t]={createComponentOfType:styleAttributes[t].componentType};return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDefinition={returnDependencies:function(){let e={};for(let t in styleAttributes)e[t]={dependencyType:"attributeComponent",attributeName:t,variableNames:["value"]};return e},definition:function({dependencyValues:e}){let t={};for(let n in styleAttributes)null!==e[n]&&(t[n]=e[n].stateValues.value,"string"==typeof t[n]&&(t[n]=t[n].toLowerCase()));return{setValue:{styleDefinition:t}}}},e}}class StyleDefinitions extends BaseComponent{static componentType="styleDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"styleDefinition",componentTypes:["styleDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({styleDefinitionChildren:{dependencyType:"child",childGroups:["styleDefinition"],variableNames:["styleNumber","styleDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.styleDefinitionChildren){let e=n.stateValues.styleNumber,r=t[e];r||(r=t[e]={}),Object.assign(r,n.stateValues.styleDefinition)}return{setValue:{value:t}}}},e}}var StyleDefinitions$1=Object.freeze({__proto__:null,StyleDefinition:StyleDefinition,StyleDefinitions:StyleDefinitions});class ComponentWithSelectableType extends BaseComponent{static componentType="_componentWithSelectableType";static rendererType=void 0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=t.type;r||(r=n.type),r?["number","letters","math","text","boolean"].includes(r)||(console.warn(`Invalid type ${r}, setting type to number`),r="number"):r="number";let a="letters"===r?"text":r;return"text"!==a&&(e=e.filter((e=>"string"!=typeof e||""!==e.trim()))),{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.type={shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"doenetAttribute",attributeName:"type"},parentType:{dependencyType:"parentStateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentName:t}){let n=e.type;return n||(n=e.parentType),n?["number","letters","math","text","boolean"].includes(n)||(console.warn(`Invalid type ${n}, setting type to number`),n="number"):n="number",{setValue:{type:n}}}},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},atMostOneChild:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=e.atMostOneChild.length>0?e.atMostOneChild[0].stateValues.value:"text"===e.type||"letters"===e.type?"":"boolean"!==e.type&&("number"===e.type?NaN:me$3.fromAst("_")),{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.atMostOneChild.length>0?{success:!0,instructions:[{setDependency:"atMostOneChild",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!1}},e}}class ComponentListWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListWithSelectableType";static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n,isAttributeComponent:r=!1,createdFromMacro:a=!1,componentInfoObjects:i}){let s=t.type;s||(s=n.type),s?["number","letters","math","text","boolean"].includes(s)||(console.warn(`Invalid type ${s}, setting type to number`),s="number"):s="number";let o="letters"===s?"text":s;if(r&&!a){return returnGroupIntoComponentTypeSeparatedBySpaces({componentType:o})({matchedChildren:e})}return returnBreakStringsIntoComponentTypeBySpaces({componentType:o})({matchedChildren:e})}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nValues={additionalStateVariablesDefined:["childForValue"],returnDependencies:()=>({anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=0,n=[];for(let[r,a]of e.anythingForSelectedType.entries()){let e=Number.isInteger(a.stateValues.nValues)?a.stateValues.nValues:1;t+=e;for(let t=0;t({nValues:{dependencyType:"stateVariable",variableName:"nValues"}}),returnArraySize:({dependencyValues:e})=>[e.nValues],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.childForValue[r];n[r]={anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values"],childIndices:[e.child],variablesOptional:!0},valueIndex:{dependencyType:"value",value:e.valueIndex}}}return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){let a={};for(let r of n)if(t[r].anythingForSelectedType&&1===t[r].anythingForSelectedType.length){let n,i=t[r].anythingForSelectedType[0];n=i.stateValues.values?i.stateValues.values[t[r].valueIndex]:i.stateValues.value,a[r]=convertValueToType(n,e.type)}return{setValue:{values:a},setCreateComponentOfType:{values:e.type}}}},e}}class ComponentListOfListsWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListOfListsWithSelectableType";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:!0});if(!0!==r.success)return{success:!1};let a=t.type;return a||(a=n.type),a?["number","letters","math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}, setting type to number`),a="number"):a="number",{success:!0,newChildren:r.pieces.map((e=>({componentType:"_componentListWithSelectableType",attributes:{type:{primitive:a}},children:e})))}}}),e}static returnChildGroups(){return[{group:"lists",componentTypes:["_componentListWithSelectableType"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nLists={returnDependencies:()=>({listChildren:{dependencyType:"child",childGroups:["lists"]}}),definition:({dependencyValues:e})=>({setValue:{nLists:e.listChildren.length}})},e.lists={isArray:!0,entryPrefixes:["list"],returnArraySizeDependencies:()=>({nLists:{dependencyType:"stateVariable",variableName:"nLists"}}),returnArraySize:({dependencyValues:e})=>[e.nLists],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={listChildren:{dependencyType:"child",childGroups:["lists"],variableNames:["values","type"],childIndices:[n]}};return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(t[a].listChildren&&1===t[a].listChildren.length){let n=t[a].listChildren[0];n.stateValues.type===e.type?r[a]=n.stateValues.values:r[a]=n.stateValues.values.map((t=>convertValueToType(t,e.type)))}return{setValue:{lists:r}}}},e}}function convertValueToType(e,t){if(Array.isArray(e)&&(e=e[0]),"number"===t){if(e instanceof me$3.class){let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}return Number(e)}if("math"===t){if("string"==typeof e)try{return me$3.fromAst(textToAst$1.convert(e))}catch(e){}return convertValueToMathExpression(e)}return"boolean"===t?Boolean(e):String(e)}var ComponentWithSelectableType$1=Object.freeze({__proto__:null,ComponentWithSelectableType:ComponentWithSelectableType,ComponentListWithSelectableType:ComponentListWithSelectableType,ComponentListOfListsWithSelectableType:ComponentListOfListsWithSelectableType});class SideBySide extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="sideBySide";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.widths={createComponentOfType:"_componentSizeList"},e.margins={createComponentOfType:"_componentSizeList"},e.valign={createComponentOfType:"text"},e.valigns={createComponentOfType:"textList"},e}static returnChildGroups(){return[{group:"blocks",componentTypes:["_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPanels={forRenderer:!0,returnDependencies:()=>({blockChildren:{dependencyType:"child",childGroups:["blocks"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nPanels:e.blockChildren.length},checkForActualChange:{nPanels:!0}})},e.essentialWidths={isArray:!0,entryPrefixes:["essentialWidth"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialWidths:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialWidths)t[n]=e.essentialWidths[n];return{success:!0,instructions:[{setEssentialValue:"essentialWidths",value:t}]}}},e.allWidthsSpecified={additionalStateVariablesDefined:["widthsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents","componentSizes"]},parentWidths:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedWidths"},parentWidthsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"widthsAbsolute"},essentialWidth:{dependencyType:"stateVariable",variableName:"essentialWidths"}}),definition({dependencyValues:e}){let t,n=[],r=null,a=!1;null!==e.widthsAttr?t=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(t=e.nPanels,a=!0):t=0;for(let i=0;iNumber.isFinite(e)?e:null)),{setValue:{allWidthsSpecified:n,widthsAbsolute:r}}}},e.essentialMargins={isArray:!0,entryPrefixes:["essentialMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialMargins:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialMargins)t[n]=e.essentialMargins[n];return{success:!0,instructions:[{setEssentialValue:"essentialMargins",value:t}]}}},e.allMarginsSpecified={additionalStateVariablesDefined:["marginsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["nComponents","componentSizes"]},parentMargins:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedMargins"},parentMarginsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"marginsAbsolute"},essentialMargins:{dependencyType:"stateVariable",variableName:"essentialMargins"}}),definition({dependencyValues:e}){let t=[],n=null;if(null===e.marginsAttr)if(e.parentMargins){n=e.parentMarginsAbsolute;for(let n=0;n<2;n++)null===e.essentialMargins[n]?t[n]=e.parentMargins[n]:t[n]=e.essentialMargins[n]}else for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(0===e.marginsAttr.stateValues.nComponents)for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(1===e.marginsAttr.stateValues.nComponents){let r=null;e.marginsAttr.stateValues.componentSizes[0]&&(r=e.marginsAttr.stateValues.componentSizes[0].size,Number.isFinite(r)||(r=null),n=Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute)),t=[r,r]}else{let r;if(n=!!e.marginsAttr.stateValues.componentSizes[0]&&Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute),r=!!e.marginsAttr.stateValues.componentSizes[1]&&Boolean(e.marginsAttr.stateValues.componentSizes[1].isAbsolute),r!==n)throw Error("SideBySide is not implemented for absolute measurements");t=e.marginsAttr.stateValues.componentSizes.slice(0,2).map((e=>e&&Number.isFinite(e.size)?e.size:null))}return{setValue:{allMarginsSpecified:t,marginsAbsolute:n}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SideBySide is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SideBySide is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0}],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},allWidthsSpecified:{dependencyType:"stateVariable",variableName:"allWidthsSpecified"},allMarginsSpecified:{dependencyType:"stateVariable",variableName:"allMarginsSpecified"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.allWidthsSpecified],r=[...e.allMarginsSpecified],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.nPanels);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.nPanels>1?t=(100-(a+s))/(e.nPanels-1):1===e.nPanels?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]},essentialWidth:{dependencyType:"stateVariable",variableName:`essentialWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r,arraySize:a}){let i,s=!1;null!==r.widthsAttr?i=r.widthsAttr.stateValues.nComponents:null!==r.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.widths){Number(n)({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={essentialMargin:{dependencyType:"stateVariable",variableName:`essentialMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyNamesByKey:n}){let r=[];if(null===t.marginsAttr)for(let t in e.margins)r.push({setDependency:n[t].essentialMargin,desiredValue:e.margins[t]});else if(t.marginsAttr.stateValues.componentSize1&&Number.isFinite(t.marginsAttr.stateValues.componentSize1.size)){let n=1===t.marginsAttr.stateValues.nComponents;for(let a in e.margins)n?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:a})}else"0"in e.margins?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[0],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:0}),"1"in e.margins&&t.marginsAttr.stateValues.nComponents>1&&r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:1});return{success:!0,instructions:r}}},e.essentialValigns={isArray:!0,entryPrefixes:["essentialValign"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialValigns:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialValigns)t[n]=e.essentialValigns[n];return{success:!0,instructions:[{setEssentialValue:"essentialValigns",value:t}]}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]},parentValign:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valign${e}`},parentValignAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valignAbsolute${e}`},essentialValign:{dependencyType:"stateVariable",variableName:`essentialValign${e}`}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],s=!0):a=0;for(let r of n){let n=Number(r);if(n({sideBySideChildren:{dependencyType:"child",childGroups:["sideBySides"],variableNames:["nPanels"]}}),definition:({dependencyValues:e})=>({setValue:{maxNPanelsPerRow:me$3.math.max(e.sideBySideChildren.map((e=>e.stateValues.nPanels)))},checkForActualChange:{maxNPanelsPerRow:!0}})},e.specifiedWidths={additionalStateVariablesDefined:[{variableName:"widthsAbsoluteArray",isArray:!0}],isArray:!0,entryPrefixes:["specifiedWidth"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]}}}return{globalDependencies:{widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o={},l=!1;null!==e.widthsAttr?a=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(a=r[0],l=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(u.useEssentialOrDefaultValue={specifiedWidths:s}),u},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r,arraySize:a}){let i,s=!1;null!==n.widthsAttr?i=n.widthsAttr.stateValues.nComponents:null!==n.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.specifiedWidths){Number(n)({widthsAbsoluteArray:{dependencyType:"stateVariable",variableName:"widthsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.widthsAbsoluteArray){let r=e.widthsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{widthsAbsolute:t}}}},e.specifiedMargins={additionalStateVariablesDefined:[{variableName:"marginsAbsoluteArray",isArray:!0,entryPrefixes:["marginAbsolute"]}],isArray:!0,entryPrefixes:["specifiedMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]}}}),arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r={},a={},i={};if(null===t.marginsAttr||0===t.marginsAttr.stateValues.nComponents)for(let e of n)a[e]=!0,i[e]=null;else if(1===t.marginsAttr.stateValues.nComponents){let e=null,a=null;t.marginsAttr.stateValues.componentSize1&&(e=t.marginsAttr.stateValues.componentSize1.size,Number.isFinite(e)||(e=null),a=Boolean(t.marginsAttr.stateValues.componentSize1.isAbsolute));for(let t of n)r[t]=e,i[t]=a}else for(let e of n)if(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`]){let n=t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].size;Number.isFinite(n)||(n=null);let a=Boolean(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].isAbsolute);r[e]=n,i[e]=a}let s={setValue:{marginsAbsoluteArray:i,specifiedMargins:r}};return Object.keys(a).length>0&&(s.useEssentialOrDefaultValue={specifiedMargins:a}),s},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r}){let a=[];if(null===n.marginsAttr)a.push({setEssentialValue:"specifiedMargins",value:e.specifiedMargins});else if(n.marginsAttr.stateValues.componentSize1&&Number.isFinite(n.marginsAttr.stateValues.componentSize1.size)){let t=1===n.marginsAttr.stateValues.nComponents;for(let n in e.specifiedMargins)t?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:n})}else"0"in e.specifiedMargins?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[0],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:0}),"1"in e.specifiedMargins&&n.marginsAttr.stateValues.nComponents>1&&a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:1});return{success:!0,instructions:a}}},e.marginsAbsolute={returnDependencies:()=>({marginsAbsoluteArray:{dependencyType:"stateVariable",variableName:"marginsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.marginsAbsoluteArray){let r=e.marginsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{marginsAbsolute:t}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SbsGroup is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SbsGroup is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"},specifiedWidths:{dependencyType:"stateVariable",variableName:"specifiedWidths"},specifiedMargins:{dependencyType:"stateVariable",variableName:"specifiedMargins"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.specifiedWidths],r=[...e.specifiedMargins],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.maxNPanelsPerRow);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.maxNPanelsPerRow>1?t=(100-(a+s))/(e.maxNPanelsPerRow-1):1===e.maxNPanelsPerRow?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedWidth:{dependencyType:"stateVariable",variableName:`specifiedWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.widths)n.push({setDependency:t[r].specifiedWidth,desiredValue:e.widths[r],variableIndex:0});return{success:!0,instructions:n}}},e.margins={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["margin"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedMargin:{dependencyType:"stateVariable",variableName:`specifiedMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.margins)n.push({setDependency:t[r].specifiedMargin,desiredValue:e.margins[r],variableIndex:0});return{success:!0,instructions:n}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],hasEssential:!0,defaultValueByArrayKey:()=>"top",returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],o=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(l.setValue={valigns:i}),Object.keys(s).length>0&&(l.useEssentialOrDefaultValue={valigns:s}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,arraySize:r}){let a,i=!1;null!==n.valignsAttr?a=n.valignsAttr.stateValues.nComponents:null!==n.valignAttr?(a=r[0],i=!0):a=0;let s=[];for(let n in e.valigns){let r=e.valigns[n].toLowerCase();["top","middle","bottom"].includes(r)&&(Number(n)({stringTextChildren:{dependencyType:"child",childGroups:["stringsTexts"],variableNames:["value"]},hChildren:{dependencyType:"child",childGroups:["hs"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;if(e.hChildren.length>0)t=e.hChildren.map((e=>e.stateValues.value));else{let n="";for(let t of e.stringTextChildren)n+="string"==typeof t?t:t.stateValues.value;t=[n]}return{setValue:{terms:t}}}},e}}var Indexing=Object.freeze({__proto__:null,H:H$2,Idx:Idx});class Div extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="div";static rendererType="containerBlock";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Span extends InlineComponent{static componentType="span";static rendererType="containerInline";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}}var Divisions=Object.freeze({__proto__:null,Div:Div,Span:Span});class Pre extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="pre";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class DisplayDoenetML extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="displayDoenetML";static rendererType="text";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({childrenDoenetML:{dependencyType:"doenetML",displayOnlyChildren:!0}}),definition:({dependencyValues:e})=>({setValue:{value:e.childrenDoenetML}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Verbatim=Object.freeze({__proto__:null,Pre:Pre,DisplayDoenetML:DisplayDoenetML});class Paginator extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{setPage:this.setPage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="paginator";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.initialPage={createComponentOfType:"integer",createStateVariable:"initialPage",defaultValue:1},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPages={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{nPages:e.children.length}})},e.currentPage={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,returnDependencies:()=>({initialPage:{dependencyType:"stateVariable",variableName:"initialPage"},nPages:{dependencyType:"stateVariable",variableName:"nPages"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentPage:{get defaultValue(){let t=e.initialPage;return Number.isInteger(t)?Math.max(1,Math.min(e.nPages,t)):1}}}}),async inverseDefinition({desiredStateVariableValues:e,stateValues:t,sourceInformation:n={}}){if(!n.fromSetPage)return{success:!1};let r=Number(e.currentPage);return Number.isInteger(r)?(r=Math.max(1,Math.min(await t.nPages,r)),{success:!0,instructions:[{setEssentialValue:"currentPage",value:r}]}):{success:!1}}},e.childIndicesToRender={returnDependencies:()=>({currentPage:{dependencyType:"stateVariable",variableName:"currentPage"}}),definition:({dependencyValues:e})=>({setValue:{childIndicesToRender:[e.currentPage-1]}}),markStale:()=>({updateRenderedChildren:!0})},e}async setPage({number:e,actionId:t}){if(!Number.isInteger(e))return void this.coreFunctions.resolveAction({actionId:t});let n=Math.max(1,Math.min(await this.stateValues.nPages,e)),r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"currentPage",value:n,sourceInformation:{fromSetPage:!0}}];await this.coreFunctions.performUpdate({updateInstructions:r,actionId:t,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class PaginatorControls extends BlockComponent{constructor(e){super(e),this.externalActions={},Object.defineProperty(this.externalActions,"setPage",{enumerable:!0,get:async function(){let e=await this.stateValues.paginatorComponentName;return e?{componentName:e,actionName:"setPage"}:void 0}.bind(this)})}static componentType="paginatorControls";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.previousLabel={createComponentOfType:"text",createStateVariable:"previousLabel",defaultValue:"Previous",forRenderer:!0,public:!0},e.nextLabel={createComponentOfType:"text",createStateVariable:"nextLabel",defaultValue:"Next",forRenderer:!0,public:!0},e.pageLabel={createComponentOfType:"text",createStateVariable:"pageLabel",defaultValue:"Page",forRenderer:!0,public:!0},e.paginator={createTargetComponentNames:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.paginatorComponentName={returnDependencies:()=>({paginator:{dependencyType:"attributeTargetComponentNames",attributeName:"paginator"}}),definition({dependencyValues:e}){let t;return t=1===e.paginator?.length?e.paginator[0].absoluteName:null,{setValue:{paginatorComponentName:t}}}},e.currentPage={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorPage:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"currentPage"}}:{},definition:({dependencyValues:e})=>"paginatorPage"in e?{setValue:{currentPage:e.paginatorPage}}:{setValue:{currentPage:1}}},e.nPages={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorNPages:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"nPages"}}:{},definition:({dependencyValues:e})=>"paginatorNPages"in e?{setValue:{nPages:e.paginatorNPages}}:{setValue:{nPages:1}}},e}}var Paginator$1=Object.freeze({__proto__:null,Paginator:Paginator,PaginatorControls:PaginatorControls});class Input extends InlineComponent{static componentType="_input";static createAttributesObject(){let e=super.createAttributesObject();return e.collaborateGroups={createComponentOfType:"collaborateGroups",createStateVariable:"collaborateGroups",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nValues={returnDependencies:()=>({}),definition:()=>({setValue:{nValues:1}})},e.answerAncestor={returnDependencies:()=>({answerAncestor:{dependencyType:"ancestor",componentType:"answer",variableNames:["delegateCheckWorkToInput","justSubmitted","creditAchieved","showCorrectness","numberOfAttemptsLeft"]}}),definition:function({dependencyValues:e}){return{setValue:{answerAncestor:e.answerAncestor}}}},e.includeCheckWork={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&(t=e.answerAncestor.stateValues.delegateCheckWorkToInput),{setValue:{includeCheckWork:t}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=0;return e.answerAncestor&&(t=e.answerAncestor.stateValues.creditAchieved),{setValue:{creditAchieved:t}}}},e.valueHasBeenValidated={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&e.answerAncestor.stateValues.justSubmitted&&(t=!0),{setValue:{valueHasBeenValidated:t}}}},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.showCorrectness:!1!==e.showCorrectnessFlag,{setValue:{showCorrectness:t}}}},e.numberOfAttemptsLeft={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.numberOfAttemptsLeft:1/0,{setValue:{numberOfAttemptsLeft:t}}}},e}}class MatrixInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateNumRows:this.updateNumRows.bind(this),updateNumColumns:this.updateNumColumns.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="matrixInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.numRows={createComponentOfType:"integer",createStateVariable:"numRowsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.numColumns={createComponentOfType:"integer",createStateVariable:"numColumnsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.showSizeControls={createComponentOfType:"boolean",createStateVariable:"showSizeControls",defaultValue:!0,public:!0,forRenderer:!0},e.defaultEntry={createComponentOfType:"math",createStateVariable:"defaultEntry",defaultValue:me$3.fromAst("_")},e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};return{success:!0,newChildren:[{componentType:"matrixInputGrid"}]}}}),e}static returnChildGroups(){return[{group:"matrixComponentInputs",componentTypes:["matrixComponentInput"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.valueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{valueOriginal:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{valueOriginal:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.valueOriginal,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"valueOriginal",value:e.valueOriginal}]}}},e.immediateValueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.valueOriginal&&!n?{setValue:{immediateValueOriginal:e.valueOriginal},setEssentialValue:{immediateValueOriginal:e.valueOriginal}}:{useEssentialOrDefaultValue:{immediateValueOriginal:{defaultValue:e.valueOriginal}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValueOriginal",value:e.immediateValueOriginal}];return t||n||r.push({setDependency:"valueOriginal",desiredValue:e.immediateValueOriginal}),{success:!0,instructions:r}}},e.haveBoundValue={returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo"}}),definition:({dependencyValues:e})=>({setValue:{haveBoundValue:null!==e.bindValueTo}})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({numRowsPreliminary:{dependencyType:"stateVariable",variableName:"numRowsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numRowsPreliminary;if(t.numRowsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][1]:vectorOperators.includes(e)&&(n=t.length-1)}}return{setValue:{numRows:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numRows;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numRowsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=t.valueOriginal.tree,i=(await n.defaultEntry).tree;if(1===await n.numColumns&&Array.isArray(e)&&vectorOperators.includes(e[0])){let t=e.length-1;if(rt){let s=deepClone(e),o=await n.accumulatedComponents;for(let e=t;e({numColumnsPreliminary:{dependencyType:"stateVariable",variableName:"numColumnsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numColumnsPreliminary;if(t.numColumnsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][2]:Array.isArray(t[1])&&vectorOperators.includes(t[1][0])&&("^"===e&&"T"===t[2]||"prime"===e)&&(n=t[1].length-1)}}return{setValue:{numColumns:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numColumns;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numColumnsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=(await n.defaultEntry).tree,i=t.valueOriginal.tree,s=i[0];if(Array.isArray(i[1])&&vectorOperators.includes(i[1][0])&&("^"===s&&"T"===i[2]||"prime"===s)){let t=i[1].length-1;if(rt){let s=deepClone(i),o=(await n.accumulatedComponents)[0];o||(o=[]);for(let n=t;n({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e,previousValues:t}){let n=[];t.accumulatedComponents&&(n=deepClone(t.accumulatedComponents));let r=e.valueOriginal.tree;if(Array.isArray(r)){let e=r[0];if("matrix"===e){let e=r[2];for(let[t,r]of e.slice(1).entries()){let e=n[t];e||(e=n[t]=[]);for(let[t,n]of r.slice(1).entries())e[t]=n}return{setValue:{accumulatedComponents:n}}}if(vectorOperators.includes(e)){for(let[e,t]of r.slice(1).entries()){let r=n[e];r||(r=n[e]=[]),r[0]=t}return{setValue:{accumulatedComponents:n}}}if(Array.isArray(r[1])&&vectorOperators.includes(r[1][0])&&("^"===e&&"T"===r[2]||"prime"===e)){let e=n[0];e||(e=n[0]=[]);for(let[t,n]of r[1].slice(1).entries())e[t]=n;return{setValue:{accumulatedComponents:n}}}}let a=n[0];return a||(a=n[0]=[]),a[0]=r,{setValue:{accumulatedComponents:n}}}},e.componentValues={isArray:!0,entryPrefixes:["componentValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.valueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.valueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.valueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentImmediateValues={isArray:!0,entryPrefixes:["componentImmediateValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.immediateValueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.immediateValueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.immediateValueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentValuesForDisplay={isArray:!0,entryPrefixes:["componentValueForDisplay"],nDimensions:2,forRenderer:!0,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={componentValue:{dependencyType:"stateVariable",variableName:`componentValue${a}`}}}return{globalDependencies:{displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,usedDefault:r}){let a={};for(let i of n){let n=roundForDisplay({value:t[i].componentValue,dependencyValues:e,usedDefault:r});a[i]=n}return{setValue:{componentValuesForDisplay:a}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentValues:{dependencyType:"stateVariable",variableName:"componentValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.valueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e.value}]}}return{success:!1}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentImmediateValues:{dependencyType:"stateVariable",variableName:"componentImmediateValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.immediateValueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e.immediateValue}]}}return{success:!1}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"matrix"}})},e}async updateRawValues({rawRendererValues:e,transient:t=!1,actionId:n}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValues",value:e}],transient:t,actionId:n});this.coreFunctions.resolveAction({actionId:n})}async updateNumRows({numRows:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numRows",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateNumColumns({numColumns:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numColumns",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}class MatrixInputGrid extends CompositeComponent{static componentType="matrixInputGrid";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numRows={returnDependencies:()=>({parentNumRows:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numRows"}}),definition:({dependencyValues:e})=>({setValue:{numRows:e.parentNumRows}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numRows;r.previousNumRows=i;for(let e=0;eo&&(u=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=u){i=e.replacementsToWithhold-u,o+=u,u=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else u-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(u>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}j;static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numColumns,s=await e.stateValues.rowInd;r.previousNumColumns=i;for(let e=0;eo&&(c=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=c){i=e.replacementsToWithhold-c,o+=c,c=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else c-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(c>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.colInd={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{colInd:!0}})},e.format={returnDependencies:()=>({parentFormat:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"format"}}),definition:({dependencyValues:e})=>({setValue:{format:e.parentFormat}})},e.functionSymbols={returnDependencies:()=>({parentFunctionSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"functionSymbols"}}),definition:({dependencyValues:e})=>({setValue:{functionSymbols:e.parentFunctionSymbols}})},e.splitSymbols={returnDependencies:()=>({parentSplitSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"splitSymbols"}}),definition:({dependencyValues:e})=>({setValue:{splitSymbols:e.parentSplitSymbols}})},e.parseScientificNotation={returnDependencies:()=>({parentParseScientificNotation:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"parseScientificNotation"}}),definition:({dependencyValues:e})=>({setValue:{parseScientificNotation:e.parentParseScientificNotation}})},e.displayDigits={returnDependencies:()=>({parentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDigits"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDigits:e.parentDisplayDigits}};return t.parentDisplayDigits&&(n.markAsUsedDefault={displayDigits:!0}),n}},e.displayDecimals={returnDependencies:()=>({parentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDecimals:e.parentDisplayDecimals}};return t.parentDisplayDecimals&&(n.markAsUsedDefault={displayDecimals:!0}),n}},e.displaySmallAsZero={returnDependencies:()=>({parentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displaySmallAsZero"}}),definition:({dependencyValues:e})=>({setValue:{displaySmallAsZero:e.parentDisplaySmallAsZero}})},e.unionFromU={returnDependencies:()=>({parentUnionFromU:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"unionFromU"}}),definition:({dependencyValues:e})=>({setValue:{unionFromU:e.parentUnionFromU}})},e.value={stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentValue${t}`}}},definition:function({dependencyValues:e}){return e.parentComponentValue?{setValue:{value:e.parentComponentValue}}:{setValue:{value:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"parentComponentValue",desiredValue:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentImmediateValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentImmediateValue${t}`}}},definition:function({dependencyValues:e}){return{setValue:{immediateValue:e.parentComponentImmediateValue}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return{success:!0,instructions:[{setDependency:"parentComponentImmediateValue",desiredValue:e.immediateValue,treatAsInitialChange:t}]}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition({dependencyValues:e,essentialValues:t}){if(void 0!==t.rawRendererValue&&deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t=stripLatex(e.valueForDisplay.toLatex());return"_"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n}){const r=async e=>{let n;e=(e=normalizeLatexString(e,{unionFromU:await t.unionFromU})).replace(/\^(\w)/g,"^{$1}");let r=getFromLatex({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(e)}catch(e){n=me$3.fromAst("_")}return n};let a=[];if("string"==typeof e.rawRendererValue){let t=n.rawRendererValue,i=e.rawRendererValue;t!==i&&a.push({setEssentialValue:"rawRendererValue",value:i});let s=await r(t),o=await r(i);deepCompare(o.tree,s.tree)||a.push({setDependency:"immediateValue",desiredValue:o,treatAsInitialChange:!0})}else{a.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let t=await r(n.rawRendererValue);if(!deepCompare(e.rawRendererValue.tree,t.tree)){let t=stripLatex(e.rawRendererValue.toLatex());"_"===t&&(t=""),a.push({setEssentialValue:"rawRendererValue",value:t})}}return{success:!0,instructions:a}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree&&n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"rawRendererValue"}],actionId:e})}}}var MatrixInput$1=Object.freeze({__proto__:null,MatrixInput:MatrixInput,MatrixInputGrid:MatrixInputGrid,MatrixInputRow:MatrixInputRow,default:MatrixComponentInput});class Document extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="document";static rendererType="section";static renderChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.documentWideCheckWork={createComponentOfType:"boolean",createStateVariable:"documentWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.displayDigitsForCreditAchieved={createComponentOfType:"integer",createStateVariable:"displayDigitsForCreditAchieved",defaultValue:3,public:!0},e.xmlns={createPrimitiveOfType:"string"},e.type={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"variantControl",componentTypes:["variantControl"]},{group:"title",componentTypes:["title"]},{group:"description",componentTypes:["description"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:""}}:{setValue:{title:e.titleChild[0].stateValues.text}}},e.description={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({descriptionChild:{dependencyType:"child",childGroups:["description"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.descriptionChild.length?{setValue:{description:""}}:{setValue:{description:e.descriptionChild[0].stateValues.text}}},e.level={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{level:0}})},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.nScoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}}),definition:({dependencyValues:e})=>({setValue:{nScoredDescendants:e.scoredDescendants.length}})},e.itemCreditAchieved={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={creditAchieved:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"creditAchieved"}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].creditAchieved;return{setValue:{itemCreditAchieved:n}}}},e.itemNumberByAnswerName={stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let n in e.scoredDescendants){let r=e.scoredDescendants[n];t[`descendantsOf${n}`]={dependencyType:"descendant",ancestorName:r.componentName,componentTypes:["answer"],recurseToMatchedChildren:!1}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n={};for(let[r,a]of e.scoredDescendants.entries()){let i=r+1;for(let t of e[`descendantsOf${r}`])n[t.componentName]=i;t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"answer"})&&(n[a.componentName]=i)}return{setValue:{itemNumberByAnswerName:n}}}},e.itemVariantInfo={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={generatedVariantInfo:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"generatedVariantInfo",variablesOptional:!0}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].generatedVariantInfo;return{setValue:{itemVariantInfo:n}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.creditAchieved={public:!0,forRenderer:!0,defaultValue:0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}}}],returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"},itemCreditAchieved:{dependencyType:"stateVariable",variableName:"itemCreditAchieved"}}),definition({dependencyValues:e}){let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e.itemCreditAchieved[t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"};return t},definition({dependencyValues:e}){let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={index:e.variantIndex,name:e.variantName,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e]?.subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({documentWideCheckWork:{dependencyType:"stateVariable",variableName:"documentWideCheckWork"}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentWideCheckWork&&(n=!0,r=!0),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r&&(r=1),t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:!0})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}:(console.log("Failed to get unique variant for document."),{success:!1})}static includeBlankStringChildren=!0}class TextList$1 extends InlineComponent{static componentType="textList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="texts";static primaryStateVariableForDefinition="textsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"text"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"text"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"texts",componentTypes:["text"]},{group:"textLists",componentTypes:["textList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.textsShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{textsShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.textAndTextListChildren.length>0){let a=0;for(let[i,s]of e.textAndTextListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"textList"})){let t=e.textListChildren[a];a++;for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["value","text"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].textAndTextListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["text"+t]}else null!==e.textsShadow&&(r[a]=e.textsShadow[a])}return{setValue:{texts:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.texts){if(!n[t])continue;let a=n[t].textAndTextListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.componentNamesInList={returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.textAndTextListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"textList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"textList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.textAndTextListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"textList"})){let t=e.textListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=["text"]}class TextList extends InlineComponent{static componentType="randomizedTextList";static stateVariableForAttributeValue="texts";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={default:!1},e.maximumNumber={default:null},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroTexts",componentType:"text",comparison:"atLeast",number:0}),r=t.newLeaf({name:"atLeastZeroTextLists",componentType:"textList",comparison:"atLeast",number:0}),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,returnSugarDependencies:()=>({stringChildren:{dependencyType:"child",childLogicName:"exactlyOneString",variableNames:["value"]}}),logicToWaitOnSugar:["atLeastZeroTexts"],replacementFunction:function({dependencyValues:e}){let t=e.stringChildren[0],n=t.stateValues.value.split(",").map((e=>({componentType:"text",state:{value:e.trim()}})));return{success:!0,newChildren:n,toDelete:[t.componentName]}}}),i=t.newOperator({name:"textAndTextLists",operator:"and",propositions:[n,r]});return t.newOperator({name:"TextsXorSugar",operator:"xor",propositions:[a,i],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["value","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},childrenToRender:{dependencyType:"stateVariable",variableName:"childrenToRender"}}),definition:function({dependencyValues:e}){let t=[],n=e.textAndTextListChildren.map((e=>e.componentName));for(let r of e.childrenToRender){let a=n.indexOf(r),i=e.textAndTextListChildren[a];i.stateValues.texts?t.push(...i.stateValues.texts):t.push(i.stateValues.value)}return{setValue:{texts:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.texts.length}}}},e.childrenToRender={returnDependencies:({sharedParameters:e})=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["childrenToRender"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},selectRng:{dependencyType:"value",value:e.selectRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.textAndTextListChildren)n.stateValues.childrenToRender?t.push(...n.stateValues.childrenToRender):t.push(n.componentName);let n=e.maximumNumber;null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),console.log("randomizing children");for(let n=t.length-1;n>0;n--){const r=e.selectRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}let r=Math.ceil(e.selectRng()*t.length);return console.log(`numChildren: ${r}`),t=t.slice(0,r),{setValue:{childrenToRender:t}}}},e}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.aslist({key:this.componentName}))}}class TupleList extends MathList{static componentType="tupleList";static rendererType="mathList";static includeBlankStringChildren=!1;static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"math",children:e}:e[0]}))}}}),e}}class NumberList extends InlineComponent{static componentType="numberList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="numbers";static primaryStateVariableForDefinition="numbersShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"number"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"number"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"numbers",componentTypes:["number"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{numbersShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;if(e.numberAndNumberListChildren.length>0)for(let[i,s]of e.numberAndNumberListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["number"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["value","number"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].numberAndNumberListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["number"+t]}else null!==e.numbersShadow&&(r[a]=e.numbersShadow[a])}return{setValue:{numbers:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.numbers){if(!n[t])continue;let a=n[t].numberAndNumberListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition({dependencyValues:e}){let t;return t=0===e.numbers.length?me$3.fromAst("_"):1===e.numbers.length?me$3.fromAst(e.numbers[0]):me$3.fromAst(["list",...e.numbers]),{setValue:{math:t}}}},e.text={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.numberAndNumberListChildren.length>0)for(let t of e.numberAndNumberListChildren)void 0!==t.stateValues.valueForDisplay?n.push(t.stateValues.text):n.push(...t.stateValues.texts);else null!==e.numbersShadow&&(n=e.numbersShadow.map((n=>roundForDisplay({value:me$3.fromAst(n),dependencyValues:e,usedDefault:t}).toString(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{text:n.join(", "),texts:n}}}},e.componentNamesInList={returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.numberAndNumberListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.numberAndNumberListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class NumberListFromString extends InlineComponent{static componentType="numberListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="numbers";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["number"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey:()=>({globalDependencies:{stringChildren:{dependencyType:"child",childGroups:["strings"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let[t,r]of e.stringChildren.entries())n[t]=Number(r);return{setValue:{numbers:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition:function({dependencyValues:e}){let t=e.numbers.map((e=>e.toString()));return{setValue:{text:t.join(", "),texts:t}}}},e}}class P$2 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="p";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class BooleanList extends InlineComponent{static componentType="booleanList";static rendererType="asList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="booleans";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"boolean"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"boolean"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]},{group:"booleanLists",componentTypes:["booleanList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,s]of e.booleanAndBooleanListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.booleans={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["boolean"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["value","boolean"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].booleanAndBooleanListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["boolean"+t]}}return{setValue:{booleans:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.booleans){if(!n[t])continue;let a=n[t].booleanAndBooleanListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"booleans"},e.componentNamesInList={returnDependencies:()=>({booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.booleanAndBooleanListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"booleanList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"booleanList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.booleanAndBooleanListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}}class Copy extends CompositeComponent{static componentType="copy";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static includeBlankStringChildren=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNewNamespaces={createPrimitiveOfType:"boolean"},e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.obtainPropFromComposite={createPrimitiveOfType:"boolean",createStateVariable:"obtainPropFromComposite",defaultValue:!1,public:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.sourceSubnames={createPrimitiveOfType:"stringArray",createStateVariable:"targetSubnames",defaultValue:null,public:!0},e.sourceSubnamesComponentIndex={createComponentOfType:"numberList",createStateVariable:"targetSubnamesComponentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:["hide"],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.link={createPrimitiveOfType:"boolean"},e.removeEmptyArrayEntries={createPrimitiveOfType:"boolean",createStateVariable:"removeEmptyArrayEntries",defaultValue:!1},e}static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetSourcesName={additionalStateVariablesDefined:[{variableName:"sourcesChildNumber",hasEssential:!0,shadowVariable:!0}],stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceNameMappings;if(!n)return{};let r=n[e.target];return r?{targetSourcesName:{dependencyType:"value",value:r.name},sourcesChildNumber:{dependencyType:"value",value:r.childNumber}}:{}},definition:function({dependencyValues:e}){let t=e.targetSourcesName,n=e.sourcesChildNumber;return t||(t=null,n=null),{setValue:{targetSourcesName:t,sourcesChildNumber:n},setEssentialValue:{targetSourcesName:t,sourcesChildNumber:n}}}},e.targetSources={stateVariablesDeterminingDependencies:["targetSourcesName"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>e.targetSourcesName?{targetSourcesComponent:{dependencyType:"componentIdentity",componentName:e.targetSourcesName}}:{},definition:function({dependencyValues:e}){let t=e.targetSourcesComponent;return t||(t=null),{setValue:{targetSources:t}}}},e.sourceIndex={stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceIndexMappings;if(!n)return{};let r=n[e.target];return void 0===r?{}:{sourceIndex:{dependencyType:"value",value:r}}},definition:function({dependencyValues:e}){let t=e.sourceIndex;return void 0===t&&(t=null),{setValue:{sourceIndex:t},setEssentialValue:{sourceIndex:t}}}},e.targetComponent={shadowVariable:!0,stateVariablesDeterminingDependencies:["targetSources","sourceIndex"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>null!==e.sourceIndex?{}:null!==e.targetSources?{targetSourcesChildren:{dependencyType:"stateVariable",componentName:e.targetSources.componentName,variableName:"childIdentities"},sourcesChildNumber:{dependencyType:"stateVariable",variableName:"sourcesChildNumber"}}:{targetComponent:{dependencyType:"targetComponent"}},definition:function({dependencyValues:e}){let t=null;return e.targetSourcesChildren?(t=e.targetSourcesChildren[e.sourcesChildNumber],t||(t=null)):e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.cid={additionalStateVariablesDefined:["doenetId"],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null}};let t=null,n=null,r=e.uri.match(/[:&]cid=([^&]+)/i);return r&&(t=r[1]),r=e.uri.match(/[:&]doenetid=([^&]+)/i),r&&(n=r[1]),{setValue:{cid:t,doenetId:n}}}},e.serializedComponentsForCid={returnDependencies:()=>({cid:{dependencyType:"stateVariable",variableName:"cid"},serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return e.cid&&e.serializedChildren?.length>0?{setValue:{serializedComponentsForCid:e.serializedChildren}}:{setValue:{serializedComponentsForCid:null}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.isPlainMacro={returnDependencies:()=>({isPlainMacro:{dependencyType:"doenetAttribute",attributeName:"isPlainMacro"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainMacro&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainMacro];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainMacro:n}}}},e.isPlainCopy={returnDependencies:()=>({isPlainCopy:{dependencyType:"doenetAttribute",attributeName:"isPlainCopy"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainCopy&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainCopy];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainCopy:n}}}},e.linkAttrForDetermineDeps={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"}}),definition({dependencyValues:e}){let t;return t=null===e.linkAttr||e.linkAttr,{setValue:{linkAttrForDetermineDeps:t}}}},e.replacementSourceIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex","propName","targetSubnames","targetSubnamesComponentIndex","obtainPropFromComposite","linkAttrForDetermineDeps"],additionalStateVariablesDefined:["addLevelToAssignNames"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={},r=!1,a=!1;if(null!==e.targetComponent){if(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})&&(!e.propName||!e.obtainPropFromComposite))if(e.linkAttrForDetermineDeps){a=!0;let t=e.targetSubnamesComponentIndex;t&&(t=[...t]),n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex,targetSubnames:e.targetSubnames,targetSubnamesComponentIndex:t}}else r=!0;a||null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})}return n.addLevelToAssignNames={dependencyType:"value",value:r},n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{replacementSourceIdentities:t,addLevelToAssignNames:e.addLevelToAssignNames}}}},e.replacementSources={stateVariablesDeterminingDependencies:["replacementSourceIdentities","propName","propIndex","isPlainMacro","isPlainCopy"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(!e.propName&&null!==e.propIndex)throw Error("You cannot specify a propIndex without specifying a prop.");if(null!==e.replacementSourceIdentities)for(let[r,a]of e.replacementSourceIdentities.entries()){let i,s=e.propName;if(e.isPlainMacro?s=t.allComponentClasses[a.componentType].variableForPlainMacro:e.isPlainCopy&&(s=t.allComponentClasses[a.componentType].variableForPlainCopy),s){n["propName"+r]={dependencyType:"value",value:s};let t=e.propIndex;t&&(t=[...t]),i={dependencyType:"stateVariable",componentName:a.componentName,variableName:s,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else i={dependencyType:"componentIdentity",componentName:a.componentName};n["target"+r]=i}return n},definition({dependencyValues:e}){let t=null,n=null;if(null!==e.replacementSourceIdentities){t=[],n=[];for(let r in e.replacementSourceIdentities){let a=e["target"+r];if(a){let i;t.push(a),a.stateValues&&(i=Object.keys(a.stateValues)[0]),!i&&e["propName"+r]&&(i="__prop_name_not_found"),n.push(i)}}}return{setValue:{replacementSources:t,effectivePropNameBySource:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;return n=null===e.linkAttr?!(e.serializedComponentsForCid||e.replacementSourceIdentities&&e.replacementSourceIdentities.some((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"module"})))):!1!==e.linkAttr,{setValue:{link:n}}}},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["targetComponent","propName","obtainPropFromComposite","link"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},link:{dependencyType:"stateVariable",variableName:"link"}};return!e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"readyToExpandWhenResolved"}),e.link||(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={stateVariablesDeterminingDependencies:["targetComponent","replacementSourceIdentities","effectivePropNameBySource","propName","obtainPropFromComposite","link","removeEmptyArrayEntries"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){if(!e.link)return{};let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(null!==e.effectivePropNameBySource)for(let[t,r]of e.effectivePropNameBySource.entries())if(r){let a=e.replacementSourceIdentities[t];n["sourceArraySize"+t]={dependencyType:"stateVariableArraySize",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0},n["sourceComponentType"+t]={dependencyType:"stateVariableComponentType",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0}}return null===e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.allReplacementIdentities={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,variableNames:["isInactiveCompositeReplacement"]}),e.removeEmptyArrayEntries&&(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e.effectiveAssignNames={returnDependencies:()=>({assignNames:{dependencyType:"doenetAttribute",attributeName:"assignNames"},addLevelToAssignNames:{dependencyType:"stateVariable",variableName:"addLevelToAssignNames"}}),definition({dependencyValues:e}){let t=e.assignNames;return t&&e.addLevelToAssignNames&&(t=[t]),{setValue:{effectiveAssignNames:t}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,resolveItem:i,publicCaseInsensitiveAliasSubstitutions:s}){await e.stateValues.nComponentsSpecified,n.numReplacementsBySource=[],n.numNonStringReplacementsBySource=[],n.propVariablesCopiedBySource=[],n.sourceNames=[],n.uniqueIdentifiersUsedBySource={};let o=e.attributes.newNamespace?.primitive,l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.serializedComponentsForCid;if(c){let t=deepClone([c[0]]),i=deepClone(c.slice(1));if(t[0].children){let n;if(n=t[0].componentName?t[0].componentName+"/":t[0].originalName+"/",e.doenetAttributes.keptNewNamespaceOfLastChild){n=n.slice(0,n.length-1);let e=n.lastIndexOf("/");n=n.slice(0,e+1)}restrictTNamesToNamespace({components:t[0].children,namespace:n,invalidateReferencesToBaseNamespace:e.doenetAttributes.keptNewNamespaceOfLastChild})}if("externalContent"===t[0].componentType)for(let n of t[0].children){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:e.attributes,componentType:n.componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in t){let n=t[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}Object.assign(n.attributes,t)}else{t[0].attributes||(t[0].attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in n){let t=n[e];t.component?setTNamesToAbsolute([t.component]):t.childrenForComponent&&setTNamesToAbsolute(t.childrenForComponent)}Object.assign(t[0].attributes,n)}return t=processAssignNames({assignNames:u,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r}).serializedComponents,e.doenetAttributes.fromCopyFromURI&&i.length>0&&this.addChildrenFromComposite({replacements:t,children:i,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:r}),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let p=await e.stateValues.sourceIndex;if(null!==p){let t=processAssignNames({assignNames:u,serializedComponents:[{componentType:"number",attributes:convertAttributesForComponentType({attributes:e.attributes,componentType:"number",componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a}),state:{value:p,fixed:!0}}],parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t.serializedComponents,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let d=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!d){let t=[];if(e.doenetAttributes.fromCopyTarget){let i=r.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],s=r.allComponentClasses[i],c=convertAttributesForComponentType({attributes:e.attributes,componentType:i,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});n.uniqueIdentifiersUsedBySource[0]=[];let p=getUniqueIdentifierFromBase(i+"|empty",n.uniqueIdentifiersUsedBySource[0]),d=deepClone(e.serializedChildren);s.includeBlankStringChildren||(d=d.filter((e=>"string"!=typeof e||""!==e.trim())));let m=c;e.attributes.assignNewNamespaces?.primitive&&(m.newNamespace={primitive:!0}),t=[{componentType:i,attributes:m,children:d,uniqueIdentifier:p}],t=processAssignNames({assignNames:u,serializedComponents:t,parentName:e.componentName,componentInfoObjects:r,originalNamesAreConsistent:!0}).serializedComponents,n.numReplacementsBySource.push(t.length),n.numNonStringReplacementsBySource.push(t.filter((e=>"string"!=typeof e)).length)}return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l})).replacements}}let m=await i({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!m.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let h=await e.stateValues.effectivePropNameBySource;for(let t in d){if(h[t]&&(m=await i({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!m.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let f=[],y=[],g=[],b=0,v=0;for(let i in d){let o,u=n.uniqueIdentifiersUsedBySource[i]=[];if(e.attributes.createComponentOfType?.primitive){let t=await e.stateValues.nComponentsSpecified,n=d.length;o=Math.floor(t/n),i"string"!=typeof e)).length,b+=y[i],v+=g[i],f.push(...p)}return n.numReplacementsBySource=y,n.numNonStringReplacementsBySource=g,n.sourceNames=d.map((e=>e.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:f,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}static async createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c,fromCopyTarget:p}){let d=(await e.stateValues.replacementSourceIdentities)[t];if("object"!=typeof d)return{serializedReplacements:[d]};let m=n[d.componentName],h=await e.stateValues.link;h&&!await e.stateValues.removeEmptyArrayEntries||(d=(await e.stateValues.replacementSources)[t]);let f=e.attributes.newNamespace?.primitive,y=await e.stateValues.effectiveAssignNames,g=(await e.stateValues.effectivePropNameBySource)[t];if(g){let t=await replacementFromProp({component:e,components:n,replacementSource:d,propName:g,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c});return{serializedReplacements:processAssignNames({assignNames:y,serializedComponents:t.serializedReplacements,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o}).serializedComponents,propVariablesCopiedByReplacement:t.propVariablesCopiedByReplacement}}let b=await e.stateValues.sourceAttributesToIgnore,v=await e.stateValues.sourceAttributesToIgnoreRecursively,N=[await m.serialize({copyAll:!h,copyVariants:!h,sourceAttributesToIgnore:b,sourceAttributesToIgnoreRecursively:v})];h||void 0===N[0].state?.fixed||delete N[0].state.fixed,N=postProcessCopy({serializedComponents:N,componentName:e.componentName,uniqueIdentifiersUsed:i,addShadowDependencies:h,unlinkExternalCopies:!h}),N.length>0&&delete N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:o,compositeAttributesObj:s,compositeCreatesNewNamespace:f,flags:c});Object.assign(t.attributes,n)}return N[0].attributes.newNamespace?.primitive&&!e.attributes.assignNewNamespaces?.primitive&&(N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow=!0),N=processAssignNames({assignNames:y,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:N,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o,originalNamesAreConsistent:f&&!y}).serializedComponents,p&&1===N.length&&e.serializedChildren.length>0&&this.addChildrenFromComposite({replacements:N,children:e.serializedChildren,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:o}),{serializedReplacements:N}}static addChildrenFromComposite({replacements:e,children:t,assignNewNamespaces:n,componentInfoObjects:r}){let a=e[0];a.children||(a.children=[]);let i=deepClone(t);if(r.allComponentClasses[a.componentType].includeBlankStringChildren||(i=i.filter((e=>"string"!=typeof e||""!==e.trim()))),e[0].attributes.newNamespace?.primitive&&n){renameAutonameBasedOnNewCounts(i,countRegularComponentTypesInNamespace(a.children))}let s=processAssignNames({serializedComponents:i,parentName:e[0].componentName,parentCreatesNewNamespace:n,componentInfoObjects:r,originalNamesAreConsistent:!0});if(e[0].attributes.newNamespace?.primitive&&!n)for(let e of s.serializedComponents)"object"==typeof e&&(e.doenetAttributes.ignoreParentNewNamespace=!0);a.children.push(...s.serializedComponents)}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,flags:i,resolveItem:s,publicCaseInsensitiveAliasSubstitutions:o}){if(await e.stateValues.serializedComponentsForCid)return[];if(null!==await e.stateValues.sourceIndex)return[];let l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!c){if(await e.stateValues.targetSources)return[];{let t=[];if(e.replacements.length>0){let n={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length};t.push(n)}let n=0===r.sourceNames.length;r.sourceNames=[],r.numReplacementsBySource=[],r.numNonStringReplacementsBySource=[],r.propVariablesCopiedBySource=[];let s=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return n?[]:s.replacementChanges}}if(await e.stateValues.targetInactive){let t=[],n=e.replacements.length;if(n>0){if(e.replacementsToWithhold!==n){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:n};t.push(e)}t=(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i})).replacementChanges}return t}let p=await s({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!p.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let d=await e.stateValues.effectivePropNameBySource;for(let t in c){if(d[t]&&(p=await s({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!p.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let m=[];if(e.replacementsToWithhold>0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};m.push(e)}let h=0,f=0,y=[],g=[],b=[],v=Math.max(c.length,r.numReplacementsBySource.length),N=!1;for(let t=0;t0){if(!N){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToDelete:e};m.push(t)}N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}r.uniqueIdentifiersUsedBySource[t]=[]}y[t]=0,g[t]=0,b.push([]);continue}let p=r.sourceNames[t],v=void 0===p||u.componentName!==p||N;if(!v)for(let n=0;ne+t),0);v.numberReplacementsToReplace=e,N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}m.push(v);continue}if(!d[t]&&r.numReplacementsBySource[t]>0){h+=r.numReplacementsBySource[t],f+=r.numNonStringReplacementsBySource[t],y[t]=r.numReplacementsBySource[t],g[t]=r.numNonStringReplacementsBySource[t];continue}let T=r.uniqueIdentifiersUsedBySource[t]=[],C=await this.createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:h,numNonStringReplacementsSoFar:f,uniqueIdentifiersUsed:T,compositeAttributesObj:l,componentInfoObjects:a,nComponentsForSource:s,publicCaseInsensitiveAliasSubstitutions:o,flags:i}),A=C.propVariablesCopiedByReplacement,V=C.serializedReplacements,x=V.length;if(x!==r.numReplacementsBySource[t]){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToReplace:e,serializedReplacements:V,assignNamesOffset:f};m.push(n),N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}else{let n=0;for(let a=0;ae!==A[a][t]))?(s=!1,i=!0):e.replacements[h+a].componentType!==V[a].componentType&&(i=!0)),0==a&&i&&s){1===await e.stateValues.nComponentsSpecified&&1===x&&!(e.replacementsToWithhold>0)&&1===r.sourceNames.length&&(i=!1)}if(i){let e={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h+a,numberReplacementsToReplace:1,serializedReplacements:[V[a]],assignNamesOffset:f+n};m.push(e)}"string"!=typeof V[a]&&n++}}let S=V.filter((e=>"string"!=typeof e)).length;h+=x,f+=S,y[t]=x,g[t]=S,b[t]=A}let T=0===r.sourceNames.length;r.numReplacementsBySource=y,r.numNonStringReplacementsBySource=g,r.sourceNames=c.map((e=>e.componentName)),r.propVariablesCopiedBySource=b;let C=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:m,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return T&&0===r.sourceNames.length?[]:C.replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,numReplacementsToDelete:a,uniqueIdentifiersUsed:i,components:s,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}){let d=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,components:s,uniqueIdentifiersUsed:i,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}),m=d.propVariablesCopiedByReplacement,h=d.serializedReplacements,f={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:a,serializedReplacements:h,assignNamesOffset:r};return{numReplacements:h.length,numNonStringReplacements:h.filter((e=>"string"!=typeof e)).length,propVariablesCopiedByReplacement:m,replacementInstruction:f}}}async function replacementFromProp({component:e,components:t,replacementSource:n,propName:r,uniqueIdentifiersUsed:a,compositeAttributesObj:i,componentInfoObjects:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=[],p=[],d=e.attributes.newNamespace?.primitive,m=-1,h=t[n.componentName],f=l({stateVariables:[r],componentClass:h.constructor})[0];if(void 0===f||"__not_public"===f.slice(0,12))return"__prop_name_not_found"!==r&&console.warn(`Could not find prop ${r} on a component of type ${n.componentType}`),{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let y=h.state[f],g=await y.value,b=await e.stateValues.link;if(y.isArray||y.isArrayEntry){let t,r,l,g;if(y.isArray?(t=y,l=await y.arraySize,r=y.getAllArrayKeys(l,!1)):(t=h.state[y.arrayStateVariable],r=await y.unflattenedArrayKeys,g=await y.arrayKeys),t.shadowingInstructions?.hasVariableComponentType&&(await e.stateValues.replacementSources,!t.shadowingInstructions.createComponentOfType))return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let v=y.wrappingComponents,N=v.length,T=o;if(y.isArray)T=l.slice(0,l.length-N).reduce(((e,t)=>e*t),1);else if(0===g.length)T=0;else if(0===N)T=g.length;else if(N>=y.nDimensions)T=1;else if(N===y.nDimensions-1)T=r.length;else{T=flattenLevels(r,y.nDimensions-N-1).length}if(0===N){let o=flattenDeep(r);for(let r=0;r1)for(let e of r){let t=await o(e,i-1);l.push(...t.pieces),c.push(...t.propVariablesCopiedByPiece)}else for(let i of r){let r,o,p=t.arrayVarNameFromArrayKey(i),d=[p],m=getUniqueIdentifierFromBase(n.componentName+"|shadow|"+p,a),f=t.shadowingInstructions.createComponentOfType;if(Array.isArray(f)&&(f=f[t.keyToIndex(i)]),t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){r={};for(let e in t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let n=t.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,a=h.state[n];a.isArray&&(n=a.arrayVarNameFromArrayKey(i)),r[e]={stateVariableToShadow:n}}}if(t.shadowingInstructions.addStateVariablesShadowingStateVariables){o={};for(let e in t.shadowingInstructions.addStateVariablesShadowingStateVariables){let n=t.shadowingInstructions.addStateVariablesShadowingStateVariables[e].stateVariableToShadow,r=h.state[n];r.isArray&&(n=r.arrayVarNameFromArrayKey(i)),o[e]={stateVariableToShadow:n}}}if(b){let t={};if(r){let n=s.allComponentClasses[f].createAttributesObject();for(let a in r){let i=r[a].stateVariableToShadow,s={componentType:n[a].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:i}]}};t[a]={component:s}}}l.push({componentType:f,attributes:t,downstreamDependencies:{[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:p,additionalStateVariableShadowing:o}]},uniqueIdentifier:m})}else{let e={};if(r){let t={};for(let e in r){let n=r[e].stateVariableToShadow,a=h.state[n],s=await a.value;a.isArray&&(s=s[a.keyToIndex[i]]),h.state[n].usedDefault||(t[e]=s)}let n=convertAttributesForComponentType({attributes:t,componentType:f,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}let n="value",a=s.allComponentClasses[f];a.primaryEssentialStateVariable?n=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(n=a.primaryStateVariableForDefinition);let o=t.keyToIndex(i);Array.isArray(o)||(o=[o]);let c=await t.value;for(let e of o)c=c[e];let p={componentType:f,attributes:e,state:{[n]:c},uniqueIdentifier:m};l.push(p)}c.push(d)}let p=v[i-1];if(l.length>0&&p&&p.length>0){for(let e=p.length-1;e>=0;e--){let t="object"==typeof p[e]?p[e].componentType:p[e],n=getUniqueIdentifierFromBase(t+"|wrapper",a),r=[],i={};for(let e of l)if(e.isAttribute){let t=e.isAttribute;delete e.isAttribute,i[t]={component:e}}else r.push(e);l=[{componentType:t,children:r,attributes:i,uniqueIdentifier:n,skipSugar:!0}],"object"==typeof p[e]&&(p[e].doenetAttributes&&(l[0].doenetAttributes=Object.assign({},p[e].doenetAttributes)),p[e].isAttribute&&(l[0].isAttribute=p[e].isAttribute))}c=[flattenDeep(c)]}return{pieces:l,propVariablesCopiedByPiece:c}},l=await o(r,y.nDimensions),N=l.pieces;p=l.propVariablesCopiedByPiece;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let r=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});Object.assign(t.attributes,r),b&&(t.downstreamDependencies={[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,ignorePrimaryStateVariable:!0}]})}if(m+=N.length,c.push(...N),N.length0?"object"==typeof i[0]?(n=i[0].componentType,r=Object.assign({},i[0].doenetAttributes)):n=i[0]:(n=t.shadowingInstructions.createComponentOfType,Array.isArray(n)&&(n=y.isArrayEntry?n[t.keyToIndex(g[e])]:n[e]));let s={componentType:n,uniqueIdentifier:getUniqueIdentifierFromBase(n+"|empty",a)};r&&(s.doenetAttributes=r),c.push(s)}else if(N>T)throw Error(`Something went wrong when creating replacements for ${e.componentName} as we ended up with too many replacements`)}}else{if(y.shadowingInstructions?.hasVariableComponentType&&await y.value,!y.shadowingInstructions?.createComponentOfType)return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};m++,(p[m]=[]).push(f);let t=getUniqueIdentifierFromBase(h.componentName+"|shadow|"+f,a);if("string"===y.shadowingInstructions.createComponentOfType)c.push(await y.value);else{let n=convertAttributesForComponentType({attributes:e.attributes,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});if(b){let r={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t=s.allComponentClasses[y.shadowingInstructions.createComponentOfType].createAttributesObject();for(let n in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let a=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[n].stateVariableToShadow,i={componentType:t[n].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:a}]}};r[n]={component:i}}}Object.assign(r,n),c.push({componentType:y.shadowingInstructions.createComponentOfType,attributes:r,downstreamDependencies:{[h.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,additionalStateVariableShadowing:y.shadowingInstructions.addStateVariablesShadowingStateVariables}]},uniqueIdentifier:t})}else{let e={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t={};for(let e in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables)if("fixed"!==e){let n=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,r=await h.state[n].value;h.state[n].usedDefault||(t[e]=r)}let n=convertAttributesForComponentType({attributes:t,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}Object.assign(e,n);let r="value",a=s.allComponentClasses[y.shadowingInstructions.createComponentOfType];a.primaryEssentialStateVariable?r=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(r=a.primaryStateVariableForDefinition);let i={componentType:y.shadowingInstructions.createComponentOfType,attributes:e,state:{[r]:g},uniqueIdentifier:t};c.push(i)}}}return{serializedReplacements:c,propVariablesCopiedByReplacement:p}}class Extract extends CompositeComponent{static componentType="extract";static assignNamesToReplacements=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.sourceComponents={stateVariablesDeterminingDependencies:["propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e}){let t,n;null!==e.componentIndex&&(n=Number(e.componentIndex),t=Number.isInteger(n)?[n-1]:[]);let r=e.propIndex;return r&&(r=[...r]),{children:{dependencyType:"child",childGroups:["anything"],variableNames:[e.propName],variablesOptional:!0,childIndices:t,propIndex:r,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.children,n=[];for(let e of t){let t;e.stateValues&&(t=Object.keys(e.stateValues)[0]),t||(t="__prop_name_not_found"),n.push(t)}return{setValue:{sourceComponents:t,effectivePropNameBySource:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({replacementClasses:{dependencyType:"stateVariable",variableName:"sourceComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({sourceComponents:{dependencyType:"stateVariable",variableName:"sourceComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=[],l=0;n.propVariablesCopiedBySource=[],n.uniqueIdentifiersUsedBySource={};let u=this.createAttributesObject(),c=await e.stateValues.sourceComponents;for(let a=0;ae.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:u,flags:a})).replacements}}static async createReplacementForSource({component:e,components:t,sourceNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,publicCaseInsensitiveAliasSubstitutions:o}){let l=(await e.stateValues.effectivePropNameBySource)[n],u=await replacementFromProp({component:e,components:t,replacementSource:(await e.stateValues.sourceComponents)[n],propName:l,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,publicCaseInsensitiveAliasSubstitutions:o}),c=u.serializedReplacements,p=u.propVariablesCopiedByReplacement,d=e.attributes.newNamespace?.primitive;return c=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:c,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:d,componentInfoObjects:i}).serializedComponents,{serializedReplacements:c,propVariablesCopiedByReplacement:p}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=0,l=[],u=[],c=this.createAttributesObject(),p=await e.stateValues.sourceComponents,d=Math.max(p.length,n.numReplacementsBySource.length),m=!1;for(let a=0;a0){if(!m){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToDelete:e};s.push(t)}m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}n.uniqueIdentifiersUsedBySource[a]=[]}l[a]=0,u.push([]);continue}let h=n.sourceNames[a],f=void 0===h||d.componentName!==h||m;if(!f)for(let t=0;te+t),0);g.numberReplacementsToReplace=e,m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}s.push(g);continue}let y=n.uniqueIdentifiersUsedBySource[a]=[],g=await this.createReplacementForSource({component:e,sourceNum:a,components:t,numReplacementsSoFar:o,uniqueIdentifiersUsed:y,componentInfoObjects:r,compositeAttributesObj:c,publicCaseInsensitiveAliasSubstitutions:i}),b=g.propVariablesCopiedByReplacement,v=g.serializedReplacements,N=v.length;if(N!==n.numReplacementsBySource[a]){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0),t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToReplace:e,serializedReplacements:v,assignNamesOffset:o};s.push(t),m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}else for(let e=0;et!==b[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o+e,numberReplacementsToReplace:1,serializedReplacements:[v[e]],assignNamesOffset:o+e};s.push(t)}o+=N,l[a]=N,u[a]=b}return n.numReplacementsBySource=l,n.numNonStringReplacementsBySource=[...l],n.sourceNames=p.map((e=>e.componentName)),n.propVariablesCopiedBySource=u,(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:c,flags:a})).replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}){let u=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,components:i,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}),c=u.propVariablesCopiedByReplacement,p=u.serializedReplacements,d={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:p,assignNamesOffset:n};return{numReplacements:p.length,propVariablesCopiedByReplacement:c,replacementInstruction:d}}}class Collect extends CompositeComponent{static componentType="collect";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:[],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.componentTypes={createComponentOfType:"textList"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.targetComponent={shadowVariable:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition:function({dependencyValues:e}){return null===e.targetComponent?(console.warn("No copy target"),{setValue:{targetName:""}}):{setValue:{targetName:e.targetComponent.componentName}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentTypesToCollect={shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"componentClassesToCollect",shadowVariable:!0}],returnDependencies:()=>({componentTypesAttr:{dependencyType:"attributeComponent",attributeName:"componentTypes",variableNames:["texts"]}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[],r=[];if(null!==e.componentTypesAttr)for(let a of e.componentTypesAttr.stateValues.texts){let e=t.componentTypeLowerCaseMapping[a.toLowerCase()],i=t.allComponentClasses[e];if(i)n.push(e),r.push(i);else{let e="Cannot collect component type "+a+". Component type not found.";console.warn(e)}}return{setValue:{componentTypesToCollect:n,componentClassesToCollect:r}}}},e.collectedComponents={stateVariablesDeterminingDependencies:["componentTypesToCollect","targetName","propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameByComponent"],returnDependencies:function({stateValues:e}){if(!e.targetName)return{};let t={dependencyType:"descendant",ancestorName:e.targetName,componentTypes:e.componentTypesToCollect,useReplacementsForComposites:!0,includeNonActiveChildren:!0,recurseToMatchedChildren:!1,componentIndex:e.componentIndex};if(e.propName){let n=e.propIndex;n&&(n=[...n]),t.variableNames=[e.propName],t.variablesOptional=!0,t.propIndex=n,t.caseInsensitiveVariableMatch=!0,t.publicStateVariablesOnly=!0,t.useMappedVariableNames=!0}return{descendants:t,maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.descendants;if(t||(t=[]),null!==e.maximumNumber&&t.length>e.maximumNumber){let n=Math.max(0,Math.floor(e.maximumNumber));t=t.slice(0,n)}let n=[];for(let r of t){let t;r.stateValues&&(t=Object.keys(r.stateValues)[0]),!t&&e.propName&&(t="__prop_name_not_found"),n.push(t)}return{setValue:{collectedComponents:t,effectivePropNameByComponent:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,nComponentsForSource:a,publicCaseInsensitiveAliasSubstitutions:i,flags:s}){if(!await e.stateValues.targetComponent)return{replacements:[]};let o=[],l=[],u=0,c=[];n.propVariablesCopiedByCollected=[],n.uniqueIdentifiersUsedByCollected={};let p=this.createAttributesObject(),d=await e.stateValues.collectedComponents;for(let m=0;me.componentName))}else l[m]=0,c[m]=[],n.propVariablesCopiedByCollected[m]=[];return n.numReplacementsByCollected=l,n.collectedNames=d.map((e=>e.componentName)),n.replacementNamesByCollected=c,{replacements:o}}static async createReplacementForCollected({component:e,components:t,collectedNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=(await e.stateValues.collectedComponents)[n],p=t[c.componentName],d=[],m=[];if(!p)return{serializedReplacements:d,propVariablesCopiedByReplacement:m};let h=e.attributes.newNamespace?.primitive,f=(await e.stateValues.effectivePropNameByComponent)[n];if(f){let n=await replacementFromProp({component:e,components:t,replacementSource:c,propName:f,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l});d=n.serializedReplacements,m=n.propVariablesCopiedByReplacement}else{let t=await e.stateValues.sourceAttributesToIgnore,r=await e.stateValues.sourceAttributesToIgnoreRecursively;d=postProcessCopy({serializedComponents:[await p.serialize({sourceAttributesToIgnore:t,sourceAttributesToIgnoreRecursively:r})],componentName:e.componentName,uniqueIdentifiersUsed:a,identifierPrefix:n+"|"});for(let t of d){t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:i,compositeAttributesObj:s,compositeCreatesNewNamespace:h,flags:u});Object.assign(t.attributes,n)}}return d=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:h,componentInfoObjects:i}).serializedComponents,{serializedReplacements:d,propVariablesCopiedByReplacement:m}}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}){let l=0;for(let t=0;t0){if(!y){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToDelete:e};u.push(t)}y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}r.uniqueIdentifiersUsedByCollected[t]=[]}p[t]=0,d.push([]),m.push([]);continue}let f=r.collectedNames[t];if(void 0===f||l.componentName!==f||y){let l=0;void 0!==f&&(l=r.numReplacementsByCollected[t]);let h=l;y&&(h=0);let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:c,numReplacementsToDelete:h,components:n,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o});c+=v.numReplacements,p[t]=v.numReplacements,d[t]=v.propVariablesCopiedByReplacement;let N=v.replacementInstruction;if(m[t]=N.serializedReplacements.map((e=>e.componentName)),!y&&v.numReplacements!==l){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);N.numberReplacementsToReplace=e,y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}u.push(N);continue}if(!await e.stateValues.propName){c+=r.numReplacementsByCollected[t],p[t]=r.numReplacementsByCollected[t],m[t]=r.replacementNamesByCollected[t],d[t]=[];continue}let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.createReplacementForCollected({component:e,collectedNum:t,components:n,numReplacementsSoFar:c,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}),N=v.propVariablesCopiedByReplacement,T=v.serializedReplacements,C=T.length;if(C!==r.numReplacementsByCollected[t]){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToReplace:e,serializedReplacements:T,assignNamesOffset:c};u.push(n),y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}else for(let e=0;et!==N[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c+e,numberReplacementsToReplace:1,serializedReplacements:[T[e]],assignNamesOffset:c+e};u.push(t)}c+=C,p[t]=C,d[t]=N,m[t]=T.map((e=>e.componentName))}return r.numReplacementsByCollected=p,r.collectedNames=h.map((e=>e.componentName)),r.propVariablesCopiedByCollected=d,r.replacementNamesByCollected=m,u}static async recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}){let p=await this.createReplacementForCollected({component:e,collectedNum:t,components:i,numReplacementsSoFar:n,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}),d=p.propVariablesCopiedByReplacement,m=p.serializedReplacements,h={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:m,assignNamesOffset:n};return{numReplacements:m.length,propVariablesCopiedByReplacement:d,replacementInstruction:h}}}class Ref extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{navigateToTarget:this.navigateToTarget.bind(this)})}static componentType="ref";static renderChildren=!0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.textType={createComponentOfType:"text",createStateVariable:"textType",defaultValue:"type-global",public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0,forRenderer:!0},e.page={createPrimitiveOfType:"integer",createStateVariable:"page",defaultValue:null,public:!0,forRenderer:!0},e.createButton={createComponentOfType:"boolean",createStateVariable:"createButton",defaultValue:!1,forRenderer:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},uri:{dependencyType:"stateVariable",variableName:"uri"},page:{dependencyType:"stateVariable",variableName:"page"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},targetAttribute:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:function({dependencyValues:e}){if(e.uri||e.page){if(e.targetAttribute){let t=e.targetAttribute;return"/"!==t[0]&&(t="/"+t),{setValue:{targetName:t}}}return{setValue:{targetName:""}}}return null===e.targetComponent||e.targetInactive?{setValue:{targetName:""}}:{setValue:{targetName:e.targetComponent.componentName}}}},e.cid={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"doenetId",forRenderer:!0},{variableName:"variantIndex",forRenderer:!0},{variableName:"edit",forRenderer:!0},{variableName:"draft",forRenderer:!0},{variableName:"hash",forRenderer:!0}],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null,variantIndex:null,edit:null,draft:null,hash:null}};let t=null,n=null,r=null,a=null,i=null,s=null,o=e.uri.match(/[:&]cid=([^&^#]+)/i);return o&&(t=o[1]),o=e.uri.match(/[:&]doenetid=([^&^#]+)/i),o&&(n=o[1]),o=e.uri.match(/[:&]variant=([^&^#]+)/i),o&&(r=Number(o[1]),!Number.isInteger(r)&&r>=1&&(r=1)),o=e.uri.match(/[:&]edit=([^&^#]+)/i),o&&(i="true"===o[1].toLowerCase()),o=e.uri.match(/[:&]draft=([^&^#]+)/i),o&&(a="true"===o[1].toLowerCase()),o=e.uri.match(/(#.+)/i),o&&(s=o[1]),{setValue:{cid:t,doenetId:n,variantIndex:r,edit:i,draft:a,hash:s}}}},e.linkText={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["targetName"],returnDependencies({stateValues:e}){let t={allChildren:{dependencyType:"child",childGroups:["anything"],variableNames:["text"],variablesOptional:!0},uri:{dependencyType:"stateVariable",variableName:"uri"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"}};return e.targetName&&(t.equationTag={dependencyType:"stateVariable",componentName:e.targetName,variableName:"equationTag",variablesOptional:!0},t.title={dependencyType:"stateVariable",componentName:e.targetName,variableName:"title",variablesOptional:!0}),t},definition:function({dependencyValues:e}){let t="";if(0===e.allChildren.length)null!==e.uri?t=e.uri:e.targetInactive||(null!==e.title?t=e.title:null!==e.equationTag&&(t="("+e.equationTag+")"));else for(let n of e.allChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return t||(t="???"),{setValue:{linkText:t}}}},e}async navigateToTarget({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.cid,n=await this.stateValues.doenetId,r=await this.stateValues.variantIndex,a=await this.stateValues.edit,i=await this.stateValues.hash,s=await this.stateValues.page,o=await this.stateValues.uri,l=await this.stateValues.targetName,u=this.componentOrAdaptedName;this.coreFunctions.navigateToTarget({cid:t,doenetId:n,variantIndex:r,edit:a,hash:i,page:s,uri:o,targetName:l,actionId:e,componentName:this.componentName,effectiveName:u})}}}class Coords extends MathComponent{static componentType="coords";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createVectors,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createVectors={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createVectors:!0}})},e}}class LineSegment extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLineSegment:this.moveLineSegment.bind(this),lineSegmentClicked:this.lineSegmentClicked.bind(this),mouseDownOnLineSegment:this.mouseDownOnLineSegment.bind(this)})}static componentType="lineSegment";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpointsDraggable={createComponentOfType:"boolean"},e.endpoints={createComponentOfType:"_pointListComponent"},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line segment"}}}},e.endpointsDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({endpointsDraggableAttr:{dependencyType:"attributeComponent",attributeName:"endpointsDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.endpointsDraggableAttr?{setValue:{endpointsDraggable:e.endpointsDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{endpointsDraggable:{defaultValue:e.draggable}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.endpointsAttr){return{setValue:{nDimensions:e.endpointsAttr.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.endpoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["endpointX","endpoint"],hasEssential:!0,set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("endpointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("endpoints"===t)return 1===e.length?"endpoint"+e[0]:`endpointX${e[0]}_${e[1]}`;if("endpoint"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0)return`endpointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,arraySize:n}){let r={},a={};for(let n of t){let[t,i]=n.split(","),s=Number(t)+1+"_"+(Number(i)+1);null!==e[n].endpointsAttr&&e[n].endpointsAttr.stateValues["pointX"+s]?r[n]=e[n].endpointsAttr.stateValues["pointX"+s]:a[n]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoints:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoints:a}),i},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.endpoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].endpointsAttr&&t[r].endpointsAttr.stateValues["pointX"+o]?i.push({setDependency:n[r].endpointsAttr,desiredValue:e.endpoints[r],childIndex:0,variableIndex:0}):i.push({setEssentialValue:"endpoints",value:{[r]:e.endpoints[r]}})}return{success:!0,instructions:i}}},e.length={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoints:{dependencyType:"stateVariable",variableName:"endpoints"}}),definition({dependencyValues:e}){let t=0,n=e.endpoints[0],r=e.endpoints[1],a=!0;for(let i=0;ie+t*t),0));r=r.map((e=>e/o));let l=e.length.evaluate_to_constant();if(!Number.isFinite(l)||l<0)return{success:!1};let u=[],c=[],p=l/2;for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={endpoint:{dependencyType:"stateVariable",variableName:"endpoint"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(Number.isNaN(e.nDimensions))return{};let r={};for(let a of n){let n=t[a].endpoint,i=[];for(let t=0;t({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0][0],n=e.numericalEndpoints[0][1],r=e.numericalEndpoints[1][0],a=e.numericalEndpoints[1][1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition({dependencyValues:e}){if(2!==e.nDimensions)return{setValue:{slope:NaN}};let t=e.numericalEndpoints;return{setValue:{slope:(t[1][1]-t[0][1])/(t[1][0]-t[0][0])}}}},e}async moveLineSegment({point1coords:e,point2coords:t,transient:n,actionId:r}){if(void 0===e||void 0===t){if(!await this.stateValues.endpointsDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};return void 0!==e&&(a["0,0"]=me$3.fromAst(e[0]),a["0,1"]=me$3.fromAst(e[1])),void 0!==t&&(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{point1:e,point2:t}}})}async lineSegmentClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLineSegment({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Ray extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveRay:this.moveRay.bind(this),rayClicked:this.rayClicked.bind(this),mouseDownOnRay:this.mouseDownOnRay.bind(this)})}static componentType="ray";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpoint={createComponentOfType:"point"},e.through={createComponentOfType:"point"},e.direction={createComponentOfType:"vector"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" ray"}}}},e.directionShadow={defaultValue:null,hasEssential:!0,essentialVarName:"direction",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{directionShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"directionShadow",value:convertValueToMathExpression(e.directionShadow)}]}}},e.throughShadow={defaultValue:null,hasEssential:!0,essentialVarName:"through",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{throughShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"throughShadow",value:convertValueToMathExpression(e.throughShadow)}]}}},e.endpointShadow={defaultValue:null,hasEssential:!0,essentialVarName:"endpoint",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{endpointShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"endpointShadow",value:convertValueToMathExpression(e.endpointShadow)}]}}},e.basedOnThrough={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr&&null!==e.directionAttr?(null!==e.throughAttr&&console.warn("Ray is prescribed by through, endpoint, and direction. Ignoring specified through."),{setValue:{basedOnThrough:!1},checkForActualChange:{basedOnThrough:!0}}):null!==e.throughAttr?{setValue:{basedOnThrough:!0},checkForActualChange:{basedOnThrough:!0}}:{setValue:{basedOnThrough:null!==e.throughShadow},checkForActualChange:{basedOnThrough:!0}}}},e.basedOnEndpoint={returnDependencies:()=>({endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr?{setValue:{basedOnEndpoint:!0},checkForActualChange:{basedOnEndpoint:!0}}:{setValue:{basedOnEndpoint:null!==e.endpointShadow},checkForActualChange:{basedOnEndpoint:!0}}}},e.basedOnDirection={returnDependencies:()=>({directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}}),definition:function({dependencyValues:e}){return null!==e.directionAttr?{setValue:{basedOnDirection:!0},checkForActualChange:{basedOnDirection:!0}}:{setValue:{basedOnDirection:null!==e.directionShadow},checkForActualChange:{basedOnDirection:!0}}}},e.nDimDirection={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["nDimensions"]}};return e.basedOnDirection||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(null!==e.directionAttr)t=e.directionAttr.stateValues.nDimensions;else if(e.directionShadow){let n=e.directionShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnThrough?e.basedOnEndpoint?e.nDimThrough===e.nDimEndpoint?e.nDimThrough:NaN:e.nDimThrough:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimDirection:t},checkForActualChange:{nDimDirection:!0}}}},e.nDimThrough={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}};return e.basedOnThrough||(e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnThrough){if(null!==e.throughAttr)t=e.throughAttr.stateValues.nDimensions;else if(e.throughShadow){let n=e.throughShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnEndpoint?e.nDimDirection===e.nDimEndpoint?e.nDimDirection:NaN:e.nDimDirection:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimThrough:t},checkForActualChange:{nDimThrough:!0}}}},e.nDimEndpoint={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["nDimensions"]}};return e.basedOnEndpoint||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnEndpoint){if(null!==e.endpointAttr)t=e.endpointAttr.stateValues.nDimensions;else if(e.endpointShadow){let n=e.endpointShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnThrough?e.nDimDirection===e.nDimThrough?e.nDimDirection:NaN:e.nDimDirection:e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimEndpoint:t},checkForActualChange:{nDimEndpoint:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"},nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"},nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(e.basedOnEndpoint){if(e.nDimDirection!==e.nDimEndpoint)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnThrough&&e.nDimDirection!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDirection}else if(e.basedOnEndpoint){if(e.basedOnThrough&&e.nDimEndpoint!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimEndpoint}else t=e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.direction={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"directionX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["directionX"],hasEssential:!0,essentialVarName:"direction2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough"],returnArraySizeDependencies:()=>({nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDirection],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["x"+e]}},!t.basedOnDirection&&t.basedOnThrough&&(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e})}return{globalDependencies:{basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;e.basedOnDirection?null!==t[i].directionAttr?r[i]=t[i].directionAttr.stateValues["x"+n]:null!==e.directionShadow&&(r[i]=e.directionShadow.get_component(Number(i))):e.basedOnThrough?r[i]=t[i].throughX.subtract(t[i].endpointX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={direction:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={direction:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.direction)t.basedOnDirection?null!==n[a].directionAttr?i.push({setDependency:r[a].directionAttr,desiredValue:e.direction[a],variableIndex:0}):s=!0:t.basedOnThrough?i.push({setDependency:r[a].throughX,desiredValue:n[a].endpointX.add(e.direction[a]).simplify()}):i.push({setEssentialValue:"direction",value:{[a]:convertValueToMathExpression(e.direction[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.direction)t[Number(n)+1]=e.direction[n].tree;t.length=a[0]+1,i.push({setDependency:"directionShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.direction&&i.push({setDependency:"directionShadow",desiredValue:e.direction[0]});return{success:!0,instructions:i}}},e.through={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["throughX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnThrough"],returnArraySizeDependencies:()=>({nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"}}),returnArraySize:({dependencyValues:e})=>[e.nDimThrough],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["x"+e]}},t.basedOnThrough||(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnThrough?null!==t[a].throughAttr?r[a]=t[a].throughAttr.stateValues["x"+n]:null!==e.throughShadow&&(r[a]=e.throughShadow.get_component(Number(a))):r[a]=t[a].endpointX.add(t[a].directionX).simplify()}return{setValue:{through:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.through)t.basedOnThrough?n[a].throughAttr&&null!==n[a].throughAttr?i.push({setDependency:r[a].throughAttr,desiredValue:e.through[a],variableIndex:0}):null!==t.throughShadow&&(s=!0):i.push({setDependency:r[a].directionX,desiredValue:e.through[a].subtract(n[a].endpointX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.through)t[Number(n)+1]=e.through[n].tree;t.length=a[0]+1,i.push({setDependency:"throughShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.through&&i.push({setDependency:"throughShadow",desiredValue:e.through[0]});return{success:!0,instructions:i}}},e.endpoint={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["endpointX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"endpoint2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnEndpoint","basedOnThrough","basedOnDirection"],returnArraySizeDependencies:()=>({nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),returnArraySize:({dependencyValues:e})=>[e.nDimEndpoint],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["x"+e]}},t.basedOnEndpoint||t.basedOnThrough&&t.basedOnDirection&&(n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].endpointAttr?r[i]=t[i].endpointAttr.stateValues["x"+n]:null!==e.endpointShadow?r[i]=e.endpointShadow.get_component(Number(i)):e.basedOnThrough&&e.basedOnDirection?r[i]=t[i].throughX.subtract(t[i].directionX).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoint:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoint:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.endpoint)n[a].endpointAttr&&null!==n[a].endpointAttr?i.push({setDependency:r[a].endpointAttr,desiredValue:e.endpoint[a],variableIndex:0}):null!==t.endpointShadow?s=!0:t.basedOnThrough&&t.basedOnDirection?i.push({setDependency:r[a].directionX,desiredValue:n[a].throughX.subtract(e.endpoint[a]).simplify()}):i.push({setEssentialValue:"endpoint",value:{[a]:convertValueToMathExpression(e.endpoint[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.endpoint)t[Number(n)+1]=e.endpoint[n].tree;t.length=a[0]+1,i.push({setDependency:"endpointShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.endpoint&&i.push({setDependency:"endpointShadow",desiredValue:e.endpoint[0]});return{success:!0,instructions:i}}},e.numericalEndpoint={forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoint:{dependencyType:"stateVariable",variableName:"endpoint"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.endpoint,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},through:{dependencyType:"stateVariable",variableName:"through"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.through,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoint:{dependencyType:"stateVariable",variableName:"numericalEndpoint"},numericalThroughpoint:{dependencyType:"stateVariable",variableName:"numericalThroughpoint"}}),definition({dependencyValues:e}){let t=e.numericalEndpoint[0],n=e.numericalEndpoint[1],r=e.numericalThroughpoint[0],a=e.numericalThroughpoint[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}async moveRay({endpointcoords:e,throughcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){let s=[];if(void 0!==e){if(await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let n;if(void 0===t){let t=await this.stateValues.numericalThroughpoint;n=e.map(((e,n)=>t[n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"endpoint",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnThrough){let t=await this.stateValues.numericalThroughpoint,n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnThrough)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"through",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=await this.stateValues.numericalEndpoint);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let e=await this.stateValues.numericalEndpoint,n=t.map(((t,n)=>t-e[n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{through:t,endpoint:e}}})}async rayClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnRay({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Polygon extends Polyline{constructor(e){super(e),Object.assign(this.actions,{movePolygon:this.movePolygon.bind(this),polygonClicked:this.polygonClicked.bind(this),mouseDownOnPolygon:this.mouseDownOnPolygon.bind(this)})}static componentType="polygon";static representsClosedPath=!0;get movePolygon(){return this.movePolyline}get polygonClicked(){return this.polylineClicked}get mouseDownOnPolygon(){return this.mouseDownOnPolyline}static createAttributesObject(){let e=super.createAttributesObject();return e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" polygon",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" polygon with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" polygon",{setValue:{styleDescriptionWithNoun:t}}}},e.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},e.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[a-1]?.[0],l=i[a-1]?.[1];for(let e=0;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}}class Triangle extends Polygon{static componentType="triangle";static rendererType="polygon";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","triangle"),{setValue:{styleDescriptionWithNoun:n}}},e.vertices.hasEssential=!0,e.vertices.defaultValueByArrayKey=function(e){return["0,1","1,0"].includes(e)?me$3.fromAst(1):me$3.fromAst(0)},e.vertices.returnArraySizeDependencies=()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),e.vertices.returnArraySize=function({dependencyValues:e}){return[3,e.nDimensions]},e.vertices.arrayDefinitionByKey=function({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let[t,i]=a.split(","),s=Number(t)+1+"_"+(Number(i)+1),o=e[a].vertices;null!==o&&o.stateValues["pointX"+s]?n[a]=o.stateValues["pointX"+s]:r[a]=!0}return{setValue:{vertices:n},useEssentialOrDefaultValue:{vertices:r}}},e.vertices.inverseArrayDefinitionByKey=async function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].vertices&&t[r].vertices.stateValues["pointX"+o]?i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0}):i.push({setEssentialValue:"vertices",value:{[r]:e.vertices[r].simplify()}})}return{success:!0,instructions:i}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:3}})},e}}class Rectangle extends Polygon{static componentType="rectangle";static rendererType="polygon";static createAttributesObject(){let e=super.createAttributesObject();return e.center={createComponentOfType:"point"},e.width={createComponentOfType:"number"},e.height={createComponentOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","rectangle"),{setValue:{styleDescriptionWithNoun:n}}},e.nVerticesSpecified={returnDependencies:()=>({verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.verticesAttr?{setValue:{nVerticesSpecified:e.verticesAttr.stateValues.nPoints}}:{setValue:{nVerticesSpecified:0}}}},e.essentialVertex={isArray:!0,entryPrefixes:["essentialVertexX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}}),returnArraySize:({dependencyValues:e})=>[0===e.nVerticesSpecified?2:0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialVertex:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialVertex)t.push({setEssentialValue:"essentialVertex",value:{[n]:e.essentialVertex[n]}});return{success:!0,instructions:t}}},e.haveSpecifiedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{haveSpecifiedCenter:null!==e.centerAttr}})},e.specifiedCenter={isArray:!0,entryPrefixes:["specifiedCenterX"],returnArraySizeDependencies:()=>({haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.haveSpecifiedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=Number(r)+1;null!==e[r].centerAttr&&(n[r]=e[r].centerAttr.stateValues["x"+t])}return{setValue:{specifiedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.specifiedCenter)t[a].centerAttr&&null!==t[a].centerAttr&&r.push({setDependency:n[a].centerAttr,desiredValue:e.specifiedCenter[a],variableIndex:0});return{success:!0,instructions:r}}},e.specifiedWidth={defaultValue:1,hasEssential:!0,essentialVarName:"width",returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.widthAttr?{setValue:{specifiedWidth:e.widthAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedWidth:!0}}:{setValue:{specifiedWidth:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.widthAttr?{success:!0,instructions:[{setDependency:"widthAttr",desiredValue:e.specifiedWidth,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedWidth",value:e.specifiedWidth}]}},e.specifiedHeight={defaultValue:1,hasEssential:!0,essentialVarName:"height",returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.heightAttr?{setValue:{specifiedHeight:e.heightAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedHeight:!0}}:{setValue:{specifiedHeight:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.heightAttr?{success:!0,instructions:[{setDependency:"heightAttr",desiredValue:e.specifiedHeight,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedHeight",value:e.specifiedHeight}]}},e.center={public:!0,isArray:!0,entryPrefixes:["centerX"],shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_"+e},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex0,a=e[r].vertex2;n[r]=t.add(a).divide(2).simplify()}return{setValue:{center:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,stateValues:r}){let a=[],i=await r.center;for(let r in e.center){let s=Number(r),o=t[r].vertex0,l=t[r].vertex2,u=e.center[s].subtract(i[s]),c=o.add(u).simplify(),p=l.add(u).simplify();a.push({setDependency:n[r].vertex0,desiredValue:c},{setDependency:n[r].vertex2,desiredValue:p})}return{success:!0,instructions:a}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_1"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_1"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{width:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.width)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_2"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_2"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{height:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.height)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["nVerticesSpecified","haveSpecifiedCenter"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[4,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}};if(0===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(",");n[t]={specifiedCenter:{dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)}},"0"===r?n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}:n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"}}else for(let t of e){let[e,r]=t.split(",");n[t]={essentialVertex:{dependencyType:"stateVariable",variableName:"essentialVertexX"+(Number(r)+1)}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else if(1===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},("0"===r&&"1"===e||"2"===e||"1"===r&&"2"===e||"3"===e)&&(n[t].specifiedCenter={dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)})}else for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else for(let t of e){let e,[r,a]=t.split(","),i="1_"+(Number(a)+1),s="2_"+(Number(a)+1);e="0"===r?i:"2"===r?s:"1"===r?"0"===a?s:i:"0"===a?i:s,n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+e]}}}return{dependenciesByKey:n,globalDependencies:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,globalDependencyValues:n}){let r={};if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let[t,a]=n.split(","),i=e[n].specifiedCenter;if("0"===a){let a=e[n].specifiedWidth;r[n]="0"===t||"3"===t?i.subtract(a/2):i.add(a/2)}else{let a=e[n].specifiedHeight;r[n]="0"===t||"1"===t?i.subtract(a/2):i.add(a/2)}}else for(let n of t){let[t,a]=n.split(","),i=e[n].essentialVertex;if("0"===a)if("0"===t||"3"===t)r[n]=i;else{let t=e[n].specifiedWidth;r[n]=i.add(t)}else if("0"===t||"1"===t)r[n]=i;else{let t=e[n].specifiedHeight;r[n]=i.add(t)}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i&&("0"===a||"3"===a)||"1"===i&&("0"===a||"1"===a))r[n]=t;else{let a=e[n].specifiedCenter;r[n]=t.add(a.subtract(t).multiply(2))}}else for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i)if("0"===a||"3"===a)r[n]=t;else{let a=e[n].specifiedWidth;r[n]=t.add(a)}else if("0"===a||"1"===a)r[n]=t;else{let a=e[n].specifiedHeight;r[n]=t.add(a)}}else for(let n of t){let t=e[n].verticesAttr;null!==t&&1===Object.keys(t.stateValues).length?r[n]=Object.values(t.stateValues)[0]:r[n]=me$3.fromAst("_")}return{setValue:{vertices:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,globalDependencyValues:n,stateValues:r,workspace:a,initialChange:i,dependencyNamesByKey:s}){if(i&&!await r.draggable)return{success:!1};if(!a.v0){let e=await r.vertices;a.v0=[...e[0]],a.v2=[...e[2]]}let o,l,u,c,p,d;for(let t in e.vertices){let[n,r]=t.split(","),i=e.vertices[t];"0"===n?a.v0[Number(r)]=i:"2"===n?a.v2[Number(r)]=i:"1"===n?"0"===r?a.v2[Number(r)]=i:a.v0[Number(r)]=i:"0"===r?a.v0[Number(r)]=i:a.v2[Number(r)]=i,"0"===r?(o=t,"0"===n||"3"===n?u=t:p=t):(l=t,"0"===n||"1"===n?c=t:d=t)}let m=[];if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==o){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant(),t=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[o].specifiedWidth,desiredValue:e},{setDependency:s[o].specifiedCenter,desiredValue:t})}if(void 0!==l){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant(),t=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[l].specifiedHeight,desiredValue:e},{setDependency:s[l].specifiedCenter,desiredValue:t})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].essentialVertex,desiredValue:e})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].essentialVertex,desiredValue:e})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[p].specifiedCenter,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[d].specifiedCenter,desiredValue:e})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else void 0!==u&&m.push({setDependency:s[u].verticesAttr,desiredValue:a.v0[0],variableIndex:0}),void 0!==p&&m.push({setDependency:s[p].verticesAttr,desiredValue:a.v2[0],variableIndex:0}),void 0!==c&&m.push({setDependency:s[c].verticesAttr,desiredValue:a.v0[1],variableIndex:0}),void 0!==d&&m.push({setDependency:s[d].verticesAttr,desiredValue:a.v2[1],variableIndex:0});return{success:!0,instructions:m}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:4}})},e}async movePolygon({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a=[],i={};for(let t in e)i[t+",0"]=me$3.fromAst(e[t][0]),i[t+",1"]=me$3.fromAst(e[t][1]);if(a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:i,sourceInformation:n}),1===Object.keys(e).length){let t=Number(Object.keys(e)[0]),n=me$3.fromAst(e[t][0]),r=me$3.fromAst(e[t][1]),i=(t+2)%4,s=await this.stateValues.vertices,o=s[i][0],l=s[i][1];if(await this.stateValues.nVerticesSpecified<2)if(await this.stateValues.haveSpecifiedCenter){let e,i;0===t?(e=n.add(o).divide(2),i=r.add(l).divide(2)):1===t?i=r.add(l).divide(2):3===t&&(e=n.add(o).divide(2)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{0:e.simplify()}}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{1:i.simplify()}})}else{let e,i;0===t?(e=o.subtract(n),i=l.subtract(r)):1===t?i=l.subtract(r):3===t&&(e=o.subtract(n)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedWidth",value:e.simplify()}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedHeight",value:i.simplify()})}}return t?await this.coreFunctions.performUpdate({updateInstructions:a,transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:a,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}}class Circle extends Curve{constructor(e){super(e),Object.assign(this.actions,{moveCircle:this.moveCircle.bind(this),circleClicked:this.circleClicked.bind(this),mouseDownOnCircle:this.mouseDownOnCircle.bind(this)})}static componentType="circle";static rendererType="circle";static representsClosedPath=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.through={createComponentOfType:"_pointListComponent"},e.center={createComponentOfType:"point"},e.radius={createComponentOfType:"math"},e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},delete e.parMin,delete e.parMax,delete e.variable,e}static returnChildGroups(){return GraphicalComponent.returnChildGroups()}static returnStateVariableDefinitions(e){let t=GraphicalComponent.returnStateVariableDefinitions(e);return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" circle",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" circle with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" circle",{setValue:{styleDescriptionWithNoun:t}}}},t.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},t.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"circle"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:NaN}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:NaN}})},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:()=>({setValue:{fs:{}}})},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.throughAttr?{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}:{setValue:{nThroughPoints:0}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],variableIndex:0})}return{success:!0,instructions:i}}},t.havePrescribedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedCenter:null!==e.centerAttr},checkForActualChange:{havePrescribedCenter:!0}})},t.prescribedCenter={isArray:!0,entryPrefixes:["prescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n){let n=Number(e)+1;null!==t[e].centerAttr&&(r[e]=t[e].centerAttr.stateValues["x"+n],r[e]||(r[e]=me$3.fromAst("_")))}return{setValue:{prescribedCenter:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t of Object.keys(e.prescribedCenter).reverse())null!==n[t].centerAttr&&i.push({setDependency:r[t].centerAttr,desiredValue:e.prescribedCenter[t],variableIndex:0});return{success:!0,instructions:i}}},t.prescribedRadius={defaultValue:null,returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius",variableNames:["value"]}}),definition:function({dependencyValues:e}){return null!==e.radiusAttr?{setValue:{prescribedRadius:e.radiusAttr.stateValues.value}}:{setValue:{prescribedRadius:null}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return null!==t.radiusAttr?{success:!0,instructions:[{setDependency:"radiusAttr",desiredValue:e.prescribedRadius,childIndex:0,variableIndex:0}]}:{success:!1}}},t.havePrescribedRadius={returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedRadius:null!==e.radiusAttr},checkForActualChange:{havePrescribedRadius:!0}})},t.numericalPrescribedRadius={returnDependencies:()=>({prescribedRadius:{dependencyType:"stateVariable",variableName:"prescribedRadius"}}),additionalStateVariablesDefined:["haveNonNumericalPrescribedRadius"],definition:function({dependencyValues:e}){let t,n=!1;return null===e.prescribedRadius?t=null:(t=e.prescribedRadius.evaluate_to_constant(),Number.isFinite(t)||(t=NaN,n=!0)),{setValue:{haveNonNumericalPrescribedRadius:n,numericalPrescribedRadius:t},checkForActualChange:{haveNonNumericalEntriesNumericalRadius:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){return await n.haveNonNumericalPrescribedRadius?{success:!1}:void 0!==e.numericalPrescribedRadius?null===t.prescribedRadius?{success:!1}:{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:me$3.fromAst(e.numericalPrescribedRadius)}]}:{success:!1}}},t.numericalPrescribedCenter={isArray:!0,entryPrefixes:["numericalPrescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].prescribedCenterX;t?(n[r]=t.evaluate_to_constant(),Number.isFinite(n[r])||(n[r]=NaN)):n[r]=NaN}return{setValue:{numericalPrescribedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.numericalPrescribedCenter)n.push({setDependency:t[r].prescribedCenterX,desiredValue:me$3.fromAst(e.numericalPrescribedCenter[r])});return{success:!0,instructions:n}}},t.haveNonNumericalPrescribedCenter={returnDependencies:()=>({numericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"}}),definition({dependencyValues:e}){let t=e.numericalPrescribedCenter.some((e=>!Number.isFinite(e)));return{setValue:{haveNonNumericalPrescribedCenter:t},checkForActualChange:{haveNonNumericalPrescribedCenter:!0}}}},t.numericalThroughPoints={returnDependencies:()=>({throughPoints:{dependencyType:"stateVariable",variableName:"throughPoints"}}),additionalStateVariablesDefined:["haveNonNumericalThroughPoints"],definition:function({dependencyValues:e}){let t=!1,n=[];for(let r of e.throughPoints){let e=[];for(let n=0;n<2;n++){let a;try{a=r[n].evaluate_to_constant()}catch(n){console.warn("Invalid point of circle"),t=!0,e=[];break}if(!Number.isFinite(a)){t=!0,e=[];break}e.push(a)}if(!(e.length>0)){n=[];break}n.push(e)}return{setValue:{haveNonNumericalThroughPoints:t,numericalThroughPoints:n},checkForActualChange:{haveNonNumericalThroughPoints:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(await n.haveNonNumericalThroughPoints)return{success:!1};if(void 0!==e.numericalThroughPoints){let t={};for(let[n,r]of e.numericalThroughPoints.entries())t[n+",0"]=me$3.fromAst(r[0]),t[n+",1"]=me$3.fromAst(r[1]);return{success:!0,instructions:[{setDependency:"throughPoints",desiredValue:t}]}}return{success:!1}}},t.haveNumericalEntries={returnDependencies:()=>({haveNonNumericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},haveNonNumericalThroughPoints:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:({dependencyValues:e})=>({setValue:{haveNumericalEntries:!(e.haveNonNumericalPrescribedCenter||e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)}})},t.numericalRadiusCalculatedWithCenter={additionalStateVariablesDefined:["numericalCenterCalculatedWithRadius"],returnDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:function({dependencyValues:e}){if(e.haveNonNumericalThroughPoints){let t="Haven't implemented circle through "+e.nThroughPoints+" points";return t+=" in case where don't have numerical values.",console.warn(t),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}if(2===e.nThroughPoints){let{numericalCenter:t,numericalRadius:n}=circleFromTwoNumericalPoints({point1:e.numericalThroughPoints[0],point2:e.numericalThroughPoints[1]});return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}if(3===e.nThroughPoints){let t,n,r=e.numericalThroughPoints[0][0],a=e.numericalThroughPoints[1][0],i=e.numericalThroughPoints[2][0],s=e.numericalThroughPoints[0][1],o=e.numericalThroughPoints[1][1],l=e.numericalThroughPoints[2][1];if(r===a&&s===o)if(r===i&&s===l)t=[r,s],n=0;else{let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[i,l]});t=e.numericalCenter,n=e.numericalRadius}else if(r===i&&s===l||a===i&&o===l){let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[a,o]});t=e.numericalCenter,n=e.numericalRadius}else{let e=r*r+s*s,u=a*a+o*o,c=i*i+l*l,p=r*(o-l)-s*(a-i)+a*l-i*o,d=e*(l-o)+u*(s-l)+c*(o-s),m=e*(a-i)+u*(i-r)+c*(r-a),h=e*(i*o-a*l)+u*(r*l-i*s)+c*(a*s-r*o);0!==p?(t=[-d/(2*p),-m/(2*p)],n=Math.sqrt((d*d+m*m-4*p*h)/(4*p*p))):(t=[NaN,NaN],n=NaN)}return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}return e.nThroughPoints>3?(console.warn("Can't calculate circle through more than 3 points"),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}):{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}},t.essentialRadius={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{essentialRadius:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"essentialRadius",value:e.essentialRadius}]}}},t.numericalRadius={forRenderer:!0,stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.numericalPrescribedRadius={dependencyType:"stateVariable",variableName:"numericalPrescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter?1===e.nThroughPoints&&(t.haveNonNumericalPrescribedCenter={dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},t.numericalPrescribedCenter={dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"},t.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}):e.nThroughPoints>1&&(t.numericalRadiusCalculatedWithCenter={dependencyType:"stateVariable",variableName:"numericalRadiusCalculatedWithCenter"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}),t},definition:function({dependencyValues:e}){if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalPrescribedCenter||e.haveNonNumericalThroughPoints)return{setValue:{numericalRadius:NaN}};if(void 0!==e.numericalPrescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalRadius:NaN}}):{setValue:{numericalRadius:Math.max(0,e.numericalPrescribedRadius)}};if(void 0!==e.numericalPrescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}if(1===e.nThroughPoints){let t=e.numericalThroughPoints[0];return void 0===t?{setValue:{numericalRadius:NaN}}:{setValue:{numericalRadius:Math.sqrt(Math.pow(t[0]-e.numericalPrescribedCenter[0],2)+Math.pow(t[1]-e.numericalPrescribedCenter[1],2))}}}return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{numericalRadius:NaN}}}if(e.nThroughPoints<2){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}return{setValue:{numericalRadius:e.numericalRadiusCalculatedWithCenter}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(void 0!==t.numericalPrescribedRadius)return{success:!0,instructions:[{setDependency:"numericalPrescribedRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(void 0!==t.numericalPrescribedCenter){if(0===t.nThroughPoints)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(1===t.nThroughPoints){let t=Math.max(0,e.numericalRadius),r=(await n.throughAngles)[0];if(!Number.isFinite(r))return{success:!1};let a=await n.numericalCenter;return{success:!0,instructions:[{setDependency:"numericalThroughPoints",desiredValue:[[a[0]+t*Math.cos(r),a[1]+t*Math.sin(r)]]}]}}return{success:!1}}if(t.nThroughPoints<2)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};{let r=[],a=Math.max(0,e.numericalRadius);for(let e=0;e0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialCenter:t}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,stateValues:t,workspace:n}){let r=[];for(let t in e.essentialCenter)r.push({setEssentialValue:"essentialCenter",value:{[t]:e.essentialCenter[t]}});return{success:!0,instructions:r}}},t.numericalCenter={forRenderer:!0,isArray:!0,entryPrefixes:["numericalCenterX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){for(let t of e){let e=Number(t)+1;r[t]={numericalPrescribedCenterX:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"},n.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.havePrescribedRadius||1==t.nThroughPoints?n.numericalRadius={dependencyType:"stateVariable",variableName:"numericalRadius"}:t.nThroughPoints>1&&(n.numericalCenterCalculatedWithRadius={dependencyType:"stateVariable",variableName:"numericalCenterCalculatedWithRadius"})}return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(void 0!==t[a].numericalPrescribedCenterX){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalCenter:[NaN,NaN]}};r[a]=t[a].numericalPrescribedCenterX}if(Object.keys(r).length>0)return{setValue:{numericalCenter:r}};if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)return{setValue:{numericalCenter:[NaN,NaN]}};if(void 0!==e.numericalRadius){if(0===e.nThroughPoints){for(let e of n){let n=t[e].essentialCenterX;if(n instanceof me$3.class){try{n=n.evaluate_to_constant()}catch(e){}Number.isFinite(n)||(n=NaN)}r[e]=n}return{setValue:{numericalCenter:r}}}if(1===e.nThroughPoints){if(e.numericalThroughPoints.length<1)return{setValue:{numericalCenter:[NaN,NaN]}};return{setValue:{numericalCenter:[e.numericalThroughPoints[0][0],e.numericalThroughPoints[0][1]-e.numericalRadius]}}}if(2===e.nThroughPoints){if(e.numericalThroughPoints.length<2)return{setValue:{numericalCenter:[NaN,NaN]}};let t=e.numericalRadius,n=e.numericalThroughPoints[0][0],r=e.numericalThroughPoints[1][0],a=e.numericalThroughPoints[0][1],i=e.numericalThroughPoints[1][1],s=Math.pow(n-r,2)+Math.pow(a-i,2),o=t*t;return t<0||4*o0)return{success:!0,instructions:s};if(0===t.nThroughPoints){for(let t in e.numericalCenter)s.push({setDependency:r[t].essentialCenterX,desiredValue:e.numericalCenter[t]});return{success:!0,instructions:s}}{i.desiredCenter||(i.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.numericalCenter[t]?i.desiredCenter[t]=e.numericalCenter[t]:void 0===i.desiredCenter[t]&&(i.desiredCenter[t]=a.numericalCenter[t]);let n=[],r=await a.throughAngles,s=await a.numericalRadius;for(let e=0;e({haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNumericalEntries"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"}}),definition:function({dependencyValues:e}){if(!(e.haveNumericalEntries&&e.nThroughPoints>0&&e.numericalRadius>0&&e.numericalCenter.every((e=>Number.isFinite(e)))))return{useEssentialOrDefaultValue:{throughAngles:!0}};let t=[];for(let n of e.numericalThroughPoints)t.push(Math.atan2(n[1]-e.numericalCenter[1],n[0]-e.numericalCenter[0]));return{setValue:{throughAngles:t},setEssentialValue:{throughAngles:t}}}},t.radius={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.prescribedRadius={dependencyType:"stateVariable",variableName:"prescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter&&1===e.nThroughPoints&&(t.prescribedCenter={dependencyType:"stateVariable",variableName:"prescribedCenter"},t.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"}),t},definition:function({dependencyValues:e}){if(Number.isFinite(e.numericalRadius))return{setValue:{radius:me$3.fromAst(e.numericalRadius)}};if(void 0!==e.prescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{radius:me$3.fromAst("_")}}):{setValue:{radius:e.prescribedRadius}};if(void 0!==e.prescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}if(1!==e.nThroughPoints)return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{radius:me$3.fromAst("_")}};try{let t=e.throughPoints[0],n=t[0],r=t[1],a=e.prescribedCenter[0],i=e.prescribedCenter[1];return{setValue:{radius:n.subtract(a).pow(2).add(r.subtract(i).pow(2)).pow(.5).simplify()}}}catch(e){return console.warn("Invalid center or through points of circle"),{setValue:{radius:me$3.fromAst("_")}}}}if(e.nThroughPoints<2){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}return console.warn(`Have not implemented circle through ${e.nThroughPoints} points when non-numerical values`),{setValue:{radius:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=e.radius.evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t.numericalRadius))return{success:!0,instructions:[{setDependency:"numericalRadius",desiredValue:n}]};if(void 0!==t.prescribedRadius)return{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:e.radius}]};if(0===t.nThroughPoints){return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:e.radius}]}}return console.warn("Can't change radius of circle with non-numerical values through points"),{success:!1}}},t.diameter={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{diameter:e.radius.multiply(2).simplify()}}),inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"radius",desiredValue:e.diameter.divide(2).simplify()}]}}},t.center={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["centerX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){n.havePrescribedCenter={dependencyType:"value",value:!0};for(let t of e){let e=Number(t)+1;r[t]={numericalCenterX:{dependencyType:"stateVariable",variableName:"numericalCenterX"+e},prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.numericalCenter={dependencyType:"stateVariable",variableName:"numericalCenter"},n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"},t.havePrescribedRadius?n.radius={dependencyType:"stateVariable",variableName:"prescribedRadius"}:1==t.nThroughPoints&&(n.radius={dependencyType:"stateVariable",variableName:"radius"})}return{dependenciesByKey:r,globalDependencies:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.havePrescribedCenter){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}};let r={};for(let e of n)Number.isFinite(t[e].numericalCenterX)?r[e]=me$3.fromAst(t[e].numericalCenterX):r[e]=t[e].prescribedCenterX;return{setValue:{center:r}}}if(e.numericalCenter.every((e=>Number.isFinite(e))))return{setValue:{center:e.numericalCenter.map((e=>me$3.fromAst(e)))}};if(void 0!==e.radius){if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}if(1===e.nThroughPoints){let t;try{t=[e.throughPoints[0][0],e.throughPoints[0][1].subtract(e.radius).simplify()]}catch(e){t=[me$3.fromAst("_"),me$3.fromAst("_")]}return{setValue:{center:t}}}return console.warn("Can't create circle through more than one point with given radius when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}}if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}return console.warn("Can't create circle through more than one point when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,stateValues:n,dependencyNamesByKey:r,workspace:a}){if(t.havePrescribedCenter){let t=[];for(let n in e.center)t.push({setDependency:r[n].prescribedCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}a.desiredCenter||(a.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.center[t]?a.desiredCenter[t]=e.center[t]:void 0===a.desiredCenter[t]&&(a.desiredCenter[t]=(await n.center)[t]);let i=[],s=!0;for(let e=0;e<2;e++){let t=a.desiredCenter[e].evaluate_to_constant();if(!Number.isFinite(t)){s=!1;break}i.push(t)}if(s&&t.numericalCenter.every((e=>Number.isFinite(e))))return{success:!0,instructions:[{setDependency:"numericalCenter",desiredValue:i}]};if(0===t.nThroughPoints){let t=[];for(let n in e.center)t.push({setDependency:r[n].essentialCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}return console.warn("Haven't implemented changing center of circle through points with non numerical values"),{success:!1}}},t.nearestPoint={returnDependencies:()=>({numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"}}),definition({dependencyValues:e}){let t=e.numericalRadius,n=e.numericalCenter[0],r=e.numericalCenter[1];return{setValue:{nearestPoint:function({variables:e,scales:a}){let i=e.x1?.evaluate_to_constant(),s=e.x2?.evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return{};if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(t)))return{};let o=Math.atan2(s-r,i-n),l={x1:n+t*Math.cos(o),x2:r+t*Math.sin(o)};return void 0!==e.x3&&(l.x3=0),l}}}}},t}async moveCircle({center:e,radius:t,throughAngles:n,transient:r,actionId:a}){let i=[],s=await this.stateValues.nThroughPoints,o=await this.stateValues.numericalPrescribedCenter;if((s<=1||null!==o)&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"numericalCenter",value:e}),s>=1){let r=[];void 0===n&&(n=await this.stateValues.throughAngles),void 0===t&&(t=await this.stateValues.numericalRadius);for(let a=0;a({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" parabola"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"function"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:1/0}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:-1/0}})},t.aShadow={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{aShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"aShadow",value:e.aShadow}]}}},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nThroughPoints:0}}:{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;if(null!==s&&s.stateValues["pointX"+i]){let e=s.stateValues["pointX"+i].evaluate_to_constant();Number.isFinite(e)?n[r]=me$3.fromAst(e):n[r]=me$3.fromAst("_")}else n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.tree));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.numericalThroughPoints){if(!t[a].throughPoint)return{success:!1};r.push({setDependency:n[a].throughPoint,desiredValue:e.numericalThroughPoints[a].map((e=>me$3.fromAst(e)))})}return{success:!0,instructions:r}}},t.numericalPrescribedVertex={returnDependencies:()=>({prescribedVertex:{dependencyType:"stateVariable",variableName:"prescribedVertex"}}),definition({dependencyValues:e}){if(null===e.prescribedVertex)return{setValue:{numericalPrescribedVertex:null}};let t,n;try{t=e.prescribedVertex.get_component(0).evaluate_to_constant(),n=e.prescribedVertex.get_component(1).evaluate_to_constant(),Number.isFinite(t)&&Number.isFinite(n)||(t=NaN,n=NaN)}catch(e){t=NaN,n=NaN}return{setValue:{numericalPrescribedVertex:[t,n]}}}},t.pointsAreNumerical={returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"}}),definition:({dependencyValues:e})=>({setValue:{pointsAreNumerical:e.numericalThroughPoints.every((e=>Number.isFinite(e[0])))&&(!e.numericalPrescribedVertex||Number.isFinite(e.numericalPrescribedVertex[0]))},checkForActualChange:{pointsAreNumerical:!0}})},t.a={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"b",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},{variableName:"c",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},"realValued"],returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"},pointsAreNumerical:{dependencyType:"stateVariable",variableName:"pointsAreNumerical"},aShadow:{dependencyType:"stateVariable",variableName:"aShadow"}}),definition:function({dependencyValues:e,componentName:t}){if(!e.pointsAreNumerical)return{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}};let n,r,a,i=!0;if(e.numericalPrescribedVertex){if(0===e.numericalThroughPoints.length){let t=e.numericalPrescribedVertex,i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}{let t=e.numericalPrescribedVertex,i=t[0],s=t[1],o=e.numericalThroughPoints[0],l=o[0];return n=(o[1]-s)/(l-i)**2,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}}if(0===e.numericalThroughPoints.length)return{setValue:{a:e.aShadow,realValued:!0},useEssentialOrDefaultValue:{b:!0,c:!0}};if(1===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}if(2===e.numericalThroughPoints.length){n=e.aShadow;let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c;return s===c?o==p?(r=-2*n*s,a=n*l+o):(i=!1,n=NaN,r=NaN,a=NaN):(r=(o-p-n*(l-d))/(s-c),a=o-n*l-r*s),{setValue:{a:n,b:r,c:a,realValued:i}}}if(3===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c,m=e.numericalThroughPoints[2],h=m[0],f=m[1],y=h*h,g=l-y,b=d-y,v=s-h,N=c-h,T=o-f,C=p-f,A=g*N-b*v;if(0===A){let t,u,d,m=!1;s===c?o===p?s===h?o==f?t=1:m=!0:(t=2,u=h,d=f):m=!0:s===h?o===f?(t=2,u=c,d=p):m=!0:c===h&&p===f?(t=2,u=c,d=p):m=!0,m?(i=!1,n=NaN,r=NaN,a=NaN):1===t?(n=e.aShadow,r=-2*n*s,a=n*s*s+o):(n=e.aShadow,r=(o-d-n*(l-u*u))/(s-u),a=o-n*l-r*s)}else n=(T*N-C*v)/A,r=(C*g-T*b)/A,a=o-r*s-n*l;return{setValue:{a:n,b:r,c:a,realValued:i}}}return console.warn("Haven't implemented parabola through more than 3 points"),{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(!t.pointsAreNumerical)return{success:!1};let a={},i=function(e){if(Number.isFinite(e))return{success:!0,value:e};if(e instanceof me$3.class){let t=e.evaluate_to_constant();if(Number.isFinite(t))return{success:!0,value:t}}return{success:!1}};if(void 0!==e.a){let t=i(e.a);if(!t.success)return{success:!1};a.a=t.value}if(void 0!==e.b){let t=i(e.b);if(!t.success)return{success:!1};a.b=t.value}if(void 0!==e.c){let t=i(e.c);if(!t.success)return{success:!1};a.c=t.value}Object.assign(r,a);let s=async function(e){return void 0!==r[e]?r[e]:await n[e]};if(0===t.numericalThroughPoints.length){let e=[];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),void 0!==a.b&&e.push({setEssentialValue:"b",value:a.b}),void 0!==a.c&&e.push({setEssentialValue:"c",value:a.c}),{success:!0,instructions:e}}if(1===t.numericalThroughPoints.length){let e=await s("a"),t=await s("b"),n=await s("c"),r=[{setDependency:"numericalThroughPoints",desiredValue:[[-t/(2*e),n-t*t/(4*e)]]}];return void 0!==a.a&&r.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:r}}if(2===t.numericalThroughPoints.length){let e=await s("a"),n=await s("b"),r=await s("c"),i=t.numericalThroughPoints[0][0],o=t.numericalThroughPoints[1][0];if(i===o){i=-n/(2*e);let t=r-n*n/(4*e),s=[{setDependency:"numericalThroughPoints",desiredValue:[[i,t],[i,t]]}];return void 0!==a.a&&s.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:s}}{let t=[{setDependency:"numericalThroughPoints",desiredValue:[[i,e*i*i+n*i+r],[o,e*o*o+n*o+r]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}if(3===t.numericalThroughPoints.length){let e,n=await s("a"),r=await s("b"),i=await s("c"),o=t.numericalThroughPoints[0][0],l=t.numericalThroughPoints[1][0],u=t.numericalThroughPoints[2][0],c=3;if(o===l?o===u?c=1:(c=2,e=3):o===u?(c=2,e=2):l===u&&(c=2,e=1),3===c){let e=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,n*l*l+r*l+i],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:e}}if(2===c){if(1===e){let e=n*l*l+r*l+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,e],[l,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}if(2===e){let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[l,n*l*l+r*l+i],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}{let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}{o=-r/(2*n);let e=i-r*r/(4*n),t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}return{success:!1}}},t.vertex={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["vertexX"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"},realValued:{dependencyType:"stateVariable",variableName:"realValued"}}}),arrayDefinitionByKey:function({globalDependencyValues:e}){let t={};return e.realValued&&0!==e.a?(t[0]=me$3.fromAst(-e.b/(2*e.a)),t[1]=me$3.fromAst(e.c-e.b**2/(4*e.a))):(t[0]=me$3.fromAst("_"),t[1]=me$3.fromAst("_")),{setValue:{vertex:t}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,workspace:n,stateValues:r}){let a,i;if(a="0"in e.vertex?e.vertex[0].evaluate_to_constant():void 0!==n.x?n.x:(await r.vertex)[0].tree,!Number.isFinite(a))return{success:!1};if(n.x=a,i="1"in e.vertex?e.vertex[1].evaluate_to_constant():void 0!==n.y?n.y:(await r.vertex)[1].tree,!Number.isFinite(i))return{success:!1};n.y=i;let s=t.a;return{success:!0,instructions:[{setDependency:"b",desiredValue:-2*s*a,additionalDependencyValues:{c:i+s*a*a}}]}}},t.equation={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalProperties:{simplify:"numberspreserveorder",displaysmallaszero:!0},returnDependencies:()=>({a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition:function({dependencyValues:e}){let t=["=","y",["+",["*",e.a,["^","x",2]],["*",e.b,"x"],e.c]];return{setValue:{equation:me$3.fromAst(t).evaluate_numbers({skip_ordering:!0})}}}},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0}],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[1],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>({setValue:{fs:[function(t){return e.a*t*t+e.b*t+e.c}],fDefinitions:[{functionType:"formula",formula:["+",["*",e.a,"x","x"],["*",e.b,"x"],e.c],variables:["x"],nInputs:1,nOutputs:1,domain:null}]}})},t.f={isAlias:!0,targetVariableName:"f1"},t.nearestPoint={returnDependencies:()=>({f:{dependencyType:"stateVariable",variableName:"f"},a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition({dependencyValues:e,componentName:t}){let n=!(Number.isFinite(e.a)&&Number.isFinite(e.b)&&Number.isFinite(e.c));return{setValue:{nearestPoint:function({variables:t,scales:r}){if(n)return{};let a=r[0],i=r[1],s=t.x1?.evaluate_to_constant(),o=t.x2?.evaluate_to_constant();if(!Number.isFinite(s)||!Number.isFinite(o))return{};s/=a,o/=i;let l=e.a*a*a/i,u=e.b*a/i,c=e.c/i;if(0===l){let e=u*u+1,n={};return n.x1=(s+u*o-u*c)/e*a,n.x2=(u*(s+u*o)+c)/e*i,void 0!==t.x3&&(n.x3=0),n}let p=c-o,d=2*l**2,m=cardano(3*l*u/d,(2*l*p+u**2+1)/d,(u*p-s)/d,1e-14),h=m[0],f=e.f(h*a)/i,y=(s-h)**2+(o-f)**2;for(let t of m.slice(1)){let n=t,r=e.f(n*a)/i,l=(s-n)**2+(o-r)**2;l0){const t=Math.sqrt(s/108),n=2*Math.sqrt(Math.cbrt(i*i/4+s/108)),r=Math.atan2(t,-i/2);return[Math.cos(r/3),Math.cos(r/3+2*Math.PI/3),Math.cos(r/3-2*Math.PI/3)].sort(((e,t)=>e-t)).map((t=>n*t-e/3))}const o=Math.sqrt(-s/108);return[Math.cbrt(-i/2+o)+Math.cbrt(-i/2-o)-e/3]}class BezierControls extends InlineComponent{static componentType="bezierControls";static rendererType="containerInline";static createAttributesObject(){let e=super.createAttributesObject();return e.alwaysVisible={createComponentOfType:"boolean",createStateVariable:"alwaysVisible",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"controlVectors",children:[{componentType:"vector",children:e}]}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"controlVectors",componentTypes:["controlVectors"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nControls={returnDependencies:()=>({nParentPoints:{dependencyType:"parentStateVariable",variableName:"nThroughPoints",skipComponentNames:!0}}),definition({dependencyValues:e}){let t=e.nParentPoints;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nControls:t}}}},e.pointIndMap={returnDependencies:()=>({controlChildren:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["pointNumber"]}}),definition:function({dependencyValues:e}){let t=[],n=-1;for(let[r,a]of e.controlChildren.entries()){let e=a.stateValues.pointNumber;Number.isFinite(e)?n=Math.round(e)-1:n+=1,t[n]=r}return{setValue:{pointIndMap:t}}}},e.directions={isArray:!0,entryPrefixes:["direction"],hasEssential:!0,defaultValueByArrayKey:()=>"none",stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["direction"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.direction:r[a]=!0}return{setValue:{directions:n},useEssentialOrDefaultValue:{directions:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.directions){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.directions[i],childIndex:0,variableIndex:0}):a[i]=e.directions[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"directions",value:a}),{success:!0,instructions:r}}},e.hiddenControls={isArray:!0,entryPrefixes:["hiddenControl"],hasEssential:!0,defaultValueByArrayKey:()=>!1,stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["hide"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.hide:r[a]=!0}return{setValue:{hiddenControls:n},useEssentialOrDefaultValue:{hiddenControls:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.hiddenControls){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.hiddenControls[i],childIndex:0,variableIndex:0}):a[i]=e.hiddenControls[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"hiddenControls",value:a}),{success:!0,instructions:r}}},e.nDimensions={returnDependencies:()=>({nParentDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t=e.nParentDimensions;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.essentialSymmetricControls={isArray:!0,entryPrefixes:["essentialSymmetricControl"],nDimensions:2,hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)n.split(",").map((e=>Number(e))),t[n]=!0;return{useEssentialOrDefaultValue:{essentialSymmetricControls:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[],n={};for(let t in e.essentialSymmetricControls)n[t]=e.essentialSymmetricControls[t];return Object.keys(n).length>0&&t.push({setEssentialValue:"essentialSymmetricControls",value:n}),{success:!0,instructions:t}}},e.controls={isArray:!0,entryPrefixes:["control"],nDimensions:3,hasEssential:!0,shadowVariable:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),stateVariablesDeterminingDependencies:["pointIndMap","directions"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1));n[r]={direction:{dependencyType:"stateVariable",variableName:"direction"+a[0]}};let i=t.directions[e[0]];if("none"!==i&&(0===e[1]||1===e[1])){let s=t.pointIndMap[e[0]];void 0!==s&&("symmetric"===i||"previous"===i&&0===e[1]||"next"===i&&1===e[1]?n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX1_"+a[2]],childIndices:[s]}:"both"===i&&(n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX"+a[1]+"_"+a[2]],childIndices:[s]})),"symmetric"===i&&(n[r].essentialSymmetricControl={dependencyType:"stateVariable",variableName:"essentialSymmetricControl"+a[0]+"_"+a[2]})}}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,componentName:n}){let r={},a={};for(let n of t){let t=n.split(",").map((e=>Number(e))),i=t.map((e=>e+1)),s=e[n].direction;if(0===t[1])if("none"===s||"next"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length){let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}o&&("symmetric"===s?r[n]=e[n].essentialSymmetricControl:a[n]=!0)}else if(1===t[1])if("none"===s||"previous"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length)if("both"===s){let e=t[0].stateValues["vectorX2_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}else{let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]="symmetric"===s?me$3.fromAst(-e):me$3.fromAst(e))}o&&("symmetric"===s?e[n].essentialSymmetricControl&&(r[n]=me$3.fromAst(-e[n].essentialSymmetricControl.tree)):a[n]=!0)}}return{setValue:{controls:r},useEssentialOrDefaultValue:{controls:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.controls){let s=i.split(",").map((e=>Number(e))),o=s.map((e=>e+1)),l=n[i].direction;if(l)if(0===s[1]){if("none"!==l&&"next"!==l){let s=n[i].controlChild,u=!0;if(s&&1===s.length){s[0].stateValues["vectorX1_"+o[2]]&&(u=!1,r.push({setDependency:t[i].controlChild,desiredValue:e.controls[i],childIndex:0,variableIndex:0}))}if(u){let n=e.controls[i].evaluate_to_constant();Number.isFinite(n)||(n=NaN),n=me$3.fromAst(n),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:n}):a[i]=n}}}else if(1===s[1]&&"none"!==l&&"previous"!==l){let s,u=n[i].controlChild,c=!0;if(u&&1===u.length)if("both"===l){u[0].stateValues["vectorX2_"+o[2]]&&(c=!1)}else{u[0].stateValues["vectorX1_"+o[2]]&&(c=!1)}s="symmetric"===l?me$3.fromAst(["-",e.controls[i].tree]):e.controls[i],c?(s=s.evaluate_to_constant(),Number.isFinite(s)||(s=NaN),s=me$3.fromAst(s),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:s}):a[i]=s):r.push({setDependency:t[i].controlChild,desiredValue:s,childIndex:0,variableIndex:0})}}return Object.keys(a).length>0&&r.push({setEssentialValue:"controls",value:a}),{success:!0,instructions:r}}},e}}class VectorListComponent extends BaseComponent{static componentType="_vectorListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"vector",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"vectors",componentTypes:["vector"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nVectors={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nVectors:e.vectorChildren.length},checkForActualChange:{nVectors:!0}})},e.nDimensions={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.vectorChildren.length)t=2;else{t=1;for(let n of e.vectorChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.vectors={isArray:!0,nDimensions:2,entryPrefixes:["vectorX","vector"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vectors"===t)return 1===e.length?"vector"+e[0]:`vectorX${e[0]}_${e[1]}`;if("vector"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vectorX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVectors:{dependencyType:"stateVariable",variableName:"nVectors"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVectors,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].vectorChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{vectors:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.vectors)n.push({setDependency:t[r].vectorChild,desiredValue:e.vectors[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class ControlVectors extends VectorListComponent{static componentType="controlVectors";static createAttributesObject(){let e=super.createAttributesObject();return e.direction={createComponentOfType:"text",createStateVariable:"direction",defaultValue:"symmetric",public:!0,toLowerCase:!0,validValues:["symmetric","previous","next","both","none"]},e.pointNumber={createComponentOfType:"number",createStateVariable:"pointNumber",defaultValue:null,public:!0},e}}class PointListComponent extends BaseComponent{static componentType="_pointListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"point",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPoints={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nPoints:e.pointChildren.length},checkForActualChange:{nPoints:!0}}}},e.nDimensions={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.pointChildren.length)t=2;else{t=1;for(let n of e.pointChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nPoints:{dependencyType:"stateVariable",variableName:"nPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].pointChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{points:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.points)n.push({setDependency:t[r].pointChild,desiredValue:e.points[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class IntervalListComponent extends BaseComponent{static componentType="_intervalListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoIntervalPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"interval",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"intervals",componentTypes:["interval"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nIntervals={returnDependencies:()=>({intervalChildren:{dependencyType:"child",childGroups:["intervals"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nIntervals:e.intervalChildren.length},checkForActualChange:{nIntervals:!0}}}},e.intervals={isArray:!0,nDimensions:1,entryPrefixes:["interval"],returnArraySizeDependencies:()=>({nIntervals:{dependencyType:"stateVariable",variableName:"nIntervals"}}),returnArraySize:({dependencyValues:e})=>[e.nIntervals],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={intervalChild:{dependencyType:"child",childGroups:["intervals"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].intervalChild[0];t&&(n[r]=t.stateValues.value)}return{setValue:{intervals:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.intervals)n.push({setDependency:t[r].intervalChild,desiredValue:e.intervals[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}function breakEmbeddedStringsIntoIntervalPieces({componentList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){if(0===t)return{success:!1};r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=a+1,n=e.substring(i,t).trim();n.length>0&&r.push(n)}n.push(r),r=[],i=a+1}t--}else if(0===t&&!s.match(/\s/))return{success:!1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t||r.length>0?{success:!1}:{success:!0,pieces:n}}class LineListComponent extends BaseComponent{static componentType="_lineListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"line",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nLines={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nLines:e.lineChildren.length},checkForActualChange:{nLines:!0}}}},e.lineNames={isArray:!0,entryPrefixes:["lineName"],returnArraySizeDependencies:()=>({nLines:{dependencyType:"stateVariable",variableName:"nLines"}}),returnArraySize:({dependencyValues:e})=>[e.nLines],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={lineChild:{dependencyType:"child",childGroups:["lines"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].lineChild[0];t&&(n[r]=t.componentName)}return{setValue:{lineNames:n}}}},e}}class AngleListComponent extends BaseComponent{static componentType="_angleListComponent";static createAttributesObject(){let e=super.createAttributesObject();return e.hide={default:!0},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"AtLeastZeroAngles",componentType:"angle",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"AtLeastOneString",componentType:"string",comparison:"atLeast",number:1}),i=t.newLeaf({name:"AtLeastOneMath",componentType:"math",comparison:"atLeast",number:1}),s=t.newOperator({name:"StringsAndMaths",operator:"or",propositions:[a,i],requireConsecutive:!0,isSugar:!0,replacementFunction:r});return t.newOperator({name:"AnglesXorSugar",operator:"xor",propositions:[n,s],setAsBase:!0}),t}updateState(e={}){if(e.init&&(this._state.angles={trackChanges:!0}),super.updateState(e),!this.childLogicSatisfied)return this.unresolvedState.angles=!0,void(this.unresolvedState.nAngles=!0);if(this.currentTracker.trackChanges.childrenChanged(this.componentName)){delete this.unresolvedState.angles,delete this.unresolvedState.nAngles;let e=this.childLogic.returnMatches("AtLeastZeroAngles");this.state.nAngles=e.length,this.state.angles=e.map((e=>this.activeChildren[e]))}}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.container({key:this.componentName}))}updateChildrenWhoRender(){this.childrenWhoRender=this.state.angles.map((e=>e.componentName))}}class Vector extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveVector:this.moveVector.bind(this),vectorClicked:this.vectorClicked.bind(this),mouseDownOnVector:this.mouseDownOnVector.bind(this)})}static componentType="vector";static primaryStateVariableForDefinition="displacementShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.headDraggable={createComponentOfType:"boolean"},e.tailDraggable={createComponentOfType:"boolean"},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.displacement={createComponentOfType:"vector"},e.head={createComponentOfType:"point"},e.tail={createComponentOfType:"point"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.displayWithAngleBrackets={createComponentOfType:"boolean",createStateVariable:"displayWithAngleBrackets",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{displacement:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{x:{component:{componentType:"math",children:e}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" vector"}}}},e.tailDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({tailDraggableAttr:{dependencyType:"attributeComponent",attributeName:"tailDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.tailDraggableAttr?{setValue:{tailDraggable:e.tailDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{tailDraggable:{defaultValue:e.draggable}}}},e.headDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({headDraggableAttr:{dependencyType:"attributeComponent",attributeName:"headDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.headDraggableAttr?{setValue:{headDraggable:e.headDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{headDraggable:{defaultValue:e.draggable}}}},e.displacementShadow={defaultValue:null,hasEssential:!0,essentialVarName:"displacement",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{displacementShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"displacementShadow",value:convertValueToMathExpression(e.displacementShadow)}]}}},e.headShadow={defaultValue:null,hasEssential:!0,essentialVarName:"head",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{headShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"headShadow",value:convertValueToMathExpression(e.headShadow)}]}}},e.tailShadow={defaultValue:null,hasEssential:!0,essentialVarName:"tail",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{tailShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"tailShadow",value:convertValueToMathExpression(e.tailShadow)}]}}},e.sourceOfDisplacement={returnDependencies:()=>({xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement"},pointChild:{dependencyType:"child",childGroups:["points"]},vectorChild:{dependencyType:"child",childGroups:["vectors"]}}),definition({dependencyValues:e}){let t=null;return e.vectorChild.length>0?t="vectorChild":e.pointChild.length>0?t="pointChild":null!==e.displacementAttr?t="displacementAttr":null!==e.xsAttr?t="xsAttr":null===e.xAttr&&null===e.yAttr&&null===e.zAttr||(t="componentAttrs"),{setValue:{sourceOfDisplacement:t}}}},e.basedOnHead={returnDependencies:()=>({headAttr:{dependencyType:"attributeComponent",attributeName:"head"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr&&null!==e.sourceOfDisplacement?(null!==e.headAttr&&console.warn("Vector is prescribed by head, tail, and displacement. Ignoring specified head."),{setValue:{basedOnHead:!1},checkForActualChange:{basedOnHead:!0}}):null!==e.headAttr?{setValue:{basedOnHead:!0},checkForActualChange:{basedOnHead:!0}}:{setValue:{basedOnHead:null!==e.headShadow},checkForActualChange:{basedOnHead:!0}}}},e.basedOnTail={returnDependencies:()=>({tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr?{setValue:{basedOnTail:!0},checkForActualChange:{basedOnTail:!0}}:{setValue:{basedOnTail:null!==e.tailShadow},checkForActualChange:{basedOnTail:!0}}}},e.basedOnDisplacement={returnDependencies:()=>({sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"}}),definition:function({dependencyValues:e}){return null!==e.sourceOfDisplacement?{setValue:{basedOnDisplacement:!0},checkForActualChange:{basedOnDisplacement:!0}}:{setValue:{basedOnDisplacement:null!==e.displacementShadow},checkForActualChange:{basedOnDisplacement:!0}}}},e.nDimDisplacement={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]}};return e.basedOnDisplacement||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":t=e.vectorChild[0].stateValues.nDimensions;break;case"pointChild":t=e.pointChild[0].stateValues.nDimensions;break;case"displacementAttr":t=e.displacementAttr.stateValues.nDimensions;break;case"xsAttr":t=e.xsAttr.stateValues.nComponents;break;case"componentAttrs":t=null!==e.zAttr?3:null!==e.yAttr?2:1;break;default:let n=e.displacementShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:1}else t=e.basedOnHead?e.basedOnTail?e.nDimHead===e.nDimTail?e.nDimHead:NaN:e.nDimHead:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimDisplacement:t},checkForActualChange:{nDimDisplacement:!0}}}},e.nDimHead={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["nDimensions"]}};return e.basedOnHead||(e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnHead){if(null!==e.headAttr)t=e.headAttr.stateValues.nDimensions;else if(e.headShadow){let n=e.headShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnTail?e.nDimDisplacement===e.nDimTail?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimHead:t},checkForActualChange:{nDimHead:!0}}}},e.nDimTail={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["nDimensions"]}};return e.basedOnTail||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnTail){if(null!==e.tailAttr)t=e.tailAttr.stateValues.nDimensions;else if(e.tailShadow){let n=e.tailShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnHead?e.nDimDisplacement===e.nDimHead?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnHead?e.nDimHead:2;return{setValue:{nDimTail:t},checkForActualChange:{nDimTail:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"},nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"},nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement){if(e.basedOnTail){if(e.nDimDisplacement!==e.nDimTail)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnHead&&e.nDimDisplacement!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDisplacement}else if(e.basedOnTail){if(e.basedOnHead&&e.nDimTail!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimTail}else t=e.basedOnHead?e.nDimHead:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.displacement={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros","displayWithAngleBrackets"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],hasEssential:!0,essentialVarName:"displacement2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","sourceOfDisplacement"],returnArraySizeDependencies:()=>({nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDisplacement],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["x"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===r&&(n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]}),!t.basedOnDisplacement&&t.basedOnHead&&(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e})}return{globalDependencies:{basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":r[i]=t[i].vectorChild[0].stateValues["x"+n];break;case"pointChild":r[i]=t[i].pointChild[0].stateValues["x"+n];break;case"displacementAttr":r[i]=t[i].displacementAttr.stateValues["x"+n];break;case"xsAttr":r[i]=t[i].xsAttr.stateValues["math"+n].simplify();break;case"componentAttrs":let s=t[i].componentAttr;null===s?a[i]={defaultValue:me$3.fromAst(0)}:r[i]=s.stateValues.value.simplify();break;default:let o=e.displacementShadow.tree;Array.isArray(o)&&vectorOperators.includes(o[0])?r[i]=e.displacementShadow.get_component(Number(i)):r[i]=e.displacementShadow}else e.basedOnHead?r[i]=t[i].headX.subtract(t[i].tailX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={displacement:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={displacement:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.displacement)if(t.basedOnDisplacement)switch(t.sourceOfDisplacement){case"vectorChild":i.push({setDependency:r[a].vectorChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"pointChild":i.push({setDependency:r[a].pointChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"displacementAttr":i.push({setDependency:r[a].displacementAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"xsAttr":i.push({setDependency:r[a].xsAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"componentAttrs":null===n[a].componentAttr?i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}}):i.push({setDependency:r[a].componentAttr,desiredValue:e.displacement[a],variableIndex:0});break;default:s=!0}else t.basedOnHead?i.push({setDependency:r[a].headX,desiredValue:n[a].tailX.add(e.displacement[a]).simplify()}):i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.displacement)t[Number(n)+1]=e.displacement[n].tree;t.length=a[0]+1,i.push({setDependency:"displacementShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.displacement&&i.push({setDependency:"displacementShadow",desiredValue:e.displacement[0]});return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.head={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"headX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["headX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnHead"],returnArraySizeDependencies:()=>({nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"}}),returnArraySize:({dependencyValues:e})=>[e.nDimHead],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["x"+e]}},t.basedOnHead||(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnHead?null!==t[a].headAttr?r[a]=t[a].headAttr.stateValues["x"+n]:null!==e.headShadow&&(r[a]=e.headShadow.get_component(Number(a))):r[a]=t[a].tailX.add(t[a].x).simplify()}return{setValue:{head:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.head)t.basedOnHead?n[a].headAttr&&null!==n[a].headAttr?i.push({setDependency:r[a].headAttr,desiredValue:e.head[a],variableIndex:0}):null!==t.headShadow&&(s=!0):i.push({setDependency:r[a].x,desiredValue:e.head[a].subtract(n[a].tailX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.head)t[Number(n)+1]=e.head[n].tree;t.length=a[0]+1,i.push({setDependency:"headShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.head&&i.push({setDependency:"headShadow",desiredValue:e.head[0]});return{success:!0,instructions:i}}},e.tail={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"tailX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["tailX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"tail2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnTail","basedOnHead","basedOnDisplacement"],returnArraySizeDependencies:()=>({nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),returnArraySize:({dependencyValues:e})=>[e.nDimTail],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["x"+e]}},t.basedOnTail||t.basedOnHead&&t.basedOnDisplacement&&(n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].tailAttr?r[i]=t[i].tailAttr.stateValues["x"+n]:null!==e.tailShadow?r[i]=e.tailShadow.get_component(Number(i)):e.basedOnHead&&e.basedOnDisplacement?r[i]=t[i].headX.subtract(t[i].x).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={tail:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={tail:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.tail)n[a].tailAttr&&null!==n[a].tailAttr?i.push({setDependency:r[a].tailAttr,desiredValue:e.tail[a],variableIndex:0}):null!==t.tailShadow?s=!0:t.basedOnHead&&t.basedOnDisplacement?i.push({setDependency:r[a].x,desiredValue:n[a].headX.subtract(e.tail[a]).simplify()}):i.push({setEssentialValue:"tail",value:{[a]:convertValueToMathExpression(e.tail[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.tail)t[Number(n)+1]=e.tail[n].tree;t.length=a[0]+1,i.push({setDependency:"tailShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.tail&&i.push({setDependency:"tailShadow",desiredValue:e.tail[0]});return{success:!0,instructions:i}}},e.magnitude={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},displacement:{dependencyType:"stateVariable",variableName:"displacement"}}),definition({dependencyValues:e}){let t=0,n=!0;for(let r=0;re/i));let s=e.magnitude.evaluate_to_constant();if(!Number.isFinite(s)||s<0)return{success:!1};let o=[];for(let e=0;e({head:{dependencyType:"stateVariable",variableName:"head"},tail:{dependencyType:"stateVariable",variableName:"tail"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t,n;if(1===e.nDimensions)e.head[0].evaluate_to_constant(),n=e.tail[0].evaluate_to_constant(),Number.isFinite(n)||(n=NaN);else{t=[],n=[];for(let r=0;r({displacement:{dependencyType:"stateVariable",variableName:"displacement"},displayWithAngleBrackets:{dependencyType:"stateVariable",variableName:"displayWithAngleBrackets"}}),definition({dependencyValues:e}){let t=[];for(let n of e.displacement)n?t.push(n.tree):t.push("_");if(t.length>1){t=[e.displayWithAngleBrackets?"altvector":"vector",...t]}else t=1===t.length?t[0]:"_";return{setValue:{displacementCoords:me$3.fromAst(t)}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=e.displacementCoords.tree;return t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.slice(1).map((e=>me$3.fromAst(e))):[e.displacementCoords],{success:!0,instructions:[{setDependency:"displacement",desiredValue:t}]}}},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({displacementCoords:{dependencyType:"stateVariable",variableName:"displacementCoords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.displacementCoords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0]?.[0],n=e.numericalEndpoints[0]?.[1],r=e.numericalEndpoints[1]?.[0],a=e.numericalEndpoints[1]?.[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}static adapters=[{stateVariable:"displacementCoords",componentType:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveVector({tailcoords:e,headcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){if(void 0!==e){if(void 0!==t){if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.tailDraggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.headDraggable)return await this.coreFunctions.resolveAction({actionId:i});let s=[];if(void 0!==e){if(await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let n;if(void 0===t){let t=await this.stateValues.numericalEndpoints;n=e.map(((e,n)=>t[1][n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"tail",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnHead){let t=await this.stateValues.numericalEndpoints,n=e.map(((e,n)=>t[1][n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnHead)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"head",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=(await this.stateValues.numericalEndpoints)[0]);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let e=await this.stateValues.numericalEndpoints,n=t.map(((t,n)=>t-e[0][n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{head:t,tail:e}}})}async vectorClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnVector({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Angle extends GraphicalComponent{static componentType="angle";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.radius={createComponentOfType:"math",createStateVariable:"radius",defaultValue:me$3.fromAst(1),public:!0},e.chooseReflexAngle={createComponentOfType:"text",createStateVariable:"chooseReflexAngle",defaultValue:"never",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["never","allowed","always"]},e.inDegrees={createComponentOfType:"boolean",createStateVariable:"inDegrees",defaultValue:!1,public:!0,forRenderer:!0},e.radians={createComponentOfType:"math"},e.degrees={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.betweenLines={createComponentOfType:"_lineListComponent"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.emphasizeRightAngle={createComponentOfType:"boolean",createStateVariable:"emphasizeRightAngle",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{radians:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({betweenLines:{dependencyType:"attributeComponent",attributeName:"betweenLines"}}),definition({dependencyValues:e}){let t=null;return null!==e.betweenLines&&(t=e.betweenLines.componentName),{setValue:{betweenLinesName:t}}}},e.nPointsSpecified={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:({dependencyValues:e})=>null!==e.through?{setValue:{nPointsSpecified:e.through.stateValues.nPoints}}:{setValue:{nPointsSpecified:0}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],stateVariablesDeterminingDependencies:["betweenLinesName"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3,2],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArrayDependenciesByKey({stateValues:e}){let t={nPointsSpecified:{dependencyType:"stateVariable",variableName:"nPointsSpecified"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["points"]},radiansAttr:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degreesAttr:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]}};return null!==e.betweenLinesName&&(t.lineChildren={dependencyType:"child",parentName:e.betweenLinesName,childGroups:["lines"],variableNames:["points","nDimensions","coeff0","coeffvar1","coeffvar2","nearestPoint"]}),{globalDependencies:t}},arrayDefinitionByKey({globalDependencyValues:e}){if(e.lineChildren){if(e.lineChildren.length>2){console.warn(`Cannot define an angle between ${e.lineChildren.length} line(s)`);let t={};for(let e=0;e<3;e++)for(let n=0;n<2;n++)t[e+","+n]=me$3.fromAst("_");return{setValue:{points:t}}}if(1===e.lineChildren.length){let t=e.lineChildren[0];if(2!==t.stateValues.nDimensions){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let n=t.stateValues.nearestPoint({variables:{x1:me$3.fromAst(0),x2:me$3.fromAst(0)}}),r=t.stateValues.points[0][0].evaluate_to_constant(),a=t.stateValues.points[0][1].evaluate_to_constant(),i=t.stateValues.points[1][0].evaluate_to_constant(),s=t.stateValues.points[1][1].evaluate_to_constant(),o=Math.atan2(s-a,i-r),l={"0,0":me$3.fromAst(n.x1+Math.cos(o)),"0,1":me$3.fromAst(n.x2+Math.sin(o)),"1,0":me$3.fromAst(n.x1),"1,1":me$3.fromAst(n.x2)},u=null;if(e.radiansAttr){if(u=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(u)){let e={};return e["2,0"]=me$3.fromAst("_"),e["2,1"]=me$3.fromAst("_"),{setValue:{points:e}}}}else if(e.degreesAttr){let t=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(t))return l["2,0"]=me$3.fromAst("_"),l["2,1"]=me$3.fromAst("_"),{setValue:{points:l}};u=t/180*Math.PI}else u=Math.PI/2;let c=o+u;return l["2,0"]=me$3.fromAst(n.x1+Math.cos(c)),l["2,1"]=me$3.fromAst(n.x2+Math.sin(c)),{setValue:{points:l}}}{let t=e.lineChildren[0],n=e.lineChildren[1],r=calculateLineIntersection(t,n);if(void 0===r){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let a=r,i=t.stateValues.points[0][0].evaluate_to_constant(),s=t.stateValues.points[0][1].evaluate_to_constant(),o=t.stateValues.points[1][0].evaluate_to_constant(),l=t.stateValues.points[1][1].evaluate_to_constant(),u=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];i=n.stateValues.points[0][0].evaluate_to_constant(),s=n.stateValues.points[0][1].evaluate_to_constant(),o=n.stateValues.points[1][0].evaluate_to_constant(),l=n.stateValues.points[1][1].evaluate_to_constant();let c=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];return{setValue:{points:{"0,0":u[0],"0,1":u[1],"1,0":a[0],"1,1":a[1],"2,0":c[0],"2,1":c[1]}}}}}let t,n=e.nPointsSpecified;t=e.throughAttr?e.throughAttr.stateValues.points:[];let r={};for(let[e,n]of t.entries())r[e+",0"]=n[0],r[e+",1"]=n[1];if(0===n&&(r["0,0"]=me$3.fromAst(1),r["0,1"]=me$3.fromAst(0)),n<2&&(r["1,0"]=me$3.fromAst(0),r["1,1"]=me$3.fromAst(0)),n<3){let t=null;if(e.radiansAttr){if(t=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(t))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}}}else if(e.degreesAttr){let n=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(n))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}};t=n/180*Math.PI}else t=Math.PI/2;let n=r["0,0"].evaluate_to_constant(),a=r["0,1"].evaluate_to_constant(),i=r["1,0"].evaluate_to_constant(),s=r["1,1"].evaluate_to_constant(),o=Math.atan2(a-s,n-i)+t;r["2,0"]=me$3.fromAst(i+Math.cos(o)),r["2,1"]=me$3.fromAst(s+Math.sin(o))}return{setValue:{points:r}}}},e.radians={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},additionalStateVariablesDefined:[{variableName:"swapPointOrder",forRenderer:!0}],returnDependencies:()=>({radians:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degrees:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]},points:{dependencyType:"stateVariable",variableName:"points"},chooseReflexAngle:{dependencyType:"stateVariable",variableName:"chooseReflexAngle"}}),definition({dependencyValues:e}){let t=!1;if(null!==e.radians)return{setValue:{radians:e.radians.stateValues.value.simplify(),swapPointOrder:t}};if(null!==e.degrees)return{setValue:{radians:e.degrees.stateValues.value.divide(me$3.fromAst(180)).simplify().multiply(me$3.fromAst("pi")).simplify(),swapPointOrder:t}};let n,r=[],a=!1;for(let t=0;t<3;t++)r.push([e.points[t][0].evaluate_to_constant(),e.points[t][1].evaluate_to_constant()]),null!==r[t][0]&&null!==r[t][1]||(a=!0);return a?{setValue:{radians:me$3.fromAst("_"),swapPointOrder:t}}:(n=Math.atan2(r[2][1]-r[1][1],r[2][0]-r[1][0])-Math.atan2(r[0][1]-r[1][1],r[0][0]-r[1][0]),n<0&&(n+=2*Math.PI),n>Math.PI?"never"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0):"always"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0),{setValue:{radians:me$3.fromAst(n),swapPointOrder:t}})}},e.value={isAlias:!0,targetVariableName:"radians"},e.angle={isAlias:!0,targetVariableName:"radians"},e.degrees={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({radians:{dependencyType:"stateVariable",variableName:"radians"}}),definition({dependencyValues:e}){let t;if("_"===e.radians.tree||Number.isNaN(e.radians.tree))t=e.radians;else{let n=e.radians.evaluate_to_constant();t=Number.isFinite(n)?me$3.fromAst(180*n/Math.PI):e.radians.multiply(me$3.fromAst(["/",180,"pi"])).simplify()}return{setValue:{degrees:t}}}},e.latexForRenderer={forRenderer:!0,returnDependencies:()=>({inDegrees:{dependencyType:"stateVariable",variableName:"inDegrees"},radians:{dependencyType:"stateVariable",variableName:"radians"},degrees:{dependencyType:"stateVariable",variableName:"degrees"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=roundForDisplay({value:e.inDegrees?e.degrees:e.radians,dependencyValues:e,usedDefault:t}).toLatex(n);return e.inDegrees&&(r+="^\\circ"),{setValue:{latexForRenderer:r}}}},e.numericalPoints={isArray:!0,entryPrefixes:["numericalPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].point,a=[];for(let e=0;e<2;e++){let n=t[e].evaluate_to_constant();Number.isFinite(n)||(n=NaN),a.push(n)}n[r]=a}return{setValue:{numericalPoints:n}}}},e.numericalRadius={forRenderer:!0,returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition({dependencyValues:e}){let t=e.radius.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{numericalRadius:t}}}},e}static adapters=["radians"]}function calculateLineIntersection(e,t){if(2!==e.stateValues.nDimensions||2!==t.stateValues.nDimensions)return void console.log("Calculating angle between two lines implemented only in 2D");let n=e.stateValues.coeffvar1.evaluate_to_constant(),r=e.stateValues.coeffvar2.evaluate_to_constant(),a=e.stateValues.coeff0.evaluate_to_constant(),i=t.stateValues.coeffvar1.evaluate_to_constant(),s=t.stateValues.coeffvar2.evaluate_to_constant(),o=t.stateValues.coeff0.evaluate_to_constant();if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(i)&&Number.isFinite(s)&&Number.isFinite(o)))return void console.log("Calculating angle between two lines implemented only for constant coefficients");let l=n*s-i*r;if(Math.abs(l)<1e-14)return Math.abs(o*n-a*i)>1e-14?void console.log("Cannot calculate angle between two parallel lines"):0===n&&0===r&&0===a||0===i&&0===s&&0===o?void 0:0!==r?[me$3.fromAst(0),me$3.fromAst(-a/r)]:[me$3.fromAst(-a/n),me$3.fromAst(0)];let u=(o*r-a*s)/l,c=(a*i-o*n)/l;return[me$3.fromAst(u),me$3.fromAst(c)]}var defaults$5={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify},util$1={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys};const DEFAULTS=defaults$5,isFunction$2=util$1.isFunction,isBoolean$1=util$1.isBoolean,isObject$2=util$1.isObject,isArray$3=util$1.isArray,isRegex=util$1.isRegex,assign$1=util$1.assign,keys$1=util$1.keys;function serialize(e){return null==e?e:isRegex(e)?e.toString():e.toJSON?e.toJSON():e}function stringifyDeterministic(e,t){t=t||assign$1({},DEFAULTS),isFunction$2(t)&&(t={compare:t});const n=t.space||DEFAULTS.space,r=isBoolean$1(t.cycles)?t.cycles:DEFAULTS.cycles,a=t.replacer||DEFAULTS.replacer,i=t.stringify||DEFAULTS.stringify,s=t.compare&&function(e){return function(t){return function(n,r){const a={key:n,value:t[n]},i={key:r,value:t[r]};return e(a,i)}}}(t.compare);r||i(e);const o=[];return function e(t,l,u,c){const p=n?"\n"+new Array(c+1).join(n):"",d=n?": ":":";if(u=serialize(u),void 0!==(u=a.call(t,l,u))){if(!isObject$2(u)||null===u)return i(u);if(isArray$3(u)){const t=[];for(let r=0;r0)for(let e of t.children)"object"!=typeof e?e.trim()&&(p=!0):i(e,"when")||(i(e,"math")||i(e,"number")||i(e,"mathList")||i(e,"numberList")?(s=!0,p=!0):i(e,"text")||i(e,"textList")?(o=!0,p=!0):i(e,"boolean")?(l=!0,p=!0):i(e,"booleanList")?l=!0:n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})&&!e.attributes?.createComponentOfType?.primitive?p=!0:i(e,"orbitalDiagram")||(p=!0));else p=!0;else i(t,"mathInput")?(h.push(!1),s=!0,c=!0):i(t,"textInput")?(h.push(!1),o=!0,c=!0):i(t,"_input")||i(t,"considerAsResponses")?(h.push(!1),c=!0):(n.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&t.attributes?.createComponentOfType?.primitive,h.push(!0),p=!0);if(c&&(d=!0),u>0){if(e=e.filter((e=>"string"!=typeof e||""!==e.trim())),e.length!==u)return{success:!1};{let n={componentType:"choiceInput",children:e};return t.shuffleOrder&&(n.attributes={shuffleOrder:{primitive:!0}}),{success:!0,newChildren:[n]}}}if(t.handGraded&&!m&&(p=!0),!p&&!d){for(let t of e)if(i(t,"award")&&t.children?.length>0&&r(t.children)){d=!0;break}if(!d)for(let t of e)i(t,"award")&&t.children?.length>0&&a(t.children)}let f=[],y=[],g=[];if(0===h.filter((e=>!e)).length)f=e;else{if(!h[0]){let t=h.indexOf(!0);-1!==t&&(y=e.slice(0,t),e=e.slice(t),h=h.slice(t))}let t=h.indexOf(!1);-1===t?f=e:(f=e.slice(0,t),g=e.slice(t))}for(;"string"==typeof f[0]&&""===f[0].trim();)f=f.slice(1);let b,v,N=f.length;for(;"string"==typeof f[N-1]&&""===f[N-1].trim();)f=f.slice(0,N-1),N=f.length;if(t.type?(v=t.type,["math","text","boolean"].includes(v)||(console.warn(`Invalid type ${v}`),v="math")):v=s?"math":o?"text":l?"boolean":"math",0===f.length)b=[...y,...g];else{let e;e=f.length>1||n.isInheritedComponentType({inheritedComponentType:f[0].componentType,baseComponentType:"_composite"})&&!f[0].props?.componentType?[{componentType:v,children:f}]:f,b=[...y,{componentType:"award",children:e},...g]}if(p&&!c){b=[{componentType:v+"Input"},...b]}return{success:!0,newChildren:b}}}),e}static returnChildGroups(){return[{group:"awards",componentTypes:["award"]},{group:"inputs",componentTypes:["_input"]},{group:"responses",componentTypes:["considerAsResponses"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"disabled",newName:"disabledOriginal"}),e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessPreliminary:{dependencyType:"stateVariable",variableName:"showCorrectnessPreliminary"},showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},handGraded:{dependencyType:"stateVariable",variableName:"handGraded"}}),definition({dependencyValues:e,usedDefault:t}){let n;return n=t.showCorrectnessPreliminary?!1!==e.showCorrectnessFlag&&!e.handGraded:e.showCorrectnessPreliminary,{setValue:{showCorrectness:n}}}},e.haveAwardThatRequiresInput={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["requireInputInAnswer"]}}),definition:({dependencyValues:e})=>({setValue:{haveAwardThatRequiresInput:e.awardChildren.some((e=>e.stateValues.requireInputInAnswer))}})},e.allInputChildrenIncludingSugared={returnDependencies:()=>({allInputChildrenIncludingSugared:{dependencyType:"child",childGroups:["inputs"]}}),definition:({dependencyValues:e})=>({setValue:{allInputChildrenIncludingSugared:e.allInputChildrenIncludingSugared}})},e.inputChildren={stateVariablesDeterminingDependencies:["allInputChildrenIncludingSugared"],additionalStateVariablesDefined:["inputChildIndices","skippedFirstInput"],forRenderer:!0,returnDependencies({stateValues:e}){let t={allInputChildrenIncludingSugared:{dependencyType:"stateVariable",variableName:"allInputChildrenIncludingSugared"},haveAwardThatRequiresInput:{dependencyType:"stateVariable",variableName:"haveAwardThatRequiresInput"},handGraded:{dependencyType:"stateVariable",variableName:"handGraded"}};return e.allInputChildrenIncludingSugared.length>0&&(t.firstInputFromSugar={dependencyType:"doenetAttribute",componentName:e.allInputChildrenIncludingSugared[0].componentName,attributeName:"createdFromSugar"}),t},definition({dependencyValues:e}){let t=[...e.allInputChildrenIncludingSugared],n=[...e.allInputChildrenIncludingSugared.keys()],r=!1;return"choiceInput"!==t[0]?.componentType&&(!(e.haveAwardThatRequiresInput||e.handGraded)||e.allInputChildrenIncludingSugared.length>1)&&e.firstInputFromSugar&&(r=!0,t=t.slice(1),n=n.slice(1)),{setValue:{inputChildren:t,inputChildIndices:n,skippedFirstInput:r}}}},e.inputChildrenWithValues={stateVariablesDeterminingDependencies:["inputChildIndices"],forRenderer:!0,returnDependencies:({stateValues:e})=>({inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["valueToRecordOnSubmit","valueRecordedAtSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0}}),definition:function({dependencyValues:e}){return{setValue:{inputChildrenWithValues:e.inputChildren}}}},e.inputChildWithValues={returnDependencies:()=>({inputChildrenWithValues:{dependencyType:"stateVariable",variableName:"inputChildrenWithValues"}}),definition({dependencyValues:e}){let t=null;return 1===e.inputChildrenWithValues.length&&(t=e.inputChildrenWithValues[0]),{setValue:{inputChildWithValues:t}}}},e.awardInputResponseChildren={returnDependencies:()=>({awardInputResponseChildren:{dependencyType:"child",childGroups:["awards","inputs","responses"]},skippedFirstInput:{dependencyType:"stateVariable",variableName:"skippedFirstInput"}}),definition({dependencyValues:e}){let t=[...e.awardInputResponseChildren];return e.skippedFirstInput&&(t=t.slice(1)),{setValue:{awardInputResponseChildren:t}}}},e.nResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","nValues"],variablesOptional:!0,recurseToMatchedChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?n["childNValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"nValues",variablesOptional:!0}:n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenWithNValues"};return n},definition({dependencyValues:e,componentInfoObjects:t}){let n=0;for(let[r,a]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"award"}))for(let a of e["child"+r])a.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_composite"})&&(void 0===a.stateValues.nValues?n+=1:n+=a.stateValues.nValues);else if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"_input"})){let t=e["childNValues"+r];n+=void 0===t?1:t}else for(let t of e["child"+r])void 0===t.stateValues.nValues?n+=1:n+=t.stateValues.nValues;return{setValue:{nResponses:n}}}},e.currentResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["currentResponse"],stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnArraySizeDependencies:()=>({nResponses:{dependencyType:"stateVariable",variableName:"nResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nResponses],returnArrayDependenciesByKey({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","value","values","formula","componentType"],variablesOptional:!0,recurseToMatchedChildren:!0,includeAttributeChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?(n["childValue"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"value",variablesOptional:!0},n["childValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"values",variablesOptional:!0},n["childComponentType"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"componentType",variablesOptional:!0}):n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenAsResponses"};return{globalDependencies:n}},arrayDefinitionByKey({globalDependencyValues:e,componentInfoObjects:t}){let n=[],r=[],a=[];for(let[n,r]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"award"}))for(let r of e["child"+n])r.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&a.push(r);else if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"_input"})){let t={componentType:r,stateValues:{value:e["childValue"+n],values:e["childValues"+n],componentType:e["childComponentType"+n]}};a.push(t)}else a.push(...e["child"+n]);for(let e of a){let t=e.stateValues.componentType;t||(t=e.componentType),"mathList"===t?t="math":"numberList"===t?t="number":"textList"===t?t="text":"booleanList"===t&&(t="boolean"),Array.isArray(e.stateValues.values)?(n.push(...e.stateValues.values),r.push(...Array(e.stateValues.values.length).fill(t))):void 0!==e.stateValues.value?(n.push(e.stateValues.value),r.push(t)):e.stateValues.formula instanceof me$3.class?(n.push(e.stateValues.formula),r.push("math")):(n.push(""),r.push("text"))}return{setValue:{currentResponses:n},setCreateComponentOfType:{currentResponses:r}}}},e.currentResponse={isAlias:!0,targetVariableName:"currentResponse1"},e.nSubmittedResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nSubmittedResponses:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmittedResponses",value:e.nSubmittedResponses}]})},e.submittedResponsesComponentType={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{submittedResponsesComponentType:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return e.submittedResponsesComponentType?{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[...e.submittedResponsesComponentType]}]}:{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[]}]}}},e.submittedResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["submittedResponse"],defaultValueByArrayKey:()=>"_",hasEssential:!0,inverseShadowToSetEntireArray:!0,doNotCombineInverseArrayInstructions:!0,returnArraySizeDependencies:()=>({nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nSubmittedResponses],returnArrayDependenciesByKey:()=>({globalDependencies:{submittedResponsesComponentType:{dependencyType:"stateVariable",variableName:"submittedResponsesComponentType"},nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[];e.submittedResponsesComponentType&&t.push(...e.submittedResponsesComponentType.slice(0,e.nSubmittedResponses));let n={};for(let r=0;r({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.delegateCheckWork={additionalStateVariablesDefined:["delegateCheckWorkToInput","delegateCheckWorkToAncestor"],forRenderer:!0,returnDependencies:()=>({inputChildren:{dependencyType:"stateVariable",variableName:"inputChildren"},forceFullCheckworkButton:{dependencyType:"stateVariable",variableName:"forceFullCheckworkButton"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition:function({dependencyValues:e}){let t=!1,n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor?.stateValues.suppressAnswerSubmitButtons?t=r=!0:1!==e.inputChildren.length||e.forceFullCheckworkButton||(n=r=!0),{setValue:{delegateCheckWork:r,delegateCheckWorkToAncestor:t,delegateCheckWorkToInput:n}}}},e.creditAchievedIfSubmit={additionalStateVariablesDefined:["awardsUsedIfSubmit","awardChildren","inputUsedIfSubmit"],stateVariablesDeterminingDependencies:["inputChildIndices"],returnDependencies:({stateValues:e})=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["credit","creditAchievedIfSubmit","fractionSatisfiedIfSubmit"]},inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["creditAchievedIfSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0},nAwardsCredited:{dependencyType:"stateVariable",variableName:"nAwardsCredited"}}),definition:function({dependencyValues:e}){let t=0,n=e.nAwardsCredited,r=Array(n).fill(null),a=null;if(0===e.awardChildren.length){if(1===e.inputChildren.length){let n=e.inputChildren[0].stateValues.creditAchievedIfSubmit;n>=0&&(t=n,a=e.inputChildren[0].componentName)}}else{let a=Array(n).fill(null),i=0;for(let t of e.awardChildren){let e=t.stateValues.creditAchievedIfSubmit;if((e>i||null===r[n-1])&&t.stateValues.fractionSatisfiedIfSubmit>0)if(null===r[0])r[0]=t.componentName,a[0]=e,i=Math.min(...a);else for(let[s,o]of a.entries())if(e>o||null===o){r.splice(s,0,t.componentName),r=r.slice(0,n),a.splice(s,0,e),a=a.slice(0,n),i=Math.min(...a);break}}t=Math.min(1,a.reduce(((e,t)=>e+t),0))}return{setValue:{creditAchievedIfSubmit:t,awardsUsedIfSubmit:r,awardChildren:e.awardChildren,inputUsedIfSubmit:a}}}},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}}},e.responseHasBeenSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{responseHasBeenSubmitted:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"responseHasBeenSubmitted",value:e.responseHasBeenSubmitted}]}}},e.autoSubmit={returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{autoSubmit:Boolean(e.autoSubmit)}})},e.creditAchievedDependencies={shadowVariable:!0,stateVariablesDeterminingDependencies:["autoSubmit"],returnDependencies:({stateValues:e})=>({currentCreditAchievedDependencies:{dependencyType:"recursiveDependencyValues",variableNames:["creditAchievedIfSubmit"],includeImmediateValueWithValue:!e.autoSubmit,includeRawValueWithImmediateValue:!e.autoSubmit,includeOnlyEssentialValues:!0}}),definition({dependencyValues:e}){let t=lib(e.currentCreditAchievedDependencies,{replacer:serializedComponentsReplacer});return{setValue:{creditAchievedDependencies:Base64.stringify(sha1(t))}}},markStale:()=>({answerCreditPotentiallyChanged:!0})},e.creditAchievedDependenciesAtSubmit={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchievedDependenciesAtSubmit:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchievedDependenciesAtSubmit",value:e.creditAchievedDependenciesAtSubmit}]}}},e.justSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({currentCreditAchievedDependencies:{dependencyType:"stateVariable",variableName:"creditAchievedDependencies"},creditAchievedDependenciesAtSubmit:{dependencyType:"stateVariable",variableName:"creditAchievedDependenciesAtSubmit"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"},hasBeenCorrect:{dependencyType:"stateVariable",variableName:"hasBeenCorrect"}}),definition:function({dependencyValues:e,justUpdatedForNewComponent:t,componentName:n}){if(e.disableAfterCorrect&&e.hasBeenCorrect)return{setValue:{justSubmitted:!0}};return e.creditAchievedDependenciesAtSubmit!==e.currentCreditAchievedDependencies&&!t?{setValue:{justSubmitted:!1},setEssentialValue:{justSubmitted:!1}}:{useEssentialOrDefaultValue:{justSubmitted:!0}}},inverseDefinition:({desiredStateVariableValues:e,componentName:t})=>({success:!0,instructions:[{setEssentialValue:"justSubmitted",value:e.justSubmitted}]})},e.allFeedbacks={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["feedbacks"]},feedbackComponents:{dependencyType:"descendant",componentTypes:["_input"],variableNames:["feedbacks"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.awardChildren)t.push(...n.stateValues.feedbacks);for(let n of e.feedbackComponents)Array.isArray(n.stateValues.feedbacks)&&t.push(...n.stateValues.feedbacks);return{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({}),definition:()=>({useEssentialOrDefaultValue:{nSubmissions:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmissions",value:e.nSubmissions}]})},e.numberOfAttemptsLeft={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({nSubmissions:{dependencyType:"stateVariable",variableName:"nSubmissions"},maximumNumberOfAttempts:{dependencyType:"stateVariable",variableName:"maximumNumberOfAttempts"}}),definition:({dependencyValues:e})=>({setValue:{numberOfAttemptsLeft:e.maximumNumberOfAttempts-e.nSubmissions}})},e.hasBeenCorrect={defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({creditAchieved:{dependencyType:"stateVariable",variableName:"creditAchieved"}}),definition:({dependencyValues:e})=>1===e.creditAchieved?{setValue:{hasBeenCorrect:!0},setEssentialValue:{hasBeenCorrect:!0}}:{useEssentialOrDefaultValue:{hasBeenCorrect:!0}}},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,stateVariablesDeterminingDependencies:["disableAfterCorrect"],returnDependencies({stateValues:e}){let t={disabledOriginal:{dependencyType:"stateVariable",variableName:"disabledOriginal"},numberOfAttemptsLeft:{dependencyType:"stateVariable",variableName:"numberOfAttemptsLeft"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"}};return e.disableAfterCorrect&&(t.hasBeenCorrect={dependencyType:"stateVariable",variableName:"hasBeenCorrect"}),t},definition:({dependencyValues:e})=>({setValue:{disabled:e.disabledOriginal||e.numberOfAttemptsLeft<1||e.disableAfterCorrect&&e.hasBeenCorrect}})},e.inItemNumber={returnDependencies:()=>({documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["itemNumberByAnswerName"]}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{inItemNumber:e.documentAncestor.stateValues.itemNumberByAnswerName[t]}})},e}async submitAnswer({actionId:e}){let t=await this.stateValues.numberOfAttemptsLeft;if(t<1)return void console.warn(`Cannot submit answer for ${this.componentName} as number of attempts left is ${t}`);let n=await this.stateValues.creditAchievedIfSubmit;await this.stateValues.handGraded&&(n=0);let r=await this.stateValues.awardsUsedIfSubmit,a=await this.stateValues.inputUsedIfSubmit,i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchieved",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"responseHasBeenSubmitted",value:!0}],s=await this.stateValues.inputChildrenWithValues;if(1===s.length){let e=s[0];a===e.componentName&&"valueToRecordOnSubmit"in e.stateValues&&"valueRecordedAtSubmit"in e.stateValues&&i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"valueRecordedAtSubmit",value:e.stateValues.valueToRecordOnSubmit})}let o=await this.stateValues.currentResponses;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponses",value:o}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponsesComponentType",value:this.state.currentResponses.shadowingInstructions.createComponentOfType}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"justSubmitted",value:!0}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchievedDependenciesAtSubmit",value:await this.stateValues.creditAchievedDependencies}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"nSubmissions",value:await this.stateValues.nSubmissions+1});for(let e of await this.stateValues.awardChildren){let t=r.includes(e.componentName);i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"awarded",value:t}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"creditAchieved",value:e.stateValues.creditAchievedIfSubmit}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"fractionSatisfied",value:e.stateValues.fractionSatisfiedIfSubmit})}let l=[];for(let e of o)if(e.toString)try{l.push(e.toString())}catch(e){l.push("_")}else l.push(e);return i.push({updateType:"recordItemSubmission",itemNumber:await this.stateValues.inItemNumber,submittedComponent:this.componentName,response:o,responseText:l,creditAchieved:n}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{response:o,responseText:l,creditAchieved:n}},suppressToast:await this.stateValues.suppressToast}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}class Award extends BaseComponent{static componentType="award";static rendererType=void 0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static variableForPlainMacro="awarded";static variableForPlainCopy="awarded";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:1,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0,fallBackToParentStateVariable:"symbolicEquality"},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"expandOnCompare"},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numberspreserveorder"],public:!0,fallBackToParentStateVariable:"simplifyOnCompare"},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"unorderedCompare"},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchByExactPositions"},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0,fallBackToParentStateVariable:"allowedErrorInNumbers"},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0,fallBackToParentStateVariable:"includeErrorInNumberExponents"},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0,fallBackToParentStateVariable:"allowedErrorIsAbsolute"},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0,fallBackToParentStateVariable:"nSignErrorsMatched"},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0,fallBackToParentStateVariable:"nPeriodicSetMatchesRequired"},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0,fallBackToParentStateVariable:"caseInsensitiveMatch"},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchBlanks"},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.sourcesAreResponses={createPrimitiveOfType:"string"},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e}static preprocessSerializedChildren({serializedChildren:e,attributes:t,componentName:n}){if(t.sourcesAreResponses){let r,a=t.sourcesAreResponses.primitive.split(/\s+/).filter((e=>e));r=t.newNamespace?.primitive?n+"/":getNamespaceFromName(n);for(let t of a){let n;if("/"===t[0])n=t;else if("../"===t.slice(0,3)){let e=getNamespaceFromName(r.slice(0,r.length-1)),a=t.slice(3);for(;"../"===a.slice(0,3);){if("/"===e){n=null;break}e=getNamespaceFromName(e.slice(0,e.length-1)),a=a.slice(3)}null!==n&&(n=e+a)}else n=r+t;addResponsesToDescendantsWithTarget(e,t,n)}}}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,parentAttributes:t,componentInfoObjects:n}){for(;"string"==typeof e[0]&&""===e[0].trim();)e=e.slice(1);let r=e.length;for(;"string"==typeof e[r-1]&&""===e[r-1].trim();)r=(e=e.slice(0,r-1)).length;if(1===e.length&&"object"==typeof e[0])return{success:!1};let a,i=n.componentIsSpecifiedType,s=!1,o=!1,l=!1;for(let t of e)"object"==typeof t&&(i(t,"math")||i(t,"number")||i(t,"mathList")||i(t,"numberList")?s=!0:i(t,"text")||i(t,"textList")?o=!0:(i(t,"boolean")||i(t,"booleanList"))&&(l=!0));return t.type?(a=t.type,["math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}`),a="math")):a=s?"math":o?"text":l?"boolean":"math",{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"whens",componentTypes:["when"]},{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]},{group:"textLists",componentTypes:["textList"]},{group:"booleanLists",componentTypes:["booleanList"]},{group:"otherComparableTypes",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["requireInputInAnswer"],returnDependencies:()=>({whenChild:{dependencyType:"child",childGroups:["whens"]},typeChildren:{dependencyType:"child",childGroups:["maths","numbers","texts","booleans","mathLists","numberLists","textLists","booleanLists","otherComparableTypes"]}}),definition:function({dependencyValues:e}){let t=null,n=!1;return 0==e.whenChild.length&&e.typeChildren.length>0&&(n=!0,t=me$3.fromAst(["=","comp1","comp2"])),{setValue:{parsedExpression:t,requireInputInAnswer:n}}}},e.creditAchievedIfSubmit={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"fractionSatisfiedIfSubmit",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({credit:{dependencyType:"stateVariable",variableName:"credit"},whenChild:{dependencyType:"child",childGroups:["whens"],variableNames:["fractionSatisfied"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value","unordered"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},textChild:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},booleanChild:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]},mathListChild:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths","unordered"]},numberListChild:{dependencyType:"child",childGroups:["numberLists"],variableNames:["numbers","unordered"]},textListChild:{dependencyType:"child",childGroups:["textLists"],variableNames:["texts","unordered"]},booleanListChild:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["booleans","unordered"]},otherComparableChild:{dependencyType:"child",childGroups:["otherComparableTypes"],variableNames:["value"]},answerInput:{dependencyType:"parentStateVariable",variableName:"inputChildWithValues"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;if(e.whenChild.length>0)n=e.whenChild[0].stateValues.fractionSatisfied;else{if(!e.answerInput||!e.parsedExpression)return{setValue:{creditAchievedIfSubmit:0,fractionSatisfiedIfSubmit:0}};n=evaluateLogicDirectlyFromChildren({dependencyValues:e,usedDefault:t})}n=Math.max(0,Math.min(1,n));let r=0;return Number.isFinite(e.credit)&&(r=Math.max(0,Math.min(1,e.credit))*n),{setValue:{fractionSatisfiedIfSubmit:n,creditAchievedIfSubmit:r}}}},e.fractionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fractionSatisfied:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"fractionSatisfied",value:e.fractionSatisfied}]}:{success:!1}}},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}:{success:!1}}},e.awarded={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{awarded:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"awarded",value:e.awarded}]}:{success:!1}}},e.allFeedbacks={returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},awarded:{dependencyType:"stateVariable",variableName:"awarded"}}),definition:function({dependencyValues:e}){if(!e.awarded)return{setValue:{allFeedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n0?n.textChildrenByCode.comp2=e.textChild[0]:e.mathChild.length>0?n.mathChildrenByCode.comp2=e.mathChild[0]:e.numberChild.length>0?n.numberChildrenByCode.comp2=e.numberChild[0]:e.booleanChild.length>0?n.booleanChildrenByCode.comp2=e.booleanChild[0]:e.textListChild.length>0?n.textListChildrenByCode.comp2=e.textListChild[0]:e.mathListChild.length>0?n.mathListChildrenByCode.comp2=e.mathListChild[0]:e.numberListChild.length>0?n.numberListChildrenByCode.comp2=e.numberListChild[0]:e.booleanListChild.length>0?n.booleanListChildrenByCode.comp2=e.booleanListChild[0]:e.otherComparableChild.length>0&&(n.otherChildrenByCode.comp2=e.otherComparableChild[0]);let a=e.answerInput.stateValues.immediateValue;void 0===a&&(a=e.answerInput.stateValues.value);let i={stateValues:{value:a}};return"textInput"===e.answerInput.componentType?n.textChildrenByCode.comp1=i:"booleanInput"===e.answerInput.componentType?n.booleanChildrenByCode.comp1=i:n.mathChildrenByCode.comp1=i,evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:r,dependencyValues:n})}function addResponsesToDescendantsWithTarget(e,t,n){for(let r of e){let e=r.props;if(e&&0!==Object.keys(e).length||(e=r.doenetAttributes),e)for(let a in e)if("target"===a.toLowerCase()&&e[a]===t||"targetcomponentname"===a.toLowerCase()&&e[a]===n){r.attributes||(r.attributes={});let e=Object.keys(r.attributes).map((e=>e.toLowerCase())).includes("isresponse");e||(r.attributes.isResponse=!0)}r.children&&addResponsesToDescendantsWithTarget(r.children,t,n)}}class When extends BooleanComponent{static componentType="when";static rendererType=void 0;static stateVariableForAttributeValue="conditionSatisfied";static createAttributesObject(){let e=super.createAttributesObject();e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"};for(let t of["symbolicEquality","expandOnCompare","simplifyOnCompare","unorderedCompare","matchByExactPositions","allowedErrorInNumbers","includeErrorInNumberExponents","allowedErrorIsAbsolute","nSignErrorsMatched","nPeriodicSetMatchesRequired","caseInsensitiveMatch","matchBlanks"])e[t].fallBackToParentStateVariable=t;return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},additionalStateVariablesDefined:[{variableName:"fractionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"conditionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"boolean"}}],returnDependencies:()=>({matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(null===e.parsedExpression)return{setValue:{conditionSatisfied:!1,value:!1,fractionSatisfied:0}};let n=t.unorderedCompare,r=evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e}),a=1===r;return{setValue:{fractionSatisfied:r,conditionSatisfied:a,value:a}}}},e}}class MathInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateRawValue:this.updateRawValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="mathInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.prefillLatex={createComponentOfType:"latex",createStateVariable:"prefillLatex",defaultValue:"",public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e.hideNaN={createComponentOfType:"boolean",createStateVariable:"hideNaN",defaultValue:!0,public:!0},e.removeStrings={createComponentOfType:"textList",createStateVariable:"removeStrings",defaultValue:null},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return 0===e.length?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"},unionFromU:{dependencyType:"stateVariable",variableName:"unionFromU"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return e.mathChild.length>0?{setValue:{value:e.mathChild[0].stateValues.value}}:e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{get defaultValue(){return!t.prefill||t.prefillLatex?e.prefill:calculateMathExpressionFromLatex({latex:e.prefillLatex,unionFromU:e.unionFromU,functionSymbols:e.functionSymbols,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation})}}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.mathChild.length>0?{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.value,variableIndex:0,childIndex:0}]}:t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n,usedDefault:r}){return!t.value||n||r.value?{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}:{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.dontUpdateRawValueInDefinition={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dontUpdateRawValueInDefinition:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dontUpdateRawValueInDefinition",value:e.dontUpdateRawValueInDefinition}]})},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},hideNaN:{dependencyType:"stateVariable",variableName:"hideNaN"},dontUpdateRawValueInDefinition:{dependencyType:"stateVariable",variableName:"dontUpdateRawValueInDefinition"},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"}}),definition({dependencyValues:e,essentialValues:t,justUpdatedForNewComponent:n,usedDefault:r}){if(void 0!==t.rawRendererValue&&(n||deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree)||e.dontUpdateRawValueInDefinition))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t;return t=r.immediateValue&&r.prefill&&!r.prefillLatex?stripLatex(e.prefillLatex):stripLatex(e.valueForDisplay.toLatex({showBlanks:!1})),e.hideNaN&&"NaN"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n,dependencyValues:r,componentName:a}){let i=[];if("string"==typeof e.rawRendererValue){let r=n.rawRendererValue,a=e.rawRendererValue;r!==a&&i.push({setEssentialValue:"rawRendererValue",value:a});let s=await t.unionFromU,o=await t.functionSymbols,l=await t.splitSymbols,u=await t.parseScientificNotation,c=await t.removeStrings,p=calculateMathExpressionFromLatex({latex:r,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c}),d=calculateMathExpressionFromLatex({latex:a,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c});deepCompare(d.tree,p.tree)||i.push({setDependency:"immediateValue",desiredValue:d,treatAsInitialChange:!0})}else if(e.rawRendererValue instanceof me$3.class){i.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let a=await t.unionFromU,s=await t.functionSymbols,o=await t.splitSymbols,l=await t.parseScientificNotation,u=await t.removeStrings,c=calculateMathExpressionFromLatex({latex:n.rawRendererValue,unionFromU:a,functionSymbols:s,splitSymbols:o,parseScientificNotation:l,removeStrings:u});if(!deepCompare(e.rawRendererValue.tree,c.tree)){let t=stripLatex(e.rawRendererValue.toLatex({showBlanks:!1}));r.hideNaN&&"NaN"===t&&(t=""),i.push({setEssentialValue:"rawRendererValue",value:t})}}else e.lastValueForDisplay instanceof me$3.class&&i.push({setEssentialValue:"lastValueForDisplay",value:e.lastValueForDisplay});return{success:!0,instructions:i}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!1},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree?n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"}):n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"lastValueForDisplay",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:e})}}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}function calculateMathExpressionFromLatex({latex:e,unionFromU:t,functionSymbols:n,splitSymbols:r,parseScientificNotation:a,removeStrings:i}){let s;if(i)for(let t of i)["$","%"].includes(t)&&(t="\\"+t),e=e.replaceAll(t,"");e=normalizeLatexString(e,{unionFromU:t});let o=getFromLatex({functionSymbols:n,splitSymbols:r,parseScientificNotation:a});try{s=o(e)}catch(e){s=me$3.fromAst("_")}return s}class Textinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="textInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.size={createComponentOfType:"number",createStateVariable:"size",defaultValue:10,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"text"},e.expanded={createComponentOfType:"boolean",createStateVariable:"expanded",defaultValue:!1,forRenderer:!0,public:!0,fallBackToParentStateVariable:"expanded"},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:120,isAbsolute:!0},forRenderer:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}:{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e}async updateImmediateValue({text:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(!await this.stateValues.disabled){let t=await this.stateValues.immediateValue;if(await this.stateValues.value!==t){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}this.coreFunctions.resolveAction({actionId:e})}}class BooleanInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateBoolean:this.updateBoolean.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="booleanInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"boolean",createStateVariable:"prefill",defaultValue:!1,public:!0},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.asToggleButton={createComponentOfType:"boolean",createStateVariable:"asToggleButton",defaultValue:!1,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"boolean"}})},e}static adapters=["value"];async updateBoolean({boolean:e,actionId:t}){if(!await this.stateValues.disabled){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],r={verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,event:r,actionId:t}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}}class Choiceinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateSelectedIndices:this.updateSelectedIndices.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="choiceInput";static renderChildren=!0;static variableForPlainMacro="values";static variableForPlainCopy="values";static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.selectMultiple={createComponentOfType:"boolean",createStateVariable:"selectMultiple",defaultValue:!1,public:!0,forRenderer:!0,fallBackToParentStateVariable:"selectMultiple"},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.inline={createComponentOfType:"boolean"},e.shuffleOrder={createPrimitiveOfType:"boolean",createStateVariable:"shuffleOrder",defaultValue:!1,public:!0},e.preselectChoice={createComponentOfType:"number",createStateVariable:"preselectChoice",defaultValue:null},e.bindValueTo={createComponentOfType:"text"},e.placeHolder={createComponentOfType:"text",createStateVariable:"placeHolder",defaultValue:"",forRenderer:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabel"},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabelNoCorrectness"},e}static returnChildGroups(){return[{group:"choices",componentTypes:["choice"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.inline={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({inlineAttr:{dependencyType:"attributeComponent",attributeName:"inline",variableNames:["value"]},parentInline:{dependencyType:"parentStateVariable",variableName:"inline"}}),definition:({dependencyValues:e})=>e.inlineAttr?{setValue:{inline:e.inlineAttr.stateValues.value}}:null!==e.parentInline?{setValue:{inline:e.parentInline}}:{useEssentialOrDefaultValue:{inline:{}}}},e.numberChoices={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:({dependencyValues:e})=>({setValue:{numberChoices:e.choiceChildren.length}})},e.choiceOrder={forRenderer:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){let t,n=e.choiceChildren.length;if(e.shuffleOrder){let r=e.variants?.desiredVariant?.indices;if(void 0!==r)if(r.length!==n)console.warn("Ignoring indices specified for choiceInput as number of indices doesn't match number of choice children.");else{if(r=r.map(Number),!r.every(Number.isInteger))throw Error("All indices specified for choiceInput must be integers");if(r.every((e=>e>=1&&e<=n)))return{setValue:{choiceOrder:r}};console.warn("Ignoring indices specified for choiceInput as some indices out of range.")}let a=e.rngClass(e.variantSeed+"co");t=[...Array(n).keys()].map((e=>e+1));for(let e=n-1;e>0;e--){const n=a(),r=Math.floor(n*(e+1));[t[e],t[r]]=[t[r],t[e]]}}else t=[...Array(n).keys()].map((e=>e+1));return{setValue:{choiceOrder:t}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}};e.shuffleOrder&&(n.indices=e.choiceOrder);let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.choiceChildrenOrdered={additionalStateVariablesDefined:[{variableName:"numberChoices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:function({dependencyValues:e}){let t=e.choiceChildren.length,n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceChildrenOrdered:n,numberChoices:t}}}},e.choiceTexts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["choiceText"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceTexts:t.map((e=>e.stateValues.text))}}}},e.choiceMaths={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["choiceMath"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceMaths:t.map((e=>e.stateValues.math))}}}},e.choicePreselects={isArray:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["preSelect"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicePreselects:t.map((e=>e.stateValues.preSelect))}}}},e.choicesDisabled={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["disabled"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesDisabled:t.map((e=>e.stateValues.disabled))}}}},e.choicesHidden={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["hidden"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesHidden:t.map((e=>e.stateValues.hidden))}}}},e.componentType={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}),definition({dependencyValues:e}){let t="text";return e.choiceChildren.length>0&&e.choiceChildren.every((e=>e.stateValues.math))&&(t="math"),{setValue:{componentType:t}}}},e.indicesMatchedByBoundValue={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));if(null!==e.bindValueTo){let n=t.map((e=>e.stateValues.text.toLowerCase().trim()));if(e.bindValueTo.stateValues.value){if(e.selectMultiple){let t=e.bindValueTo.stateValues.value.toLowerCase().split(",").map((e=>e.trim())),r=[];for(let e of t){let t=n.indexOf(e);-1===t||r.includes(t+1)||r.push(t+1)}return r.sort(((e,t)=>e-t)),{setValue:{indicesMatchedByBoundValue:r}}}{let t=n.indexOf(e.bindValueTo.stateValues.value.toLowerCase().trim());if(-1!==t)return{setValue:{indicesMatchedByBoundValue:[t+1]}}}}}return{setValue:{indicesMatchedByBoundValue:[]}}}},e.allSelectedIndices={hasEssential:!0,returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},indicesMatchedByBoundValue:{dependencyType:"stateVariable",variableName:"indicesMatchedByBoundValue"},preselectChoice:{dependencyType:"stateVariable",variableName:"preselectChoice"},choicePreselects:{dependencyType:"stateVariable",variableName:"choicePreselects"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>null!==e.bindValueTo?{setValue:{allSelectedIndices:e.indicesMatchedByBoundValue}}:{useEssentialOrDefaultValue:{allSelectedIndices:{get defaultValue(){let t=e.choicePreselects.indexOf(!0);return-1!==t?[t+1]:null!==e.preselectChoice?[e.preselectChoice]:[]}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null===t.bindValueTo)return{success:!0,instructions:[{setEssentialValue:"allSelectedIndices",value:e.allSelectedIndices}]};{let n="";if(e.allSelectedIndices.length>0){let r=t.choiceOrder.map((e=>t.choiceChildren[e-1])),a=[];for(let t of e.allSelectedIndices){let e=r[t-1];e&&a.push(e.stateValues.text)}n=a.join(", ")}return{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:n,variableIndex:0}]}}}},e.nSelectedIndices={returnDependencies:()=>({allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}),definition:({dependencyValues:e})=>({setValue:{nSelectedIndices:e.allSelectedIndices.length}})},e.selectedIndices={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["selectedIndex"],forRenderer:!0,returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n in e.allSelectedIndices)t[n]=e.allSelectedIndices[n];return{setValue:{selectedIndices:t}}}},e.selectedIndex={isAlias:!0,targetVariableName:"selectedIndex1"},e.selectedValues={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["selectedValue"],returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceTexts:{dependencyType:"stateVariable",variableName:"choiceTexts"},choiceMaths:{dependencyType:"stateVariable",variableName:"choiceMaths"},componentType:{dependencyType:"stateVariable",variableName:"componentType"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={},r=e.componentType;for(let a of t)n[a]="math"===r?e.choiceMaths[e.selectedIndices[a]-1]:e.choiceTexts[e.selectedIndices[a]-1];return{setValue:{selectedValues:n},setCreateComponentOfType:{selectedValues:r}}}},e.selectedValue={isAlias:!0,targetVariableName:"selectedValue1"},e.values={isAlias:!0,targetVariableName:"selectedValues"},e.nValues={isAlias:!0,targetVariableName:"nSelectedIndices"},e.childIndicesSelected={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"}}),definition({dependencyValues:e}){let t=e.selectedIndices.map((t=>e.choiceOrder[t-1]));return{setValue:{childIndicesSelected:t}}}},e.creditAchievedIfSubmit={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["selected","credit"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"}}),definition:function({dependencyValues:e}){let t=0;if(e.selectMultiple){let n=0,r=0,a=0;for(let t of e.choiceChildren)t.stateValues.selected?1===t.stateValues.credit?n++:r++:1===t.stateValues.credit&&a++;if(e.matchPartial){let e=n+r+a;t=0===e?1:n/e}else r+a===0&&(t=1)}else for(let n of e.choiceChildren)if(n.stateValues.selected){t=n.stateValues.credit;break}return{setValue:{creditAchievedIfSubmit:t}}}},e.valueToRecordOnSubmit={isAlias:!0,targetVariableName:"selectedIndices"},e.submittedIndices={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["submitted"]}}),definition({dependencyValues:e}){let t=[],n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));for(let[e,r]of n.entries())r.stateValues.submitted&&t.push(e+1);return{setValue:{submittedIndices:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=[];for(let[r,a]of t.choiceOrder.entries())n.push({setDependency:"choiceChildren",desiredValue:e.submittedIndices.includes(r+1),variableIndex:0,childIndex:a-1});return{success:!0,instructions:n}}},e.valueRecordedAtSubmit={isAlias:!0,targetVariableName:"submittedIndices"},e.allFeedbacks={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["feedbacks"]}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1])),n=[];for(let e of t)n.push(...e.stateValues.feedbacks);return{setValue:{allFeedbacks:n}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;nr[e-1]))}},i=await this.stateValues.answerAncestor;return i&&(a.context={answerAncestor:i.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:t,event:a}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){if(!e.attributes?.shuffleOrder?.primitive)return super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});let n=0;for(let r of e.children)if("choice"===r.componentType)n++;else{if(!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})||"choice"!==r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,numberOfChoices:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};if(!e.attributes.shuffleOrder?.primitive)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,s=e.variants.uniqueVariantData.numberOfPermutations,o=e.variants.uniqueVariantData.numberOfChoices,l=[...a];l.push(s);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(o).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],h=!1,f=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};f.push(r.desiredVariant),h=!0}else f.push({});let y={indices:m};return h&&(y.subvariants=f),{success:!0,desiredVariant:y}}}class Choice extends InlineComponent{static componentType="choice";static rendererType="containerInline";static renderChildren=!0;static variableForPlainMacro="submitted";static variableForPlainCopy="submitted";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:0,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.preSelect={createComponentOfType:"boolean",createStateVariable:"preSelect",defaultValue:!1},e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{text:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["value","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=null;if(1===e.inlineChildren.length){let n=e.inlineChildren[0];if("object"==typeof n){let e=n.stateValues.value;if(e instanceof me$3.class)t=e;else if("number"==typeof e)t=me$3.fromAst(e);else if("string"==typeof n.stateValues.latex)try{t=me$3.fromLatex(n.stateValues.latex)}catch(e){}}}return{setValue:{math:t}}}},e.selected={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},childIndicesSelected:{dependencyType:"parentStateVariable",parentComponentType:"choiceInput",variableName:"childIndicesSelected"},primaryShadow:{dependencyType:"primaryShadow",variableNames:["selected"]}}),definition({dependencyValues:e,componentName:t}){let n;return n=e.childIndicesSelected?e.childIndicesSelected.includes(e.countAmongSiblings):!!e.primaryShadow&&e.primaryShadow.stateValues.selected,{setValue:{selected:n}}}},e.submitted={defaultValue:!1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},doNotShadowEssential:!0,returnDependencies:()=>({primaryShadow:{dependencyType:"primaryShadow",variableNames:["submitted"]}}),definition:({dependencyValues:e})=>e.primaryShadow?{setValue:{submitted:e.primaryShadow.stateValues.submitted}}:{useEssentialOrDefaultValue:{submitted:!0}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.primaryShadow?{success:!1}:{success:!0,instructions:[{setEssentialValue:"submitted",value:e.submitted}]}}},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedbacktext"},returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},submitted:{dependencyType:"stateVariable",variableName:"submitted"}}),definition({dependencyValues:e}){if(!e.submitted)return{setValue:{feedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{feedbacks:t}}}},e}static includeBlankStringChildren=!0;static adapters=["text","math"]}class NumberComponent extends InlineComponent{static componentType="number";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderAsMath={createComponentOfType:"boolean",createStateVariable:"renderAsMath",defaultValue:!1,public:!0,forRenderer:!0},e.convertBoolean={createPrimitiveOfType:"boolean",createStateVariable:"convertBoolean",defaultValue:!1},e.valueOnNaN={createPrimitiveOfType:"number",createStateVariable:"valueOnNaN",defaultValue:NaN},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:({matchedChildren:e,componentAttributes:t})=>({success:!t.convertBoolean,newChildren:[{componentType:"math",children:e}]})}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"maths",componentTypes:["math"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDigits"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDecimals"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.numberMathChildren[0].stateValues.displayDecimals}};r=!0,n=e.numberMathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displaySmallAsZero"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberMathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.numberMathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["padZeros"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.numberMathChildren.length&&0==e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].padZeros)return{setValue:{padZeros:e.numberMathChildren[0].stateValues.padZeros}};r=!0,n=e.numberMathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.singleNumberOrStringChild={additionalStateVariablesDefined:["singleMathChild"],returnDependencies:()=>({numberChildren:{dependencyType:"child",childGroups:["numbers"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},booleanChildren:{dependencyType:"child",childGroups:["booleans"]},textChildren:{dependencyType:"child",childGroups:["texts"]}}),definition({dependencyValues:e}){let t=e.numberChildren.length+e.stringChildren.length,n=e.mathChildren.length,r=e.booleanChildren.length+e.textChildren.length;return{setValue:{singleNumberOrStringChild:t<=1&&n+r===0,singleMathChild:1===n&&t+r===0}}}},e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["textChildrenByCode","numberChildrenByCode","booleanChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","booleans"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s=0,o=e.codePre;for(let l of e.allChildren)if("string"!=typeof l){let e=o+s;t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"math"})?n[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"number"})?r[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"text"})?a[e]=l:i[e]=l,s+=1}return{setValue:{mathChildrenByCode:n,numberChildrenByCode:r,textChildrenByCode:a,booleanChildrenByCode:i}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,stateVariablesDeterminingDependencies:["singleNumberOrStringChild"],returnDependencies:({stateValues:e})=>e.singleNumberOrStringChild?{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}}:{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","unordered"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}},definition({dependencyValues:e,componentInfoObjects:t}){if(e.singleNumberOrStringChild){if(0===e.numberChild.length){if(0===e.stringChild.length)return{useEssentialOrDefaultValue:{value:{defaultValue:e.valueOnNaN}}};let n=Number(e.stringChild[0]);if(Number.isNaN(n))try{if(n=me$3.fromAst(textToAst$1.convert(e.stringChild[0])).evaluate_to_constant(),"boolean"==typeof n)n=e.convertBoolean?n?1:0:e.valueOnNaN;else if(null===n||Number.isNaN(n))if(e.convertBoolean){n=evaluateLogic({logicTree:buildParsedExpression({dependencyValues:{stringChildren:e.stringChild,allChildren:e.stringChild},componentInfoObjects:t}).setValue.parsedExpression.tree,dependencyValues:{booleanChildrenByCode:{},booleanListChildrenByCode:{},textChildrenByCode:{},textListChildrenByCode:{},mathChildrenByCode:{},mathListChildrenByCode:{},numberChildrenByCode:{},numberListChildrenByCode:{},otherChildrenByCode:{}},valueOnInvalid:e.valueOnNaN})}else n=e.valueOnNaN;else n?.re===1/0||n?.re===-1/0||n?.im===1/0||n?.im===-1/0?n=numberToMathExpression(n).evaluate_to_constant():0===n?.im&&(n=n.re)}catch(t){n=e.valueOnNaN}return{setValue:{value:n}}}{let t=e.numberChild[0].stateValues.value;return Number.isNaN(t)&&(t=e.valueOnNaN),{setValue:{value:t}}}}if(null===e.parsedExpression)return{setValue:{value:e.valueOnNaN}};if(0===Object.keys(e.textChildrenByCode).length&&0===Object.keys(e.booleanChildrenByCode).length){let t,n=function(t){if("string"==typeof t){let n=e.mathChildrenByCode[t];return void 0!==n?n.stateValues.value.tree:(n=e.numberChildrenByCode[t],void 0!==n?numberToMathExpression(n.stateValues.value).tree:t)}return Array.isArray(t)?[t[0],...t.slice(1).map(n)]:t};try{t=me$3.fromAst(n(e.parsedExpression.tree)).evaluate_to_constant()}catch(n){t=e.valueOnNaN}if(!Number.isNaN(t)&&("number"==typeof t||"number"==typeof t?.re&&"number"==typeof t?.im))return t.re===1/0||t.re===-1/0||t.im===1/0||t.im===-1/0?t=numberToMathExpression(t).evaluate_to_constant():0===t.im&&(t=t.re),{setValue:{value:t}}}if(!e.convertBoolean)return{setValue:{value:e.valueOnNaN}};return(e=Object.assign({},e)).mathListChildrenByCode={},e.numberListChildrenByCode={},e.textListChildrenByCode={},e.booleanListChildrenByCode={},e.otherChildrenByCode={},{setValue:{value:evaluateLogic({logicTree:e.parsedExpression.tree,dependencyValues:e,valueOnInvalid:e.valueOnNaN})}}},set:function(e){if(null===e)return NaN;if("number"==typeof e||"number"==typeof e?.re&&"number"==typeof e?.im)return e;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst$1.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return t},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,overrideFixed:r}){if(!await n.canBeModified&&!r)return{success:!1};let a,i=e.value;return i instanceof me$3.class?(i=i.evaluate_to_constant(),(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=t.valueOnNaN)):(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=Number(i),Number.isNaN(i)&&(i=t.valueOnNaN)),t.singleNumberOrStringChild?(a=0===t.numberChild.length?0===t.stringChild.length?[{setEssentialValue:"value",value:numberToMathExpression(i).evaluate_to_constant()}]:[{setDependency:"stringChild",desiredValue:numberToMathExpression(i).toString(),childIndex:0,variableIndex:0}]:[{setDependency:"numberChild",desiredValue:i,childIndex:0,variableIndex:0}],{success:!0,instructions:a}):t.singleMathChild?{success:!0,instructions:[{setDependency:"allChildren",desiredValue:numberToMathExpression(i),childIndex:0,variableIndex:0}]}:{success:!1}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:numberToMathExpression(e.value),dependencyValues:e,usedDefault:t}).evaluate_to_constant()}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{text:numberToMathExpression(e.valueForDisplay).toString(n)}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=Number(e.text);if(Number.isFinite(n))return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]};{let t,r=getFromText({parseScientificNotation:!1});try{t=r(e.text)}catch(e){return{success:!1}}return n=t.evaluate_to_constant(),Number.isFinite(n)?{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}:{success:!1}}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"value",mathVariableName:"math",isPublic:!0}),e.math.shadowingInstructions.attributesToShadow=["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:numberToMathExpression(e.valueForDisplay).toLatex(n)}}}},e.canBeModified={returnDependencies:()=>({numberChildModifiable:{dependencyType:"child",childGroups:["numbers"],variableNames:["canBeModified"]},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"}}),definition:function({dependencyValues:e}){return!e.modifyIndirectly||e.fixed||!e.singleNumberOrStringChild&&!e.singleMathChild?{setValue:{canBeModified:!1}}:1!==e.numberChildModifiable.length||e.numberChildModifiable[0].stateValues.canBeModified?{setValue:{canBeModified:!0}}:{setValue:{canBeModified:!1}}}},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Integer extends NumberComponent{static componentType="integer";static rendererType="number";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreRound"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({valuePreRound:{dependencyType:"stateVariable",variableName:"valuePreRound"}}),set:function(e){if(null===e)return NaN;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return Math.round(t)},definition:({dependencyValues:e})=>({setValue:{value:Math.round(e.valuePreRound)}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.value;return t instanceof me$3.class?(t=t.evaluate_to_constant(),Number.isFinite(t)||(t=NaN)):t=Number(t),t=Math.round(t),{success:!0,instructions:[{setDependency:"valuePreRound",desiredValue:t}]}}},e}}const maxWidth=850,sizePossibilities=["tiny","small","medium","large","full"],widthFractions=[1/12,.3,.5,.7,1],fractionMidpoints=widthFractions.map(((e,t)=>(e+(widthFractions[t+1]||1/0))/2)),orderedWidthMidpoints=fractionMidpoints.map((e=>maxWidth*e)),orderedPercentWidthMidpoints=fractionMidpoints.map((e=>100*e)),widthsBySize={};sizePossibilities.forEach(((e,t)=>widthsBySize[e]=Math.floor(widthFractions[t]*maxWidth)));const percentWidthsBySize={};sizePossibilities.forEach(((e,t)=>percentWidthsBySize[e]=Math.round(100*widthFractions[t])));class Graph$1 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{changeAxisLimits:this.changeAxisLimits.bind(this),addChildren:this.addChildren.bind(this),deleteChildren:this.deleteChildren.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="graph";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.identicalAxisScales={createPrimitiveOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"label"},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.xTickScaleFactor={createComponentOfType:"math",createStateVariable:"xTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.ylabel={createComponentOfType:"label"},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e.yTickScaleFactor={createComponentOfType:"math",createStateVariable:"yTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.showNavigation={createComponentOfType:"boolean",createStateVariable:"showNavigation",defaultValue:!0,public:!0,forRenderer:!0},e.fixAxes={createComponentOfType:"boolean",createStateVariable:"fixAxes",defaultValue:!1,public:!0,forRenderer:!0},e.grid={createComponentOfType:"text"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"xlabels",componentTypes:["xlabel"]},{group:"ylabels",componentTypes:["ylabel"]},{group:"graphical",componentTypes:["_graphical","text","image","math","m","md","label"]},{group:"childrenThatShouldNotBeHere",componentTypes:["_base"],matchAfterAdapters:!0}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({xlabelAttr:{dependencyType:"attributeComponent",attributeName:"xlabel",variableNames:["value","hasLatex"]},xlabelChild:{dependencyType:"child",childGroups:["xlabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.xlabelChild.length>0){let t=e.xlabelChild[e.xlabelChild.length-1];return{setValue:{xlabel:t.stateValues.value,xlabelHasLatex:t.stateValues.hasLatex}}}return e.xlabelAttr?{setValue:{xlabel:e.xlabelAttr.stateValues.value,xlabelHasLatex:e.xlabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{xlabel:!0},setValue:{xlabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.xlabel)return{success:!1};if(t.xlabelChild.length>0){let n=t.xlabelChild.length-1;return{success:!0,instructions:[{setDependency:"xlabelChild",desiredValue:e.xlabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"xlabel",value:e.xlabel}]}}},e.ylabel={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"ylabelHasLatex"}}},hasEssential:!0,defaultValue:"",additionalStateVariablesDefined:[{variableName:"ylabelHasLatex",forRenderer:!0}],returnDependencies:()=>({ylabelAttr:{dependencyType:"attributeComponent",attributeName:"ylabel",variableNames:["value","hasLatex"]},ylabelChild:{dependencyType:"child",childGroups:["ylabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.ylabelChild.length>0){let t=e.ylabelChild[e.ylabelChild.length-1];return{setValue:{ylabel:t.stateValues.value,ylabelHasLatex:t.stateValues.hasLatex}}}return e.ylabelAttr?{setValue:{ylabel:e.ylabelAttr.stateValues.value,ylabelHasLatex:e.ylabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{ylabel:!0},setValue:{ylabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.ylabel)return{success:!1};if(t.ylabelChild.length>0){let n=t.ylabelChild.length-1;return{success:!0,instructions:[{setDependency:"ylabelChild",desiredValue:e.ylabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"ylabel",value:e.ylabel}]}}},e.graphicalDescendants={forRenderer:!0,returnDependencies:()=>({graphicalDescendants:{dependencyType:"descendant",componentTypes:["_graphical"]}}),definition:function({dependencyValues:e}){return{setValue:{graphicalDescendants:e.graphicalDescendants}}}},e.childIndicesToRender={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"]},allChildren:{dependencyType:"child",childGroups:["graphical","xlabels","ylabels","childrenThatShouldNotBeHere"]}}),definition({dependencyValues:e}){let t=[],n=e.graphicalChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())n.includes(a.componentName)&&t.push(r);return{setValue:{childIndicesToRender:t}}}},e.nChildrenAdded={defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nChildrenAdded:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nChildrenAdded",value:e.nChildrenAdded}]})},e.size={public:!0,defaultValue:"medium",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="medium";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatioFromAxisScales={returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]}}),definition:({dependencyValues:e})=>(null!==e.heightAttr&&console.warn("Height attribute of graph is deprecated and is being ignored. Use aspectRatio attribute instead."),{setValue:{aspectRatioFromAxisScales:e.identicalAxisScales&&null===e.aspectRatioAttr},checkForActualChange:{aspectRatioFromAxisScales:!0}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:1,hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["aspectRatioFromAxisScales"],returnDependencies:({stateValues:e})=>e.aspectRatioFromAxisScales?{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"}}:{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}},definition({dependencyValues:e}){if(e.aspectRatioFromAxisScales){return{setValue:{aspectRatio:e.xscale/e.yscale}}}if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.aspectRatio,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.xminPrelim;if(s){let t=e.aspectRatio,a=(e.ymaxPrelim-e.yminPrelim)*t;if(o){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,s=e.aspectRatio;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/s;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/s}}:{setValue:{ymin:-10/s}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.yminPrelim,u=e.aspectRatio;if(o){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(s){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e.gridAttrCompName={returnDependencies:()=>({gridAttr:{dependencyType:"attributeComponent",attributeName:"grid"}}),definition:({dependencyValues:e})=>e.gridAttr?{setValue:{gridAttrCompName:e.gridAttr.componentName}}:{setValue:{gridAttrCompName:null}}},e.gridAttrCompChildren={stateVariablesDeterminingDependencies:["gridAttrCompName"],returnDependencies:({stateValues:e})=>e.gridAttrCompName?{gridAttrCompChildren:{dependencyType:"child",parentName:e.gridAttrCompName,childGroups:["textLike"],variableNames:["value"]}}:{},definition:({dependencyValues:e})=>e.gridAttrCompChildren?{setValue:{gridAttrCompChildren:e.gridAttrCompChildren}}:{setValue:{gridAttrCompChildren:null}}},e.grid={public:!0,shadowingInstructions:{hasVariableComponentType:!0,attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,stateVariablesDeterminingDependencies:["gridAttrCompChildren"],returnDependencies({stateValues:e}){if(e.gridAttrCompChildren){let t={gridAttrCompChildren:{dependencyType:"stateVariable",variableName:"gridAttrCompChildren"},gridAttr:{dependencyType:"attributeComponent",attributeName:"grid",variableNames:["value"]}};for(let[n,r]of e.gridAttrCompChildren.entries())t["childAdapter"+n]={dependencyType:"adapterSourceStateVariable",componentName:r.componentName,variableName:"value"};return t}return{}},definition({dependencyValues:e}){if(!e.gridAttrCompChildren)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};let t=e.gridAttr.stateValues.value.toLowerCase().trim();if("true"===t?t="medium":"false"===t&&(t="none"),["medium","dense","none"].includes(t))return{setValue:{grid:t},setCreateComponentOfType:{grid:"text"}};let n=[],r=[];for(let t of e.gridAttrCompChildren)if("string"!=typeof t)r.push(t);else{let e=t.split(/\s+/),a=e[0];""===a?r.length>0&&(n.push(r),r=[]):r.push(a);for(let t of e.slice(1))r.length>0&&(n.push(r),r=[]),""!==t&&r.push(t)}if(r.length>0&&n.push(r),n.length<2)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t=[];for(let r of n)if(1===r.length){let n=r[0];if("string"==typeof n){let e=me$3.fromText(n).evaluate_to_constant();if(!(e>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(e)}else{let r=e.gridAttrCompChildren.indexOf(n),a=e["childAdapter"+r];if(a instanceof me$3.class&&(a=a.evaluate_to_constant()),!(a>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(a)}}else{let n=1;for(let t of r)if("string"==typeof t)n*=me$3.fromText(t).evaluate_to_constant();else{let r=e.gridAttrCompChildren.indexOf(t),a=e["childAdapter"+r];a instanceof me$3.class&&(a=a.evaluate_to_constant()),n*=a}if(!(n>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(n)}return{setValue:{grid:t},setCreateComponentOfType:{grid:"numberList"}}}},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}async addChildren({serializedComponents:e,actionId:t}){if(e&&e.length>0){let n=processAssignNames({serializedComponents:e,parentName:this.componentName,parentCreatesNewNamespace:this.attributes.newNamespace?.primitive,componentInfoObjects:this.componentInfoObjects,indOffset:await this.stateValues.nChildrenAdded});return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"addComponents",serializedComponents:n.serializedComponents,parentName:this.componentName,assignNamesOffset:await this.stateValues.nChildrenAdded},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded+n.serializedComponents.length}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}async deleteChildren({number:e,actionId:t}){let n=Math.min(e,await this.stateValues.nChildrenAdded);if(n>0){let e=this.definingChildren.length,r=this.definingChildren.slice(e-n,e).map((e=>e.componentName));return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"deleteComponents",componentNames:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded-n}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Variables extends MathList{static componentType="variables";static stateVariableForAttributeValue="variables";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.variables={public:!0,shadowingInstructions:{createComponentOfType:"variable"},isArray:!0,entryPrefixes:["var"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={math:{dependencyType:"stateVariable",variableName:"math"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].math;return{setValue:{variables:n}}}};let t=this.componentType;return e.validVariables={returnDependencies:()=>({variables:{dependencyType:"stateVariable",variableName:"variables"}}),definition:function({dependencyValues:e}){let n=[];for(let r of e.variables){let e=isValidVariable(r);e||(console.warn("Invalid value for "+t),e=!1),n.push(e)}return{setValue:{validVariables:n}}}},e}}class Variable extends MathComponent{static componentType="variable";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validVariable={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=isValidVariable(e.value);return t||console.warn("Invalid value of a "+this.componentType),{setValue:{validVariable:t}}}},e}}class Interval extends MathComponent{static componentType="interval";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createIntervals,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createIntervals={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createIntervals:!0}})},e}}class Group extends Template{static componentType="group";static renderedDefault=!0}class Option$1 extends Group{static componentType="option";static renderedDefault=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.selectForVariants={createComponentOfType:"textListFromString",createStateVariable:"selectForVariants",defaultValue:[],public:!0},e.selectWeight={createComponentOfType:"number",createStateVariable:"selectWeight",defaultValue:1,public:!0},e}}class Sequence extends CompositeComponent{static componentType="sequence";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();e.fixed={leaveRaw:!0},e.displayDigits={leaveRaw:!0},e.displayDecimals={leaveRaw:!0},e.displaySmallAsZero={leaveRaw:!0},e.padZeros={leaveRaw:!0};let t=returnStandardSequenceAttributes();return Object.assign(e,t),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.readyToExpandWhenResolved={returnDependencies:()=>({from:{dependencyType:"stateVariable",variableName:"from"},length:{dependencyType:"stateVariable",variableName:"length"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"},exclude:{dependencyType:"stateVariable",variableName:"exclude"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validSequence)return t.lastReplacementParameters={from:null,length:null,step:null,type:null,exclude:null},{replacements:[]};let a=await e.stateValues.from,i=await e.stateValues.length,s=await e.stateValues.step,o=await e.stateValues.type,l=await e.stateValues.exclude;t.lastReplacementParameters={from:a,length:i,step:s,type:o,exclude:l};let u=e.attributes.newNamespace?.primitive,c=returnSequenceValues({from:a,step:s,length:i,exclude:l,type:o,lowercase:await e.stateValues.lowercase}),p=o;"letters"===o&&(p="text");let d=[],m={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(m[t]=e.attributes[t]);for(let e of c){let t={};Object.keys(m).length>0&&(t=convertAttributesForComponentType({attributes:m,componentType:p,componentInfoObjects:n,compositeCreatesNewNamespace:u,flags:r}));let a={componentType:p,attributes:t,state:{value:e,fixed:!0}};d.push(a)}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,parentCreatesNewNamespace:u,componentInfoObjects:n}).serializedComponents}}static async calculateReplacementChanges({component:e,workspace:t,componentInfoObjects:n,flags:r}){let a=t.lastReplacementParameters,i=[];if(!await e.stateValues.validSequence){let t=e.replacementsToWithhold;if(t||(t=0),e.replacements.length-t>0){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};i.push(t)}return a.length=0,i}let s=await e.stateValues.from,o=await e.stateValues.length,l=await e.stateValues.step,u=await e.stateValues.type,c=await e.stateValues.exclude,p=await e.stateValues.lowercase;if(a.type!==u||a.exclude.length>0||c.length>0){let a=(await this.createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r})).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:a,replacementsToWithhold:0};i.push(s)}else{let t=!1;"math"===u?s.equals(a.from)&&l.equals(a.step)||(t=!0):s===a.from&&l===a.step||(t=!0);let c,d=a.length,m=0,h=0,f=d;if(od&&(m=o-d,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=m){c=e.replacementsToWithhold-m,h+=m,d+=m,m=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:c};i.push(t)}else m-=e.replacementsToWithhold,h+=e.replacementsToWithhold,d+=e.replacementsToWithhold,c=0;if(!0===t&&(h=d,f=0),h>0)for(let t=f;t0){let t=[],a=e.attributes.newNamespace?.primitive,o={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(o[t]=e.attributes[t]);for(let i=d;i0&&(m=convertAttributesForComponentType({attributes:o,componentType:d,componentInfoObjects:n,compositeCreatesNewNamespace:a,flags:r}));let h={componentType:d,attributes:m,state:{value:c,fixed:!0}};t.push(h)}let c={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:d,serializedReplacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:n,indOffset:d}).serializedComponents,replacementsToWithhold:0,assignNamesOffset:d};i.push(c)}}return a.type=u,a.from=s,a.length=o,a.step=l,a.exclude=c,i}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t="number";this.attributes.type&&this.attributes.type.primitive&&(t=this.attributes.type.primitive);let n=this.componentInfoObjects.allComponentClasses["letters"===t?"text":t].rendererType;return e.includes(n)||e.push(n),e}}class Map$1 extends CompositeComponent{static componentType="map";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.behavior={createComponentOfType:"text",createStateVariable:"behavior",defaultValue:"combination",public:!0,trim:!0},e.isResponse={leaveRaw:!0},e}static returnChildGroups(){return[{group:"templates",componentTypes:["template"]},{group:"sources",componentTypes:["sources"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nSources={additionalStateVariablesDefined:["sourcesNames","sourceAliases","sourceIndexAliases"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["alias","indexAlias"]}}),definition:function({dependencyValues:e}){return{setValue:{nSources:e.sourcesChildren.length,sourcesNames:e.sourcesChildren.map((e=>e.componentName)),sourceAliases:e.sourcesChildren.map((e=>e.stateValues.alias)),sourceIndexAliases:e.sourcesChildren.map((e=>e.stateValues.indexAlias))}}}},e.nIterates={additionalStateVariablesDefined:["minNIterates","sourcesChildNames"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["numberOfChildren","childComponentNames"]}}),definition:function({dependencyValues:e}){let t=e.sourcesChildren.map((e=>e.stateValues.numberOfChildren)),n=Math.min(...t),r=e.sourcesChildren.map((e=>[...e.stateValues.childComponentNames]));return{setValue:{nIterates:t,minNIterates:n,sourcesChildNames:r}}}},e.template={returnDependencies:()=>({templateChild:{dependencyType:"child",childGroups:["templates"],variableNames:["serializedChildren","newNamespace"]}}),definition:function({dependencyValues:e}){let t=e.templateChild[0];if(!t)return{setValue:{template:null}};let n={componentType:"template",state:{rendered:!0},children:t.stateValues.serializedChildren,originalName:t.componentName};return t.stateValues.newNamespace&&(n.attributes={newNamespace:{primitive:!0}}),{setValue:{template:n}}}},e.validBehavior={returnDependencies:()=>({behavior:{dependencyType:"stateVariable",variableName:"behavior"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition:function({dependencyValues:e}){let t=!0;return"parallel"===e.behavior?e.nIterates.slice(1).some((t=>t!=e.nIterates[0]))&&console.warn("Warning: map with parallel behavior and different numbers of iterates in sources activeChildren. Extra iterates will be ignored."):"combination"!==e.behavior&&(console.warn("Invalid map behavior: "+e.behavior),t=!1),{setValue:{validBehavior:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({validBehavior:{dependencyType:"stateVariable",variableName:"validBehavior"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validBehavior)return t.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0},{replacements:[]};t.lastReplacementParameters={sourcesNames:await e.stateValues.sourcesNames,sourcesChildNames:await e.stateValues.sourcesChildNames,behavior:await e.stateValues.behavior,nIterates:await e.stateValues.nIterates,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]};let a=[];if("parallel"===await e.stateValues.behavior)for(let t=0;t=c-1){r++;let t=[deepClone(p)],n={};n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:a,compositeAttributesObj:d,compositeCreatesNewNamespace:l,flags:i}),t[0].attributes||(t[0].attributes={}),Object.assign(t[0].attributes,n),!t[0].attributes.newNamespace?.primitive&&t[0].children&&markToCreateAllUniqueNames(t[0].children);let u=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:a,indOffset:r}).serializedComponents[0];await addSharedParameters(u,e,o),s.push(u)}else{let n=await this.recurseThroughCombinations({component:e,sourcesNumber:t+1,childnumberArray:o,iterateNumber:r,componentInfoObjects:a,flags:i});s.push(...n.replacements),r=n.iterateNumber}return{replacements:s,iterateNumber:r}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=[];if(!await e.stateValues.validBehavior){if(n.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},e.replacements.length>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length,replacementsToWithhold:0};i.push(t)}return i}let s=n.lastReplacementParameters,o=!1,l=!0,u=await e.stateValues.nSources,c=await e.stateValues.sourcesNames;if(u!==s.sourcesNames.length)l=!1;else for(let e=0;e1&&(o=!0)}else o=!0;if(o){let t=await this.createSerializedReplacements({component:e,workspace:n,componentInfoObjects:r,flags:a}).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:t,replacementsToWithhold:0};return i.push(s),n.lastReplacementParameters={sourcesNames:c,sourcesChildNames:d,behavior:m,nIterates:p,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},i}let h=await e.stateValues.minNIterates,f=s.minNIterates,y=0,g=e.replacementsToWithhold;g||(g=0);let b=s.withheldSubstitutionChildNames,v=!1;if(hf){let t=h-f;if(g>0)if(g>=t){y=g-t,t=0;let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:y};i.push(e)}else t-=g,f+=g,y=0;if(t>0){let t=[];for(let n=f;nr?{success:!1}:{success:!0,desiredVariant:{index:t}}}}async function addSharedParameters(e,t,n){let r=e.doenetAttributes.addToSharedParameters=[],a=await t.stateValues.sourcesNames;for(let[e,i]of(await t.stateValues.sourceAliases).entries())if(i){let t=a[e];r.push({parameterName:"sourceNameMappings",key:i,value:{name:t,childNumber:n[e]}})}for(let[e,a]of(await t.stateValues.sourceIndexAliases).entries())a&&r.push({parameterName:"sourceIndexMappings",key:a,value:n[e]+1})}class Sources extends BaseComponent{static componentType="sources";static rendererType="containerInline";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.alias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Aliases can contain only letters, numbers, hyphens, and underscores");return e}},e.indexAlias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All index aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Index aliases can contain only letters, numbers, hyphens, and underscores");return e}},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.alias={returnDependencies:()=>({alias:{dependencyType:"attributePrimitive",attributeName:"alias"}}),definition:({dependencyValues:e})=>({setValue:{alias:e.alias}})},e.indexAlias={returnDependencies:()=>({indexAlias:{dependencyType:"attributePrimitive",attributeName:"indexAlias"}}),definition:({dependencyValues:e})=>({setValue:{indexAlias:e.indexAlias}})},e.numberOfChildren={additionalStateVariablesDefined:["childComponentNames","childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:function({dependencyValues:e}){let t=e.children.length,n=e.children.map((e=>e.componentName));return{setValue:{numberOfChildren:t,childComponentNames:n,childIdentities:e.children}}}},e}}class Slider extends BaseComponent{constructor(e){super(e),this.changeValue=this.changeValue.bind(this),Object.assign(this.actions,{changeValue:this.changeValue})}static componentType="slider";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultValue:"number",toLowerCase:!0,validValues:["number","text"],forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:100,isAbsolute:!0},public:!0,forRenderer:!0},e.initialValue={createComponentOfType:"_componentWithSelectableType",createStateVariable:"initialValue",defaultValue:null},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showControls={createComponentOfType:"boolean",createStateVariable:"showControls",defaultValue:!1,public:!0,forRenderer:!0},e.showTicks={createComponentOfType:"boolean",createStateVariable:"showTicks",defaultValue:!0,public:!0,forRenderer:!0},e.showValue={createComponentOfType:"boolean",createStateVariable:"showValue",defaultValue:!0,public:!0,forRenderer:!0},e.from={createComponentOfType:"number",createStateVariable:"from",defaultValue:0,public:!0,forRenderer:!0},e.to={createComponentOfType:"number",createStateVariable:"to",defaultValue:10,public:!0,forRenderer:!0},e.step={createComponentOfType:"number",createStateVariable:"step",defaultValue:1,public:!0,forRenderer:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"_componentWithSelectableType"},e}static returnChildGroups(){return[{group:"numbersTexts",componentTypes:["number","text"]},{group:"markers",componentTypes:["markers"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberAndTextChildren:{dependencyType:"child",childGroups:["numbersTexts"],variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];if("text"===e.type)for(let r of e.numberAndTextChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"text"})?n.push(r.stateValues.value):n.push(r.stateValues.value.toString());else if(e.numberAndTextChildren.length>0){for(let r of e.numberAndTextChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else{let e=Number(r.stateValues.value);Number.isFinite(e)&&n.push(e)}n.sort(((e,t)=>e-t))}return{setValue:{items:n},setCreateComponentOfType:{items:e.type}}}},e.nItems={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t=e.items.length;return 0===t&&"number"===e.type&&(t=Math.floor((e.to-e.from)/e.step+1e-10)+1,t>=0&&Number.isFinite(t)||(t=0)),{setValue:{nItems:t}}}},e.firstItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[0]:"number"===e.type?e.from:null,{setValue:{firstItem:t}}}},e.lastItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},nItems:{dependencyType:"stateVariable",variableName:"nItems"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.items.length-1]:"number"===e.type?e.from+(e.nItems-1)*e.step:null,{setValue:{lastItem:t}}}},e.valueToIndex={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.items.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e.preliminaryValue={hasEssential:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>e.bindValueTo?{setValue:{preliminaryValue:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{preliminaryValue:{get defaultValue(){return e.initialValue}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.preliminaryValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"preliminaryValue",value:e.preliminaryValue}]}},e.index={forRenderer:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},valueToIndex:{dependencyType:"stateVariable",variableName:"valueToIndex"},items:{dependencyType:"stateVariable",variableName:"items"},preliminaryValue:{dependencyType:"stateVariable",variableName:"preliminaryValue"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},nItems:{dependencyType:"stateVariable",variableName:"nItems"}}),definition:function({dependencyValues:e}){let t=findIndexOfClosestValidValue(e);return void 0===t&&(t=0),{setValue:{index:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.items.length){let n=t.from,r=t.step,a=e.index;return Number.isInteger(a)&&(a>=0&&a({type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"},index:{dependencyType:"stateVariable",variableName:"index"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition:function({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.index]:e.from+e.step*e.index,{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:invertSliderValue},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}).tree}}}},e.markers={forRenderer:!0,returnDependencies:()=>({markersChild:{dependencyType:"child",childGroups:["markers"],variableNames:["markerType","markers"]},type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t=[];if(e.markersChild.length>0){let n=e.markersChild[0].stateValues.markerType;"empty"===n?t=[...e.items]:n!==e.type?(console.warn("Markers type doesn't match slider type."),t=[]):t=e.markersChild[0].stateValues.markers}return{setValue:{markers:t}}}},e}async changeValue({value:e,transient:t,actionId:n}){if(!await this.stateValues.disabled)return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],transient:t,actionId:n}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],actionId:n,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}}});this.coreFunctions.resolveAction({actionId:n})}}function findIndexOfClosestValidValue({preliminaryValue:e,valueToIndex:t,type:n,items:r,from:a,step:i,nItems:s}){let o=e;if(0===r.length){if(!Number.isFinite(o))return;let e=Math.round((o-a)/i);return e>=0?er[e]?t:e;let n=Math.round((t+e)/2);return o>r[n]?u(n,t):u(e,n)},c=u();if(0!==c){let e=r[c-1],t=r[c];Math.abs(o-e)({textChildren:{dependencyType:"child",childGroups:["texts"]},numberChildren:{dependencyType:"child",childGroups:["numbers"]}}),definition:function({dependencyValues:e}){let t;return t=e.textChildren.length>0?"text":e.numberChildren.length>0?"number":"empty",{setValue:{markerType:t}}}},e.markers={public:!0,isArray:!0,shadowingInstructions:{hasVariableComponentType:!0},entryPrefixes:["item"],returnDependencies:()=>({markerType:{dependencyType:"stateVariable",variableName:"markerType"},textChildren:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},numberChildren:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=[],n=e.markerType;return"text"===e.markerType?t=e.textChildren.map((e=>e.stateValues.value)):"number"===e.markerType?(t=e.numberChildren.map((e=>e.stateValues.value)),t.sort(((e,t)=>e-t))):n="text",{setValue:{markers:t},setCreateComponentOfType:{markers:n}}}},e}}class Pegboard extends GraphicalComponent{static componentType="pegboard";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0,forRenderer:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0,forRenderer:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0,forRenderer:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0,forRenderer:!0},e}}function applyConstraintFromComponentConstraints({variables:e,applyComponentConstraint:t,scales:n}){let r={},a=!1;for(let i in e){let s=t({variables:{[i]:e[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}return a?{constrained:a,variables:r}:{}}class Constraints extends BaseComponent{static componentType="constraints";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.baseOnGraph={createTargetComponentNames:!0},e}static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["independentComponentConstraints"]}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.constraintChildren.every((e=>e.stateValues.independentComponentConstraints))}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({arrayEntryPrefixForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayEntryPrefixForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayEntryPrefixForConstraints:e.arrayEntryPrefixForConstraints}})},e.arrayVariableForConstraints={returnDependencies:()=>({arrayVariableForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayVariableForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayVariableForConstraints:e.arrayVariableForConstraints}})},e.nDimensions={returnDependencies:()=>({nDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensionsForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{nDimensions:e.nDimensions}})},e.graphComponentName={returnDependencies:()=>({graphComponentName:{dependencyType:"attributeTargetComponentNames",attributeName:"baseOnGraph"}}),definition:({dependencyValues:e})=>1===e.graphComponentName?.length?{setValue:{graphComponentName:e.graphComponentName[0].absoluteName}}:{setValue:{graphComponentName:null}}},e.scales={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xscale","yscale"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(e.graph){let t=e.graph.stateValues,n=[t.xscale,t.yscale,1];if(n.every((e=>Number.isFinite(e)&&e>0)))return{setValue:{scales:n}}}return{setValue:{scales:[1,1,1]}}}},e.graphXmin={additionalStateVariablesDefined:["graphXmax","graphYmin","graphYmax"],stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xmin","xmax","ymin","ymax"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(!e.graph)return{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}};let t=e.graph.stateValues.xmin,n=e.graph.stateValues.xmax,r=e.graph.stateValues.ymin,a=e.graph.stateValues.ymax;return[t,n,r,a].every(Number.isFinite)?{setValue:{graphXmin:t,graphXmax:n,graphYmin:r,graphYmax:a}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}}},e.constraintResults={additionalStateVariablesDefined:[{variableName:"constraintUsedByComponent",isArray:!0,entryPrefixes:["constraintUsedByComponent"]}],isArray:!0,entryPrefixes:["constraintResult"],stateVariablesDeterminingDependencies:["independentComponentConstraints","arrayEntryPrefixForConstraints","arrayVariableForConstraints"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},scales:{dependencyType:"stateVariable",variableName:"scales"}},r=t.arrayEntryPrefixForConstraints,a={};if(t.independentComponentConstraints)for(let t of e)a[t]={x:{dependencyType:"parentStateVariable",variableName:r+(Number(t)+1)}};else{let e=t.arrayVariableForConstraints?t.arrayVariableForConstraints:"__null";n.xs={dependencyType:"parentStateVariable",variableName:e}}return{globalDependencies:n,dependenciesByKey:a}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.independentComponentConstraints){let r={},a={};for(let i of n){let n=Number(i)+1,s={["x"+n]:t[i].x},o=!1;for(let t of e.constraintChildren){let r=t.stateValues.applyComponentConstraint({variables:s,scales:e.scales});r.constrained&&(s["x"+n]=convertValueToMathExpression(r.variables["x"+n]),o=!0)}r[i]=s["x"+n],a[i]=o}return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}{let t={},n=!1;for(let n in e.xs)t[`x${Number(n)+1}`]=e.xs[n];for(let r of e.constraintChildren){let a;if(a=r.stateValues.applyConstraint?r.stateValues.applyConstraint({variables:t,scales:e.scales}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:r.stateValues.applyComponentConstraint,scales:e.scales}),a.constrained){for(let e in a.variables)t[e]=convertValueToMathExpression(a.variables[e]);n=!0}}let r={},a={};for(let i in e.xs)r[i]=t[`x${Number(i)+1}`],a[i]=n;return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.independentComponentConstraints){let n=[];for(let a in e.constraintResults){let i=Number(a)+1,s={["x"+i]:convertValueToMathExpression(e.constraintResults[a])};for(let e of t.constraintChildren){let n=e.stateValues.applyComponentConstraint({variables:s,scales:t.scales});n.constrained&&(s["x"+i]=convertValueToMathExpression(n.variables["x"+i]))}n.push({setDependency:r[a].x,desiredValue:s["x"+i]})}return{success:!0,instructions:n}}{let n={};i.desiredConstraintResults||(i.desiredConstraintResults={}),Object.assign(i.desiredConstraintResults,e.constraintResults);let r=await a.constraintResults;for(let e in r){let t=Number(e)+1;e in i.desiredConstraintResults?n["x"+t]=convertValueToMathExpression(i.desiredConstraintResults[e]):n["x"+t]=convertValueToMathExpression(r[e])}for(let e of t.constraintChildren){let r;if(r=e.stateValues.applyConstraint?e.stateValues.applyConstraint({variables:n,scales:t.scales}):applyConstraintFromComponentConstraints({variables:n,applyComponentConstraint:e.stateValues.applyComponentConstraint,scales:t.scales}),r.constrained)for(let e in r.variables)n[e]=convertValueToMathExpression(r.variables[e])}let s={};for(let e in i.desiredConstraintResults)s[e]=n[`x${Number(e)+1}`];return{success:!0,instructions:[{setDependency:"xs",desiredValue:s}]}}}},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintUsedByComponent:{dependencyType:"stateVariable",variableName:"constraintUsedByComponent"}}),definition:function({dependencyValues:e}){let t=Object.values(e.constraintUsedByComponent).some((e=>e));return{setValue:{constraintUsed:t}}}},e}}class ConstraintComponent extends BaseComponent{static componentType="_constraint";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!1}})},e}}class ConstrainToGrid extends ConstraintComponent{static componentType="constrainToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x1:s}}}return{}}if("x2"in t){let n=findFiniteNumericalValue(t.x2);if(!Number.isFinite(n))return{};let a=e.dy,i=e.yoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphYmin,n=e.constraintAncestor.stateValues.graphYmax):"graph"===r&&(t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x2:s}}}return{}}if("x3"in t){let n=findFiniteNumericalValue(t.x3);if(!Number.isFinite(n))return{};let r=e.dz,a=e.zoffset,i=Math.round((n-a)/r)*r+a;return Number.isFinite(i)?{constrained:!0,variables:{x3:i}}:{}}return{}}}})},e}}class ConstrainToGraph extends ConstraintComponent{static componentType="constrainToGraph";static createAttributesObject(){let e=super.createAttributesObject();return e.buffer={createComponentOfType:"number",createStateVariable:"buffer",defaultValue:.01,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},buffer:{dependencyType:"stateVariable",variableName:"buffer"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),!r)return{};if("x1"in t){let n,a,i=findFiniteNumericalValue(t.x1);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphXmin,a=e.constraintAncestor.stateValues.graphXmax):(n=e.graphAncestor.stateValues.xmin,a=e.graphAncestor.stateValues.xmax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x1:Math.max(s,Math.min(o,i))}}}if("x2"in t){let n,a,i=findFiniteNumericalValue(t.x2);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphYmin,a=e.constraintAncestor.stateValues.graphYmax):(n=e.graphAncestor.stateValues.ymin,a=e.graphAncestor.stateValues.ymax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x2:Math.max(s,Math.min(o,i))}}}return{}}}})},e}}class AttractToGrid extends ConstraintComponent{static componentType="attractToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.xthreshold={createComponentOfType:"number",createStateVariable:"xthreshold",defaultValue:.2,public:!0},e.ythreshold={createComponentOfType:"number",createStateVariable:"ythreshold",defaultValue:.2,public:!0},e.zthreshold={createComponentOfType:"number",createStateVariable:"zthreshold",defaultValue:.2,public:!0},e.includeGridlines={createComponentOfType:"boolean",createStateVariable:"includeGridlines",defaultValue:!1,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.includeGridlines}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(!Number.isFinite(s))return{};if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)n&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"},applyComponentConstraint:{dependencyType:"stateVariable",variableName:"applyComponentConstraint"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r={},a=!1;for(let i in t){let s=e.applyComponentConstraint({variables:{[i]:t[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}if(!a)return{};if(!e.includeGridlines){if(void 0!==t.x1&&void 0===r.x1)return{};if(void 0!==t.x2&&void 0===r.x2)return{};if(void 0!==t.x3&&void 0===r.x3)return{}}return{constrained:a,variables:r}}}})},e}}class ConstrainTo extends ConstraintComponent{static componentType="constrainTo";static returnChildGroups(){return[{group:"graphical",componentTypes:["_graphical"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r=1/0,a={},i=!1,s={};for(let e in t)s[e]=findFiniteNumericalValue(t[e]);for(let o of e.nearestPointFunctions){let e=o({variables:t,scales:n});if(void 0===e)continue;let l={},u=0;if(void 0!==s.x1){if(void 0===e.x1)continue;l.x1=e.x1,u+=Math.pow(s.x1-e.x1,2)}if(void 0!==s.x2){if(void 0===e.x2)continue;l.x2=e.x2,u+=Math.pow(s.x2-e.x2,2)}if(void 0!==s.x3){if(void 0===e.x3)continue;l.x3=e.x3,u+=Math.pow(s.x3-e.x3,2)}u({thresholdAttr:{dependencyType:"attributeComponent",attributeName:"threshold",variableNames:["value"]},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin"]}}),definition({dependencyValues:e}){if(e.thresholdAttr)return{setValue:{threshold:e.thresholdAttr.stateValues.value}};{let t=.02;return null!==e.constraintsAncestor&&null!==e.constraintsAncestor.stateValues.graphXmin||(t=.5),{useEssentialOrDefaultValue:{threshold:{defaultValue:t}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.thresholdAttr?{success:!0,instructions:[{setDependency:"thresholdAttr",desiredValue:e.threshold}]}:{success:!0,instructions:[{setEssentialValue:"threshold",value:e.threshold}]}},e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.graphXscale={additionalStateVariablesDefined:["graphYscale"],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){if(!e.graphAncestor)return{setValue:{graphXscale:null,graphYscale:null}};return{setValue:{graphXscale:e.graphAncestor.stateValues.xscale,graphYscale:e.graphAncestor.stateValues.yscale}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"},threshold:{dependencyType:"stateVariable",variableName:"threshold"},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){let t=1,n=1;return e.constraintsAncestor&&([t,n]=e.constraintsAncestor.stateValues.scales),{setValue:{applyConstraint:function({variables:r,scales:a}){let i=1/0,s={},o={};for(let e in r)o[e]=findFiniteNumericalValue(r[e]);for(let l of e.nearestPointFunctions){let e=l({variables:r,scales:a});if(void 0===e)continue;let u={},c=0;if(void 0!==o.x1){if(void 0===e.x1)continue;u.x1=e.x1,c+=Math.pow((o.x1-e.x1)/t,2)}if(void 0!==o.x2){if(void 0===e.x2)continue;u.x2=e.x2,c+=Math.pow((o.x2-e.x2)/n,2)}if(void 0!==o.x3){if(void 0===e.x3)continue;u.x3=e.x3,c+=Math.pow(o.x3-e.x3,2)}ce.threshold*e.threshold?{}:{constrained:!0,variables:s}}}}}},e}}class ConstraintUnion extends ConstraintComponent{static componentType="constraintUnion";static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.applyConstraint={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r;if(1===e.constraintChildren.length){let a=e.constraintChildren[0];return r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n}),r}let a,i=1/0,s={};for(let[o,l]of e.constraintChildren.entries()){if(r=l.stateValues.applyConstraint?l.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:l.stateValues.applyComponentConstraint,scales:n}),!r.constrained)continue;let e=0;for(let n in r.variables){let a=findFiniteNumericalValue(t[n]),i=findFiniteNumericalValue(r.variables[n]);if(!Number.isFinite(a)||!Number.isFinite(i)){e=1/0;break}e+=Math.pow(a-i,2)}e({constraintChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r,a=e.constraintChild[0];if(!a)return{};r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n});let i=0;for(let e in r.variables){let n=findFiniteNumericalValue(t[e]),a=findFiniteNumericalValue(r.variables[e]);if(!Number.isFinite(n)||!Number.isFinite(a))return{};i+=Math.pow(n-a,2)}return i>e.threshold*e.threshold?{}:r}}})},e}}class Intersection extends CompositeComponent{static componentType="intersection";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.lineChildren={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],variableNames:["numericalCoeff0","numericalCoeffvar1","numericalCoeffvar2","nDimensions"]}}),definition:({dependencyValues:e})=>({setValue:{lineChildren:e.lineChildren}})},e.readyToExpandWhenResolved={returnDependencies:()=>({lineChildren:{dependencyType:"stateVariable",variableName:"lineChildren"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=await e.stateValues.lineChildren,a=r.length;if(0===a)return{replacements:[]};if(1===a){let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}if(a>2)return console.warn("Haven't implemented intersection for more than two objects"),{replacements:[]};let i=r[0],s=r[1];if(2!==i.stateValues.nDimensions||2!==s.stateValues.nDimensions)return console.log("Intersection of lines implemented only in 2D"),{replacements:[]};let o=i.stateValues.numericalCoeffvar1,l=i.stateValues.numericalCoeffvar2,u=i.stateValues.numericalCoeff0,c=s.stateValues.numericalCoeffvar1,p=s.stateValues.numericalCoeffvar2,d=s.stateValues.numericalCoeff0;if(!(Number.isFinite(o)&&Number.isFinite(l)&&Number.isFinite(u)&&Number.isFinite(c)&&Number.isFinite(p)&&Number.isFinite(d)))return console.log("Intersection of lines implemented only for constant coefficients"),{replacements:[]};let m=o*p-c*l;if(Math.abs(m)<1e-14){if(Math.abs(d*o-u*c)>1e-14)return{replacements:[]};if(0===o&&0===l&&0===u||0===c&&0===p&&0===d)return{replacements:[]};{let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}}let h=(d*l-u*p)/m,f=(u*c-d*o)/m,y=[{componentType:"point",state:{coords:me$3.fromAst(["vector",h,f]),draggable:!1,fixed:!0}}],g=e.attributes.newNamespace?.primitive;return y=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:y,parentName:e.componentName,parentCreatesNewNamespace:g,componentInfoObjects:n}).serializedComponents,{replacements:y}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n}){let r=[],a=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n})).replacements,i=a.length,s=!0;if(i===e.replacements.length){s=!1;for(let t=0;t({children:{dependencyType:"child",childGroups:["anything"],variableNames:["width"]},columns:{dependencyType:"stateVariable",variableName:"columns"}}),definition:function({dependencyValues:e}){let t=[],n=e.children.map((e=>e.stateValues.width));if(null!==e.columns){let r;if(-1!==e.columns.indexOf(","))r=e.columns.split(",").map(Number);else if(-1!==e.columns.indexOf("-")){let[t,n]=e.columns.split("-");r=[];for(let e=Number(t);e<=n;e++)r.push(e)}else r=[Number(e.columns)];let a={},i={};for(let e of r){let t=[],r=0;for(let a=0;ai&&(i=n[t]);t.push(i),r+=Number(i)}a[e]=t,i[e]=r}let s=-1;for(let e of r){let e=Number.POSITIVE_INFINITY,n=-1;for(let t of r)i[t]<=e&&t>s&&(e=i[t],n=t);e=this.state.threshold?{}:{variables:{x1:p,x2:d},constraintIndices:[i+1],constrained:!0}}}class ConditionalContent extends CompositeComponent{static componentType="conditionalContent";static includeBlankStringChildren=!0;static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];let n=t.componentIsSpecifiedType,r=[];for(let[t,a]of e.children.entries())n(a,"case")||n(a,"else")||r.push(t);return r}static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.maximumNumberToShow={createComponentOfType:"number",createStateVariable:"maximumNumberToShow",defaultValue:null,public:!0},e.condition={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"cases",componentTypes:["case"]},{group:"elses",componentTypes:["else"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.baseConditionSatisfied={returnDependencies:()=>({conditionAttr:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=!0;return e.conditionAttr&&(t=e.conditionAttr.stateValues.value),{setValue:{baseConditionSatisfied:t}}}},e.nCases={additionalStateVariablesDefined:["caseChildren"],returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"]}}),definition:({dependencyValues:e})=>({setValue:{caseChildren:e.caseChildren,nCases:e.caseChildren.length}})},e.elseChild={returnDependencies:()=>({elseChild:{dependencyType:"child",childGroups:["elses"]}}),definition({dependencyValues:e}){let t=null;return e.elseChild.length>0&&(t=e.elseChild[0]),{setValue:{elseChild:t}}}},e.haveCasesOrElse={returnDependencies:()=>({nCases:{dependencyType:"stateVariable",variableName:"nCases"},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"}}),definition:({dependencyValues:e})=>({setValue:{haveCasesOrElse:e.nCases>0||null!==e.elseChild}})},e.selectedIndices={returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"],variableNames:["conditionSatisfied"]},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"},maximumNumberToShow:{dependencyType:"stateVariable",variableName:"maximumNumberToShow"}}),definition({dependencyValues:e}){let t=[];for(let[n,r]of e.caseChildren.entries())r.stateValues.conditionSatisfied&&t.push(n);if(0===t.length&&e.elseChild&&t.push(e.caseChildren.length),null!==e.maximumNumberToShow&&t.length>e.maximumNumberToShow){let n=Math.max(0,Math.floor(e.maximumNumberToShow));t=t.slice(0,n)}return{setValue:{selectedIndices:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({baseConditionSatisfied:{dependencyType:"stateVariable",variableName:"baseConditionSatisfied"},haveCasesOrElse:{dependencyType:"stateVariable",variableName:"haveCasesOrElse"},selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r}){let a=await this.getReplacements(e,t,r);return n.previousSelectedIndices=[...await e.stateValues.selectedIndices],n.previousBaseConditionSatisfied=await e.stateValues.baseConditionSatisfied,{replacements:a}}static async getReplacements(e,t,n){if(!await e.stateValues.baseConditionSatisfied)return[];let r=[];if(await e.stateValues.haveCasesOrElse){let n=await e.stateValues.caseChildren;for(let[a,i]of(await e.stateValues.selectedIndices).entries()){let s,o,l;ie===i[t]))){if(r.previousBaseConditionSatisfied===s)return[];if(!s){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};return r.previousBaseConditionSatisfied=s,[t]}if(e.replacements.length===e.serializedChildren.length){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};return r.previousBaseConditionSatisfied=s,[e]}}let o=[],l=await this.getReplacements(e,n,a),u={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:l,replacementsToWithhold:0};return o.push(u),r.previousSelectedIndices=[...i],r.previousBaseConditionSatisfied=s,o}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;if(this.serializedChildren){let t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n)}return e}}class AsList extends InlineComponent{static componentType="asList";static renderChildren=!0;static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{text:t.join(", ")}}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.latex?t.push(n.stateValues.latex):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{latex:t.join(", ")}}}},e}}function normalizeIndex(e){if(null!==e&&""!==e){if(Number.isFinite(Number(e)))return Number(e)-1;if("string"==typeof e)return lettersToNumber(e)}}function lettersToNumber(e){let t=0,n=(e=e.toUpperCase()).length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t--,t} +let n=poly_div(e,[t]),r=0,a=n[0].length;for(var i=0;i15?n:(t=Math.round(t),round_numbers_to_precision_sub(n,t))}const round_numbers_to_precision_sub=function(e,t=14){if("number"==typeof e&&Number.isFinite(e)&&0!==e){const n=math$1.floor(math$1.log10(math$1.abs(e))),r=t-n-1;return r<0?parseFloat(toFixed(e,r)+"0".repeat(math$1.abs(r))):parseFloat(toFixed(e,r))}return Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_precision_sub(e,t)))]:e};function round_numbers_to_decimals(e,t=14){var n=get_tree(e);if(!Number.isFinite(t))throw Error("For round_numbers_to_decimals, ndecimals must be a number");return t=Math.round(t),t=Math.max(-330,Math.min(330,t)),round_numbers_to_decimals_sub(n,t)}const round_numbers_to_decimals_sub=function(e,t=0){return"number"==typeof e?t<0?parseFloat(toFixed(e,t)+"0".repeat(math$1.abs(t))):parseFloat(toFixed(e,t)):Array.isArray(e)?[e[0],...e.slice(1).map((e=>round_numbers_to_decimals_sub(e,t)))]:e};var round=Object.freeze({__proto__:null,round_numbers_to_precision:round_numbers_to_precision,round_numbers_to_decimals:round_numbers_to_decimals});const match=function(e,t,n){let r=get_tree(e),a=get_tree(t);return match$2(r,a,n)};var match$1=Object.freeze({__proto__:null,match:match});const expression_to_tree$1=[simplify$1,differentiation,normalization,arithmetic,transformation,solve,sets,matrix$1,rational,round],expression_to_other=[variables$1,printing,equality,integration,evaluation,analytic,sign_error,match$1];function abs(e){return["apply","abs",get_tree(e)]}function exp(e){return["apply","exp",get_tree(e)]}function log(e){return["apply","log",get_tree(e)]}function log10(e){return["apply","log10",get_tree(e)]}function sign(e){return["apply","sign",get_tree(e)]}function sqrt(e){return["apply","sqrt",get_tree(e)]}function conj(e){return["apply","conj",get_tree(e)]}function im(e){return["apply","im",get_tree(e)]}function re(e){return["apply","re",get_tree(e)]}function factorial(e){return["apply","factorial",get_tree(e)]}function gamma(e){return["apply","gamma",get_tree(e)]}function erf(e){return["apply","erf",get_tree(e)]}function acos(e){return["apply","acos",get_tree(e)]}function acosh(e){return["apply","acosh",get_tree(e)]}function acot(e){return["apply","acot",get_tree(e)]}function acoth(e){return["apply","acoth",get_tree(e)]}function acsc(e){return["apply","acsc",get_tree(e)]}function acsch(e){return["apply","acsch",get_tree(e)]}function asec(e){return["apply","asec",get_tree(e)]}function asech(e){return["apply","asech",get_tree(e)]}function asin(e){return["apply","asin",get_tree(e)]}function asinh(e){return["apply","asinh",get_tree(e)]}function atan(e){return["apply","atan",get_tree(e)]}function atanh(e){return["apply","atanh",get_tree(e)]}function cos(e){return["apply","cos",get_tree(e)]}function cosh(e){return["apply","cosh",get_tree(e)]}function cot(e){return["apply","cot",get_tree(e)]}function coth(e){return["apply","coth",get_tree(e)]}function csc(e){return["apply","csc",get_tree(e)]}function csch(e){return["apply","csch",get_tree(e)]}function sec(e){return["apply","sec",get_tree(e)]}function sech(e){return["apply","sech",get_tree(e)]}function sin(e){return["apply","sin",get_tree(e)]}function sinh(e){return["apply","sinh",get_tree(e)]}function tan(e){return["apply","tan",get_tree(e)]}function tanh(e){return["apply","tanh",get_tree(e)]}function atan2(e,t){return["apply","atan2",["tuple",get_tree(e),get_tree(t)]]}var standard=Object.freeze({__proto__:null,abs:abs,exp:exp,log:log,log10:log10,sign:sign,sqrt:sqrt,conj:conj,im:im,re:re,factorial:factorial,gamma:gamma,erf:erf,acos:acos,acosh:acosh,acot:acot,acoth:acoth,acsc:acsc,acsch:acsch,asec:asec,asech:asech,asin:asin,asinh:asinh,atan:atan,atanh:atanh,cos:cos,cosh:cosh,cot:cot,coth:coth,csc:csc,csch:csch,sec:sec,sech:sech,sin:sin,sinh:sinh,tan:tan,tanh:tanh,atan2:atan2});const expression_to_tree=[standard],whitespace_rule="\\s|\\\\,|\\\\!|\\\\ |\\\\>|\\\\;|\\\\:|\\\\quad\\b|\\\\qquad\\b",sci_notat_exp_regex="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))?",number_rules_sci=[["[0-9]+(\\.[0-9]*)?"+sci_notat_exp_regex,"NUMBER"],["\\.[0-9]+"+sci_notat_exp_regex,"NUMBER"]],number_rules_non_sci=[["[0-9]+(\\.[0-9]*)?","NUMBER"],["\\.[0-9]+","NUMBER"]],base_latex_rules=[["\\*","*"],["\\/","/"],["-","-"],["\\+","+"],["\\^","^"],["\\(","("],["\\\\left\\s*\\(","("],["\\\\bigl\\s*\\(","("],["\\\\Bigl\\s*\\(","("],["\\\\biggl\\s*\\(","("],["\\\\Biggl\\s*\\(","("],["\\)",")"],["\\\\right\\s*\\)",")"],["\\\\bigr\\s*\\)",")"],["\\\\Bigr\\s*\\)",")"],["\\\\biggr\\s*\\)",")"],["\\\\Biggr\\s*\\)",")"],["\\[","["],["\\\\left\\s*\\[","["],["\\\\bigl\\s*\\[","["],["\\\\Bigl\\s*\\[","["],["\\\\biggl\\s*\\[","["],["\\\\Biggl\\s*\\[","["],["\\]","]"],["\\\\right\\s*\\]","]"],["\\\\bigr\\s*\\]","]"],["\\\\Bigr\\s*\\]","]"],["\\\\biggr\\s*\\]","]"],["\\\\Biggr\\s*\\]","]"],["\\|","|"],["\\\\left\\s*\\|","|L"],["\\\\bigl\\s*\\|","|L"],["\\\\Bigl\\s*\\|","|L"],["\\\\biggl\\s*\\|","|L"],["\\\\Biggl\\s*\\|","|L"],["\\\\right\\s*\\|","|"],["\\\\bigr\\s*\\|","|"],["\\\\Bigr\\s*\\|","|"],["\\\\biggr\\s*\\|","|"],["\\\\Biggr\\s*\\|","|"],["\\\\big\\s*\\|","|"],["\\\\Big\\s*\\|","|"],["\\\\bigg\\s*\\|","|"],["\\\\Bigg\\s*\\|","|"],["{","{"],["}","}"],["\\\\{","LBRACE"],["\\\\left\\s*\\\\{","LBRACE"],["\\\\bigl\\s*\\\\{","LBRACE"],["\\\\Bigl\\s*\\\\{","LBRACE"],["\\\\biggl\\s*\\\\{","LBRACE"],["\\\\Biggl\\s*\\\\{","LBRACE"],["\\\\}","RBRACE"],["\\\\right\\s*\\\\}","RBRACE"],["\\\\bigr\\s*\\\\}","RBRACE"],["\\\\Bigr\\s*\\\\}","RBRACE"],["\\\\biggr\\s*\\\\}","RBRACE"],["\\\\Biggr\\s*\\\\}","RBRACE"],["\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\left\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Bigl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\Biggl\\s*\\\\lfloor(?![a-zA-Z])","LFLOOR"],["\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\right\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Bigr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\Biggr\\s*\\\\rfloor(?![a-zA-Z])","RFLOOR"],["\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\left\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Bigl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\Biggl\\s*\\\\lceil(?![a-zA-Z])","LCEIL"],["\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\right\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Bigr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\Biggr\\s*\\\\rceil(?![a-zA-Z])","RCEIL"],["\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\left\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Bigl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\Biggl\\s*\\\\langle(?![a-zA-Z])","LANGLE"],["\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\right\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Bigr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\Biggr\\s*\\\\rangle(?![a-zA-Z])","RANGLE"],["\\\\cdot(?![a-zA-Z])","*"],["\\\\div(?![a-zA-Z])","/"],["\\\\times(?![a-zA-Z])","*"],[",",","],[":",":"],["\\\\mid(?![a-zA-Z])","MID"],["\\\\vartheta(?![a-zA-Z])","LATEXCOMMAND","\\theta"],["\\\\varepsilon(?![a-zA-Z])","LATEXCOMMAND","\\epsilon"],["\\\\varrho(?![a-zA-Z])","LATEXCOMMAND","\\rho"],["\\\\varphi(?![a-zA-Z])","LATEXCOMMAND","\\phi"],["\\\\infty(?![a-zA-Z])","INFINITY"],["\\\\asin(?![a-zA-Z])","LATEXCOMMAND","\\arcsin"],["\\\\acos(?![a-zA-Z])","LATEXCOMMAND","\\arccos"],["\\\\atan(?![a-zA-Z])","LATEXCOMMAND","\\arctan"],["\\\\sqrt(?![a-zA-Z])","SQRT"],["\\\\land(?![a-zA-Z])","AND"],["\\\\wedge(?![a-zA-Z])","AND"],["\\\\lor(?![a-zA-Z])","OR"],["\\\\vee(?![a-zA-Z])","OR"],["\\\\lnot(?![a-zA-Z])","NOT"],["=","="],["\\\\neq(?![a-zA-Z])","NE"],["\\\\ne(?![a-zA-Z])","NE"],["\\\\not\\s*=","NE"],["\\\\leq(?![a-zA-Z])","LE"],["\\\\le(?![a-zA-Z])","LE"],["\\\\geq(?![a-zA-Z])","GE"],["\\\\ge(?![a-zA-Z])","GE"],["<","<"],["\\\\lt(?![a-zA-Z])","<"],[">",">"],["\\\\gt(?![a-zA-Z])",">"],["\\\\forall(?![a-zA-Z])","FORALL"],["\\\\exists(?![a-zA-Z])","EXISTS"],["\\\\in(?![a-zA-Z])","IN"],["\\\\notin(?![a-zA-Z])","NOTIN"],["\\\\not\\s*\\\\in(?![a-zA-Z])","NOTIN"],["\\\\ni(?![a-zA-Z])","NI"],["\\\\not\\s*\\\\ni(?![a-zA-Z])","NOTNI"],["\\\\subset(?![a-zA-Z])","SUBSET"],["\\\\subseteq(?![a-zA-Z])","SUBSETEQ"],["\\\\not\\s*\\\\subset(?![a-zA-Z])","NOTSUBSET"],["\\\\not\\s*\\\\subseteq(?![a-zA-Z])","NOTSUBSETEQ"],["\\\\supset(?![a-zA-Z])","SUPERSET"],["\\\\supseteq(?![a-zA-Z])","SUPERSETEQ"],["\\\\not\\s*\\\\supset(?![a-zA-Z])","NOTSUPERSET"],["\\\\not\\s*\\\\supseteq(?![a-zA-Z])","NOTSUPERSETEQ"],["\\\\cup(?![a-zA-Z])","UNION"],["\\\\cap(?![a-zA-Z])","INTERSECT"],["\\\\perp(?![a-zA-Z])","PERP"],["\\\\bot(?![a-zA-Z])","PERP"],["\\\\parallel(?![a-zA-Z])","PARALLEL"],["\\\\\\|","PARALLEL"],["\\\\angle(?![a-zA-Z])","ANGLE"],["\\\\int(?![a-zA-Z])","INT"],["!","!"],["'","'"],["_","_"],["&","&"],["\\\\ldots(?![a-zA-Z])","LDOTS"],["\\\\\\\\","LINEBREAK"],["\\\\begin\\s*{\\s*[a-zA-Z0-9]+\\s*}","BEGINENVIRONMENT"],["\\\\end\\s*{\\s*[a-zA-Z0-9]+\\s*}","ENDENVIRONMENT"],["\\\\operatorname\\s*{\\s*[a-zA-Z0-9\\+\\-]+\\s*}","VARMULTICHAR"],["\\\\[a-zA-Z]+(?![a-zA-Z])","LATEXCOMMAND"],["\\\\[$%]","LATEXCOMMAND"],["[a-zA-Z_$%]","VAR"]],allowSimplifiedFunctionApplicationDefault=!0,allowedLatexSymbolsDefault=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","angle","circ","%","$"],appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","conj","Re","Im","det","trace","nPr","nCr","floor","ceil","round"],functionSymbolsDefault=["f","g"],operatorSymbolsDefault={frac:{nargs:2,substitute:"/"},binom:{nargs:2},vec:{nargs:1},overline:{nargs:1,substitute:"linesegment",remove_products:!0}},unitsDefault=get_all_units();unitsDefault.circ=unitsDefault.deg,unitsDefault.circ.substitute="deg",unitsDefault.circ.isExponent=!0,delete unitsDefault.deg;const parseLeibnizNotationDefault=!0;class latexToAst$1{constructor({allowSimplifiedFunctionApplication:e=allowSimplifiedFunctionApplicationDefault,allowedLatexSymbols:t=allowedLatexSymbolsDefault,appliedFunctionSymbols:n=appliedFunctionSymbolsDefault,functionSymbols:r=functionSymbolsDefault,operatorSymbols:a=operatorSymbolsDefault,units:i=unitsDefault,parseLeibnizNotation:s=parseLeibnizNotationDefault,parseScientificNotation:o=!0}={}){this.allowSimplifiedFunctionApplication=e,this.allowedLatexSymbols=t,this.appliedFunctionSymbols=n,this.functionSymbols=r,this.operatorSymbols=a,this.units=i,this.parseLeibnizNotation=s;let l=base_latex_rules;l=o?[...number_rules_sci,...l]:[...number_rules_non_sci,...l],this.lexer=new lexer(l,whitespace_rule)}advance(e){if(this.token=this.lexer.advance(e),"INVALID"===this.token.token_type)throw new ParseError("Invalid symbol '"+this.token.original_text+"'",this.lexer.location)}return_state(){return{lexer_state:this.lexer.return_state(),token:Object.assign({},this.token)}}set_state(e){this.lexer.set_state(e.lexer_state),this.token=Object.assign({},e.token)}convert(e){this.lexer.set_input(e),this.advance();var t=this.statement_list();if("EOF"!==this.token.token_type)throw new ParseError("Invalid location of '"+this.token.original_text+"'",this.lexer.location);return flatten(t)}statement_list(){for(var e=[this.statement()];","===this.token.token_type;)this.advance(),e.push(this.statement());return e.length>1?["list"].concat(e):e[0]}statement({inside_absolute_value:e=0}={}){if("LDOTS"===this.token.token_type)return this.advance(),["ldots"];var t;try{t=this.return_state();let n=this.statement_a({inside_absolute_value:e});if(":"!==this.token.token_type&&"MID"!==this.token.token_type)return n;let r=":"===this.token.token_type?":":"|";return this.advance(),[r,n,this.statement_a()]}catch(e){try{this.set_state(t);let n=this.statement_a({parse_absolute_value:!1});if("|"!==this.token.token_type[0])throw e;return this.advance(),["|",n,this.statement_a({parse_absolute_value:!1})]}catch(t){throw e}}}statement_a({inside_absolute_value:e=0,parse_absolute_value:t=!0}={}){for(var n=this.statement_b({inside_absolute_value:e,parse_absolute_value:t});"OR"===this.token.token_type;){let r=this.token.token_type.toLowerCase();this.advance(),n=[r,n,this.statement_b({inside_absolute_value:e,parse_absolute_value:t})]}return n}statement_b(e){for(var t=this.relation(e);"AND"===this.token.token_type;){let n=this.token.token_type.toLowerCase();this.advance(),t=[n,t,this.relation(e)]}return t}relation(e){if("NOT"===this.token.token_type||"!"===this.token.token_type)return this.advance(),["not",this.relation(e)];if("FORALL"===this.token.token_type||"EXISTS"===this.token.token_type){let t=this.token.token_type.toLowerCase();return this.advance(),[t,this.relation(e)]}for(var t=this.expression(e);"="===this.token.token_type||"NE"===this.token.token_type||"<"===this.token.token_type||">"===this.token.token_type||"LE"===this.token.token_type||"GE"===this.token.token_type||"IN"===this.token.token_type||"NOTIN"===this.token.token_type||"NI"===this.token.token_type||"NOTNI"===this.token.token_type||"SUBSET"===this.token.token_type||"NOTSUBSET"===this.token.token_type||"SUBSETEQ"===this.token.token_type||"NOTSUBSETEQ"===this.token.token_type||"SUPERSET"===this.token.token_type||"NOTSUPERSET"===this.token.token_type||"SUPERSETEQ"===this.token.token_type||"NOTSUPERSETEQ"===this.token.token_type;){let n=this.token.token_type.toLowerCase(),r=0;"<"===this.token.token_type||"LE"===this.token.token_type?r=-1:">"!==this.token.token_type&&"GE"!==this.token.token_type||(r=1),this.advance();let a=this.expression(e);if(-1===r)if("<"===this.token.token_type||"LE"===this.token.token_type){let r=["tuple"];"<"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;"<"===this.token.token_type||"LE"===this.token.token_type;)"<"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["lts",i,r]}else t=[n,t,a];else if(1===r)if(">"===this.token.token_type||"GE"===this.token.token_type){let r=["tuple"];">"===n?r.push(!0):r.push(!1);let i=["tuple",t,a];for(;">"===this.token.token_type||"GE"===this.token.token_type;)">"===this.token.token_type?r.push(!0):r.push(!1),this.advance(),i.push(this.expression(e));t=["gts",i,r]}else t=[n,t,a];else if("="===n)for(t=["=",t,a];"="===this.token.token_type;)this.advance(),t.push(this.expression(e));else t=[n,t,a]}return t}expression(e){let t=!1;"+"===this.token.token_type&&(t=!0,this.advance());let n=!1;"-"===this.token.token_type&&(n=!0,this.advance());var r=this.term(e);if(n||t){if(!1===r)return(t?"+":"")+(n?"-":"");if("string"==typeof r&&[...r].every((e=>["+","-"].includes(e))))return(t?"+":"")+(n?"-":"")+r}for(!1===r&&(r="_"),n&&(r=r>0?-r:["-",r]),t&&(r=["+",r]);["+","-","UNION","INTERSECT","PERP","PARALLEL"].includes(this.token.token_type);){let t=this.token.token_type.toLowerCase(),n=!1,a=!1;"-"===this.token.token_type?(t="+",n=!0,this.advance()):(this.advance(),"+"===t&&"-"===this.token.token_type&&(n=!0,a=!0,this.advance()));let i=this.term(e);if("+"===t){if(!1===i&&("number"==typeof r||"string"==typeof r))return a?r+"+-":n?r+"-":r+"+";if("string"==typeof i&&[...i].every((e=>["+","-"].includes(e)))&&("number"==typeof r||"string"==typeof r))return a?r+"+-"+i:n?r+"-"+i:r+"+"+i}!1===i&&(i="_"),n&&(i=i>0?-i:["-",i]),r=[t,r,i]}return r}term(e){var t=this.factor(e),n=!1;do{if(n=!1,"*"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["*",t,r],n=!0}else if("/"===this.token.token_type){this.advance(),!1===t&&(t="_");let r=this.factor(e);!1===r&&(r="_"),t=["/",t,r],n=!0}else{let r=Object.assign({},e);r.allow_absolute_value_closing=!0;let a=this.nonMinusFactor(r);!1!==a&&(!1===t&&(t="_"),t=["*",t,a],n=!0)}}while(n);return this.convert_units_in_term(flatten(t))}convert_units_in_term(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);if("*"===t){let e=n.length;for(let[t,r]of n.entries()){let a=this.units[r];if(a){if(a.prefix&&t0){let i,s=r;return a.substitute&&(s=a.substitute),i=1===t?["unit",n[0],s]:["unit",["*",...n.slice(0,t).map(this.convert_units_in_term.bind(this))],s],t===e-1?i:this.convert_units_in_term(["*",i,...n.slice(t+1)])}}}return[t,...n.map(this.convert_units_in_term.bind(this))]}if("/"===t)return["/",this.convert_units_in_term(n[0]),this.convert_units_in_term(n[1])];if("^"===t){let e=this.units[n[1]];if(e&&e.isExponent){let t=n[1];return e.substitute&&(t=e.substitute),["unit",n[0],t]}return[t,...n.map(this.convert_units_in_term.bind(this))]}return[t,...n.map(this.convert_units_in_term.bind(this))]}factor(e){if("+"===this.token.token_text){this.advance();let t=this.factor(e);return!1===t?"+":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"+"+t:["+",t]}if("-"===this.token.token_type){this.advance();let t=this.factor(e);return t>0?-t:!1===t?"-":"string"==typeof t&&[...t].every((e=>["+","-"].includes(e)))?"-"+t:["-",t]}let t=this.nonMinusFactor(e);return!1===t&&"PERP"===this.token.token_type&&(t="perp",this.advance()),t}nonMinusFactor(e){for(var t=this.baseFactor(e);"^"===this.token.token_type||"!"===this.token.token_type||"'"===this.token.token_type;)!1===t&&(t="_"),"^"===this.token.token_type?(this.advance(),t=["^",t,this.get_subsuperscript(e)]):"!"===this.token.token_type?(t=["apply","factorial",t],this.advance()):(t=["prime",t],this.advance());return t}get_single_digit_as_number(){if("NUMBER"===this.token.token_type&&"."!==this.token.token_text[0]){let e=Number(this.token.token_text[0]);return this.token.token_text.length>1&&this.lexer.unput(this.token.token_text.slice(1)),this.advance(),e}return null}get_subsuperscript({parse_absolute_value:e}){let t=this.get_single_digit_as_number();if(null!==t)return t;if(["+","-","PERP"].includes(this.token.token_type)){let e=this.token.token_type.toLowerCase();return this.advance(),e}{let t=this.baseFactor({parse_absolute_value:e,in_subsuperscript_with_no_delimiters:!0});return!1===t&&(t="_"),t}}baseFactor({inside_absolute_value:e=0,parse_absolute_value:t=!0,allow_absolute_value_closing:n=!1,in_subsuperscript_with_no_delimiters:r=!1}={}){var a=!1;if("BEGINENVIRONMENT"===this.token.token_type){let e=/\\begin\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1];if(["matrix","pmatrix","bmatrix"].includes(e)){let n=0,r=0,i=[],s=[],o=0,l=this.token.token_type;for(this.advance();"ENDENVIRONMENT"!==this.token.token_type;)"&"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),l=this.token.token_type,this.advance()):"LINEBREAK"===this.token.token_type?("&"!==l&&"LINEBREAK"!==l||(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,o=0,s=[],l=this.token.token_type,this.advance()):(s.push(this.statement({parse_absolute_value:t})),o+=1,l=" ");if(/\\end\s*{\s*([a-zA-Z0-9]+)\s*}/.exec(this.token.token_text)[1]!==e)throw new ParseError("Expecting \\end{"+e+"}",this.lexer.location);"&"===l&&(s.push(0),o+=1),i.push(s),o>r&&(r=o),n+=1,this.advance(),a=["matrix",["tuple",n,r]];let u=["tuple"];for(let e of i){let t=["tuple"].concat(e);for(let n=e.length;n=2?a[0]="("===n||"{"===n?"tuple":"["===n?"array":"LBRACE"===n?"set":"altvector":"LBRACE"===n&&("|"===a[0]||a[0],a=["set",a]);this.advance()}else if("|"!==this.token.token_type[0]||!t||0!==e&&n&&"L"!==this.token.token_type[1]){if("LFLOOR"===this.token.token_type||"LCEIL"===this.token.token_type){let e,t;if("LFLOOR"===this.token.token_type?(e="RFLOOR",t="floor"):"LCEIL"===this.token.token_type&&(e="RCEIL",t="ceil"),this.advance(),a=["apply",t,a=this.statement()],this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance()}else if("ANGLE"===this.token.token_type)if(this.advance(),"{"===this.token.token_type||"("===this.token.token_type){let e;e="{"===this.token.token_type?"}":")",this.advance();let t=this.statement_list();if(this.token.token_type!==e)throw new ParseError("Expecting "+e,this.lexer.location);this.advance(),"list"===t[0]?a=["angle",...t.slice(1)]:"*"===t[0]&&(a=["angle",t])}else{let e=[],n=this.nonMinusFactor({parse_absolute_value:t});for(;!1!==n;)e.push(n),n=this.nonMinusFactor({parse_absolute_value:t});a=0===e.length?"angle":["angle",...e]}else if("INT"===this.token.token_type){this.advance();let e="int";"_"===this.token.token_type&&(this.advance(),e=["_",e,this.get_subsuperscript({parse_absolute_value:t})]),"^"===this.token.token_type&&(this.advance(),e=["^",e,this.get_subsuperscript({parse_absolute_value:t})]);let n=flatten(this.term({parse_absolute_value:t}));if(Array.isArray(n)&&"*"===n[0]){let e=[];for(let t=0;tn)return!1;if(s===n){if("}"!==this.token.token_type)return!1;this.advance();let s="derivative_leibniz";"∂"===t&&(s="partial_"+s),e=[s],1===n?e.push(r):e.push(["tuple",r,n]);let o=[];for(let e=0;e,larger":function(e){return[">",e[0],e[1]]},"<=,smallerEq":function(e){return["le",e[0],e[1]]},">=,largerEq":function(e){return["ge",e[0],e[1]]},"!=,unequal":function(e){return["ne",e[0],e[1]]},"!,factorial":function(e){return["apply","factorial",e[0]]}};class mathjsToAst{convert(e){if(e.isConstantNode)return e.value;if(e.isSymbolNode)return e.name;if(e.isOperatorNode){var t=[e.op,e.fn].join(",");if(t in operators)return operators[t](e.args.map(function(e,t){return this.convert(e)}.bind(this)));throw Error("Unsupported operator: "+e.op+", "+e.fn)}if(e.isFunctionNode){var n=e.args.map(function(e,t){return this.convert(e)}.bind(this));n=n.length>1?["tuple"].concat(n):n[0];var r=["apply",e.name];return r.push(n),r}if(e.isArrayNode)return["vector"].concat(e.args.map(function(e,t){return this.convert(e)}.bind(this)));if(e.isParenthesisNode)return this.convert(e.content);throw Error("Unsupported node type: "+e.type)}}class mathjsToGuppy{constructor(){this.mathjsToAst=new mathjsToAst,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.mathjsToAst.convert(e))}}class mathjsToLatex{constructor(){this.mathjsToAst=new mathjsToAst,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.mathjsToAst.convert(e))}}class mathjsToText{constructor(){this.mathjsToAst=new mathjsToAst,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.mathjsToAst.convert(e))}}function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n0)return parse$1(e);if("number"===n&&!1===isNaN(e))return t.long?fmtLong(e):fmtShort(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};function parse$1(e){if(!((e=String(e)).length>100)){var t=/^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec(e);if(t){var n=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return n*y;case"days":case"day":case"d":return n*d;case"hours":case"hour":case"hrs":case"hr":case"h":return n*h;case"minutes":case"minute":case"mins":case"min":case"m":return n*m;case"seconds":case"second":case"secs":case"sec":case"s":return n*s;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return n;default:return}}}}function fmtShort(e){return e>=d?Math.round(e/d)+"d":e>=h?Math.round(e/h)+"h":e>=m?Math.round(e/m)+"m":e>=s?Math.round(e/s)+"s":e+"ms"}function fmtLong(e){return plural(e,d,"day")||plural(e,h,"hour")||plural(e,m,"minute")||plural(e,s,"second")||e+" ms"}function plural(e,t,n){if(!(e=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage="undefined"!=typeof chrome&&void 0!==chrome.storage?chrome.storage.local:function(){try{return window.localStorage}catch(e){}}(),t.colors=["lightseagreen","forestgreen","goldenrod","dodgerblue","darkorchid","crimson"],t.formatters.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}},t.enable(n())}(browser,browser.exports);var debug=browser.exports("xml-parser"),xmlParser=parse;function parse(e){return e=(e=e.trim()).replace(//g,""),{declaration:function(){if(n(/^<\?xml\s*/)){for(var e={attributes:{}};!r()&&!a("?>");){var i=t();if(!i)return e;e.attributes[i.name]=i.value}return n(/\?>\s*/),e}}(),root:function i(){debug("tag %j",e);var s=n(/^<([\w-:.]+)\s*/);if(s){for(var o,l={name:s[1],attributes:{},children:[]};!(r()||a(">")||a("?>")||a("/>"));){var u=t();if(!u)return l;l.attributes[u.name]=u.value}if(n(/^\s*\/>\s*/))return l;for(n(/\??>\s*/),l.content=function(){debug("content %j",e);var t=n(/^([^<]*)/);return t?t[1]:""}();o=i();)l.children.push(o);return n(/^<\/[\w-:.]+>\s*/),l}}()};function t(){debug("attribute %j",e);var t,r=n(/([\w:-]+)\s*=\s*("[^"]*"|'[^']*'|\w+)\s*/);if(r)return{name:r[1],value:(t=r[2],t.replace(/^['"]|['"]$/g,""))}}function n(t){var n=e.match(t);if(n)return e=e.slice(n[0].length),n}function r(){return 0==e.length}function a(t){return 0==e.indexOf(t)}}const entities={"Α":"\\Alpha","Α":"\\Alpha","Α":"\\Alpha","\\u0391;":"\\Alpha","Β":"\\Beta","Β":"\\Beta","Β":"\\Beta","\\u0392;":"\\Beta","Γ":"\\Gamma","Γ":"\\Gamma","Γ":"\\Gamma","\\u0393;":"\\Gamma","Δ":"\\Delta","Δ":"\\Delta","Δ":"\\Delta","\\u0394;":"\\Delta","Ε":"\\Epsilon","Ε":"\\Epsilon","Ε":"\\Epsilon","\\u0395;":"\\Epsilon","Ζ":"\\Zeta","Ζ":"\\Zeta","Ζ":"\\Zeta","\\u0396;":"\\Zeta","Η":"\\Eta","Η":"\\Eta","Η":"\\Eta","\\u0397;":"\\Eta","Θ":"\\Theta","Θ":"\\Theta","Θ":"\\Theta","\\u0398;":"\\Theta","Ι":"\\Iota","Ι":"\\Iota","Ι":"\\Iota","\\u0399;":"\\Iota","Κ":"\\Kappa","Κ":"\\Kappa","Κ":"\\Kappa","\\u039A;":"\\Kappa","Λ":"\\Lambda","Λ":"\\Lambda","Λ":"\\Lambda","\\u039B;":"\\Lambda","Μ":"\\Mu","Μ":"\\Mu","Μ":"\\Mu","\\u039C;":"\\Mu","Ν":"\\Nu","Ν":"\\Nu","Ν":"\\Nu","\\u039D;":"\\Nu","Ξ":"\\Xi","Ξ":"\\Xi","Ξ":"\\Xi","\\u039E;":"\\Xi","Ο":"\\Omicron","Ο":"\\Omicron","Ο":"\\Omicron","\\u039F;":"\\Omicron","Π":"\\Pi","Π":"\\Pi","Π":"\\Pi","\\u03A0;":"\\Pi","Ρ":"\\Rho","Ρ":"\\Rho","Ρ":"\\Rho","\\u03A1;":"\\Rho","Σ":"\\Sigma","Σ":"\\Sigma","Σ":"\\Sigma","\\u03A3;":"\\Sigma","Τ":"\\Tau","Τ":"\\Tau","Τ":"\\Tau","\\u03A4;":"\\Tau","Υ":"\\Upsilon","Υ":"\\Upsilon","Υ":"\\Upsilon","\\u03A5;":"\\Upsilon","Φ":"\\Phi","Φ":"\\Phi","Φ":"\\Phi","\\u03A6;":"\\Phi","Χ":"\\Chi","Χ":"\\Chi","Χ":"\\Chi","\\u03A7;":"\\Chi","Ψ":"\\Psi","Ψ":"\\Psi","Ψ":"\\Psi","\\u03A8;":"\\Psi","Ω":"\\Omega","Ω":"\\Omega","Ω":"\\Omega","\\u03A9;":"\\Omega","α":"\\alpha","α":"\\alpha","α":"\\alpha","\\u03B1;":"\\alpha","β":"\\beta","β":"\\beta","β":"\\beta","\\u03B2;":"\\beta","γ":"\\gamma","γ":"\\gamma","γ":"\\gamma","\\u03B3;":"\\gamma","δ":"\\delta","δ":"\\delta","δ":"\\delta","\\u03B4;":"\\delta","ε":"\\epsilon","ε":"\\epsilon","ε":"\\epsilon","\\u03B5;":"\\epsilon","ζ":"\\zeta","ζ":"\\zeta","ζ":"\\zeta","\\u03B6;":"\\zeta","η":"\\eta","η":"\\eta","η":"\\eta","\\u03B7;":"\\eta","θ":"\\theta","θ":"\\theta","θ":"\\theta","\\u03B8;":"\\theta","ι":"\\iota","ι":"\\iota","ι":"\\iota","\\u03B9;":"\\iota","κ":"\\kappa","κ":"\\kappa","κ":"\\kappa","\\u03BA;":"\\kappa","λ":"\\lambda","λ":"\\lambda","λ":"\\lambda","\\u03BB;":"\\lambda","μ":"\\mu","μ":"\\mu","μ":"\\mu","\\u03BC;":"\\mu","ν":"\\nu","ν":"\\nu","ν":"\\nu","\\u03BD;":"\\nu","ξ":"\\xi","ξ":"\\xi","ξ":"\\xi","\\u03BE;":"\\xi","ο":"\\omicron","ο":"\\omicron","ο":"\\omicron","\\u03BF;":"\\omicron","π":"\\pi","π":"\\pi","π":"\\pi","\\u03C0;":"\\pi","ρ":"\\rho","ρ":"\\rho","ρ":"\\rho","\\u03C1;":"\\rho","ς":"\\sigma",";":"\\sigma","ς":"\\sigma","\\u03C2;":"\\sigma","σ":"\\sigma","σ":"\\sigma","σ":"\\sigma","\\u03C3;":"\\sigma","τ":"\\tau","τ":"\\tau","τ":"\\tau","\\u03C4;":"\\tau","υ":"\\upsilon","υ":"\\upsilon","υ":"\\upsilon","\\u03C5;":"\\upsilon","φ":"\\phi","φ":"\\phi","φ":"\\phi","\\u03C6;":"\\phi","χ":"\\chi","χ":"\\chi","χ":"\\chi","\\u03C7;":"\\chi","ψ":"\\psi","ψ":"\\psi","ψ":"\\psi","\\u03C8;":"\\psi","ω":"\\omega","ω":"\\omega","ω":"\\omega","\\u03C9;":"\\omega","−":"-","−":"-","∞":"\\infty","∞":"\\infty","∞":"\\infty","⋅":"\\cdot","⋅":"\\cdot","⋅":"\\cdot","×":"\\times","×":"\\times","×":"\\times"};class mmlToLatex{parse(e){return"mi"===e.name?entities[e.content]?entities[e.content]:e.content.length>1?"\\"+e.content:e.content:"mn"===e.name?e.content:"msup"===e.name?this.parse(e.children[0])+"^{"+this.parse(e.children[1])+"}":"mroot"===e.name?"\\sqrt["+this.parse(e.children[1])+"]{"+this.parse(e.children[1])+"}":"mfrac"===e.name?"\\frac{"+this.parse(e.children[0])+"}{"+this.parse(e.children[1])+"}":"msqrt"===e.name?"\\sqrt{"+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+"}":"mo"===e.name?entities[e.content]?entities[e.content]:"⁡"===e.content?" ":e.content:"mrow"===e.name&&"MJX-TeXAtom-ORD"===e.attributes.class?e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" "):"math"===e.name||"mrow"===e.name?"("+e.children.map(function(e,t){return this.parse(e)}.bind(this)).join(" ")+")":void 0}convert(e){return this.parse(xmlParser(e).root)}}class mmlToAst$1{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1}convert(e){return this.latexToAst.convert(this.mmlToLatex.convert(e))}}class mmlToGuppy{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToMathjs{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class mmlToText{constructor(){this.mmlToLatex=new mmlToLatex,this.latexToAst=new latexToAst$1,this.astToText=new astToText$2}convert(e){return this.astToText.convert(this.latexToAst.convert(this.mmlToLatex.convert(e)))}}class textToGuppy{constructor(){this.textToAst=new textToAst$4,this.astToGuppy=new astToGuppy$1}convert(e){return this.astToGuppy.convert(this.textToAst.convert(e))}}class textToLatex{constructor(){this.textToAst=new textToAst$4,this.astToLatex=new astToLatex$1}convert(e){return this.astToLatex.convert(this.textToAst.convert(e))}}class textToMathjs{constructor(){this.textToAst=new textToAst$4,this.astToMathjs=new astToMathjs$1}convert(e){return this.astToMathjs.convert(this.textToAst.convert(e))}}var converters=Object.freeze({__proto__:null,astToLatexObj:astToLatex$1,astToTextObj:astToText$2,astToGuppyObj:astToGuppy$1,astToMathjsObj:astToMathjs$1,latexToAstObj:latexToAst$1,latexToGuppyObj:latexToGuppy,latexToMathjsObj:latexToMathjs,latexToTextObj:latexToText,mathjsToAstObj:mathjsToAst,mathjsToGuppyObj:mathjsToGuppy,mathjsToLatexObj:mathjsToLatex,mathjsToTextObj:mathjsToText,mmlToAstObj:mmlToAst$1,mmlToGuppyObj:mmlToGuppy,mmlToLatexObj:mmlToLatex,mmlToMathjsObj:mmlToMathjs,mmlToTextObj:mmlToText,textToAstObj:textToAst$4,textToGuppyObj:textToGuppy,textToLatexObj:textToLatex,textToMathjsObj:textToMathjs,astToGLSL:astToGLSL$1}),textToAst=new textToAst$4,latexToAst=new latexToAst$1,mmlToAst=new mmlToAst$1,utils={match:match$2,flatten:flatten$5,unflattenLeft:unflattenLeft,unflattenRight:unflattenRight};function Expression(e,t){this.tree=flatten$5(e),this.context=t,this.toJSON=function(){let e={objectType:"math-expression",tree:this.tree},t={};for(let e in this.context.assumptions)Object.keys(this.context.assumptions[e]).length>0&&(t[e]=this.context.assumptions[e]);return Object.keys(t).length>0&&(e.assumptions=t),e}}function extend(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)t?function(){var t=r;e[t]=function(){return this.fromAst(n[t].apply(null,arguments))}}():e[r]=n[r]})),e}function extend_prototype(e,t){return flatten_array(Array.prototype.slice.call(arguments,2)).forEach((function(n){if(n)for(var r in n)!function(){var a=r;e[a]=function(){var e=[this].concat(Array.prototype.slice.call(arguments));return t?this.context.fromAst(n[a].apply(null,e)):n[a].apply(null,e)}}()})),e}function create_from_multiple(e,t){if(Array.isArray(e)||"number"==typeof e)return new Expression(e,Context);if("string"==typeof e)try{return new Expression(textToAst.convert(e),Context)}catch(t){try{return new Expression(latexToAst.convert(e),Context)}catch(n){try{return new Expression(mmlToAst.convert(e),Context)}catch(r){if(-1!==e.indexOf("\\"))throw n;if(-1!==e.indexOf(">>2]>>>24-i%4*8&255;t[r+i>>>2]|=s<<24-(r+i)%4*8}else for(i=0;i>>2]=n[i>>>2];return this.sigBytes+=a,this},clamp:function(){var t=this.words,n=this.sigBytes;t[n>>>2]&=4294967295<<32-n%4*8,t.length=e.ceil(n/4)},clone:function(){var e=i.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var n,r=[],a=function(t){var n=987654321,r=4294967295;return function(){var a=((n=36969*(65535&n)+(n>>16)&r)<<16)+(t=18e3*(65535&t)+(t>>16)&r)&r;return a/=4294967296,(a+=.5)*(e.random()>.5?1:-1)}},i=0;i>>2]>>>24-a%4*8&255;r.push((i>>>4).toString(16)),r.push((15&i).toString(16))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>3]|=parseInt(e.substr(r,2),16)<<24-r%8*4;return new s.init(n,t/2)}},u=o.Latin1={stringify:function(e){for(var t=e.words,n=e.sigBytes,r=[],a=0;a>>2]>>>24-a%4*8&255;r.push(String.fromCharCode(i))}return r.join("")},parse:function(e){for(var t=e.length,n=[],r=0;r>>2]|=(255&e.charCodeAt(r))<<24-r%4*8;return new s.init(n,t)}},c=o.Utf8={stringify:function(e){try{return decodeURIComponent(escape(u.stringify(e)))}catch(e){throw new Error("Malformed UTF-8 data")}},parse:function(e){return u.parse(unescape(encodeURIComponent(e)))}},p=a.BufferedBlockAlgorithm=i.extend({reset:function(){this._data=new s.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=c.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var n=this._data,r=n.words,a=n.sigBytes,i=this.blockSize,o=a/(4*i),l=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*i,u=e.min(4*l,a);if(l){for(var c=0;c>>31}var p=(r<<5|r>>>27)+l+i[u];p+=u<20?1518500249+(a&s|~a&o):u<40?1859775393+(a^s^o):u<60?(a&s|a&o|s&o)-1894007588:(a^s^o)-899497514,l=o,o=s,s=a<<30|a>>>2,a=r,r=p}n[0]=n[0]+r|0,n[1]=n[1]+a|0,n[2]=n[2]+s|0,n[3]=n[3]+o|0,n[4]=n[4]+l|0},_doFinalize:function(){var e=this._data,t=e.words,n=8*this._nDataBytes,r=8*e.sigBytes;return t[r>>>5]|=128<<24-r%32,t[14+(r+64>>>9<<4)]=Math.floor(n/4294967296),t[15+(r+64>>>9<<4)]=n,e.sigBytes=4*t.length,this._process(),this._hash},clone:function(){var e=r.clone.call(this);return e._hash=this._hash.clone(),e}});e.SHA1=r._createHelper(s),e.HmacSHA1=r._createHmacHelper(s)}(),CryptoJS.SHA1);var sha1=sha1$1.exports,encBase64={exports:{}};!function(e,t){e.exports=function(e){return function(){var t=e,n=t.lib.WordArray;function r(e,t,r){for(var a=[],i=0,s=0;s>>6-s%4*2;a[i>>>2]|=(o|l)<<24-i%4*8,i++}return n.create(a,i)}t.enc.Base64={stringify:function(e){var t=e.words,n=e.sigBytes,r=this._map;e.clamp();for(var a=[],i=0;i>>2]>>>24-i%4*8&255)<<16|(t[i+1>>>2]>>>24-(i+1)%4*8&255)<<8|t[i+2>>>2]>>>24-(i+2)%4*8&255,o=0;o<4&&i+.75*o>>6*(3-o)&63));var l=r.charAt(64);if(l)for(;a.length%4;)a.push(l);return a.join("")},parse:function(e){var t=e.length,n=this._map,a=this._reverseMap;if(!a){a=this._reverseMap=[];for(var i=0;iArray.isArray(t)?e.concat(flattenDeep(t)):e.concat(t)),[])}function flattenLevels(e,t){return console.log(`levels: ${t}`),e.reduce(((e,n)=>Array.isArray(n)&&t>1?e.concat(flattenLevels(n,t-1)):e.concat(n)),[])}class Subset{union(e){return this.complement().intersect(e.complement()).complement()}intersectWithOpenInterval(e){return this.intersect(e)}setMinus(e){return this.intersect(e.complement())}symmetricDifference(e){return this.setMinus(e).union(e.setMinus(this))}equals(e){return this.symmetricDifference(e).isEmpty()}toJSON(){return{objectType:"subset",data:Object.assign({},this),subsetType:this.constructor.subsetType}}static reviver(e,t){if(t&&"subset"===t.objectType&&void 0!==t.subsetType){if("emptySet"===t.subsetType)return new EmptySet;if("realLine"===t.subsetType)return new RealLine;if("singleton"===t.subsetType)return new Singleton(t.data.element);if("union"===t.subsetType)return new Union(t.data.subsets);if("openInterval"===t.subsetType)return new OpenInterval(t.data.left,t.data.right)}return t}copy(){return this.constructor.reviver(null,this.toJSON())}}class EmptySet extends Subset{static subsetType="emptySet";union(e){return e}intersect(){return new EmptySet}contains(){return!1}isEmpty(){return!0}complement(){return new RealLine}toString(){return"∅"}toMathExpression(){return me$3.fromAst("∅")}}class RealLine extends Subset{static subsetType="realLine";union(){return new RealLine}intersect(e){return e}contains(){return!0}complement(){return new EmptySet}isEmpty(){return!1}toString(){return"ℝ"}toMathExpression(){return me$3.fromAst("R")}}class Singleton extends Subset{static subsetType="singleton";constructor(e){if(super(),!Number.isFinite(e))return new EmptySet;this.element=e}union(e){return e.contains(this.element)?e:new Union([e,this])}intersect(e){return e.contains(this.element)?new Singleton(this.element):new EmptySet}isEmpty(){return!1}contains(e){return e===this.element}complement(){return new Union([new OpenInterval(-1/0,this.element),new OpenInterval(this.element,1/0)])}toString(){return`{${this.element}}`}toMathExpression(){return me$3.fromAst(["set",this.element])}}class Union extends Subset{static subsetType="union";intersect(e){return new Union(this.subsets.map((t=>e.intersect(t))))}toString(){return this.subsets.map((e=>e.toString())).join(" U ")}toMathExpression(){return me$3.fromAst(["union",...this.subsets.map((e=>e.toMathExpression().tree))])}constructor(e){super();let t=e.filter((e=>!e.isEmpty()));if(0===t.length)return new EmptySet;t=t.reduce(((e,t)=>t instanceof Union?e.concat(t.subsets):e.concat(t)),[]),this.subsets=[];for(let e=0;ea&&s.elementi.left&&at.contains(e)))}isEmpty(){return this.subsets.every((e=>e.isEmpty()))}complement(){return this.subsets.map((e=>e.complement())).reduce(((e,t)=>e.intersect(t)))}}class Interval$1 extends Subset{constructor(e,t){return super(),this.left=e,this.right=t,this.left<=this.right?this.left===-1/0&&this.right===1/0?new RealLine:this:new EmptySet}}class OpenInterval extends Interval$1{static subsetType="openInterval";constructor(e,t){return super(e,t),e===t?new EmptySet:this}intersect(e){return e.intersectWithOpenInterval(this)}intersectWithOpenInterval(e){return new OpenInterval(Math.max(this.left,e.left),Math.min(this.right,e.right))}complement(){return new Union([new OpenClosedInterval(-1/0,this.left),new ClosedOpenInterval(this.right,1/0)])}isEmpty(){return this.left>=this.right}contains(e){return e>this.left&&ebuildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if("intersect"===n||"and"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new RealLine:n.reduce(((e,t)=>e.intersect(t)))}if("set"===n){let n=e.slice(1).map((e=>buildSubsetFromIntervals(e,t))).filter((e=>e));return 0===n.length?new EmptySet:1===n.length?n[0]:new Union(n)}if(["<","le",">","ge","=","ne"].includes(n)){let r=e[1],a=!1;if(!Number.isFinite(r))if(deepCompare(r,t))a=!0;else if(r=me$3.fromAst(r).evaluate_to_constant(),!Number.isFinite(r)&&r!==1/0&&r!==-1/0)return new EmptySet;let i=e[2],s=!1;if(!Number.isFinite(i))if(deepCompare(i,t))s=!0;else if(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0)return new EmptySet;return a?s?new EmptySet:"<"===n?new OpenInterval(-1/0,i):"le"===n?new OpenClosedInterval(-1/0,i):">"===n?new OpenInterval(i,1/0):"ge"===n?new ClosedOpenInterval(i,1/0):"="===n?Number.isFinite(i)?new Singleton(i):new EmptySet:Number.isFinite(i)?new Union([new OpenInterval(-1/0,i),new OpenInterval(i,1/0)]):new RealLine:s?"<"===n?new OpenInterval(r,1/0):"le"===n?new ClosedOpenInterval(r,1/0):">"===n?new OpenInterval(-1/0,r):"ge"===n?new OpenClosedInterval(-1/0,r):"="===n?Number.isFinite(r)?new Singleton(r):new EmptySet:Number.isFinite(r)?new Union([new OpenInterval(-1/0,r),new OpenInterval(r,1/0)]):new RealLine:new EmptySet}if(["lts","gts"].includes(n)){let r=e[1].slice(1),a=e[2].slice(1);if(3!==r.length||!deepCompare(r[1],t))return new EmptySet;"gts"===n&&(r.reverse(),a.reverse());let i=r[0];if(!Number.isFinite(i)&&(i=me$3.fromAst(i).evaluate_to_constant(),!Number.isFinite(i)&&i!==1/0&&i!==-1/0))return new EmptySet;let s=r[2];return Number.isFinite(s)||(s=me$3.fromAst(s).evaluate_to_constant(),Number.isFinite(s)||s===1/0||s===-1/0)?a[0]?a[1]?new OpenInterval(i,s):new OpenClosedInterval(i,s):a[1]?new ClosedOpenInterval(i,s):new ClosedInterval(i,s):new EmptySet}if("|"===n){let t=e[1];return buildSubsetFromIntervals(e[2],t)}if("^"!==n||"C"!==e[2]&&"c"!==e[2]){if("in"===n)return deepCompare(e[1],t)?buildSubsetFromIntervals(e[2],t):new EmptySet;if("ni"===n)return deepCompare(e[2],t)?buildSubsetFromIntervals(e[1],t):new EmptySet;if("notin"===n){if(deepCompare(e[1],t)){let n=buildSubsetFromIntervals(e[2],t);if(n)return n.complement()}return new EmptySet}if("notni"===n){if(deepCompare(e[2],t)){let n=buildSubsetFromIntervals(e[1],t);if(n)return n.complement()}return new EmptySet}{let t=me$3.fromAst(e).evaluate_to_constant();return Number.isFinite(t)?new Singleton(t):new EmptySet}}{let n=buildSubsetFromIntervals(e[1],t);return n?n.complement():new EmptySet}}function buildSubsetFromMathExpression(e,t){return buildSubsetFromIntervals(e.to_intervals().tree,t.tree)}function deepClone(e,t,n){if(Object(e)!==e||e instanceof Function)return e;if(void 0!==t&&e instanceof t)return e;if(e instanceof me$3.class||e instanceof theModule.Subset)return e.copy();if(void 0===n&&(n=new WeakMap),Array.isArray(e))return[...e.map((e=>deepClone(e,t,n)))];if(e.constructor===Object&&0===Object.entries(e).length)return{};if(n.has(e))return n.get(e);try{var r=new e.constructor}catch(t){r=Object.create(Object.getPrototypeOf(e))}return e instanceof Map?Array.from(e,(([e,a])=>r.set(deepClone(e,t,n),deepClone(a,t,n)))):e instanceof Set&&Array.from(e,(e=>r.add(deepClone(e,t,n)))),n.set(e,r),Object.assign(r,...Object.keys(e).map((r=>({[r]:deepClone(e[r],t,n)}))))}function deepCompare(e,t,n){var r,a;return r=[],a=[],function e(t,i){var s;if(Number.isNaN(t)&&Number.isNaN(i))return!0;if(t===i)return!0;if(void 0!==n&&t instanceof n&&i instanceof n)return t.componentName===i.componentName;if(t instanceof me$3.class&&i instanceof me$3.class)return e(t.tree,i.tree);if("function"==typeof t&&"function"==typeof i||t instanceof Date&&i instanceof Date||t instanceof RegExp&&i instanceof RegExp||t instanceof String&&i instanceof String||t instanceof Number&&i instanceof Number)return t.toString()===i.toString();if(!(t instanceof Object&&i instanceof Object))return!1;if(t.isPrototypeOf(i)||i.isPrototypeOf(t))return!1;if(t.constructor!==i.constructor)return!1;if(t.prototype!==i.prototype)return!1;if(r.indexOf(t)>-1||a.indexOf(i)>-1)return!1;for(s in i){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1}for(s in t){if(i.hasOwnProperty(s)!==t.hasOwnProperty(s))return!1;if(typeof i[s]!=typeof t[s])return!1;switch(typeof t[s]){case"object":case"function":if(r.push(t),a.push(i),!e(t[s],i[s]))return!1;r.pop(),a.pop();break;default:if(!(t[s]===i[s]||Number.isNaN(t[s])&&Number.isNaN(i[s])))return!1}}return!0}(e,t)}function breakStringsAndOthersIntoComponentsByStringCommas(e){return null}function returnBreakStringsSugarFunction({childrenToComponentFunction:e,mustStripOffOuterParentheses:t=!1}){return function({matchedChildren:n}){let r=0,a=[],i=[],s=!1,o=n.length;if(t){let e=n[0];if("string"!=typeof e||"("!==e.trimLeft()[0])return{success:!1}}for(let[e,l]of n.entries()){if("string"!=typeof l){i.push(l);continue}let u=l.trim();if(0===e&&t&&"("===u[0]){let e=n[o-1];if("string"==typeof e){let t=e.trimRight();")"===t[t.length-1]&&(s=!0,u=u.substring(1))}}let c=0;for(let t=0;tc&&i.push(u.substring(c,t)),a.push(i),i=[],c=t+1)}u.length>c&&i.push(u.substring(c,u.length))}return 0!==r?{success:!1}:(a.push(i),{success:!0,newChildren:a.map(e)})}}function breakEmbeddedStringByCommas({childrenList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=e.substring(i,a).trim();r.push(t)}n.push(r),r=[],i=a+1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t?{success:!1}:(n.push(r),{success:!0,pieces:n})}function breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:t=!1}){let n=0,r=[],a=[];for(let i of e){if("string"!=typeof i){0===n?r.push([i]):a.push(i);continue}let e=i.trim(),s=0;for(let i=0;is){let n=t?i:i+1,r=e.substring(s,n).trim();r.length>0&&a.push(r)}r.push(a),a=[],s=i+1}n--}else if(0===n&&!o.match(/\s/))return{success:!1}}if(e.length>s){let t=e.substring(s,e.length).trim();a.push(t)}}return 0!==n?{success:!1}:(a.length>0&&r.push(a),{success:!0,pieces:r})}var global$1="undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};function defaultSetTimout(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout(){throw new Error("clearTimeout has not been defined")}var cachedSetTimeout=defaultSetTimout,cachedClearTimeout=defaultClearTimeout;function runTimeout(e){if(cachedSetTimeout===setTimeout)return setTimeout(e,0);if((cachedSetTimeout===defaultSetTimout||!cachedSetTimeout)&&setTimeout)return cachedSetTimeout=setTimeout,setTimeout(e,0);try{return cachedSetTimeout(e,0)}catch(t){try{return cachedSetTimeout.call(null,e,0)}catch(t){return cachedSetTimeout.call(this,e,0)}}}function runClearTimeout(e){if(cachedClearTimeout===clearTimeout)return clearTimeout(e);if((cachedClearTimeout===defaultClearTimeout||!cachedClearTimeout)&&clearTimeout)return cachedClearTimeout=clearTimeout,clearTimeout(e);try{return cachedClearTimeout(e)}catch(t){try{return cachedClearTimeout.call(null,e)}catch(t){return cachedClearTimeout.call(this,e)}}}"function"==typeof global$1.setTimeout&&(cachedSetTimeout=setTimeout),"function"==typeof global$1.clearTimeout&&(cachedClearTimeout=clearTimeout);var queue=[],draining=!1,currentQueue,queueIndex=-1;function cleanUpNextTick(){draining&¤tQueue&&(draining=!1,currentQueue.length?queue=currentQueue.concat(queue):queueIndex=-1,queue.length&&drainQueue())}function drainQueue(){if(!draining){var e=runTimeout(cleanUpNextTick);draining=!0;for(var t=queue.length;t;){for(currentQueue=queue,queue=[];++queueIndex1)for(var n=1;n{throw new Error("This node type doesn't define a deserialize function")})}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return"function"!=typeof e&&(e=NodeType.match(e)),t=>{let n=e(t);return void 0===n?null:[this,n]}}}NodeProp.closedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.openedBy=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.group=new NodeProp({deserialize:e=>e.split(" ")}),NodeProp.contextHash=new NodeProp({perNode:!0}),NodeProp.lookAhead=new NodeProp({perNode:!0}),NodeProp.mounted=new NodeProp({perNode:!0});const noProps=Object.create(null);class NodeType{constructor(e,t,n,r=0){this.name=e,this.props=t,this.id=n,this.flags=r}static define(e){let t=e.props&&e.props.length?Object.create(null):noProps,n=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(null==e.name?8:0),r=new NodeType(e.name||"",t,e.id,n);if(e.props)for(let n of e.props)if(Array.isArray(n)||(n=n(r)),n){if(n[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[n[0].id]=n[1]}return r}prop(e){return this.props[e.id]}get isTop(){return(1&this.flags)>0}get isSkipped(){return(2&this.flags)>0}get isError(){return(4&this.flags)>0}get isAnonymous(){return(8&this.flags)>0}is(e){if("string"==typeof e){if(this.name==e)return!0;let t=this.prop(NodeProp.group);return!!t&&t.indexOf(e)>-1}return this.id==e}static match(e){let t=Object.create(null);for(let n in e)for(let r of n.split(" "))t[r]=e[n];return e=>{for(let n=e.prop(NodeProp.group),r=-1;r<(n?n.length:0);r++){let a=t[r<0?e.name:n[r]];if(a)return a}}}}NodeType.none=new NodeType("",Object.create(null),0,8);class NodeSet{constructor(e){this.types=e;for(let t=0;te.node;;){let s=!1;if(e.from<=a&&e.to>=r&&(e.type.isAnonymous||!1!==t(e.type,e.from,e.to,i))){if(e.firstChild())continue;e.type.isAnonymous||(s=!0)}for(;s&&n&&n(e.type,e.from,e.to,i),s=e.type.isAnonymous,!e.nextSibling();){if(!e.parent())return;s=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:balanceRange(NodeType.none,this.children,this.positions,0,this.children.length,0,this.length,((e,t,n)=>new Tree(this.type,e,t,n,this.propValues)),e.makeTree||((e,t,n)=>new Tree(NodeType.none,e,t,n)))}static build(e){return buildTree(e)}}Tree.empty=new Tree(NodeType.none,[],[],0);class FlatBufferCursor{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new FlatBufferCursor(this.buffer,this.index)}}class TreeBuffer{constructor(e,t,n){this.buffer=e,this.length=t,this.set=n}get type(){return NodeType.none}toString(){let e=[];for(let t=0;t0));o=i[o+3]);return s}slice(e,t,n,r){let a=this.buffer,i=new Uint16Array(t-e);for(let r=e,s=0;r=t&&nt;case 1:return n<=t&&r>t;case 2:return r>t;case 4:return!0}}function enterUnfinishedNodesBefore(e,t){let n=e.childBefore(t);for(;n;){let t=n.lastChild;if(!t||t.to!=n.to)break;t.type.isError&&t.from==t.to?(e=n,n=t.prevSibling):n=t}return e}function resolveNode(e,t,n,r){for(var a;e.from==e.to||(n<1?e.from>=t:e.from>t)||(n>-1?e.to<=t:e.to0?s.length:-1;e!=l;e+=t){let l=s[e],u=o[e]+i._from;if(checkSide(r,n,u,u+l.length))if(l instanceof TreeBuffer){if(2&a)continue;let s=l.findChild(0,l.buffer.length,t,n-u,r);if(s>-1)return new BufferNode(new BufferContext(i,l,e,u),null,s)}else if(1&a||!l.type.isAnonymous||hasChild(l)){let s;if(!(1&a)&&l.props&&(s=l.prop(NodeProp.mounted))&&!s.overlay)return new TreeNode(s.tree,u,e,i);let o=new TreeNode(l,u,e,i);return 1&a||!o.type.isAnonymous?o:o.nextChild(t<0?l.children.length-1:0,t,n,r)}}if(1&a||!i.type.isAnonymous)return null;if(e=i.index>=0?i.index+t:t<0?-1:i._parent.node.children.length,i=i._parent,!i)return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this.node.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this.node.children.length-1,-1,e,-2)}enter(e,t,n=!0,r=!0){let a;if(n&&(a=this.node.prop(NodeProp.mounted))&&a.overlay){let n=e-this.from;for(let{from:e,to:r}of a.overlay)if((t>0?e<=n:e=n:r>n))return new TreeNode(a.tree,a.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,r?0:2)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get cursor(){return new TreeCursor(this)}get tree(){return this.node}toTree(){return this.node}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}toString(){return this.node.toString()}}function getChildren(e,t,n,r){let a=e.cursor,i=[];if(!a.firstChild())return i;if(null!=n)for(;!a.type.is(n);)if(!a.nextSibling())return i;for(;;){if(null!=r&&a.type.is(r))return i;if(a.type.is(t)&&i.push(a.node),!a.nextSibling())return null==r?i:[]}}class BufferContext{constructor(e,t,n,r){this.parent=e,this.buffer=t,this.index=n,this.start=r}}class BufferNode{constructor(e,t,n){this.context=e,this._parent=t,this.index=n,this.type=e.buffer.set.types[e.buffer.buffer[n]]}get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}child(e,t,n){let{buffer:r}=this.context,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.context.start,n);return a<0?null:new BufferNode(this.context,this,a)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}enter(e,t,n,r=!0){if(!r)return null;let{buffer:a}=this.context,i=a.findChild(this.index+4,a.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return i<0?null:new BufferNode(this.context,this,i)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new BufferNode(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new BufferNode(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get cursor(){return new TreeCursor(this)}get tree(){return null}toTree(){let e=[],t=[],{buffer:n}=this.context,r=this.index+4,a=n.buffer[this.index+3];if(a>r){let i=n.buffer[this.index+1],s=n.buffer[this.index+2];e.push(n.slice(r,a,i,s)),t.push(0)}return new Tree(this.type,e,t,this.to-this.from)}resolve(e,t=0){return resolveNode(this,e,t,!1)}resolveInner(e,t=0){return resolveNode(this,e,t,!0)}enterUnfinishedNodesBefore(e){return enterUnfinishedNodesBefore(this,e)}toString(){return this.context.buffer.childString(this.index)}getChild(e,t=null,n=null){let r=getChildren(this,e,t,n);return r.length?r[0]:null}getChildren(e,t=null,n=null){return getChildren(this,e,t,n)}}class TreeCursor{constructor(e,t=0){if(this.mode=t,this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,e instanceof TreeNode)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let t=e._parent;t;t=t._parent)this.stack.unshift(t.index);this.bufferNode=e,this.yieldBuf(e.index)}}get name(){return this.type.name}yieldNode(e){return!!e&&(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0)}yieldBuf(e,t){this.index=e;let{start:n,buffer:r}=this.buffer;return this.type=t||r.set.types[r.buffer[e]],this.from=n+r.buffer[e+1],this.to=n+r.buffer[e+2],!0}yield(e){return!!e&&(e instanceof TreeNode?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)))}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,n){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree.node.children.length-1:0,e,t,n,this.mode));let{buffer:r}=this.buffer,a=r.findChild(this.index+4,r.buffer[this.index+3],e,t-this.buffer.start,n);return!(a<0)&&(this.stack.push(this.index),this.yieldBuf(a))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,n=!0,r=!0){return this.buffer?!!r&&this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,n&&!(1&this.mode),r))}parent(){if(!this.buffer)return this.yieldNode(1&this.mode?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=1&this.mode?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return!!this._tree._parent&&this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode));let{buffer:t}=this.buffer,n=this.stack.length-1;if(e<0){let e=n<0?0:this.stack[n]+4;if(this.index!=e)return this.yieldBuf(t.findChild(e,this.index,-1,0,4))}else{let e=t.buffer[this.index+3];if(e<(n<0?t.buffer.length:t.buffer[this.stack[n]+3]))return this.yieldBuf(e)}return n<0&&this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode))}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,n,{buffer:r}=this;if(r){if(e>0){if(this.index-1)for(let r=t+e,a=e<0?-1:n.node.children.length;r!=a;r+=e){let e=n.node.children[r];if(1&this.mode||e instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let i=e;i;i=i._parent)if(i.index==r){if(r==this.index)return i;t=i,n=a+1;break e}r=this.stack[--a]}for(let e=n;ee instanceof TreeBuffer||!e.type.isAnonymous||hasChild(e)))}function buildTree(e){var t;let{buffer:n,nodeSet:r,maxBufferLength:a=DefaultBufferLength,reused:i=[],minRepeatType:s=r.types.length}=e,o=Array.isArray(n)?new FlatBufferCursor(n,n.length):n,l=r.types,u=0,c=0;function p(e,t,n,f,y){let{id:g,start:b,end:v,size:N}=o,T=c;for(;N<0;){if(o.next(),-1==N){let t=i[g];return n.push(t),void f.push(b-e)}if(-3==N)return void(u=g);if(-4==N)return void(c=g);throw new RangeError(`Unrecognized record size: ${N}`)}let C,A,V=l[g],x=b-e;if(v-b<=a&&(A=function(e,t){let n=o.fork(),r=0,i=0,l=0,u=n.end-a,c={size:0,start:0,skip:0};e:for(let a=n.pos-e;n.pos>a;){let e=n.size;if(n.id==t&&e>=0){c.size=r,c.start=i,c.skip=l,l+=4,r+=4,n.next();continue}let o=n.pos-e;if(e<0||o=s?4:0,d=n.start;for(n.next();n.pos>o;){if(n.size<0){if(-3!=n.size)break e;p+=4}else n.id>=s&&(p+=4);n.next()}i=d,r+=e,l+=p}(t<0||r==e)&&(c.size=r,c.start=i,c.skip=l);return c.size>4?c:void 0}(o.pos-t,y))){let t=new Uint16Array(A.size-A.skip),n=o.pos-A.size,a=t.length;for(;o.pos>n;)a=h(A.start,t,a);C=new TreeBuffer(t,v-A.start,r),x=A.start-e}else{let e=o.pos-N;o.next();let t=[],n=[],r=g>=s?g:-1,i=0,l=v;for(;o.pos>e;)r>=0&&o.id==r&&o.size>=0?(o.end<=l-a&&(d(t,n,b,i,o.end,l,r,T),i=t.length,l=o.end),o.next()):p(b,e,t,n,r);if(r>=0&&i>0&&i-1&&i>0){let e=function(e){return(t,n,r)=>{let a,i,s=0,o=t.length-1;if(o>=0&&(a=t[o])instanceof Tree){if(!o&&a.type==e&&a.length==r)return a;(i=a.prop(NodeProp.lookAhead))&&(s=n[o]+a.length+i)}return m(e,t,n,r,s)}}(V);C=balanceRange(V,t,n,0,t.length,0,v-b,e,e)}else C=m(V,t,n,v-b,T-v)}n.push(C),f.push(x)}function d(e,t,n,a,i,s,o,l){let u=[],c=[];for(;e.length>a;)u.push(e.pop()),c.push(t.pop()+n-i);e.push(m(r.types[o],u,c,s-i,l-s)),t.push(i-n)}function m(e,t,n,r,a=0,i){if(u){let e=[NodeProp.contextHash,u];i=i?[e].concat(i):[e]}if(a>25){let e=[NodeProp.lookAhead,a];i=i?[e].concat(i):[e]}return new Tree(e,t,n,r,i)}function h(e,t,n){let{id:r,start:a,end:i,size:l}=o;if(o.next(),l>=0&&r4){let r=o.pos-(l-4);for(;o.pos>r;)n=h(e,t,n)}t[--n]=s,t[--n]=i-e,t[--n]=a-e,t[--n]=r}else-3==l?u=r:-4==l&&(c=r);return n}let f=[],y=[];for(;o.pos>0;)p(e.start||0,e.bufferStart||0,f,y,-1);let g=null!==(t=e.length)&&void 0!==t?t:f.length?y[0]+f[0].length:0;return new Tree(l[e.topID],f.reverse(),y.reverse(),g)}const nodeSizeCache=new WeakMap;function nodeSize(e,t){if(!e.isAnonymous||t instanceof TreeBuffer||t.type!=e)return 1;let n=nodeSizeCache.get(t);if(null==n){n=1;for(let r of t.children){if(r.type!=e||!(r instanceof Tree)){n=1;break}n+=nodeSize(e,r)}nodeSizeCache.set(t,n)}return n}function balanceRange(e,t,n,r,a,i,s,o,l){let u=0;for(let n=r;n=c)break;h+=t}if(u==a+1){if(h>c){let e=n[a];t(e.children,e.positions,0,e.children.length,r[a]+o);continue}p.push(n[a])}else{let t=r[u-1]+n[u-1].length-m;p.push(balanceRange(e,n,r,a,u,m,t,null,l))}d.push(m+o-i)}}(t,n,r,a,0),(o||l)(p,d,s)}class Parser$1{startParse(e,t,n){return"string"==typeof e&&(e=new StringInput(e)),n=n?n.length?n.map((e=>new Range(e.from,e.to))):[new Range(0,0)]:[new Range(0,e.length)],this.createParse(e,t||[],n)}parse(e,t,n){let r=this.startParse(e,t,n);for(;;){let e=r.advance();if(e)return e}}}class StringInput{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new NodeProp({perNode:!0});class Stack$1{constructor(e,t,n,r,a,i,s,o,l,u=0,c){this.p=e,this.stack=t,this.state=n,this.reducePos=r,this.pos=a,this.score=i,this.buffer=s,this.bufferBase=o,this.curContext=l,this.lookAhead=u,this.parent=c}toString(){return`[${this.stack.filter(((e,t)=>t%3==0)).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,n=0){let r=e.parser.context;return new Stack$1(e,[],t,n,n,0,[],0,r?new StackContext(r,r.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){let t=e>>19,n=65535&e,{parser:r}=this.p,a=r.dynamicPrecedence(n);if(a&&(this.score+=a),0==t)return this.pushState(r.getGoto(this.state,n,!0),this.reducePos),ni;)this.stack.pop();this.reduceContext(n,s)}storeNode(e,t,n,r=4,a=!1){if(0==e){let e=this,r=this.buffer.length;if(0==r&&e.parent&&(r=e.bufferBase-e.parent.bufferBase,e=e.parent),r>0&&0==e.buffer[r-4]&&e.buffer[r-1]>-1){if(t==n)return;if(e.buffer[r-2]>=t)return void(e.buffer[r-2]=n)}}if(a&&this.pos!=n){let a=this.buffer.length;if(a>0&&0!=this.buffer[a-4])for(;a>0&&this.buffer[a-2]>n;)this.buffer[a]=this.buffer[a-4],this.buffer[a+1]=this.buffer[a-3],this.buffer[a+2]=this.buffer[a-2],this.buffer[a+3]=this.buffer[a-1],a-=4,r>4&&(r-=4);this.buffer[a]=e,this.buffer[a+1]=t,this.buffer[a+2]=n,this.buffer[a+3]=r}else this.buffer.push(e,t,n,r)}shift(e,t,n){let r=this.pos;if(131072&e)this.pushState(65535&e,this.pos);else if(0==(262144&e)){let a=e,{parser:i}=this.p;(n>this.pos||t<=i.maxNode)&&(this.pos=n,i.stateFlag(a,1)||(this.reducePos=n)),this.pushState(a,r),this.shiftContext(t,r),t<=i.maxNode&&this.buffer.push(t,r,n,4)}else this.pos=n,this.shiftContext(t,r),t<=this.p.parser.maxNode&&this.buffer.push(t,r,n,4)}apply(e,t,n){65536&e?this.reduce(e):this.shift(e,t,n)}useNode(e,t){let n=this.p.reused.length-1;(n<0||this.p.reused[n]!=e)&&(this.p.reused.push(e),n++);let r=this.pos;this.reducePos=this.pos=r+e.length,this.pushState(t,r),this.buffer.push(n,r,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(;t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let n=e.buffer.slice(t),r=e.bufferBase+t;for(;e&&r==e.bufferBase;)e=e.parent;return new Stack$1(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,n,r,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let n=e<=this.p.parser.maxNode;n&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,n?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new SimulatedStack(this);;){let n=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(0==(65536&n))return!0;if(0==n)return!1;t.reduce(n)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r,a=0;a1&t&&e==r))||n.push(t[e],r)}t=n}let n=[];for(let e=0;e>19,r=65535&e,a=this.stack.length-3*n;if(a<0||t.getGoto(this.stack[a],r,!1)<0)return!1;this.storeNode(0,this.reducePos,this.reducePos,4,!0),this.score-=100}return this.reduce(e),!0}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(3!=this.stack.length)return!1;let{parser:e}=this.p;return 65535==e.data[e.stateSlot(this.state,1)]&&!e.stateSlot(this.state,4)}restart(){this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;tthis.lookAhead&&(this.emitLookAhead(),this.lookAhead=e)}close(){this.curContext&&this.curContext.tracker.strict&&this.emitContext(),this.lookAhead>0&&this.emitLookAhead()}}class StackContext{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}var Recover;!function(e){e[e.Insert=200]="Insert",e[e.Delete=190]="Delete",e[e.Reduce=100]="Reduce",e[e.MaxNext=4]="MaxNext",e[e.MaxInsertStackDepth=300]="MaxInsertStackDepth",e[e.DampenInsertStackDepth=120]="DampenInsertStackDepth"}(Recover||(Recover={}));class SimulatedStack{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=65535&e,n=e>>19;0==n?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=3*(n-1);let r=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=r}}class StackBufferCursor{constructor(e,t,n){this.stack=e,this.pos=t,this.index=n,this.buffer=e.buffer,0==this.index&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new StackBufferCursor(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;null!=e&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,0==this.index&&this.maybeNext()}fork(){return new StackBufferCursor(this.stack,this.pos,this.index)}}class CachedToken{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const nullToken=new CachedToken;class InputStream{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=nullToken,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let n=this.range,r=this.rangeIndex,a=this.pos+e;for(;an.to:a>=n.to;){if(r==this.ranges.length-1)return null;let e=this.ranges[++r];a+=e.from-n.to,n=e}return a}peek(e){let t,n,r=this.chunkOff+e;if(r>=0&&r=this.chunk2Pos&&tr.to&&(this.chunk2=this.chunk2.slice(0,r.to-t)),n=this.chunk2.charCodeAt(0)}}return t>=this.token.lookAhead&&(this.token.lookAhead=t+1),n}acceptToken(e,t=0){let n=t?this.resolveOffset(t,-1):this.pos;if(null==n||n=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=nullToken,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let n="";for(let r of this.ranges){if(r.from>=t)break;r.to>e&&(n+=this.input.read(Math.max(r.from,e),Math.min(r.to,t)))}return n}}class TokenGroup{constructor(e,t){this.data=e,this.id=t}token(e,t){readToken(this.data,e,t,this.id)}}TokenGroup.prototype.contextual=TokenGroup.prototype.fallback=TokenGroup.prototype.extend=!1;class ExternalTokenizer{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function readToken(e,t,n,r){let a=0,i=1<0){let n=e[r];if(o.allows(n)&&(-1==t.token.value||t.token.value==n||s.overrides(n,t.token.value))){t.acceptToken(n);break}}for(let r=t.next,i=0,s=e[a+2];i>1,l=n+o+(o<<1),u=e[l],c=e[l+1];if(r=c)){a=e[l+2],t.advance();continue e}i=o+1}}break}}function decodeArray(e,t=Uint16Array){if("string"!=typeof e)return e;let n=null;for(let r=0,a=0;r=92&&t--,t>=34&&t--;let a=t-32;if(a>=46&&(a-=46,n=!0),i+=a,n)break;i*=46}n?n[a++]=i:n=new t(i)}return n}const verbose=void 0!==browser$1&&/\bparse\b/.test(browser$1.env.LOG);let stackIDs=null;var Safety,Rec;function cutAt(e,t,n){let r=e.fullCursor();for(r.moveTo(t);;)if(!(n<0?r.childBefore(t):r.childAfter(t)))for(;;){if((n<0?r.tot)&&!r.type.isError)return n<0?Math.max(0,Math.min(r.to-1,t-25)):Math.min(e.length,Math.max(r.from+1,t+25));if(n<0?r.prevSibling():r.nextSibling())break;if(!r.parent())return n<0?0:e.length}}!function(e){e[e.Margin=25]="Margin"}(Safety||(Safety={}));class FragmentCursor{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?cutAt(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?cutAt(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=i,null;if(a instanceof Tree){if(i==e){if(i=Math.max(this.safeFrom,e)&&(this.trees.push(a),this.start.push(i),this.index.push(0))}else this.index[t]++,this.nextStart=i+a.length}}}class TokenCache{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map((e=>new CachedToken))}getActions(e){let t=0,n=null,{parser:r}=e.p,{tokenizers:a}=r,i=r.stateSlot(e.state,3),s=e.curContext?e.curContext.hash:0,o=0;for(let r=0;ru.end+25&&(o=Math.max(u.lookAhead,o)),0!=u.value)){let r=t;if(u.extended>-1&&(t=this.addActions(e,u.extended,u.end,t)),t=this.addActions(e,u.value,u.end,t),!l.extend&&(n=u,t>r))break}}for(;this.actions.length>t;)this.actions.pop();return o&&e.setLookAhead(o),n||e.pos!=this.stream.end||(n=new CachedToken,n.value=e.p.parser.eofTerm,n.start=n.end=e.pos,t=this.addActions(e,n.value,n.end,t)),this.mainToken=n,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new CachedToken,{pos:n,p:r}=e;return t.start=n,t.end=Math.min(n+1,r.stream.end),t.value=n==r.stream.end?r.parser.eofTerm:0,t}updateCachedToken(e,t,n){if(t.token(this.stream.reset(n.pos,e),n),e.value>-1){let{parser:t}=n.p;for(let r=0;r=0&&n.p.parser.dialect.allows(a>>1)){0==(1&a)?e.value=a>>1:e.extended=a>>1;break}}}else e.value=0,e.end=Math.min(n.p.stream.end,n.pos+1)}putAction(e,t,n,r){for(let t=0;t4*e.bufferLength?new FragmentCursor(n,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e,t,n=this.stacks,r=this.minStackPos,a=this.stacks=[];for(let i=0;ir)a.push(s);else{if(this.advanceStack(s,a,n))continue;{e||(e=[],t=[]),e.push(s);let n=this.tokens.getMainToken(s);t.push(n.value,n.end)}}break}}if(!a.length){let t=e&&findFinished(e);if(t)return this.stackToTree(t);if(this.parser.strict)throw verbose&&e&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+r);this.recovering||(this.recovering=5)}if(this.recovering&&e){let n=null!=this.stoppedAt&&e[0].pos>this.stoppedAt?e[0]:this.runRecovery(e,t,a);if(n)return this.stackToTree(n.forceAll())}if(this.recovering){let e=1==this.recovering?1:3*this.recovering;if(a.length>e)for(a.sort(((e,t)=>t.score-e.score));a.length>e;)a.pop();a.some((e=>e.reducePos>r))&&this.recovering--}else if(a.length>1)e:for(let e=0;e500&&r.buffer.length>500){if(!((t.score-r.score||t.buffer.length-r.buffer.length)>0)){a.splice(e--,1);continue e}a.splice(n--,1)}}}this.minStackPos=a[0].pos;for(let e=1;e ":"";if(null!=this.stoppedAt&&r>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let t=e.curContext&&e.curContext.tracker.strict,n=t?e.curContext.hash:0;for(let s=this.fragments.nodeAt(r);s;){let r=this.parser.nodeSet.types[s.type.id]==s.type?a.getGoto(e.state,s.type.id):-1;if(r>-1&&s.length&&(!t||(s.prop(NodeProp.contextHash)||0)==n))return e.useNode(s,r),verbose&&console.log(i+this.stackID(e)+` (via reuse of ${a.getName(s.type.id)})`),!0;if(!(s instanceof Tree)||0==s.children.length||s.positions[0]>0)break;let o=s.children[0];if(!(o instanceof Tree&&0==s.positions[0]))break;s=o}}let s=a.stateSlot(e.state,4);if(s>0)return e.reduce(s),verbose&&console.log(i+this.stackID(e)+` (via always-reduce ${a.getName(65535&s)})`),!0;if(e.stack.length>=15e3)for(;e.stack.length>9e3&&e.forceReduce(););let o=this.tokens.getActions(e);for(let s=0;sr?t.push(d):n.push(d)}return!1}advanceFully(e,t){let n=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>n)return pushStackDedup(e,t),!0}}runRecovery(e,t,n){let r=null,a=!1;for(let i=0;i ":"";if(s.deadEnd){if(a)continue;if(a=!0,s.restart(),verbose&&console.log(u+this.stackID(s)+" (restarted)"),this.advanceFully(s,n))continue}let c=s.split(),p=u;for(let e=0;c.forceReduce()&&e<10;e++){if(verbose&&console.log(p+this.stackID(c)+" (via force-reduce)"),this.advanceFully(c,n))break;verbose&&(p=this.stackID(c)+" -> ")}for(let e of s.recoverByInsert(o))verbose&&console.log(u+this.stackID(e)+" (via recover-insert)"),this.advanceFully(e,n);this.stream.end>s.pos?(l==s.pos&&(l++,o=0),s.recoverByDelete(o,l),verbose&&console.log(u+this.stackID(s)+` (via recover-delete ${this.parser.getName(o)})`),pushStackDedup(s,n)):(!r||r.scoree;class ContextTracker{constructor(e){this.start=e.start,this.shift=e.shift||id,this.reduce=e.reduce||id,this.reuse=e.reuse||id,this.hash=e.hash||(()=>0),this.strict=!1!==e.strict}}class LRParser extends Parser$1{constructor(e){if(super(),this.wrappers=[],13!=e.version)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (13)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let n=0;ne.topRules[t][1])),r=[];for(let e=0;e=0)a(r,e,t[n++]);else{let i=t[n+-r];for(let s=-r;s>0;s--)a(t[n++],e,i);n++}}}this.nodeSet=new NodeSet(t.map(((t,a)=>NodeType.define({name:a>=this.minRepeatTerm?void 0:t,id:a,props:r[a],top:n.indexOf(a)>-1,error:0==a,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1})))),this.strict=!1,this.bufferLength=DefaultBufferLength;let i=decodeArray(e.tokenData);if(this.context=e.context,this.specialized=new Uint16Array(e.specialized?e.specialized.length:0),this.specializers=[],e.specialized)for(let t=0;t"number"==typeof e?new TokenGroup(i,e):e)),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,n){let r=new Parse(this,e,t,n);for(let a of this.wrappers)r=a(r,e,t,n);return r}getGoto(e,t,n=!1){let r=this.goto;if(t>=r[0])return-1;for(let a=r[t+1];;){let t=r[a++],i=1&t,s=r[a++];if(i&&n)return s;for(let n=a+(t>>1);a0}validAction(e,t){if(t==this.stateSlot(e,4))return!0;for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])return!1;n=pair(this.data,n+2)}if(t==pair(this.data,n+1))return!0}}nextStates(e){let t=[];for(let n=this.stateSlot(e,1);;n+=3){if(65535==this.data[n]){if(1!=this.data[n+1])break;n=pair(this.data,n+2)}if(0==(1&this.data[n+2])){let e=this.data[n+1];t.some(((t,n)=>1&n&&t==e))||t.push(this.data[n],e)}}return t}overrides(e,t){let n=findOffset(this.data,this.tokenPrecTable,t);return n<0||findOffset(this.data,this.tokenPrecTable,e){let n=e.tokenizers.find((e=>e.from==t));return n?n.to:t}))),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),null!=e.strict&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),null!=e.bufferLength&&(t.bufferLength=e.bufferLength),t}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return null==t?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),n=t.map((()=>!1));if(e)for(let r of e.split(" ")){let e=t.indexOf(r);e>=0&&(n[e]=!0)}let r=null;for(let e=0;ee)&&n.p.parser.stateFlag(n.state,2)&&(!t||t.score=65&&e<=90||95==e||e>=97&&e<=122||e>=161}function isSpace(e){return 9==e||10==e||13==e||32==e}let cachedName=null,cachedInput=null,cachedPos=0;function tagNameAfter(e,t){let n=e.pos+t;if(cachedInput==e&&cachedPos==n)return cachedName;for(;isSpace(e.peek(t));)t++;let r="";for(;;){let n=e.peek(t);if(!nameChar(n))break;r+=String.fromCharCode(n),t++}return cachedInput=e,cachedPos=n,cachedName=r||null}function ElementContext(e,t){this.name=e,this.parent=t,this.hash=t?t.hash:0;for(let t=0;tt==StartTag?new ElementContext(tagNameAfter(r,1)||"",e):e,reduce:(e,t)=>t==Element&&e?e.parent:e,reuse(e,t,n,r){let a=t.type.id;return a==StartTag||a==OpenTag?new ElementContext(tagNameAfter(r,1)||"",e):e},hash:e=>e?e.hash:0,strict:!1}),startTag=new ExternalTokenizer(((e,t)=>{if(60==e.next)if(e.advance(),47==e.next){e.advance();let n=tagNameAfter(e,0);if(!n)return e.acceptToken(incompleteStartCloseTag);if(t.context&&n.toLowerCase()==t.context.name.toLowerCase())return e.acceptToken(StartCloseTag);for(let r=t.context;r;r=r.parent)if(r.name==n)return e.acceptToken(MissingCloseTag,-2);e.acceptToken(mismatchedStartCloseTag)}else if(33!=e.next&&63!=e.next&&!isSpace(e.next))return e.acceptToken(StartTag)}),{contextual:!0});function scanTo(e,t){return new ExternalTokenizer((n=>{for(let r=0,a=0;;a++){if(n.next<0){a&&n.acceptToken(e);break}if(n.next==t.charCodeAt(r)){if(r++,r==t.length){a>t.length&&n.acceptToken(e,1-t.length);break}}else r=0;n.advance()}}))}const commentContent=scanTo(commentContent$1,"--\x3e"),parser=LRParser.deserialize({version:13,states:"*[OQOTOOO]OYO'#CdOeO`O'#CfO!OOTO'#CeOOOP'#Ce'#CeOOOP'#Cx'#CxOOOP'#Co'#CoQQOTOOOOOQ'#Cp'#CpO!VOYO,59OOOOP,59O,59OO!_OpO,59QO!mO`O'#ClOOOP'#DT'#DTOOOP'#Cu'#CuO!rOTO,59PO!yO`O'#CmOOOP,59P,59POOOP-E6m-E6mOOOQ-E6n-E6nOOOP1G.j1G.jOOOO'#Cq'#CqO#ROpO1G.lO#aOpO'#ChOOOO'#Cr'#CrO#rOpO1G.lOOOP1G.l1G.lOOOP1G.t1G.tO#}OWO,59WOOOP-E6s-E6sOOOP1G.k1G.kO$SO`O,59XO$[OWO,59XOOOO-E6o-E6oO$dOpO7+$WOOOP7+$W7+$WOOOP7+$`7+$`O$oOpO,59SO%QOWO,59SOOOO-E6p-E6pOOOP1G.r1G.rO%]OWO1G.sO%]OWO1G.sOOOP1G.s1G.sOOOP< tag. Found ${e.slice(a-1,i)}`)}n.firstChild();let t=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=!0}else{n.nextSibling();let a=e.substring(n.from+1,n.to-1);if(t in i)throw Error(`Duplicate attribute ${t}. Found in component of type ${r} at indices ${n.from}-${n.to}`);i[t]=a}n.parent()}n.parent();let s=n.to,o={componentType:r,props:{...i},children:[]};for(;n.nextSibling();)if("Text"===n.name){let t=e.substring(n.from,n.to);""!==t&&o.children.push(t)}else{if("Element"!==n.name){if("CloseTag"===n.name)break;if("Comment"===n.name)continue;throw"MismatchedCloseTag"===n.name?Error(`Invalid DoenetML at position ${n.from}. Mismatched closing tag. Expected . Found ${e.slice(n.from,n.to)}.`):Error(`Invalid DoenetML at position ${n.from}. Expected a closing tag. Instead found ${e.slice(n.from,n.to)}.`)}o.children.push(t(n.node.cursor))}return o.range={openBegin:a,openEnd:s,closeBegin:n.from,closeEnd:n.to},o}if("SelfClosingTag"===n.name){n.firstChild(),n.nextSibling();let t=e.substring(n.from,n.to),r=n.from,a={};for(;n.nextSibling();){if("Attribute"!==n.name)throw Error(`Invalid DoenetML at positions ${n.from} to ${n.to}. Error in self-closing <${t}/> tag.`);n.firstChild();let r=e.substring(n.from,n.to);if(!1===n.nextSibling()){if(r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);a[r]=!0}else{if(n.nextSibling(),r in a)throw Error(`Duplicate attribute ${r}. Found in component of type ${t} at indices ${n.from}-${n.to}`);let i=e.substring(n.from+1,n.to-1);a[r]=i}n.parent()}let i={selfCloseBegin:r,selfCloseEnd:n.to+2};return{componentType:t,props:{...a},children:[],range:i}}throw Error("Non SelfClosingTag/OpenTag in Element. How did you do that?")}function n(n){if("Element"===n.node.name)return t(n.node.cursor);if("Comment"===n.node.name)return null;if("Text"!==n.node.name)throw Error(`Invalid DoenetML at positions ${n.node.from} to ${n.node.to}. Found ${e.substring(n.node.from,n.node.to)}`);{let t=e.substring(n.node.from,n.node.to);if(""!==t)return t}}if(!e)return[];let r=parse(e),a=[];if(!r.firstChild())return a;let i=n(r);for(null!=i&&a.push(i);r.nextSibling();){let e=n(r);null!=e&&a.push(e)}return a}var base32$1={exports:{}};!function(e){!function(){var t="object"==typeof window?window:{};!t.HI_BASE32_NO_NODE_JS&&"object"==typeof browser$1&&browser$1.versions&&browser$1.versions.node&&(t=commonjsGlobal);var n=!t.HI_BASE32_NO_COMMON_JS&&e.exports,r="ABCDEFGHIJKLMNOPQRSTUVWXYZ234567".split(""),a={A:0,B:1,C:2,D:3,E:4,F:5,G:6,H:7,I:8,J:9,K:10,L:11,M:12,N:13,O:14,P:15,Q:16,R:17,S:18,T:19,U:20,V:21,W:22,X:23,Y:24,Z:25,2:26,3:27,4:28,5:29,6:30,7:31},i=[0,0,0,0,0,0,0,0],s=function(e,t){t.length>10&&(t="..."+t.substr(-10));var n=new Error("Decoded data is not valid UTF-8. Maybe try base32.decode.asBytes()? Partial data after reading "+e+" bytes: "+t+" <-");throw n.position=e,n},o=function(e){if(""===e)return[];if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");for(var t,n,r,i,s,o,l,u,c=[],p=0,d=(e=e.replace(/=/g,"")).length,m=0,h=d>>3<<3;m>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3),c[p++]=255&(l<<5|u);var f=d-h;return 2===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2)):4===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4)):5===f?(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1)):7===f&&(t=a[e.charAt(m++)],n=a[e.charAt(m++)],r=a[e.charAt(m++)],i=a[e.charAt(m++)],s=a[e.charAt(m++)],o=a[e.charAt(m++)],l=a[e.charAt(m++)],c[p++]=255&(t<<3|n>>>2),c[p++]=255&(n<<6|r<<1|i>>>4),c[p++]=255&(i<<4|s>>>1),c[p++]=255&(s<<7|o<<2|l>>>3)),c},l=function(e,t){if(!t)return function(e){for(var t,n,r="",a=e.length,i=0,o=0;i191&&t<=223?(n=31&t,o=1):t<=239?(n=15&t,o=2):t<=247?(n=7&t,o=3):s(i,r);for(var l=0;l191)&&s(i,r),n<<=6,n+=63&t;n>=55296&&n<=57343&&s(i,r),n>1114111&&s(i,r),n<=65535?r+=String.fromCharCode(n):(n-=65536,r+=String.fromCharCode(55296+(n>>10)),r+=String.fromCharCode(56320+(1023&n)))}return r}(o(e));if(""===e)return"";if(!/^[A-Z2-7=]+$/.test(e))throw new Error("Invalid base32 characters");var n,r,i,l,u,c,p,d,m="",h=e.indexOf("=");-1===h&&(h=e.length);for(var f=0,y=h>>3<<3;f>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))+String.fromCharCode(255&(p<<5|d));var g=h-y;return 2===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))):4===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))):5===g?(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))):7===g&&(n=a[e.charAt(f++)],r=a[e.charAt(f++)],i=a[e.charAt(f++)],l=a[e.charAt(f++)],u=a[e.charAt(f++)],c=a[e.charAt(f++)],p=a[e.charAt(f++)],m+=String.fromCharCode(255&(n<<3|r>>>2))+String.fromCharCode(255&(r<<6|i<<1|l>>>4))+String.fromCharCode(255&(l<<4|u>>>1))+String.fromCharCode(255&(u<<7|c<<2|p>>>3))),m},u={encode:function(e,t){var n="string"!=typeof e;return n&&e.constructor===ArrayBuffer&&(e=new Uint8Array(e)),n?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e[u],o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e[u++],n=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e[u++],n=e[u++],a=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e[u++],n=e[u++],a=e[u++],i=e[u],o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):t?function(e){for(var t,n,a,i,s,o="",l=e.length,u=0,c=5*parseInt(l/5);u>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[31&(i<<3|s>>>5)]+r[31&s];var p=l-c;return 1===p?(t=e.charCodeAt(u),o+=r[t>>>3]+r[t<<2&31]+"======"):2===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===p?(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):4===p&&(t=e.charCodeAt(u++),n=e.charCodeAt(u++),a=e.charCodeAt(u++),i=e.charCodeAt(u),o+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|i>>>7)]+r[i>>>2&31]+r[i<<3&31]+"="),o}(e):function(e){var t,n,a,s,o,l,u,c=!1,p="",d=0,m=0,h=e.length;if(""===e)return p;do{for(i[0]=i[5],i[1]=i[6],i[2]=i[7],u=m;d>6,i[u++]=128|63&l):l<55296||l>=57344?(i[u++]=224|l>>12,i[u++]=128|l>>6&63,i[u++]=128|63&l):(l=65536+((1023&l)<<10|1023&e.charCodeAt(++d)),i[u++]=240|l>>18,i[u++]=128|l>>12&63,i[u++]=128|l>>6&63,i[u++]=128|63&l);m=u-5,d===h&&++d,d>h&&u<6&&(c=!0),t=i[0],u>4?(n=i[1],a=i[2],s=i[3],o=i[4],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[31&(s<<3|o>>>5)]+r[31&o]):1===u?p+=r[t>>>3]+r[t<<2&31]+"======":2===u?(n=i[1],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[n<<4&31]+"===="):3===u?(n=i[1],a=i[2],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[a<<1&31]+"==="):(n=i[1],a=i[2],s=i[3],p+=r[t>>>3]+r[31&(t<<2|n>>>6)]+r[n>>>1&31]+r[31&(n<<4|a>>>4)]+r[31&(a<<1|s>>>7)]+r[s>>>2&31]+r[s<<3&31]+"=")}while(!c);return p}(e)},decode:l};l.asBytes=o,n?e.exports=u:t.base32=u}()}(base32$1);var base32=base32$1.exports;async function cidFromText(e){let t=(new TextEncoder).encode(e);return await cidFromArrayBuffer(t)}async function cidFromArrayBuffer(e){let t=await crypto.subtle.digest("SHA-256",e),n=new Uint8Array(36);return n.set([1,85,18,32]),n.set(new Uint8Array(t),4),"b"+base32.encode(n).toLowerCase().replace(/=+/,"")}const textByCid={};function retrieveTextFileForCid(e,t="doenet"){return void 0!==textByCid[e]?Promise.resolve(textByCid[e]):new Promise(((n,r)=>{let a,i,s=retrieveTextFileFromIPFS(e),o=s.promise,l=s.controller,u=!1,c=!1;o.then((t=>{clearTimeout(i),a&&!c&&a.abort(),textByCid[e]=t,n(t)})).catch((e=>{u=!0,c&&(clearTimeout(i),r(e))})),i=setTimeout((()=>{let s=retrieveTextFileFromServer(e,t),o=s.promise;a=s.controller,o.then((t=>{u||l.abort(),textByCid[e]=t,n(t)})).catch((e=>{c=!0,u?r(e):i=setTimeout((()=>{l.abort(),r(e)}),5e3)}))}),100)}))}function retrieveTextFileFromIPFS(e){let t=new AbortController,n=t.signal;return{promise:async function(){try{let t=await fetch(`https://${e}.ipfs.dweb.link/`,{signal:n});if(t.ok){let n=await t.text();return await cidFromText(n)===e?n:Promise.reject(new Error("cid mismatch"))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:t}}function retrieveTextFileFromServer(e,t){let n=new AbortController,r=n.signal;return{promise:async function(){try{let n=await fetch(`/media/${e}.${t}`,{signal:r});if(n.ok){let t=await n.text(),r=await cidFromText(t);return r===e?t:(console.warn(`cid mismatch, ${e}, ${r}`),Promise.reject(new Error("cid mismatch")))}return Promise.reject(new Error(`cid not found: ${e}`))}catch(t){return Promise.reject(new Error(`cid not found: ${e}`))}}(),controller:n}}async function expandDoenetMLsToFullSerializedComponents({cids:e,doenetMLs:t,componentInfoObjects:n}){let r=[],a={};for(let e of t){let t=parseAndCompile(e);t=cleanIfHaveJustDocument(t),substituteDeprecations(t),temporarilyRenameSourceBackToTarget(t),correctComponentTypeCapitalization(t,n.componentTypeLowerCaseMapping),copyTargetOrFromURIAttributeCreatesCopyComponent(t,n.isCompositeComponent),createAttributesFromProps(t,n),breakUpTargetIntoPropsAndIndices(t,n),applyMacros(t,n),removeBlankStringChildren(t,n),decodeXMLEntities(t),applySugar({serializedComponents:t,componentInfoObjects:n}),r.push(t);let i=findContentCopies({serializedComponents:t});for(let e in i.cidComponents)void 0===a[e]&&(a[e]=[]),a[e].push(...i.cidComponents[e])}let i=Object.keys(a);if(i.length>0){let{newDoenetMLs:e,newCids:t}=await cidsToDoenetMLs(i);for(let[e,n]of i.entries())if(t[e]&&t[e].substring(0,n.length)!==n)return Promise.reject(new Error(`Requested cid ${n} but got back ${t[e]}!`));let r=i.length;for(let n=0;n"string"!=typeof e||e.trim())),r=1===t.length&&"object"==typeof t[0],a=e.doenetAttributes?.fromCopyFromURI;if(a||r)if(a&&!r)console.warn("ignoring copyFromURI as it was not a single component");else{let n=t[0];n.attributes||(n.attributes={}),e.doenetAttributes||(e.doenetAttributes={}),e.doenetAttributes.keptNewNamespaceOfLastChild=Boolean(n.attributes.newNamespace?.primitive),n.attributes.newNamespace={primitive:!0},e.children=[n,...e.children],e.doenetAttributes.nameFirstChildIndependently=!0}else{let t={componentType:"externalContent",children:JSON.parse(JSON.stringify(n)),attributes:{newNamespace:{primitive:!0}},doenetAttributes:{createUniqueName:!0}};e.children=[t,...e.children]}}}}return{cids:e,fullSerializedComponents:r}}function cidsToDoenetMLs(e){let t=[],n=e;for(let n of e)t.push(retrieveTextFileForCid(n,"doenet"));return Promise.all(t).then((e=>Promise.resolve({newDoenetMLs:e,newCids:n}))).catch((e=>{let t;return t=1===n.length?`Could not retrieve cid ${n[0]}`:`Could not retrieve cids ${n.join(",")}`,t+=": "+e.message,console.error(t),Promise.reject(new Error(t))}))}function removeBlankStringChildren(e,t){for(let n of e){if(n.children){let e=t.allComponentClasses[n.componentType];e&&!e.includeBlankStringChildren&&(n.children=n.children.filter((e=>"string"!=typeof e||""!==e.trim()))),removeBlankStringChildren(n.children,t)}for(let e in n.attributes){let r=n.attributes[e].component;r&&r.children&&removeBlankStringChildren([r],t)}}}function findContentCopies({serializedComponents:e}){let t={};for(let n of e)if("copy"===n.componentType){if(n.attributes&&n.attributes.uri){let e=n.attributes.uri.primitive;if(e&&"doenet:"===e.substring(0,7).toLowerCase()){let r=e.match(/[:&]cid=([^&]+)/i);if(r){let e=r[1];void 0===t[e]&&(t[e]=[]),t[e].push(n)}}}}else if(void 0!==n.children){let e=findContentCopies({serializedComponents:n.children});for(let n in e.cidComponents)void 0===t[n]&&(t[n]=[]),t[n].push(...e.cidComponents[n])}return{cidComponents:t}}function addDocumentIfItsMissing(e){if(1!==e.length||"document"!==e[0].componentType){let t=e.splice(0);e.push({componentType:"document",children:t})}}function substituteDeprecations(e){let t={tname:"target",triggerwithtnames:"triggerWith",updatewithtname:"updateWith",paginatortname:"paginator",randomizeorder:"shuffleOrder",copytarget:"copySource",triggerwithtargets:"triggerWith",triggerwhentargetsclicked:"triggerWhenObjectsClicked",fortarget:"forObject",targetattributestoignore:"sourceAttributesToIgnore",targetattributestoignorerecursively:"sourceAttributesToIgnoreRecursively",targetsareresponses:"sourcesAreResponses",updatewithtarget:"updateWith",targetsarefunctionsymbols:"sourcesAreFunctionSymbols",selectforvariantnames:"selectForVariants"},n={copy:{target:"source",tname:"source"},collect:{target:"source",tname:"source"},summarystatistics:{target:"source"}};for(let r of e)if("object"==typeof r){if(r.props){let e=r.componentType,a=n[e.toLowerCase()];a||(a={});let i=!0;for(;i;){i=!1;for(let n in r.props){let s=n.toLowerCase();if(s in a){let t=a[s];console.warn(`Attribute ${n} of component type ${e} is deprecated. Use ${t} instead.`),r.props[t]=r.props[n],delete r.props[n],i=!0;break}if(s in t){let e=t[s];console.warn(`Attribute ${n} is deprecated. Use ${e} instead.`),r.props[e]=r.props[n],delete r.props[n],i=!0;break}}}}r.children&&substituteDeprecations(r.children)}}function temporarilyRenameSourceBackToTarget(e){let t={copysource:"copyTarget"},n={copy:{source:"target"},collect:{source:"target"}};for(let r of e)if("object"==typeof r){if(r.props){let e=n[r.componentType.toLowerCase()];e||(e={});let a=!0;for(;a;){a=!1;for(let n in r.props){let i=n.toLowerCase();if(i in e){let t=e[i];r.props[t]=r.props[n],delete r.props[n],a=!0;break}if(i in t){let e=t[i];r.props[e]=r.props[n],delete r.props[n],a=!0;break}}}}r.children&&temporarilyRenameSourceBackToTarget(r.children)}}function cleanIfHaveJustDocument(e){let t=e.filter((e=>"string"!=typeof e||""!==e.trim()));return 1===t.length&&"document"===t[0].componentType?t:e}function correctComponentTypeCapitalization(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t[n.componentType.toLowerCase()];if(!e)throw Error(`Invalid component type${indexRangeString(n)}: ${n.componentType}`);n.componentType=e,n.children&&correctComponentTypeCapitalization(n.children,t)}}function copyTargetOrFromURIAttributeCreatesCopyComponent(e,t){for(let n of e){if(n.props){let e=!1,r=!1,a=!1,i=n.componentType,s=t({componentType:i,includeNonStandard:!1}),o=t({componentType:i,includeNonStandard:!0});for(let t of Object.keys(n.props)){let l=t.toLowerCase();if("copytarget"===l){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(r)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(e=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.target=n.props[t],"string"!=typeof n.props.target)throw Error(`Must specify value for copyTarget. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyTarget=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("copyfromuri"===l){if(r)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);if(e)throw Error(`Cannot combine copyTarget and copyFromURI attribiutes. For in component of type ${i}${indexRangeString(n)}`);if(a)throw o?Error(`A component of type ${i} cannot have both assignNames and copyFromURI. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);if(r=!0,n.doenetAttributes||(n.doenetAttributes={}),s||(n.props.createComponentOfType=i,n.doenetAttributes.nameBecomesAssignNames=!0),n.componentType="copy",n.props.uri=n.props[t],"string"!=typeof n.props.uri)throw Error(`Must specify value for copyFromURI. Found in component of type ${i}${indexRangeString(n)}`);delete n.props[t],n.doenetAttributes.fromCopyFromURI=!0,n.doenetAttributes.createNameFromComponentType=i,n.props.assignNamesSkip="1"}else if("assignnames"===l&&!s){if(e||r)throw o?Error(`A component of type ${i} cannot have both assignNames and copyTarget. Found${indexRangeString(n)}.`):Error(`Invalid attribute assignNames for component of type ${i}${indexRangeString(n)}`);a=!0}}if(e){for(let e of Object.keys(n.props)){if("prop"===e.toLowerCase())throw Error(`Invalid attribute prop for component of type ${i}${indexRangeString(n)}`)}let e=!1;for(let t of Object.keys(n.props)){if("copyprop"===t.toLowerCase()){if(e)throw Error(`Cannot repeat attribute ${t}. Found in component type ${i}${indexRangeString(n)}`);n.props.prop=n.props[t],delete n.props[t],e=!0}}}}n.children&©TargetOrFromURIAttributeCreatesCopyComponent(n.children,t)}}function breakUpTargetIntoPropsAndIndices(e,t,n=""){for(let[r,a]of e.entries()){if(a.props&&["copy","updateValue","animateFromSequence"].includes(a.componentType)){let i,s,o,l,u,c,p;for(let e of Object.keys(a.props)){if("target"===e.toLowerCase()){if(i)throw Error(`Cannot repeat attribute ${e}. Found in component type ${a.componentType}${indexRangeString(a)}`);i=e,p=a.props[e];let t=buildSourcePieces(p,!0);t.success&&t.matchLength===p.length&&(s=t.sourceName,o=t.componentIndex,l=t.componentAttributes,u=t.propArray,c=t.subNames)}}if(i&&s)if(o||l||u.length>0){if(a.attributes.prop)throw Error(`Cannot combine the prop attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.propIndex)throw Error(`Cannot combine the propIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);if(a.attributes.componentIndex)throw Error(`Cannot combine the componentIndex attribute with an extended source attribute. Found in component type ${a.componentType}${indexRangeString(a)}`);let d=createComponentFromExtendedSource({sourceName:s,componentIndex:o,subNames:c,componentAttributes:l,propArray:u,componentInfoObjects:t});if(d.success){let t=d.newComponent;if("copy"===a.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes),a.doenetAttributes.createNameFromComponentType||(a.doenetAttributes.createNameFromComponentType=a.componentType),a.componentType=t.componentType,0!==u.length||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes.isPlainCopy=!0),t.children&&(a.children=t.children);else if("copy"===t.componentType)delete a.props[i],Object.assign(a.attributes,t.attributes),a.doenetAttributes||(a.doenetAttributes={}),Object.assign(a.doenetAttributes,t.doenetAttributes);else{let s=createUniqueName("extract","fromExtendedSource"+n+"|"+r);t.doenetAttributes.prescribedName=s,t.doenetAttributes.createdFromMacro=!0;let o={componentType:"setup",children:[t],doenetAttributes:{createdFromMacro:!0}};e.push(o),delete a.props[i],a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.target=s,a.doenetAttributes.allowDoubleUnderscoreTarget=!0}}else"copy"===a.componentType?console.warn(`invalid copy source: ${p}`):console.warn(`invalid target: ${p}`)}else"copy"!==a.componentType||a.attributes.prop||a.attributes.propIndex||(a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isPlainCopy=!0)}a.children&&breakUpTargetIntoPropsAndIndices(a.children,t,n+"|"+r)}}function createAttributesFromProps(e,t){for(let n of e){if("object"!=typeof n)continue;let e=t.allComponentClasses[n.componentType],r=e.createAttributesObject(),a={};for(let e in r)a[e.toLowerCase()]=e;let i={},s=Object.assign({},n.props);if(n.props)for(let o in n.props){let l=a[o.toLowerCase()],u=r[l];if(u){if(l in i)throw Error(`Cannot repeat attribute ${l}. Found in component type ${n.componentType}${indexRangeString(n)}`);i[l]=componentFromAttribute({attrObj:u,value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}else if(!["name","assignnames","target"].includes(o.toLowerCase())){if(!e.acceptAnyAttribute)throw Error(`Invalid attribute ${o} for component of type ${n.componentType}${indexRangeString(n)}`);i[o]=componentFromAttribute({value:n.props[o],originalComponentProps:s,componentInfoObjects:t}),delete n.props[o]}}for(let e in r){let n=r[e];n.createPrimitiveOfType&&"defaultPrimitiveValue"in n&&!(e in i)&&(i[e]=componentFromAttribute({attrObj:n,originalComponentProps:s,value:n.defaultPrimitiveValue.toString(),componentInfoObjects:t}))}n.attributes=i,void 0!==n.children&&createAttributesFromProps(n.children,t)}}function componentFromAttribute({attrObj:e,value:t,originalComponentProps:n,componentInfoObjects:r}){if("object"!=typeof t?t={rawString:t.toString()}:null===t&&(t={rawString:""}),e&&e.createComponentOfType){let a,i=t.rawString.trim().toLowerCase();if("true"===i&&void 0!==e.valueForTrue)a={componentType:e.createComponentOfType,state:{value:e.valueForTrue}};else if("false"===i&&void 0!==e.valueForFalse)a={componentType:e.createComponentOfType,state:{value:e.valueForFalse}};else if(r.isInheritedComponentType({inheritedComponentType:e.createComponentOfType,baseComponentType:"boolean"})&&["true","false"].includes(i))a={componentType:e.createComponentOfType,state:{value:"true"===i}};else{let n=t.childrenForComponent;n=n?JSON.parse(JSON.stringify(n)):[t.rawString],a={componentType:e.createComponentOfType,children:n},removeBlankStringChildren([a],r)}if(e.attributesForCreatedComponent||e.copyComponentAttributesForCreatedComponent){if(e.attributesForCreatedComponent?a.props=e.attributesForCreatedComponent:a.props={},e.copyComponentAttributesForCreatedComponent)for(let t of e.copyComponentAttributesForCreatedComponent)n[t]&&(a.props[t]=JSON.parse(JSON.stringify(n[t])));createAttributesFromProps([a],r)}let s={component:a};return e.ignoreFixed&&(s.ignoreFixed=!0),s}if(e&&e.createPrimitiveOfType){let n;if("boolean"===e.createPrimitiveOfType){n="true"===t.rawString.trim().toLowerCase()}else n="number"===e.createPrimitiveOfType?Number(t.rawString):"integer"===e.createPrimitiveOfType?Math.round(Number(t.rawString)):"stringArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/):"numberArray"===e.createPrimitiveOfType?t.rawString.trim().split(/\s+/).map(Number):t.rawString;return e.validationFunction&&(n=e.validationFunction(n)),{primitive:n}}if(e&&e.createTargetComponentNames){return{targetComponentNames:t.rawString.trim().split(/\s+/).map((e=>("$"===e[0]&&"$"!==e[1]&&"("===(e=e.slice(1))[0]&&")"===e[e.length-1]&&(e=e.slice(1,e.length-1)),{relativeName:e})))}}return t.childrenForComponent||(t.childrenForComponent=[t.rawString]),t}function findPreSugarIndsAndMarkFromSugar(e){let t=[];for(let n of e)if("object"==typeof n)if(void 0!==n.preSugarInd)t.push(n.preSugarInd);else if(n.doenetAttributes||(n.doenetAttributes={}),n.doenetAttributes.createdFromSugar=!0,n.children){let e=findPreSugarIndsAndMarkFromSugar(n.children);t.push(...e)}return t}function applyMacros(e,t){for(let n of e)if(n.children&&applyMacros(n.children,t),n.attributes)for(let e in n.attributes){let r=n.attributes[e];r.component?applyMacros([r.component],t):r.childrenForComponent&&applyMacros(r.childrenForComponent,t)}substituteMacros(e,t)}function substituteMacros(e,t){for(let n=0;n0&&e[n-1].range){let t=e[n-1].range;t.closeEnd?r+=t.closeEnd:t.selfCloseEnd&&(r+=t.selfCloseBegin)}throw Error(`${d.message}. At indices ${r}-${r+c}. Found: ${t}`)}l=d.newComponent,markCreatedFromMacro([l]),0===s.propArray.length&&(l.doenetAttributes.isPlainMacro=!0),o=[l];let m=1,h=i.substring(u+c);if(2===p){let r=i.slice(u+c).match(/^\s*\(/);if(!r){a=u+2;continue}let s=c+r[0].length,l=[],p=!1;i.length>u+s&&(p=!0,l.push(i.substring(u+s))),l.push(...e.slice(n+1));let d=createEvaluateIfFindMatchedClosingParens({componentsFromMacro:o,remainingComponents:l,includeFirstInRemaining:p,componentInfoObjects:t});if(!d.success){a=u+2;continue}o=d.componentsFromMacro,m=d.lastComponentIndMatched+1,p||m++,h=""}let f=[];u>0&&f.push(i.substring(0,u)),f.push(...o),h.length>0&&f.push(h),e.splice(n,m,...f),u>0&&n++;break}}}}function createComponentFromExtendedSource({sourceName:e,componentIndex:t,componentAttributes:n,propArray:r,subNames:a,componentInfoObjects:i}){let s={componentType:"copy",doenetAttributes:{target:e},attributes:{}};if(t){let e=[t];applyMacros(e,i),s.attributes.componentIndex={component:{componentType:"integer",children:e}}}if(a?.length>0){let e=[],t=[];for(let n of a)e.push(n.subName),void 0!==n.subNameComponentIndex&&(t.length0){let e=[t.join(" ")];applyMacros(e,i),s.attributes.sourceSubnamesComponentIndex={component:{componentType:"numberList",children:e}}}}let o=!1;if(n){o=!0;let e=createAttributesFromString(n,i);if(!e.success)return e;Object.assign(s.attributes,e.newAttributes),e.assignNames&&(s.props={assignNames:e.assignNames})}for(let e of r){if(o&&(s.doenetAttributes.createdFromMacro=!0,s={componentType:"extract",attributes:{},doenetAttributes:{},children:[s]}),s.attributes.prop={primitive:e.prop},e.propIndex){let t=[e.propIndex.join(" ")];applyMacros(t,i),s.attributes.propIndex={component:{componentType:"numberList",children:t}}}if(e.attributes){let t=createAttributesFromString(e.attributes,i);if(!t.success)return t;Object.assign(s.attributes,t.newAttributes),t.assignNames&&(s.props={assignNames:t.assignNames})}o=!0}return{success:!0,newComponent:s}}function createAttributesFromString(e,t){let n,r=``;try{n=parseAndCompile(r)}catch(e){return{success:!1,message:"Error in macro"}}createAttributesFromProps(n,t),markCreatedFromMacro(n),applyMacros(n,t);let a,i=n[0].attributes;if(i.prop||i.propIndex||i.componentIndex)return{success:!1,message:"Error in macro: macro cannot directly add attributes prop, propIndex, or componentIndex"};if(n[0].props)for(let e in n[0].props)if("assignnames"===e.toLowerCase()){if(a)return{success:!1,message:"Error in macro: cannot repeat assignNames"};a=n[0].props[e]}return{success:!0,newAttributes:i,assignNames:a}}function findFirstFullMacroInString(e){let t,n=0;for(;;){let r=e.substring(n).match(/(\$+)(.?)/);if(!r)return{success:!1};if(t=r[1].length,n+=r.index+t,t<=2){let r=!1,a=e.substring(n),i=0,s=findWordOrDelimitedGroup(a,r);"("===s.startDelim&&(r=!0,a=s.group,i=s.group.length);let o=buildSourcePieces(a,r);if(o.success){if(r){if(o.matchLength!==i)return{success:!1};o.matchLength+=2}return o.nDollarSigns=t,o.firstIndMatched=n-t,o.matchLength+=t,o}}}}function buildSourcePieces(e,t){let n=findWordOrDelimitedGroup(e,t),r=0;if(n.withPeriod||!n.word)return{success:!1};let a={sourceName:(n.withSlash?"/":"")+n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.componentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let i=[];for(;n.withSlash;){let a={subName:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t),"["===n.startDelim&&(a.subNameComponentIndex=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),i.push(a)}a.subNames=i,"{"===n.startDelim&&(a.componentAttributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t));let s=[];for(;n.withPeriod;){let a={prop:n.word};r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);let i=[];for(;"["===n.startDelim;)i.push(n.group),r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t);i.length>0&&(a.propIndex=i),"{"===n.startDelim&&(a.attributes=n.group,r+=n.matchLength,n=findWordOrDelimitedGroup(e=e.substring(n.matchLength),t)),s.push(a)}return a.propArray=s,a.matchLength=r,a.success=!0,a}function findWordOrDelimitedGroup(e,t=!1){let n,r=!1,a=!1;"."===e[0]&&"."!==e[1]&&(r=!0,e=e.substring(1)),t?r?n=/^[\w-]+/:("/"===e[0]&&e[1].match(/\w/)&&(a=!0,e=e.substring(1)),n=/^([\w\/-]|\.\.\/)+/):n=/^[a-zA-Z_]\w*/;let i=e.match(n);if(i)return{success:!0,withPeriod:r,withSlash:a,word:i[0],matchLength:i[0].length+(r?1:0)+(a?1:0)};if(r||a)return{success:!1};let s=[],o={"(":")","{":"}","[":"]"},l=Object.values(o),u=e[0],c=o[u];if(!c)return{success:!1};s.push(c);for(let t=1;t0?t[i]=s.substring(0,a.charInd):t=t.slice(0,i);let l=breakEmbeddedStringByCommas({childrenList:t});l.pieces.forEach((e=>applyMacros(e,r)));let u=l.pieces.map((e=>1===e.length&&"string"!=typeof e[0]?e[0]:{componentType:"math",doenetAttributes:{createdFromMacro:!0},children:e})),c=[{componentType:"evaluate",doenetAttributes:{createdFromMacro:!0},attributes:{function:{component:{componentType:"function",doenetAttributes:{createdFromMacro:!0},children:e}},input:{component:{componentType:"mathList",doenetAttributes:{createdFromMacro:!0},children:u}}}}];return o.length>0&&c.push(o),{success:!0,componentsFromMacro:c,lastComponentIndMatched:i}}function findFirstUnmatchedClosingParens(e){let t=0;for(let[n,r]of e.entries())if("string"==typeof r){let e=r;for(let r=0;r").replace(/</g,"<").replace(/$/g,"$").replace(/&/g,"&")}for(let[n,r]of e.entries())if("string"==typeof r)e[n]=t(r);else if(r.children&&decodeXMLEntities(r.children),r.attributes)for(let e in r.attributes){let n=r.attributes[e];n.component?decodeXMLEntities([n.component]):n.primitive?"string"==typeof n.primitive&&(n.primitive=t(n.primitive)):(n.childrenForComponent&&decodeXMLEntities(n.childrenForComponent),n.rawString&&(n.rawString=t(n.rawString)))}}function applySugar({serializedComponents:e,parentParametersFromSugar:t={},parentAttributes:n={},componentInfoObjects:r,parentUniqueId:a="",isAttributeComponent:i=!1}){for(let[s,o]of e.entries()){if("object"!=typeof o)continue;let e=o.componentType,l=r.allComponentClasses[e];if(!l)throw Error(`Unrecognized component type ${e}`);let u=a+"|"+e+s,c={};for(let e in o.attributes){let t=o.attributes[e];void 0!==t.primitive&&(c[e]=t.primitive)}if(o.children){let a={};if(!o.skipSugar)for(let[s,p]of l.returnSugarInstructions().entries()){let l=o.children.map((e=>"string"==typeof e?"s":"n")).join("");if(p.childrenRegex){let e=l.match(p.childrenRegex);if(!e||e[0].length!==o.children.length)continue}let d=deepClone(o.children),m=0;for(let e of d)"string"!=typeof e&&(e.preSugarInd=m,m++);let h=!1;o.doenetAttributes&&o.doenetAttributes.createdFromMacro&&(h=!0);let f=p.replacementFunction({matchedChildren:d,parentParametersFromSugar:t,parentAttributes:n,componentAttributes:c,uniqueId:u+"|sugar"+s,componentInfoObjects:r,isAttributeComponent:i,createdFromMacro:h});if(f.success){let t=f.newChildren,n=f.newAttributes,r=[],i=[];if(t&&(r=findPreSugarIndsAndMarkFromSugar(t)),n)for(let e in n){let t=n[e].component;t&&i.push(...findPreSugarIndsAndMarkFromSugar(t.children))}let s=[...r,...i];if(s.length!==m||!s.sort(((e,t)=>e-t)).every(((e,t)=>e===t)))throw Error(`Invalid sugar for ${e} as didn't return set of original components`);if(r.length>0){let t=[...r].sort(((e,t)=>e-t));if(!t.every(((e,t)=>e===r[t])))throw Error(`Invalid sugar for ${e} as didn't return original components in order`)}f.parametersForChildrenSugar&&Object.assign(a,f.parametersForChildrenSugar),o.children=t||[],n&&(o.attributes||(o.attributes={}),Object.assign(o.attributes,n))}}l.removeBlankStringChildrenPostSugar&&(o.children=o.children.filter((e=>"string"!=typeof e||/\S/.test(e)))),applySugar({serializedComponents:o.children,parentParametersFromSugar:a,parentAttributes:c,componentInfoObjects:r,parentUniqueId:u})}if(o.attributes)for(let e in o.attributes){let t=o.attributes[e];t.component&&applySugar({serializedComponents:[t.component],parentAttributes:c,componentInfoObjects:r,parentUniqueId:u,isAttributeComponent:!0})}}}function breakStringInPiecesBySpacesOrParens(e){if("string"!=typeof e)return{success:!1};let t=0,n=[];e=e.trim();let r=0;for(let a=0;a0&&n.push(t),r=a}t++}else if(")"===i){if(0===t)return{success:!1};if(1===t){let t=e.substring(r+1,a).trim();if(t.length>0){let e=breakStringInPiecesBySpacesOrParens(t);!0===e.success?n.push(e.pieces):n.push(t)}r=a+1}t--}else if(0===t&&i.match(/\s/)){let t=e.substring(r,a).trim();t.length>0&&n.push(t),r=a}}if(0!==t)return{success:!1};let a=e.substring(r,e.length).trim();return a.length>0&&n.push(a),{success:!0,pieces:n}}function countRegularComponentTypesInNamespace(e,t={}){for(let n of e)if("object"==typeof n){let e=n.componentType,r=t[e];void 0===r&&(r=0);let a=n.doenetAttributes;a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro||(t[e]=++r),n.children&&!n.attributes?.newNamespace?.primitive&&(t=countRegularComponentTypesInNamespace(n.children,t))}return t}function renameAutonameBasedOnNewCounts(e,t={}){let n={...t};for(let t of e)if("object"==typeof t){let e=t.componentType,r=n[e];void 0===r&&(r=0);let a=t.doenetAttributes;if(!(a?.isAttributeChild||a?.createdFromSugar||a?.createdFromMacro)&&(n[e]=++r,t.componentName)){let n=t.componentName.lastIndexOf("/"),a=t.componentName.substring(n+1),i="_"+e.toLowerCase();a.substring(0,i.length)===i&&(t.componentName=t.componentName.substring(0,n+1)+i+r)}t.children&&!t.attributes?.newNamespace?.primitive&&(n=renameAutonameBasedOnNewCounts(t.children,n))}return n}function createComponentNames({serializedComponents:e,namespaceStack:t=[],componentInfoObjects:n,parentDoenetAttributes:r={},parentName:a,useOriginalNames:i=!1,attributesByTargetComponentName:s,indOffset:o=0,createNameContext:l="",initWithoutShadowingComposite:u=!1}){0===t.length&&t.push({namespace:"",componentCounts:{},namesUsed:{}});let c=t.length-1,p=t[c];for(let[r,d]of e.entries()){if("object"!=typeof d)continue;let e=d.componentType,m=n.allComponentClasses[e],h=d.doenetAttributes;void 0===h&&(h=d.doenetAttributes={});let f=d.attributes;f||(f=d.attributes={}),h.createNameFromComponentType&&(e=h.createNameFromComponentType);let y,g=h.prescribedName,b=h.assignNames,v=h.target,N=h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||h.createUniqueName;(f.newNamespace?.primitive||i&&d.originalAttributes&&d.originalAttributes.newNamespace)&&(y=!0);let T=void 0!==g,C=d.props;if(void 0===C)C=d.props={};else for(let t in C){let n=t.toLowerCase();if("name"===n){if(void 0!==g)throw Error(`Cannot define name twice. Found in component of type ${e}${indexRangeString(d)}`);g=C[t],delete C[t]}else if("assignnames"===n){if(void 0!==b)throw Error(`Cannot define assignNames twice for a component. Found in component of type ${e}${indexRangeString(d)}`);{let n=breakStringInPiecesBySpacesOrParens(C[t]);if(!n.success)throw Error(`Invalid format for assignnames. Found in component of type ${e}${indexRangeString(d)}`);b=n.pieces,delete C[t]}}else if("target"===n){if(void 0!==v)throw Error(`Cannot define target twice for a component. Found in component of type ${e}${indexRangeString(d)}`);if("string"!=typeof C[t])throw Error(`Must specify value for target. Found in component of type ${e}${indexRangeString(d)}`);v=C[t].trim(),delete C[t]}}if(g){if(!T&&!h.createdFromSugar){if(!/[a-zA-Z]/.test(g.substring(0,1)))throw Error(`Invalid component name: ${g}. Component name must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(g))throw Error(`Invalid component name: ${g}. Component name can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}h.prescribedName=g}else if(N){let t=a+"|createUniqueName|";d.downstreamDependencies?t+=JSON.stringify(d.downstreamDependencies):t+=r+"|"+o+"|"+l,g=createUniqueName(e.toLowerCase(),t)}if(!b&&i&&d.originalDoenetAttributes&&d.originalDoenetAttributes.assignNames&&(b=d.originalDoenetAttributes.assignNames),b){if(!m.assignNamesToReplacements)throw Error(`Cannot assign names for component type ${e}${indexRangeString(d)}`);if(h.assignNames=b,!h.createUniqueAssignNames){let t=flattenDeep(b);if(!h.fromCopyTarget&&!h.fromCopyFromURI)for(let n of t){if(!/[a-zA-Z]/.test(n.substring(0,1)))throw Error(`All assigned names must begin with a letter. Found in component of type ${e}${indexRangeString(d)}`);if(!/^[a-zA-Z0-9_\-]+$/.test(n))throw Error(`Assigned names can contain only letters, numbers, hyphens, and underscores. Found in component of type ${e}${indexRangeString(d)}`)}if(t.length!==new Set(t).size)throw Error(`Duplicate assigned names. Found in component of type ${e}${indexRangeString(d)}`)}}y&&(f.newNamespace={primitive:y});let A=p.componentCounts[e];void 0===A&&(A=0),h.isAttributeChild||h.createdFromSugar||h.createdFromMacro||(p.componentCounts[e]=++A);let V="";for(let e=0;e<=c;e++)V+=t[e].namespace+"/";if(!g){if(i&&d.originalName){let e=d.originalName.lastIndexOf("/");g=d.originalName.substring(e+1)}g||(g="_"+e.toLowerCase()+A)}if(h.nameBecomesAssignNames){y&&(f.assignNewNamespaces={primitive:!0},delete f.newNamespace,y=!1),b=h.assignNames=[g],delete h.nameBecomesAssignNames;let e=a+"|createUniqueName|";h.createUniqueName=!0,delete h.prescribedName,d.downstreamDependencies?e+=JSON.stringify(d.downstreamDependencies):e+=r+"|"+o+"|"+l,g=createUniqueName("copy",e)}if(V+=g,d.componentName=V,g){if(g in p.namesUsed)throw Error(`Duplicate component name ${V}. Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[g]=!0}if(!y&&b)for(let t of flattenDeep(b)){if(t in p.namesUsed)throw Error(`Duplicate component name ${t} (from assignNames of ${V}). Found in component of type ${e}${indexRangeString(d)}`);p.namesUsed[t]=!0}if(d.doenetAttributes.createUniqueAssignNames&&d.originalName){let e=d.doenetAttributes.assignNames;e||(e=d.doenetAttributes.originalAssignNames);let n,r=V+"|createUniqueName|assignNames|",a="";if(y)a=V+"/",n=d.originalName+"/";else{for(let e=0;e<=c;e++)a+=t[e].namespace+"/";let e=d.originalName.lastIndexOf("/");n=d.originalName.slice(0,e+1)}let i=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:r,namespace:a,oldNamespace:n,attributesByTargetComponentName:s});b=d.doenetAttributes.assignNames=i}if(renameMatchingTargetNames(d,s),v){if(!m.acceptTarget)throw Error(`Component type ${e} does not accept a target attribute. Found in component ${V}${indexRangeString(d)}`);if(v.includes("|"))throw Error(`target cannot include |. Found in component of type ${e}${indexRangeString(d)}`);h.target=v,h.targetComponentName=convertComponentTarget({relativeName:v,oldAbsoluteName:h.targetComponentName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}for(let e in f){let n=f[e];if(n.targetComponentNames)for(let e of n.targetComponentNames)e.absoluteName=convertComponentTarget({relativeName:e.relativeName,oldAbsoluteName:e.absoluteName,namespaceStack:t,acceptDoubleUnderscore:h.createdFromSugar||h.allowDoubleUnderscoreTarget})}if(d.children)if(y||f.assignNewNamespaces?.primitive){let e={};b&&flattenDeep(b).forEach((t=>e[t]=!0));let r=d.children;if(h.nameFirstChildIndependently&&d.children.length>0){r=r.slice(1);let e={namespace:g,componentCounts:{},namesUsed:{}};t.push(e),createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}let a={namespace:g,componentCounts:{},namesUsed:e};if(h.haveNewNamespaceOnlyFromShadow){let e=!0,o=[...r];for(;o.length>0;){let r=[];for(let t of o){if(Boolean(t.doenetAttributes?.ignoreParentNewNamespace)===e)break;r.push(t)}o.splice(0,r.length),e?t.push(a):u&&r.forEach((e=>e.doenetAttributes.createUniqueName=!0)),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),e&&t.pop(),e=!e}}else t.push(a),createComponentNames({serializedComponents:r,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),t.pop()}else{let e=d.children;if(h.nameFirstChildIndependently&&e.length>0){e=e.slice(1);let r=p.namesUsed,a=p.componentCounts;p.namesUsed={},p.componentCounts={},createComponentNames({serializedComponents:[d.children[0]],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s}),p.namesUsed=r,p.componentCounts=a}createComponentNames({serializedComponents:e,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s})}if(d.attributes)for(let e in d.attributes){let r=d.attributes[e];if(r.component){let a=r.component;a.doenetAttributes||(a.doenetAttributes={}),a.doenetAttributes.isAttributeChild=!0,r.ignoreFixed&&(a.doenetAttributes.ignoreParentFixed=!0),createComponentNames({serializedComponents:[a],namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}else r.childrenForComponent&&createComponentNames({serializedComponents:r.childrenForComponent,namespaceStack:t,componentInfoObjects:n,parentDoenetAttributes:h,parentName:V,useOriginalNames:i,attributesByTargetComponentName:s,createNameContext:e})}}return e}function createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:e,longNameIdBase:t,namespace:n,oldNamespace:r,attributesByTargetComponentName:a}){let i=[];for(let[s,o]of e.entries())if(Array.isArray(o)){let e=createNewAssignNamesAndrenameMatchingTargetNames({originalAssignNames:o,longNameIdBase:t+s+"_",namespace:n,oldNamespace:r,attributesByTargetComponentName:a});i.push(e)}else{let e=createUniqueName("fromAssignNames",t+s);i.push(e),renameMatchingTargetNames({componentName:n+e,originalName:r+o},a,!0)}return i}function convertComponentTarget({relativeName:e,oldAbsoluteName:t,namespaceStack:n,acceptDoubleUnderscore:r}){if(!t&&/__/.test(e)&&!r)throw Error("Invalid reference target: "+e);let a;if("/"===e.substring(0,1))a=e;else{let t=n.length-1;for(;"../"===e.substring(0,3);)e=e.substring(3),t--;t<0&&(t=0),a="";for(let e=0;e<=t;e++)a+=n[e].namespace+"/";a+=e}return a}function serializedComponentsReplacer(e,t){return t!=t?{objectType:"special-numeric",stringValue:"NaN"}:t===1/0?{objectType:"special-numeric",stringValue:"Infinity"}:t===-1/0?{objectType:"special-numeric",stringValue:"-Infinity"}:t}let nanInfinityReviver=function(e,t){if(t&&"special-numeric"===t.objectType){if("NaN"===t.stringValue)return NaN;if("Infinity"===t.stringValue)return 1/0;if("-Infinity"===t.stringValue)return-1/0}return t};function serializedComponentsReviver(e,t){return me$3.reviver(e,theModule.Subset.reviver(e,nanInfinityReviver(e,t)))}function processAssignNames({assignNames:e=[],assignNewNamespaces:t=!1,serializedComponents:n,parentName:r,parentCreatesNewNamespace:a,componentInfoObjects:i,indOffset:s=0,originalNamesAreConsistent:o=!1,shadowingComposite:l=!1}){let u=n.length;moveComponentNamesToOriginalNames(n);let c={},p=null;if(o){if(u>0){let e=n.filter((e=>"object"==typeof e))[0];if(e&&e.originalName){let t=e.originalName.lastIndexOf("/");p=e.originalName.substring(0,t)}}if(null!==p)for(let e of n)setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[e],attributesByTargetComponentName:c})}else for(let e=0;e0&&t.originalName){let e=t.originalName.lastIndexOf("/");p=t.originalName.substring(0,e)}null!==p&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:p,components:[t],attributesByTargetComponentName:c})}}let d=[],m=0;for(let h=0;h0&&y.originalName)){let e=y.originalName.lastIndexOf("/");p=y.originalName.substring(0,e)}if(g)if(i.allComponentClasses[y.componentType].assignNamesSkipOver)g=[g];else if(y.attributes?.assignNamesSkip){let e=y.attributes.assignNamesSkip.primitive;if(e>0)for(let t=0;t({namespace:e,componentCounts:{},namesUsed:{}})));"/"!==e[0]&&c.splice(0,0,{componentCounts:{},namesUsed:{},namespace:""}),t.doenetAttributes||(t.doenetAttributes={}),t.attributes||(t.attributes={}),t.attributes.newNamespace?.primitive||s?u=!0:(u=!1,t.children&&markToCreateAllUniqueNames(t.children));for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}createComponentNames({serializedComponents:[t],namespaceStack:c,componentInfoObjects:a,parentName:e,useOriginalNames:u,attributesByTargetComponentName:i,indOffset:n,initWithoutShadowingComposite:!o})}function setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:t,attributesByTargetComponentName:n}){let r=e.length;for(let a of t)if("object"==typeof a){if(a.doenetAttributes&&a.doenetAttributes.target){let t=a.doenetAttributes.targetComponentName;void 0!==t&&(t.substring(0,r)!==e&&(a.doenetAttributes.target=t),n[t]||(n[t]=[]),n[t].push(a.doenetAttributes))}for(let t in a.attributes){let i=a.attributes[t];if(i.targetComponentNames)for(let t of i.targetComponentNames){let a=t.absoluteName;void 0!==a&&(a.substring(0,r)!==e&&(t.relativeName=a),n[a]||(n[a]=[]),n[a].push(t))}}if(a.children&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:a.children,attributesByTargetComponentName:n}),a.attributes)for(let t in a.attributes){let r=a.attributes[t];r.component?setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:[r.component],attributesByTargetComponentName:n}):r.childrenForComponent&&setTargetsOutsideNamespaceToAbsoluteAndRecordAllTargetComponentNames({namespace:e,components:r.childrenForComponent,attributesByTargetComponentName:n})}}}function renameMatchingTargetNames(e,t,n=!1){if(e.originalName&&t&&e.componentName!==e.originalName){if(t[e.originalName])for(let n of t[e.originalName])n.relativeName?(n.relativeName=e.componentName,n.absoluteName=e.componentName):(n.target=e.componentName,n.targetComponentName=e.componentName);if(n){let n=e.originalName+"/",r=n.length;for(let a in t)if(a.substring(0,r)===n){let n=a.substring(r);for(let r of t[a])r.relativeName?(r.relativeName=e.componentName+"/"+n,r.absoluteName=e.componentName+"/"+n):(r.target=e.componentName+"/"+n,r.targetComponentName=e.componentName+"/"+n)}}}}function moveComponentNamesToOriginalNames(e){for(let t of e)if(t.componentName&&(t.originalName=t.componentName,delete t.componentName),t.children&&moveComponentNamesToOriginalNames(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?moveComponentNamesToOriginalNames([n.component]):n.childrenForComponent&&moveComponentNamesToOriginalNames(n.childrenForComponent)}}function markToCreateAllUniqueNames(e){for(let t of e)if("object"==typeof t&&(t.doenetAttributes||(t.doenetAttributes={}),t.doenetAttributes.createUniqueName=!0,delete t.doenetAttributes.prescribedName,t.attributes?.newNamespace?.primitive||(t.doenetAttributes.assignNames?(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.doenetAttributes.assignNames,delete t.doenetAttributes.assignNames):t.originalDoenetAttributes&&t.originalDoenetAttributes.assignNames&&(t.doenetAttributes.createUniqueAssignNames=!0,t.doenetAttributes.originalAssignNames=t.originalDoenetAttributes.assignNames),t.children&&markToCreateAllUniqueNames(t.children)),t.attributes))for(let e in t.attributes){let n=t.attributes[e];n.component?markToCreateAllUniqueNames([n.component]):n.childrenForComponent&&markToCreateAllUniqueNames(n.childrenForComponent)}}function setTNamesToAbsolute(e){for(let t of e){if(t.doenetAttributes&&t.doenetAttributes.target){let e=t.doenetAttributes.targetComponentName;void 0!==e&&(t.doenetAttributes.target=e)}if(t.children&&setTNamesToAbsolute(t.children),t.attributes)for(let e in t.attributes){let n=t.attributes[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}}}function restrictTNamesToNamespace({components:e,namespace:t,parentNamespace:n,parentIsCopy:r=!1,invalidateReferencesToBaseNamespace:a=!1}){void 0===n&&(n=t);let i=t.length;for(let s of e){if(s.doenetAttributes&&s.doenetAttributes.target){let e=s.doenetAttributes.target;if("/"===e[0]){if(e.substring(0,i)!==t){let n=t.split("/").slice(1),r=e.split("/").slice(1),a=!1,i=t+e.slice(1);for(;n.length>0&&n[0]===r[0];)n=n.slice(1),r=r.slice(1),a=!0;if(a)i=t+r.join("/");else{let n=t.split("/").slice(1);for(let t=1;tn){r&&t<=n&&a.push({begin:t,end:n,componentName:r}),s=!0;break}r&&o.indBegin>t&&a.push({begin:t,end:o.indBegin-1,componentName:r});let l=extractRangeIndexPieces({componentArray:e.slice(i+1),lastInd:o.indBegin,stopInd:o.indEnd,enclosingComponentName:o.componentName});i+=l.componentsConsumed+1,a.push(...l.rangePieces),t=o.indEnd+1}return!s&&Number.isFinite(n)&&n>=t&&a.push({begin:t,end:n,componentName:r}),{componentsConsumed:i,rangePieces:a}}function createStateProxyHandler(){return{get:function(e,t){let n=e[t];return void 0!==n&&(n=n.isArray&&(n.public||n.trackChanges)?new Proxy(n.value,createArrayProxyHandler({variable:t,nDimensions:n.nDimensions})):n.value),n},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function createArrayProxyHandler({variable:e,nDimensions:t,indicesSoFar:n=[]}){return{variable:e,nDimensions:t,indicesSoFar:n,get:function(e,n){if("then"===n&&e instanceof Promise)return t=>e.then.bind(e)((e=>t(null!==e&&"object"==typeof e?new Proxy(e,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions,indicesSoFar:this.indicesSoFar})):e)));let r=e[n];return null!==r&&"object"==typeof r&&t>1&&(r=new Proxy(r,createArrayProxyHandler({variable:this.variable,nDimensions:this.nDimensions-1,indicesSoFar:[...this.indicesSoFar,n]}))),r},set:function(e,t,n){throw Error("Property "+t+" is read-only")},deleteProperty:function(e,t){throw Error("Property "+t+" is read-only")}}}function postProcessCopy({serializedComponents:e,componentName:t,addShadowDependencies:n=!0,markAsPrimaryShadow:r=!1,uniqueIdentifiersUsed:a=[],identifierPrefix:i="",unlinkExternalCopies:s=!1,copiesByTargetComponentName:o={},componentNamesFound:l=[],assignNamesFound:u=[],activeAliases:c=[],init:p=!0}){for(let d in e){let m,h=e[d];if("object"==typeof h){if(h.originalName){if(s){if(l.push(h.originalName),h.originalDoenetAttributes&&h.originalDoenetAttributes.assignNames){let e;if(h.attributes.newNamespace?.primitive)e=h.originalName;else{let t=h.originalName.lastIndexOf("/");e=h.originalName.substring(0,t)}for(let t of h.originalDoenetAttributes.assignNames)l.push(e+"/"+t),u.push(e+"/"+t)}h.attributes&&(h.attributes.alias&&c.push(h.attributes.alias.primitive),h.attributes.indexAlias&&c.push(h.attributes.indexAlias.primitive))}if(m=i+h.originalName+"|shadow",!h.originalNameFromSerializedComponent)if(n){let e={[h.originalName]:[{dependencyType:"referenceShadow",compositeName:t}]};if(p&&(e[h.originalName][0].firstLevelReplacement=!0),r&&(e[h.originalName][0].isPrimaryShadow=!0),h.state){let t=Object.keys(h.state);e[h.originalName].downstreamStateVariables=t,e[h.originalName].upstreamStateVariables=t}h.downstreamDependencies=e}else h.unlinkedCopySource=h.originalName}else m=i+h.componentType+"|shadowUnnamed";if("copy"===h.componentType&&s){let e=h.doenetAttributes.targetComponentName;if(e)c.includes(h.doenetAttributes.target)?h.doenetAttributes.targetComponentName=h.doenetAttributes.target:(void 0===o[e]&&(o[e]=[]),o[e].push(h));else if(!h.attributes.uri)throw Error("we need to create a targetComponentName here, then.")}h.uniqueIdentifier=getUniqueIdentifierFromBase(m,a)}}for(let p in e){let d=e[p];if("object"==typeof d){postProcessCopy({serializedComponents:d.children,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1});for(let e in d.attributes){let p=d.attributes[e];p.component&&(p.component=postProcessCopy({serializedComponents:[p.component],componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})[0])}d.replacements&&postProcessCopy({serializedComponents:d.replacements,componentName:t,addShadowDependencies:n,markAsPrimaryShadow:r,uniqueIdentifiersUsed:a,identifierPrefix:i,unlinkExternalCopies:s,copiesByTargetComponentName:o,componentNamesFound:l,assignNamesFound:u,activeAliases:[...c],init:!1})}}if(p&&s)for(let e in o)if(!l.includes(e)){let t=!1;for(let n of u){let r=n+"/",a=r.length;if(e.substring(0,a)===r){t=!0;break}}if(!t)for(let t of o[e])t.attributes||(t.attributes={}),t.attributes.link={primitive:!1},t.doenetAttributes.target=t.doenetAttributes.targetComponentName}return e}function convertAttributesForComponentType({attributes:e,componentType:t,componentInfoObjects:n,compositeAttributesObj:r={},compositeCreatesNewNamespace:a,flags:i}){let s=n.allComponentClasses[t],o=s.createAttributesObject(),l={};for(let e in o)l[e.toLowerCase()]=e;let u={};for(let t in e){if(t in r&&!r[t].leaveRaw)continue;let i=l[t.toLowerCase()],c=o[i];if(c){if(i in u)throw Error(`Cannot repeat prop ${i}`);if(u[i]=componentFromAttribute({attrObj:c,value:JSON.parse(JSON.stringify(e[t])),componentInfoObjects:n}),u[i].component?.children){let e=[u[i].component];if(applyMacros(e,n),removeBlankStringChildren(e,n),applySugar({serializedComponents:e,componentInfoObjects:n,isAttributeComponent:!0}),a)for(let e of u[i].component.children)if("copy"===e.componentType){let t=e.doenetAttributes.target;/[a-zA-Z_]/.test(t[0])&&(e.doenetAttributes.target="../"+t)}}}else s.acceptAnyAttribute&&(u[t]=JSON.parse(JSON.stringify(e[t])))}return u}async function verifyReplacementsMatchSpecifiedType({component:e,replacements:t,replacementChanges:n,assignNames:r,workspace:a={},componentInfoObjects:i,compositeAttributesObj:s,flags:o}){if(!e.attributes.createComponentOfType?.primitive&&!e.sharedParameters.compositesMustHaveAReplacement)return{replacements:t,replacementChanges:n};let l,u=e.replacementsToWithhold;if(n){l=e.replacements.map((e=>e.componentType));for(let e of n)if("add"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),!e.changeTopLevelReplacements)continue;if(e.serializedReplacements){let t=e.numberReplacementsToReplace;t>0||(t=0);let n=e.firstReplacementInd,r=e.serializedReplacements.map((e=>e.componentType));l.splice(n,t,...r)}}else if("delete"===e.changeType){if(void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold),e.changeTopLevelReplacements){let t=e.firstReplacementInd,n=e.numberReplacementsToDelete;l.splice(t,n)}}else"changeReplacementsToWithhold"===e.changeType&&void 0!==e.replacementsToWithhold&&(u=e.replacementsToWithhold)}else i.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"template"})&&(t=t.filter((e=>e.componentType||e.trim().length>0))),l=t.map((e=>e.componentType)),1===l.length&&"externalContent"===l[0]&&(l=t[0].children.filter((e=>e.componentType||e.trim().length>0)).map((e=>e.componentType)));if(u>0&&(l=l.slice(0,l.length-u)),!e.attributes.createComponentOfType?.primitive&&e.sharedParameters.compositesMustHaveAReplacement&&l.length>0)return{replacements:t,replacementChanges:n};let c=e.attributes.createComponentOfType?.primitive,p=await e.stateValues.nComponentsSpecified;if(!c){if(c=e.sharedParameters.compositesDefaultReplacementType,!c)throw Error("A component class specified descendantCompositesMustHaveAReplacement but didn't specify descendantCompositesDefaultReplacementType");p=1}if(c=i.componentTypeLowerCaseMapping[c.toLowerCase()],l.length!==p||!l.every((e=>e===c))){if(1===t?.length&&i.isInheritedComponentType({inheritedComponentType:t[0].componentType,baseComponentType:"template"}))return t[0].attributes||(t[0].attributes={}),t[0].attributes.createComponentOfType={primitive:c},t[0].attributes.nComponents={primitive:p},{replacements:t,replacementChanges:n};let d,m=l.length===p&&!(u>0)&&a.sourceNames?.length===p;m&&n&&(1===n.length&&n[0].numberReplacementsToReplace===p?d=n[0].serializedReplacements:m=!1),m?d||(d=t):(a.numReplacementsBySource=[],a.numNonStringReplacementsBySource=[],a.propVariablesCopiedBySource=[],a.sourceNames=[],a.uniqueIdentifiersUsedBySource={},a.uniqueIdentifiersUsedBySource[0]=[]);let h=e.attributes.newNamespace?.primitive;t=[];for(let n=0;n"string"!=typeof e)).length),n){n=[],e.replacementsToWithhold>0&&n.push({changeType:"changeReplacementsToWithhold",replacementsToWithhold:0});let r=0;e.replacements&&(r=e.replacements.length),n.push({changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:r,serializedReplacements:t})}}return{replacements:t,replacementChanges:n}}function gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n=!0,useReplacementsForComposites:r=!1,includeNonActiveChildren:a=!1,skipOverAdapters:i=!1,ignoreReplacementsOfMatchedComposites:s=!1,ignoreReplacementsOfEncounteredComposites:o=!1,init:l=!0,componentInfoObjects:u}){let c=e=>t.some((t=>u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:t}))),p=[];if(r&&u.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"}))l&&p.push(...replacementsForComposites({composite:e,componentInfoObjects:u,includeComposites:a}).filter((e=>"object"==typeof e)));else for(let t of e.allChildrenOrdered){let n,r=e.allChildren[t],s=!1,o=!1;if(r)n=r.component,n.adaptedFrom&&(o=!0),e.activeChildren.includes(n)&&(s=!0);else for(let r of e.activeChildren){if(r.placeholderInd===t){n=r,s=!0,"string"==typeof t&&"adapt"===t.substring(t.length-5,t.length)&&(o=!0);break}if(r.adaptedFrom&&achild.adaptedFrom.placeholderInd===t){n=r.adaptedFrom;break}}n&&(o&&i?p.includes(n.adaptedFrom)||p.push(n.adaptedFrom):(s||a)&&p.push(n))}if(s||o){let e=[];for(let t of p){let n=c(t);o&&!n&&(n=!("copy"===t.componentType&&t.doenetAttributes.copiedURI)),n&&u.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&(e=[...e,...replacementsForComposites({composite:t,componentInfoObjects:u,includeComposites:!0}).filter((e=>"object"==typeof e)).map((e=>e.componentName?e.componentName:e.placeholderInd))])}e.length>0&&(p=p.filter((t=>!(e.includes(t.componentName)||e.includes(t.placeholderInd)))))}let d=[];for(let e of p){let l=c(e);if(l&&d.push({componentName:e.componentName?e.componentName:e.placeholderInd,componentType:e.componentType}),(!l||n)&&void 0===e.placeholderInd){let l=gatherDescendants({ancestor:e,descendantTypes:t,recurseToMatchedChildren:n,useReplacementsForComposites:r,includeNonActiveChildren:a,skipOverAdapters:i,ignoreReplacementsOfMatchedComposites:s,ignoreReplacementsOfEncounteredComposites:o,init:!1,componentInfoObjects:u});d.push(...l)}}return d}function replacementsForComposites({composite:e,includeComposites:t=!1,componentInfoObjects:n}){let r=[];if(e.replacements){let a;if(e.replacementsToWithhold){let t=e.replacements.length-e.replacementsToWithhold;a=e.replacements.slice(0,t)}else a=e.replacements;for(let e of a)n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})?(t&&r.push(e),r.push(...replacementsForComposites({composite:e,componentInfoObjects:n,includeComposites:t}))):r.push(e)}return r}function ancestorsIncludingComposites(e,t){if(void 0===e.ancestors||0===e.ancestors.length)return[];let n=[e.ancestors[0].componentName],r=t[e.ancestors[0].componentName];if(r&&n.push(...ancestorsIncludingComposites(r,t)),e.replacementOf){n.push(e.replacementOf.componentName);let r=ancestorsIncludingComposites(e.replacementOf,t);for(let e of r)n.includes(e)||n.push(e)}return n}const dependencyTypeArray=[];class DependencyHandler{constructor({_components:e,componentInfoObjects:t,core:n}){this.upstreamDependencies={},this.downstreamDependencies={},this.switchDependencies={},this.circularCheckPassed={},this.circularResolveBlockedCheckPassed={},this.dependencyTypes={},dependencyTypeArray.forEach((e=>this.dependencyTypes[e.dependencyType]=e)),this.core=n,this._components=e,this.componentInfoObjects=t,this.updateTriggers={descendantDependenciesByAncestor:{},ancestorDependenciesByPotentialAncestor:{},replacementDependenciesByComposite:{},childDependenciesByParent:{},parentDependenciesByParent:{},dependenciesMissingComponentBySpecifiedName:{},dependenciesBasedOnDependenciesOfStateVariables:{},primaryShadowDependencies:{}},this.resolveBlockers={neededToResolve:{},resolveBlockedBy:{}}}async setUpComponentDependencies(e){this.downstreamDependencies[e.componentName]&&this.deleteAllDownstreamDependencies({component:e}),this.downstreamDependencies[e.componentName]={},this.upstreamDependencies[e.componentName]||(this.upstreamDependencies[e.componentName]={});let t=[],n=[];for(let r in e.state)e.state[r].isArrayEntry||e.state[r].isAlias||n.includes(r)||(t.push(r),e.state[r].additionalStateVariablesDefined&&n.push(...e.state[r].additionalStateVariablesDefined));for(let n of t){let t=[n];e.state[n].additionalStateVariablesDefined&&t.push(...e.state[n].additionalStateVariablesDefined),await this.setUpStateVariableDependencies({component:e,stateVariable:n,allStateVariablesAffected:t})}}async setUpStateVariableDependencies({component:e,stateVariable:t,allStateVariablesAffected:n}){let r,a=e.state[t];a.stateVariablesDeterminingDependencies?(r={},a.stateVariablesDeterminingDependencies&&(r.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies})):r=await a.returnDependencies({componentInfoObjects:this.componentInfoObjects,sharedParameters:e.sharedParameters});for(let a in r){let i=r[a];if(!(i.dependencyType in this.dependencyTypes))throw Error(`Unrecognized dependency type ${i.dependencyType} for ${a} of ${t} of ${e.componentName}`);let s=new this.dependencyTypes[i.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:a,dependencyDefinition:i,dependencyHandler:this,expandComposites:!1,forceExpandComposites:!1});await s.initialize(),s.checkForCircular()}}deleteAllDownstreamDependencies({component:e,stateVariables:t="__all__"}){let n,r=e.componentName;n="__all__"===t?Object.keys(this.downstreamDependencies[r]):t;for(let e of n){let t=this.downstreamDependencies[r][e];for(let e in t)t[e].deleteDependency();delete this.downstreamDependencies[r][e]}0!==Object.keys(this.downstreamDependencies[r]).length||this.components[r]||delete this.downstreamDependencies[r]}async deleteAllUpstreamDependencies({component:e,stateVariables:t="__all__",completelyDelete:n=!1}){let r,a=e.componentName;r="__all__"===t?Object.keys(this.upstreamDependencies[a]):t;for(let e of r){if(this.upstreamDependencies[a][e])for(let t of[...this.upstreamDependencies[a][e]])if(n){for(let e of t.upstreamVariableNames)this._components[t.upstreamComponentName].state[e].initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:this.components[t.upstreamComponentName],varName:e});t.deleteDependency()}else await t.removeDownstreamComponent({indexToRemove:t.downstreamComponentNames.indexOf(a)});delete this.upstreamDependencies[a][e]}0!==Object.keys(this.upstreamDependencies[a]).length||this._components[a]||delete this.upstreamDependencies[a]}async addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:t}){let n=this.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];if(n)for(let r of t){let t=n[r];if(t)for(let n of t)if(n.gettingValue){let t=n.varsWithUpdatedDeps[e];t||(t=n.varsWithUpdatedDeps[e]=[]),t.includes(r)||t.push(r)}else for(let e of n.upstreamVariableNames)await this.addBlocker({blockerComponentName:n.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:n.dependencyName,componentNameBlocked:n.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}async addBlockersFromChangedActiveChildren({parent:e}){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let t of this.updateTriggers.childDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let t of this.updateTriggers.parentDependenciesByParent[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let t of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}}async resolveBlockersFromChangedActiveChildren(e,t=!1){if(await this.collateCountersAndPropagateToAncestors(e),this.updateTriggers.childDependenciesByParent[e.componentName])for(let n of this.updateTriggers.childDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});if(e.ancestors){if(this.updateTriggers.parentDependenciesByParent[e.componentName])for(let n of this.updateTriggers.parentDependenciesByParent[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t});for(let n of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.resolveDescendantBlockersToAncestor(n,t);if(this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])for(let n of this.updateTriggers.ancestorDependenciesByPotentialAncestor[e.componentName])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}}async addDescendantBlockersToAncestor(e){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let t of this.updateTriggers.descendantDependenciesByAncestor[e]){for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});await this.addBlockersFromChangedStateVariableDependencies({componentName:t.upstreamComponentName,stateVariables:t.upstreamVariableNames})}}async resolveDescendantBlockersToAncestor(e,t=!1){if(this.updateTriggers.descendantDependenciesByAncestor[e])for(let n of this.updateTriggers.descendantDependenciesByAncestor[e])await this.resolveIfReady({componentName:n.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:n.representativeStateVariable,dependency:n.dependencyName,force:t})}async addBlockersFromChangedReplacements(e){if(this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let t of this.updateTriggers.replacementDependenciesByComposite[e.componentName])for(let e of t.upstreamVariableNames)await this.addBlocker({blockerComponentName:t.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:t.dependencyName,componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t of[e.componentName,...ancestorsIncludingComposites(e,this.components)])await this.addDescendantBlockersToAncestor(t)}checkForCircularDependency({componentName:e,varName:t,previouslyVisited:n=[]}){let r=e+":"+t;if(n.includes(r)){console.log("found circular",r,n);let e,t=/^(.*):/,a=n.map((e=>e.match(t)[1])),i=a.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);throw 0===i.length&&(i=[a[0]]),1===i.length?e=i[0]:2===i.length?e=i.join(" and "):(i[i.length-2]=i.slice(i.length-2).join(", and "),i.pop(),e=i.join(", ")),Error(`Circular dependency involving ${e}`)}if(n=[...n,r],!this.circularCheckPassed[r]&&(this.circularCheckPassed[r]=!0,e in this.downstreamDependencies)){let r=this.downstreamDependencies[e][t];for(let e in r){let t=r[e],a=t.downstreamComponentNames;if(!a)continue;let i=t.mappedDownstreamVariableNamesByComponent;if(i)for(let[e,t]of a.entries()){let r=i[e];for(let e of r)this.checkForCircularDependency({componentName:t,varName:e,previouslyVisited:n})}}}}resetCircularCheckPassed(e,t){let n=e+":"+t;if(this.circularCheckPassed[n]){delete this.circularCheckPassed[n];let r=this.upstreamDependencies[e][t];if(r)for(let e of r)for(let t of e.upstreamVariableNames)"__identity"!==t&&this.resetCircularCheckPassed(e.upstreamComponentName,t)}}async updateDependencies({componentName:e,stateVariable:t,dependency:n}){let r=this._components[e],a=r.state[t],i=[t];a.additionalStateVariablesDefined&&i.push(...a.additionalStateVariablesDefined);let s,o=this.downstreamDependencies[e][t].__determine_dependencies;if(o){let t=!0;if(o.originalDownstreamVariableNames.length>0)for(let[r,a]of o.downstreamComponentNames.entries()){let s=this._components[a];for(let l of o.mappedDownstreamVariableNamesByComponent[r]){let r=s.state[l].isResolved;if(!r){r=(await this.resolveItem({componentName:a,type:"stateVariable",stateVariable:l})).success}if(!r){t=!1;for(let t of i)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:l,componentNameBlocked:e,typeBlocked:"determineDependencies",stateVariableBlocked:t,dependencyBlocked:n})}}}if(!t)return{success:!1};s=await o.getValue()}else s={changes:{},value:{stateValues:{}}};if(0===Object.keys(s.changes).length&&void 0!==a._previousValue)return{success:!0};let l={stateValues:Object.assign({},s.value.stateValues),componentInfoObjects:this.componentInfoObjects,sharedParameters:r.sharedParameters},u=await a.returnDependencies(l);a.stateVariablesDeterminingDependencies&&(u.__determine_dependencies={dependencyType:"determineDependencies",variableNames:a.stateVariablesDeterminingDependencies});let c=await this.replaceDependenciesIfChanged({component:r,stateVariable:t,newDependencies:u,allStateVariablesAffected:i});if(!c.changedDependency&&!l.changedDependency)return{success:!0};for(let e of c.newlyCreatedDependencies)e.checkForCircular();for(let e of i)this.checkForCircularDependency({componentName:r.componentName,varName:e}),r.state[e].forceRecalculation=!0;a.initiallyResolved&&await this.core.markStateVariableAndUpstreamDependentsStale({component:r,varName:t});for(let e of i)r.state[e].initiallyResolved&&this.recordActualChangeInUpstreamDependencies({component:r,varName:e});return await this.addBlockersFromChangedStateVariableDependencies({componentName:e,stateVariables:i}),{success:!0}}async replaceDependenciesIfChanged({component:e,stateVariable:t,newDependencies:n,allStateVariablesAffected:r}){let a=this.downstreamDependencies[e.componentName][t],i=!1,s=[];for(let e in a)e in n||(i=!0,a[e].deleteDependency());for(let o in n)if(o in a){if(!deepCompare(n[o],a[o].definition)){i=!0,a[o].deleteDependency();let l=n[o],u=new this.dependencyTypes[l.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:l,dependencyHandler:this});await u.initialize(),s.push(u)}}else{i=!0;let a=n[o],l=new this.dependencyTypes[a.dependencyType]({component:e,stateVariable:t,allStateVariablesAffected:r,dependencyName:o,dependencyDefinition:a,dependencyHandler:this});await l.initialize(),s.push(l)}return{changedDependency:i,newlyCreatedDependencies:s}}async checkForDependenciesOnNewComponent(e){let t=[],n={};if(this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){for(let r of this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]){let a=this._components[r.upstreamComponentName];if(!a)continue;let i=!0;for(let e of r.upstreamVariableNames)if(!(e in a.state)){i=!1;break}if(i){for(let e of r.upstreamVariableNames){a.state[e].initiallyResolved&&(n[r.upstreamComponentName]&&n[r.upstreamComponentName][e]||t.push({componentName:r.upstreamComponentName,varName:e}))}for(let t of r.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:r.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:r.dependencyName,blockerComponentName:e,blockerType:"componentIdentity"});if((await this.resolveIfReady({componentName:r.upstreamComponentName,type:"recalculateDownstreamComponents",stateVariable:r.representativeStateVariable,dependency:r.dependencyName,expandComposites:!1,recurseUpstream:!0})).success)for(let e of r.upstreamVariableNames)a.state[e].initiallyResolved||(n[r.upstreamComponentName]||(n[r.upstreamComponentName]={}),n[r.upstreamComponentName][e]=!0);else for(let e of r.upstreamVariableNames)await this.addBlocker({blockerComponentName:r.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:r.dependencyName,componentNameBlocked:r.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e})}}delete this.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]}return t}async getStateVariableDependencyValues({component:e,stateVariable:t}){let n={},r={},a={},i=this.downstreamDependencies[e.componentName][t];for(let e in i){let{value:t,changes:s,usedDefault:o}=await i[e].getValue();n[e]=t,Object.keys(s).length>0&&(r[e]=s),o&&(a[e]=o)}return{dependencyValues:n,changes:r,usedDefault:a}}recordActualChangeInUpstreamDependencies({component:e,varName:t,changes:n}){let r=e.componentName,a=this.upstreamDependencies[r][t];if(a)for(let i of a)if(i.valuesChanged){let a=i.downstreamComponentNames.indexOf(r),s=i.valuesChanged[a][t];if(!s&&e.stateVarAliases)for(let n in e.stateVarAliases)e.stateVarAliases[n]===t&&n in upValuesChangedSub&&(s=upValuesChangedSub[n]);if(!s){if(!e.state[t].isArrayEntry)throw Error(`Something is wrong, as a variable ${t} of ${e.componentName} actually changed, but wasn't marked with a potential change`);s=upValuesChangedSub[t]={changed:{}}}e.state[t]&&e.state[t].isArray?(void 0===s.changed?s.changed={arrayKeysChanged:{}}:!0===s.changed&&(s.changed={allArrayKeysChanged:!0,arraySizeChanged:!0,arrayKeysChanged:{}}),n&&(n.allArrayKeysChanged&&(s.changed.allArrayKeysChanged=!0),n.arraySizeChanged&&(s.changed.arraySizeChanged=!0),Object.assign(s.changed.arrayKeysChanged,n.arrayKeysChanged))):s.changed=!0}}async collateCountersAndPropagateToAncestors(e){let t=Object.keys(e.counters);for(let n of e.allChildrenOrdered){let e=this._components[n];if(e)for(let n in e.counters)t.includes(n)||t.push(n)}let n=!1;for(let r of t){let t=e.counters[r];t||(t=e.counters[r]={dependencies:[],componentList:[]});let a=[];t.dependencies.length>0&&a.push(e.componentName);for(let t of e.allChildrenOrdered){let e=this._components[t];if(e){let t=e.counters[r];t&&a.push(...t.componentList)}}(a.length!==t.componentList.length||t.componentList.some(((e,t)=>e!=a[t])))&&(n=!0,t.componentList=a)}if(!n)return{foundChange:!1};if(!e.ancestors[0]){for(let n of t){let t=e.counters[n];for(let[e,r]of t.componentList.entries()){let t=this._components[r],a=t.counters[n];a.value=e+1;for(let e of a.dependencies)if(t.state[e.representativeStateVariable].initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:t,varName:e.representativeStateVariable});for(let n of e.upstreamVariableNames)t.state[n].forceRecalculation=!0,this.recordActualChangeInUpstreamDependencies({component:t,varName:n})}}}return{foundChange:!0,finishedPropagation:!0}}let r=this._components[e.ancestors[0].componentName];if(!r||!r.allChildrenOrdered.includes(e.componentName))return{foundChange:!0,finishedPropagation:!1};let a=await this.collateCountersAndPropagateToAncestors(r);return a.foundChange||console.error(`we found a change in propagating counters for ${e.componentName}, but no change for ancestors!`),{foundChange:!0,finishedPropagation:a.finishedPropagation}}getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];a||(a=this.resolveBlockers.neededToResolve[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r,blockerType:a,blockerCode:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:n,blockerDependency:r,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:a,blockerStateVariable:r,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:n,blockerStateVariable:a,blockerDependency:i,typeBlocked:t,codeBlocked:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.neededToResolve[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.neededToResolve[e]}}checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.neededToResolve[e];if(!a)return!1;let i=a[t];if(!i)return!1;if(n){if(i=i[n],!i)return!1;if(r){if(i=i[r],!i)return!1}}return Object.keys(i).length>0}getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}){let a=this.resolveBlockers.resolveBlockedBy[e];a||(a=this.resolveBlockers.resolveBlockedBy[e]={});let i=a[t];if(i||(i=a[t]={}),n){let e=i;if(i=e[n],i||(i=e[n]={}),r){let e=i;i=e[r],i||(i=e[r]={})}}return i}deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:a,codeBlocked:i,deleteFromReciprocal:s=!0}){let o=e;n&&(o+="|"+n,r&&(o+="|"+r));let l=function(e){if(a){if(e[a])if(i){let n=e[a].indexOf(i);if(-1!==n&&e[a].splice(n,1),0===e[a].length&&delete e[a],s){let[e,n,r]=i.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:n,dependencyBlocked:r,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}else{if(s)for(let n of e[a]){let[e,r,i]=n.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:a,stateVariableBlocked:r,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}delete e[a]}}else if(s)for(let n in e)for(let r of e[n]){let[e,a,i]=r.split("|");this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:n,stateVariableBlocked:a,dependencyBlocked:i,blockerType:t,blockerCode:o,deleteFromReciprocal:!1})}}.bind(this),u=this.resolveBlockers.resolveBlockedBy[e];if(u){let i=u[t];if(i)if(n){let e=i[n];if(e)if(r){let t=e[r];t&&(l(t),a&&0!==Object.keys(t).length||delete e[r]),0===Object.keys(e).length&&delete i[n]}else l(e),a&&0!==Object.keys(e).length||delete i[n];0===Object.keys(i).length&&delete u[t]}else l(i),a&&0!==Object.keys(i).length||delete u[t];0===Object.keys(u).length&&delete this.resolveBlockers.resolveBlockedBy[e]}}async addBlocker({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,componentNameBlocked:a,typeBlocked:i,stateVariableBlocked:s,dependencyBlocked:o}){let l=e;n&&(l+="|"+n,r&&(l+="|"+r));let u=a;s&&(u+="|"+s,o&&(u+="|"+o));let c=this.getNeededToResolve({componentName:a,type:i,stateVariable:s,dependency:o}),p=c[t];if(p||(p=c[t]=[]),p.includes(l))return;if(p.push(l),"stateVariable"===i){let e=this._components[a];if(e){let t=e.state[s];if(t.isResolved=!1,t.initiallyResolved){await this.core.markStateVariableAndUpstreamDependentsStale({component:e,varName:s});let t=this.upstreamDependencies[a][s];if(t)for(let e of t)if(this._components[e.upstreamComponentName])for(let t of e.upstreamVariableNames)await this.addBlocker({blockerComponentName:a,blockerType:"stateVariable",blockerStateVariable:s,componentNameBlocked:e.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t})}}}let d=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r}),m=d[i];m||(m=d[i]=[]),m.includes(u)||m.push(u),this.resetCircularResolveBlockerCheckPassed({componentName:a,type:i,stateVariable:s,dependency:o}),this.checkForCircularResolveBlocker({componentName:a,type:i,stateVariable:s,dependency:o})}async processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){if("stateVariable"===t){let t=this._components[e];if(t){t.state[n]&&(t.state[n].isResolved=!0,t.state[n].initiallyResolved=!0)}}else if("componentIdentity"===t){if(!(e in this._components)&&!i)return{success:!1}}else if("recalculateDownstreamComponents"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let e=await t.recalculateDownstreamComponents({force:i});if(!e.success&&!i)return e;for(let e of t.upstreamVariableNames)this.deleteFromNeededToResolve({componentNameBlocked:t.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"recalculateDownstreamComponents",blockerCode:t.upstreamComponentName+"|"+e+"|"+r});for(let e of t.upstreamVariableNames)await this.resolveIfReady({componentName:t.upstreamComponentName,type:"stateVariable",stateVariable:e,expandComposites:a,force:i,recurseUpstream:s});return{success:!0}}}else if("determineDependencies"===t){let t;try{t=this.downstreamDependencies[e][n][r]}catch(e){}if(t){let o=this.getNeededToResolve({componentName:e,type:"stateVariable",stateVariable:n}),l=!1,u=[];if(o.determineDependencies)for(let t of o.determineDependencies){let[r,a,i]=t.split("|");if(this.checkIfHaveNeededToResolve({componentName:e,type:"determineDependency",stateVariable:n,dependency:i})){l=!0;break}u.push(i)}if(l)return{success:!0};if(!(await this.updateDependencies({componentName:e,stateVariable:n,dependency:r})).success)return{success:!1};for(let n of t.upstreamVariableNames){for(let e of u)this.deleteFromResolveBlockedBy({blockerComponentName:t.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:n,blockerDependency:e});await this.resolveIfReady({componentName:e,type:"stateVariable",stateVariable:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}}else if("childMatches"===t){let t=this._components[e];if(t&&!t.childrenMatched){if(!(await this.core.deriveChildResultsFromDefiningChildren({parent:t,expandComposites:a,forceExpandComposites:i})).skipping&&!t.childrenMatchedWithPlaceholders&&!i)return{success:!1}}}else{if("expandComposite"!==t)throw Error(`Unrecognized type newly resolved: ${t}`);if(!this._components[e].isExpanded){if(this.core.updateInfo.compositesBeingExpanded.includes(e))return{success:!1};await this.core.expandCompositeComponent(this._components[e])}}let o=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});o=Object.assign({},o);for(let l in o)for(let u of[...o[l]])if(this.deleteFromResolveBlockedBy({blockerComponentName:e,blockerType:t,blockerStateVariable:n,blockerDependency:r,typeBlocked:l,codeBlocked:u}),s){let[e,t,n]=u.split("|");await this.resolveIfReady({componentName:e,type:l,stateVariable:t,dependency:n,expandComposites:a,force:i,recurseUpstream:s})}return{success:!0}}async resolveStateVariablesIfReady({component:e,stateVariables:t}){let n=e.componentName;t||(await this.resolveIfReady({componentName:n,type:"componentIdentity",expandComposites:!1}),t=Object.keys(e.state));for(let r of t){let t=e.state[r];if(t&&t.determineDependenciesImmediately){let e=this.getNeededToResolve({componentName:n,type:"stateVariable",stateVariable:r}).determineDependencies;if(e)for(let t of e){let[e,n,r]=t.split("|");await this.resolveIfReady({componentName:e,type:"determineDependencies",stateVariable:n,dependency:r,expandComposites:!0})}}await this.resolveIfReady({componentName:n,type:"stateVariable",stateVariable:r,expandComposites:!1})}}async resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,expandComposites:a=!0,force:i=!1,recurseUpstream:s=!1}){return this.checkIfHaveNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})?{success:!1}:(this.deleteFromNeededToResolve({componentNameBlocked:e,typeBlocked:t,stateVariableBlocked:n,dependencyBlocked:r}),await this.processNewlyResolved({componentNameNewlyResolved:e,typeNewlyResolved:t,stateVariableNewlyResolved:n,dependencyNewlyResolved:r,expandComposites:a,force:i,recurseUpstream:s}))}async resolveItem({componentName:e,type:t,stateVariable:n,dependency:r,force:a=!1,recurseUpstream:i=!1,expandComposites:s=!0,numPreviouslyNeeded:o}){let l,u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),c=u.determineDependencies;if(c&&c.length>0)for(let e of[...c]){let[t,n,r]=e.split("|"),i=await this.resolveItem({componentName:t,type:"determineDependencies",stateVariable:n,dependency:r,force:a,expandComposites:s});if(!i.success)return i}"stateVariable"===t&&this._components[e]&&(l=this._components[e].state[n],l&&(l.currentlyResolving=!0));let p=1/0,d=1/0;for(;(Object.keys(u).length>0||d>0)&&!(Number.isFinite(d)&&d>=p);){d>0&&(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r})),p=d,d=0;for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,expandComposites:s});if(!o.success){if(!a)return o;d++}}}}if(d>0)for(u=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});Object.keys(u).length>0;)for(let i in u){if("determineDependencies"===i)throw Error(`Shouldn't have determine dependencies blocker after determining dependencies: ${e}, ${t}, ${n}, ${r}`);for(let e of[...u[i]]){let[t,n,r]=e.split("|"),o=await this.resolveItem({componentName:t,type:i,stateVariable:n,dependency:r,force:a,expandComposites:s});if(!o.success)return o}}l&&(l.currentlyResolving=!1);let m=await this.resolveIfReady({componentName:e,type:t,stateVariable:n,dependency:r,force:a,recurseUpstream:i,expandComposites:s});if(!m.success){let l=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r}),u=Object.keys(l).length;u>0&&(void 0===o||ue.match(t)[1])),r=n.filter((e=>"__"!==e.slice(0,2))).reduce(((e,t)=>e.includes(t)?e:[...e,t]),[]);0===r.length&&(r=[n[0]]),1===r.length?e=r[0]:2===r.length?e=r.join(" and "):(r[r.length-2]=r.slice(r.length-2).join(", and "),r.pop(),e=r.join(", "));let i=[],o=[];for(let e of a){let[t,n]=e.split("|"),r=this._components[t];if(r){this.componentInfoObjects.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&!r.attributes.createComponentOfType?.primitive&&("readyToExpandWhenResolved"===n?i.push(t):n===r.constructor.stateVariableToEvaluateAfterReplacements&&o.push(t))}}let l=!1;for(let e of i)if(o.includes(e)){l=!0;break}let u=`Circular dependency involving ${e}.`;throw l&&(u+=" Specifying the type of a composite component may address this circular dependency."),Error(u)}if(a=[...a,s],!this.circularResolveBlockedCheckPassed[s]){this.circularResolveBlockedCheckPassed[s]=!0;let i=this.getNeededToResolve({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in i)for(let t of i[e]){let[n,r,i]=t.split("|");this.checkForCircularResolveBlocker({componentName:n,type:e,stateVariable:r,dependency:i,previouslyVisited:a})}}}resetCircularResolveBlockerCheckPassed({componentName:e,type:t,stateVariable:n,dependency:r}){let a=e;n&&(a+="|"+n,r&&(a+="|"+r));let i=a+"|"+t;if(this.circularResolveBlockedCheckPassed[i]){delete this.circularResolveBlockedCheckPassed[i];let a=this.getResolveBlockedBy({componentName:e,type:t,stateVariable:n,dependency:r});for(let e in a)for(let t of a[e]){let[n,r,a]=t.split("|");this.resetCircularResolveBlockerCheckPassed({componentName:n,type:e,stateVariable:r,dependency:a})}}}get components(){return this._components}set components(e){return null}}class Dependency{constructor({component:e,stateVariable:t,allStateVariablesAffected:n,dependencyName:r,dependencyDefinition:a,dependencyHandler:i}){this.dependencyName=r,this.dependencyHandler=i,this.upstreamComponentName=e.componentName,this.upstreamVariableNames=n,this.definition=Object.assign({},a),this.representativeStateVariable=t,a.doNotProxy&&(this.doNotProxy=!0),a.variablesOptional&&(this.variablesOptional=!0),a.publicStateVariablesOnly&&(this.publicStateVariablesOnly=!0),a.caseInsensitiveVariableMatch&&(this.caseInsensitiveVariableMatch=!0),a.useMappedVariableNames&&(this.useMappedVariableNames=!0),a.propIndex&&(a.propIndex.every(Number.isFinite)?this.propIndex=a.propIndex.map(Math.round):this.propIndex=[]),this.returnSingleVariableValue=!1,this.returnSingleComponent=!1,this.originalDownstreamVariableNames=[]}static dependencyType="_base";downstreamVariableNameIfNoVariables="__identity";static get rendererType(){return this.componentType}get dependencyType(){return this.constructor.dependencyType}setUpParameters(){}async determineDownstreamComponents(){return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async initialize(){this.setUpParameters();let e=await this.determineDownstreamComponents(),t=e.downstreamComponentNames,n=e.downstreamComponentTypes;this.componentIdentitiesChanged=!0;let r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];r||(r=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName]={});for(let e of this.upstreamVariableNames)r[e]||(r[e]={}),r[e][this.dependencyName]=this;0!==this.originalDownstreamVariableNames.length||this.originalVariablesByComponent?(this.mappedDownstreamVariableNamesByComponent=[],this.valuesChanged=[]):(delete this.mappedDownstreamVariableNamesByComponent,delete this.upValuesChanged),this.downstreamComponentNames=[],this.downstreamComponentTypes=[];for(let[e,r]of t.entries())await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:n[e],index:e})}async addDownstreamComponent({downstreamComponentName:e,downstreamComponentType:t,index:n}){this.componentIdentitiesChanged=!0,this.downstreamComponentNames.splice(n,0,e),this.downstreamComponentTypes.splice(n,0,t);let r=this.dependencyHandler._components[e];if(r){let t;t=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[n]:this.originalDownstreamVariableNames,this.caseInsensitiveVariableMatch&&(t=this.dependencyHandler.core.findCaseInsensitiveMatches({stateVariables:t,componentClass:r.constructor})),this.publicStateVariablesOnly&&(t=this.dependencyHandler.core.matchPublicStateVariables({stateVariables:t,componentClass:r.constructor}));let a=this.dependencyHandler.core.substituteAliases({stateVariables:t,componentClass:r.constructor});this.constructor.convertToArraySize&&(a=a.map((function(e){let t=r.state[e];if(t)return t.arraySizeStateVariable?t.arraySizeStateVariable:`__${e}_is_not_an_array`;if(r.arrayEntryPrefixes){let t=Object.keys(r.arrayEntryPrefixes).sort(((e,t)=>t.length-e.length));for(let n of t)if(e.substring(0,n.length)===n){let t=r.arrayEntryPrefixes[n],a=r.state[t];if(a.getArrayKeysFromVarName({arrayEntryPrefix:n,varEnding:e.substring(n.length),nDimensions:a.nDimensions}).length>0)return r.state[t].arraySizeStateVariable}}return`__${e}_is_not_an_array`}))),void 0!==this.propIndex&&(a=await this.dependencyHandler.core.arrayEntryNamesFromPropIndex({stateVariables:a,component:r,propIndex:this.propIndex}));let i=a;if(t.length>0||this.originalVariablesByComponent){this.mappedDownstreamVariableNamesByComponent.splice(n,0,a);let t={};for(let e of a)t[e]={changed:!0};this.valuesChanged.splice(n,0,t),this.variablesOptional&&(i=i.filter((e=>e in r.state||this.dependencyHandler.core.checkIfArrayEntry({stateVariable:e,component:r}))));for(let t of i)if(r.state[t]||await this.dependencyHandler.core.createFromArrayEntry({component:r,stateVariable:t}),!r.state[t].isResolved)for(let n of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:n}),"determineDependencies"===this.dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:t,componentNameBlocked:this.upstreamComponentName,typeBlocked:"determineDependencies",stateVariableBlocked:n,dependencyBlocked:this.dependencyName})}0===i.length&&(i=[this.downstreamVariableNameIfNoVariables]);let s=this.dependencyHandler.upstreamDependencies[e];s||(s=this.dependencyHandler.upstreamDependencies[e]={});for(let e of i)if(void 0===s[e]&&(s[e]=[]),s[e].push(this),e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async removeDownstreamComponent({indexToRemove:e,recordChange:t=!0}){t&&(this.componentIdentitiesChanged=!0);let n=this.downstreamComponentNames[e];if(this.downstreamComponentNames.splice(e,1),this.downstreamComponentTypes.splice(e,1),n in this.dependencyHandler._components){let t;this.mappedDownstreamVariableNamesByComponent?(t=this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent.splice(e,1),this.valuesChanged.splice(e,1),this.variablesOptional&&t.push(this.downstreamVariableNameIfNoVariables)):t=[this.downstreamVariableNameIfNoVariables];for(let e of t){let t=this.dependencyHandler.upstreamDependencies[n][e];if(t){let r=t.indexOf(this);-1!==r&&(1===t.length?delete this.dependencyHandler.upstreamDependencies[n][e]:t.splice(r,1))}if(e!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}}if(t)for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}async swapDownstreamComponents(e,t){this.componentIdentitiesChanged=!0,[this.downstreamComponentNames[e],this.downstreamComponentNames[t]]=[this.downstreamComponentNames[t],this.downstreamComponentNames[e]],[this.downstreamComponentTypes[e],this.downstreamComponentTypes[t]]=[this.downstreamComponentTypes[t],this.downstreamComponentTypes[e]],(this.originalDownstreamVariableNames.length>0||this.originalVariablesByComponent)&&([this.mappedDownstreamVariableNamesByComponent[e],this.mappedDownstreamVariableNamesByComponent[t]]=[this.mappedDownstreamVariableNamesByComponent[t],this.mappedDownstreamVariableNamesByComponent[e]],[this.valuesChanged[e],this.valuesChanged[t]]=[this.valuesChanged[t],this.valuesChanged[e]]);for(let e of this.upstreamVariableNames)this.dependencyHandler._components[this.upstreamComponentName].state[e].initiallyResolved&&await this.dependencyHandler.core.markStateVariableAndUpstreamDependentsStale({component:this.dependencyHandler.components[this.upstreamComponentName],varName:e})}deleteDependency(){let e=[];if(this.mappedDownstreamVariableNamesByComponent){if(e=this.mappedDownstreamVariableNamesByComponent,this.variablesOptional){let t=[];for(let[n,r]of this.downstreamComponentNames.entries()){let a=[];for(let t of e[n])this.dependencyHandler.components[r].state[t]&&a.push(t);a.length>0?t.push(a):t.push([this.downstreamVariableNameIfNoVariables])}e=t}}else e=Array(this.downstreamComponentNames.length).fill([this.downstreamVariableNameIfNoVariables]);for(let[t,n]of this.downstreamComponentNames.entries())for(let r of e[t]){let e=this.dependencyHandler.upstreamDependencies[n][r];if(e){let t=e.indexOf(this);-1!==t&&(1===e.length?delete this.dependencyHandler.upstreamDependencies[n][r]:e.splice(t,1))}for(let e of this.upstreamVariableNames)this.dependencyHandler.deleteFromNeededToResolve({componentNameBlocked:this.componentName,typeBlocked:"stateVariable",stateVariableBlocked:e,blockerType:"stateVariable",blockerCode:n+"|"+r});if(r!==this.downstreamVariableNameIfNoVariables)for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e)}this.deleteFromUpdateTriggers();let t=this.dependencyHandler.downstreamDependencies[this.upstreamComponentName];for(let e of this.upstreamVariableNames)delete t[e][this.dependencyName]}deleteFromUpdateTriggers(){}async getValue({verbose:e=!1,skipProxy:t=!1}={}){let n=[],r={},a=[];this.componentIdentitiesChanged&&(r.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1);for(let[e,t]of this.downstreamComponentNames.entries()){let i=this.dependencyHandler._components[t];if(a[e]=!1,i){let s,o={componentType:i.componentType};if(this.skipComponentNames||(o.componentName=t),s=this.originalVariablesByComponent?this.originalDownstreamVariableNamesByComponent[e]:this.originalDownstreamVariableNames,s.length>0){o.stateValues={};let t={},n=!1;for(let[a,l]of s.entries()){let s=this.mappedDownstreamVariableNamesByComponent[e][a],u=this.useMappedVariableNames?s:l;if(!this.variablesOptional||s in i.state){let a=i.state[s];if(!a.deferred)if(o.stateValues[u]=await a.value,this.valuesChanged[e][s].changed&&(r.valuesChanged||(r.valuesChanged={}),r.valuesChanged[e]||(r.valuesChanged[e]={}),r.valuesChanged[e][u]=this.valuesChanged[e][s]),this.valuesChanged[e][s]={},a.usedDefault)t[u]=!0,n=!0;else if(a.isArrayEntry&&1===a.arrayKeys.length){i.state[a.arrayStateVariable].usedDefaultByArrayKey[a.arrayKeys[0]]&&(t[u]=!0,n=!0)}}}n&&(a[e]=t)}n.push(o)}else n.push({componentType:this.downstreamComponentTypes[e]})}if(!e)if(this.returnSingleVariableValue)if(1===n.length){n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0];let e=Object.keys(n.stateValues);if(1===e.length){let t=e[0];n=n.stateValues[t],r.valuesChanged&&r.valuesChanged[t]&&(r.valuesChanged=r.valuesChanged[t]),a&&(a=a[t])}else n=null,r={},a=!1}else n=null,r={},a=!1;else this.returnSingleComponent&&(1===n.length?(n=n[0],r.valuesChanged&&r.valuesChanged[0]?r.valuesChanged=r.valuesChanged[0]:delete r.valuesChanged,a=a[0]):(n=null,a=!1));return{value:n,changes:r,usedDefault:a}}checkForCircular(){for(let e of this.upstreamVariableNames)this.dependencyHandler.resetCircularCheckPassed(this.upstreamComponentName,e);for(let e of this.upstreamVariableNames)this.dependencyHandler.checkForCircularDependency({componentName:this.upstreamComponentName,varName:e})}async recalculateDownstreamComponents({force:e=!1}={}){let t=await this.determineDownstreamComponents({force:e}),n=t.downstreamComponentNames,r=n.length!==this.downstreamComponentNames.length||this.downstreamComponentNames.some(((e,t)=>e!=n[t]));if(r){this.componentIdentitiesChanged=!0;let e=0;for(let[t,r]of[...this.downstreamComponentNames].entries())n.includes(r)||(await this.removeDownstreamComponent({indexToRemove:t-e}),e++);for(let[e,r]of n.entries()){let n=this.downstreamComponentNames.indexOf(r);-1!==n?n!==e&&await this.swapDownstreamComponents(n,e):await this.addDownstreamComponent({downstreamComponentName:r,downstreamComponentType:t.downstreamComponentTypes[e],index:e})}}if(this.originalVariablesByComponent)for(let[e,n]of[...this.downstreamComponentNames].entries())(this.mappedDownstreamVariableNamesByComponent[e].length!==this.originalDownstreamVariableNamesByComponent[e].length||this.mappedDownstreamVariableNamesByComponent[e].some(((t,n)=>this.originalDownstreamVariableNamesByComponent[e][n]!==t)))&&(await this.removeDownstreamComponent({indexToRemove:e}),await this.addDownstreamComponent({downstreamComponentName:n,downstreamComponentType:t.downstreamComponentTypes[e],index:e}));return{success:t.success}}}class StateVariableDependency extends Dependency{static dependencyType="stateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableName is not defined`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.returnAsComponentObject?this.returnSingleComponent=!0:this.returnSingleVariableValue=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(StateVariableDependency);class MultipleStateVariablesDependency extends Dependency{static dependencyType="multipleStateVariables";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(MultipleStateVariablesDependency);class StateVariableComponentTypeDependency extends StateVariableDependency{static dependencyType="stateVariableComponentType";async getValue({verbose:e=!1}={}){let t=[],n={};if(this.staticValue)t=[this.staticValue];else if(this.componentIdentitiesChanged&&(n.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let e=this.downstreamComponentNames[0],r=this.dependencyHandler.components[e],a={componentName:r.componentName,componentType:r.componentType,stateValues:{}},i=this.originalDownstreamVariableNames[0],s=this.mappedDownstreamVariableNamesByComponent[0][0],o=this.useMappedVariableNames?s:i;if((!this.variablesOptional||s in r.state)&&!r.state[s].deferred){let e=r.state[s];if(await e.value,a.stateValues[o]=e.componentType,e.isArray&&e.wrappingComponents?.length>0){let t=e.wrappingComponents[e.wrappingComponents.length-1][0];"object"==typeof t&&(t=t.componentType),a.stateValues[o]=t}this.valuesChanged[0][s].changed&&(n.valuesChanged||(n.valuesChanged={}),n.valuesChanged[0]||(n.valuesChanged[0]={}),n.valuesChanged[0][o]=this.valuesChanged[0][s]),this.valuesChanged[0][s]={};let t=e.shadowingInstructions?.hasVariableComponentType;if(!t&&e.isArrayEntry){t=r.state[e.arrayStateVariable].shadowingInstructions?.hasVariableComponentType}t||(this.staticValue=a,await this.removeDownstreamComponent({indexToRemove:0,recordChange:!1}))}t=[a]}if(!e)if(this.returnSingleVariableValue)if(1===t.length){t=t[0];let e=Object.keys(t.stateValues);n.valuesChanged&&n.valuesChanged[0]&&n.valuesChanged[0][0]&&(n.valuesChanged=n.valuesChanged[0][0]),t=1===e.length?t.stateValues[e[0]]:null}else t=null;else this.returnSingleComponent&&(1===t.length?(t=t[0],n.valuesChanged&&n.valuesChanged[0]&&(n.valuesChanged=n.valuesChanged[0])):t=null);return{value:t,changes:n,usedDefault:!1}}}dependencyTypeArray.push(StateVariableComponentTypeDependency);class StateVariableArraySizeDependency extends StateVariableDependency{static dependencyType="stateVariableArraySize";static convertToArraySize=!0}dependencyTypeArray.push(StateVariableArraySizeDependency);class RecursiveDependencyValuesDependency extends Dependency{static dependencyType="recursiveDependencyValues";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.startingVariableNames=this.definition.variableNames,this.originalVariablesByComponent=!0,this.includeImmediateValueWithValue=this.definition.includeImmediateValueWithValue,this.includeRawValueWithImmediateValue=this.definition.includeRawValueWithImmediateValue,this.includeOnlyEssentialValues=this.definition.includeOnlyEssentialValues,this.variablesOptional=!0}async determineDownstreamComponents({force:e=!1}={}){this.missingComponents=[],this.originalDownstreamVariableNamesByComponent=[];let t=await this.getRecursiveDependencyVariables({componentName:this.componentName,variableNames:this.startingVariableNames,force:e});if(!t.success)return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=[],r=[];for(let e in t.components)if(this.includeOnlyEssentialValues){let a=[],i=this.dependencyHandler._components[e];for(let n of t.components[e].variableNames)(i.state[n]?.hasEssential||i.state[n]?.isArrayEntry&&i.state[i.state[n].arrayStateVariable].hasEssential)&&a.push(n);a.length>0&&(n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(a))}else n.push(e),r.push(t.components[e].componentType),this.originalDownstreamVariableNamesByComponent.push(t.components[e].variableNames);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getRecursiveDependencyVariables({componentName:e,variableNames:t,force:n,components:r={}}){let a=this.dependencyHandler._components[e];if(!a){if(!this.missingComponents.includes(e)){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(this)||t.push(this)}for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}this.includeImmediateValueWithValue&&t.includes("value")&&!t.includes("immediateValue")&&"immediateValue"in a.state&&(t=[...t,"immediateValue"]),this.includeRawValueWithImmediateValue&&t.includes("immediateValue")&&!t.includes("rawRendererValue")&&"rawRendererValue"in a.state&&(t=[...t,"rawRendererValue"]);let i=r[e];i||(i=r[e]={componentName:e,componentType:a.componentType,variableNames:[]});let s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e];s||(s=this.dependencyHandler.updateTriggers.dependenciesBasedOnDependenciesOfStateVariables[e]={});for(let o of t)if(!i.variableNames.includes(o)){i.variableNames.push(o);let t=s[o];t||(t=s[o]=[]),t.includes(this)||t.push(this);let l=a.state[o];if(l){if(!l.isResolved){if(!n){for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:o,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});return{success:!1}}await l.value}let t=this.dependencyHandler.downstreamDependencies[a.componentName][o];for(let e in t){let a=t[e];for(let[e,t]of a.downstreamComponentNames.entries()){let i=[];if((a.originalDownstreamVariableNames.length>0||a.originalVariablesByComponent)&&(i=a.mappedDownstreamVariableNamesByComponent[e]),!(await this.getRecursiveDependencyVariables({componentName:t,variableNames:i,force:n,components:r})).success)return{success:!1}}}}}return{success:!0,components:r}}async getValue(){let e;this.gettingValue=!0,this.varsWithUpdatedDeps={};let t={},n=!0,r={};for(;n;){if(n=!1,e=await super.getValue(),e.changes.valuesChanged)if(r.valuesChanged)for(let t in e.changes.valuesChanged){let n=e.changes.valuesChanged[t];if(r.valuesChanged[t])for(let e in n)r.valuesChanged[t][e]=n[e];else r.valuesChanged[t]=n}else r.valuesChanged=e.changes.valuesChanged;for(let e in this.varsWithUpdatedDeps){let r=t[e];r||(r=t[e]=[]);for(let t of this.varsWithUpdatedDeps[e])r.includes(t)||(r.push(t),n=!0)}n&&await this.recalculateDownstreamComponents()}return this.gettingValue=!1,e.changes=r,e}deleteFromUpdateTriggers(){for(let e of this.missingComponents){let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}}dependencyTypeArray.push(RecursiveDependencyValuesDependency);class ComponentIdentityDependency extends Dependency{static dependencyType="componentIdentity";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ComponentIdentityDependency);class AttributeComponentDependency extends Dependency{static dependencyType="attributeComponent";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.attributeName=this.definition.attributeName,this.returnSingleComponent=!0,this.shadowDepth=0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=e.attributes[this.attributeName];if(this.shadowDepth=0,t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]};let n=e;for(;n.shadows;){let e=n.shadows,r=n.shadows.propVariable;if(n=this.dependencyHandler._components[e.componentName],!n)break;if(r){if(!n.state[r]?.shadowingInstructions?.attributesToShadow?.includes(this.attributeName)&&!n.constructor.createAttributesObject()[this.attributeName]?.propagateToProps)break}else{let t=this.dependencyHandler._components[e.compositeName];if("sourceAttributesToIgnoreRecursively"in t.state){if((await t.stateValues.sourceAttributesToIgnoreRecursively).includes(this.attributeName))break}if(e.firstLevelReplacement&&"sourceAttributesToIgnore"in t.state){if((await t.stateValues.sourceAttributesToIgnore).includes(this.attributeName))break}}if(this.shadowDepth++,t=n.attributes[this.attributeName],t?.component)return{success:!0,downstreamComponentNames:[t.component.componentName],downstreamComponentTypes:[t.component.componentType]}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0});return t.value&&(t.value.shadowDepth=this.shadowDepth),t}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AttributeComponentDependency);class ChildDependency extends Dependency{static dependencyType="child";setUpParameters(){if(this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];if(this.childGroups=this.definition.childGroups,!Array.isArray(this.childGroups))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups must be an array`);void 0!==this.definition.childIndices&&(this.childIndices=this.definition.childIndices.map((e=>Number(e)))),this.skipComponentNames=this.definition.skipComponentNames,this.skipPlaceholders=this.definition.skipPlaceholders,this.proceedIfAllChildrenNotMatched=this.definition.proceedIfAllChildrenNotMatched}async determineDownstreamComponents(){this.downstreamPrimitives?this.previousDownstreamPrimitives=[...this.downstreamPrimitives]:this.previousDownstreamPrimitives=[],this.downstreamPrimitives=[];let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];t||(t=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),t.includes(this)||t.push(this);let n=e.returnMatchedChildIndices(this.childGroups);if(void 0===n)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: childGroups ${this.childGroups} does not exist.`);if(this.childIndices&&(n=n.filter(((e,t)=>this.childIndices.includes(t)))),!e.childrenMatched&&!this.proceedIfAllChildrenNotMatched){let t=!1;if(e.childrenMatchedWithPlaceholders&&(this.skipPlaceholders&&(n=n.filter((t=>!e.placeholderActiveChildrenIndices.includes(t)))),t=!(!this.skipComponentNames||0!==this.originalDownstreamVariableNames.length)||n.every((t=>!e.placeholderActiveChildrenIndices.includes(t)))),!t){let t=e.unexpandedCompositesNotReady.length>0;if(!t&&e.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(t){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});let t=[],r=[];for(let a of e.unexpandedCompositesNotReady){if(e.childrenMatchedWithPlaceholders){if(e.placeholderActiveChildrenIndicesByComposite[a].every((e=>!n.includes(e))))continue}this.dependencyHandler._components[a].attributes.createComponentOfType?.primitive?t.push(a):r.push(a)}let a=r;0===a.length&&(a=t);for(let e of a)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}let r=n.map((t=>e.activeChildren[t]));if(this.compositeReplacementRange=[],e.compositeReplacementActiveRange&&r.length>0){let t=0;for(;t=r){let e=t,i=t;for(;a.lastInd>r&&t=r);)i=t;if(this.compositeReplacementRange.push({compositeName:a.compositeName,target:a.target,firstInd:e,lastInd:i}),t++,t===n.length)break;r=n[t]}t++}}this.shadowDepthByChild=[];for(let t of r){let n=0,r=t,a=e;for(;r?.shadows&&r.shadows.compositeName===a?.shadows?.compositeName;)n++,a=this.dependencyHandler._components[a.shadows.componentName],r=this.dependencyHandler._components[r.shadows.componentName];this.shadowDepthByChild.push(n)}this.activeChildrenIndices=n;let a=[],i=[];for(let[e,t]of r.entries())"object"==typeof t?(this.downstreamPrimitives.push(null),a.push(t.componentName?t.componentName:`__placeholder_${e}`),i.push(t.componentType)):this.downstreamPrimitives.push(t);return{success:!0,downstreamComponentNames:a,downstreamComponentTypes:i}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let[e,a]of this.downstreamPrimitives.entries())if(null===a){t.value[r].shadowDepth=this.shadowDepthByChild[e],n.push(t.value[r]),r++}else n.push(a);return n.compositeReplacementRange=this.compositeReplacementRange,t.value=n,(this.downstreamPrimitives.length!==this.previousDownstreamPrimitives.length||this.downstreamPrimitives.some(((e,t)=>e!==this.previousDownstreamPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousDownstreamPrimitives=[...this.downstreamPrimitives]),t}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ChildDependency);class DescendantDependency extends Dependency{static dependencyType="descendant";setUpParameters(){if(this.definition.ancestorName?(this.ancestorName=this.definition.ancestorName,this.specifiedComponentName=this.ancestorName):this.ancestorName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.componentTypes=this.definition.componentTypes,this.recurseToMatchedChildren=this.definition.recurseToMatchedChildren,this.useReplacementsForComposites=this.definition.useReplacementsForComposites,this.includeNonActiveChildren=this.definition.includeNonActiveChildren,this.includeAttributeChildren=this.definition.includeAttributeChildren,this.skipOverAdapters=this.definition.skipOverAdapters,this.ignoreReplacementsOfMatchedComposites=this.definition.ignoreReplacementsOfMatchedComposites,this.ignoreReplacementsOfEncounteredComposites=this.definition.ignoreReplacementsOfEncounteredComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.ancestorName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.ancestorName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];t||(t=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName]=[]),t.includes(this)||t.push(this);let n=this.gatherUnexpandedComposites(e);if(n.haveCompositesNotReady||n.haveUnexpandedCompositeReady){for(let e of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let t in n.unexpandedCompositesReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});for(let t in n.unexpandedCompositesNotReadyByParentName)await this.dependencyHandler.addBlocker({blockerComponentName:t,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName})}return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let r=gatherDescendants({ancestor:e,descendantTypes:this.componentTypes,recurseToMatchedChildren:this.recurseToMatchedChildren,useReplacementsForComposites:this.useReplacementsForComposites,includeNonActiveChildren:this.includeNonActiveChildren,skipOverAdapters:this.skipOverAdapters,ignoreReplacementsOfMatchedComposites:this.ignoreReplacementsOfMatchedComposites,ignoreReplacementsOfEncounteredComposites:this.ignoreReplacementsOfEncounteredComposites,componentInfoObjects:this.dependencyHandler.componentInfoObjects});if(void 0!==this.componentIndex){let e=r[this.componentIndex-1];r=e?[e]:[]}return{success:!0,downstreamComponentNames:r.map((e=>e.componentName)),downstreamComponentTypes:r.map((e=>e.componentType))}}gatherUnexpandedComposites(e){let t={},n={},r=!1,a=!1,i=this.skipComponentNames&&0===this.originalDownstreamVariableNames.length;if(!e.childrenMatched)if(e.childrenMatchedWithPlaceholders){if(e.unexpandedCompositesReady.length>0){let n=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesReady,i);n.length>0&&(t[e.componentName]=n,r=!0)}if(e.unexpandedCompositesNotReady.length>0){let t=this.unexpandedCompositesAdjustedForPlacedholders(e.unexpandedCompositesNotReady,i);t.length>0&&(n[e.componentName]=t,a=!0)}}else e.unexpandedCompositesReady.length>0&&(t[e.componentName]=e.unexpandedCompositesReady,r=!0),e.unexpandedCompositesNotReady.length>0&&(n[e.componentName]=e.unexpandedCompositesNotReady,a=!0);for(let i in e.allChildren){let s=e.allChildren[i].component;if("object"==typeof s){let e=this.gatherUnexpandedComposites(s);e.haveUnexpandedCompositeReady&&(Object.assign(t,e.unexpandedCompositesReadyByParentName),r=!0),e.haveCompositesNotReady&&(Object.assign(n,e.unexpandedCompositesNotReadyByParentName),a=!0)}}return{unexpandedCompositesReadyByParentName:t,haveUnexpandedCompositeReady:r,unexpandedCompositesNotReadyByParentName:n,haveCompositesNotReady:a}}unexpandedCompositesAdjustedForPlacedholders(e,t){let n=[];for(let r of e){let e=this.dependencyHandler._components[r];if(e.attributes.createComponentOfType){let a=this.dependencyHandler.componentInfoObjects.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],i=this.componentTypes.some((e=>this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:a,baseComponentType:e})));i&&t||n.push(r)}else n.push(r)}return n}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.descendantDependenciesByAncestor[this.ancestorName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DescendantDependency);class ParentDependency extends Dependency{static dependencyType="parentStateVariable";setUpParameters(){if(this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentDependency);class ParentIdentityDependency extends Dependency{static dependencyType="parentIdentity";setUpParameters(){this.definition.childName?(this.childName=this.definition.childName,this.specifiedComponentName=this.childName):this.childName=this.upstreamComponentName,this.definition.parentComponentType&&(this.parentComponentType=this.definition.parentComponentType),this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.childName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.childName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.childName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(this.parentComponentType&&!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.parentComponentType}))return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];return n||(n=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.parentDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}}dependencyTypeArray.push(ParentIdentityDependency);class AncestorDependency extends Dependency{static dependencyType="ancestor";setUpParameters(){if(this.definition.descendantName?(this.descendantName=this.definition.descendantName,this.specifiedComponentName=this.descendantName):this.descendantName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.definition.componentType&&(this.componentType=this.definition.componentType)}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.descendantName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.descendantName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.descendantName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!(this.dependencyHandler.core.documentName in this.dependencyHandler._components)){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e}),await this.dependencyHandler.addBlocker({blockerComponentName:this.dependencyHandler.core.documentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.findMatchingAncestor(e);if(t.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[t.missingComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:t.missingComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of t.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];t||(t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e]=[]),t.includes(this)||t.push(this)}return this.ancestorResults=t,t.ancestorFound?{success:!0,downstreamComponentNames:[t.ancestorFound.componentName],downstreamComponentTypes:[t.ancestorFound.componentClass.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}findMatchingAncestor(e){let t=[];if(this.componentType){for(let n of e.ancestors){let e=this.dependencyHandler._components[n.componentName];if(!e)return{missingComponentName:n.componentName};if(t.push(n.componentName),this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:this.componentType}))return{ancestorsExamined:t,ancestorFound:n}}return{ancestorsExamined:t}}if(0===this.originalDownstreamVariableNames.length)return console.warn(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must specify componentType or variableNames to find ancestor`),{ancestorsExamined:t};let n=this.originalDownstreamVariableNames;for(let r of e.ancestors){let e=this.dependencyHandler._components[r.componentName];if(!e)return{missingComponentName:r.componentName};t.push(r.componentName);let a=!0;for(let t of n)if(!(t in e.state)&&!this.dependencyHandler.core.checkIfArrayEntry({stateVariable:t,component:e})){a=!1;break}if(a)return{ancestorsExamined:t,ancestorFound:r}}return{ancestorsExamined:t}}deleteFromUpdateTriggers(){for(let e of this.ancestorResults.ancestorsExamined){let t=this.dependencyHandler.updateTriggers.ancestorDependenciesByPotentialAncestor[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}if(this.ancestorResults&&this.ancestorResults.missingComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.ancestorResults.missingComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AncestorDependency);class ReplacementDependency extends Dependency{static dependencyType="replacement";setUpParameters(){if(this.definition.compositeName?(this.compositeName=this.definition.compositeName,this.specifiedComponentName=this.compositeName):this.compositeName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.recursive=this.definition.recursive,this.recurseNonStandardComposites=this.definition.recurseNonStandardComposites,null!==this.definition.componentIndex&&void 0!==this.definition.componentIndex&&(Number.isInteger(this.definition.componentIndex)?this.componentIndex=this.definition.componentIndex:this.componentIndex=NaN),this.definition.targetSubnames&&(this.targetSubnames=this.definition.targetSubnames),this.definition.targetSubnamesComponentIndex&&(this.definition.targetSubnamesComponentIndex.every(Number.isInteger)?this.targetSubnamesComponentIndex=this.definition.targetSubnamesComponentIndex:this.targetSubnamesComponentIndex=[NaN]),this.includeWithheldReplacements=this.definition.includeWithheldReplacements,this.expandReplacements=!0}async determineDownstreamComponents(){this.replacementPrimitives?this.previousReplacementPrimitives=[...this.replacementPrimitives]:this.previousReplacementPrimitives=[],this.replacementPrimitives=[];let e=this.dependencyHandler._components[this.compositeName];if(!e){let a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName];a||(a=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.compositeName]=[]),a.includes(this)||a.push(this);for(let i of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:i,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:i,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:i});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.isExpanded){for(let s of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:s,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:s}),await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:s,dependencyBlocked:this.dependencyName});return e.state.readyToExpandWhenResolved.isResolved||await this.dependencyHandler.addBlocker({blockerComponentName:this.compositeName,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.compositeName,typeBlocked:"expandComposite"}),{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}this.compositesFound=[this.compositeName];let t=e.replacements;if(!this.includeWithheldReplacements&&e.replacementsToWithhold>0&&(t=t.slice(0,-e.replacementsToWithhold)),this.recursive){let o=this.dependencyHandler.core.recursivelyReplaceCompositesWithReplacements({replacements:t,recurseNonStandardComposites:this.recurseNonStandardComposites,includeWithheldReplacements:this.includeWithheldReplacements});if(o.unexpandedCompositesNotReady.length>0||o.unexpandedCompositesReady.length>0){for(let l of this.upstreamVariableNames){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:l,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:l});for(let u of[...o.unexpandedCompositesReady,...o.unexpandedCompositesNotReady])await this.dependencyHandler.addBlocker({blockerComponentName:u,blockerType:"expandComposite",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:l,dependencyBlocked:this.dependencyName})}for(let c of o.unexpandedCompositesNotReady)await this.dependencyHandler.addBlocker({blockerComponentName:c,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:c,typeBlocked:"expandComposite"});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}t=o.newReplacements,this.compositesFound.push(...o.compositesFound)}for(let p of this.compositesFound){let d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p];d||(d=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[p]=[]),d.includes(this)||d.push(this)}if(void 0!==this.componentIndex){let m=t[this.componentIndex-1];t=m?[m]:[]}if(this.targetSubnames){function h({components:e,subNames:t,subNamesComponentIndex:n,dep:r}){if(0===t.length)return e;let a=t.slice(1),i=[];for(let s of e){let e=s.componentName+"/"+t[0],o=r.dependencyHandler._components[e];if(o)r.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:o.componentType,baseComponentType:"_composite"})?console.warn("Have not yet implemented recursing subnames to multiple levels of composites"):0===a.length&&(n?.length,1)&&i.push(o);else{let t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e];t||(t=r.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[e]=[]),t.includes(r)||t.push(r)}}return i}t=h({components:t,subNames:this.targetSubnames,subNamesComponentIndex:this.targetSubnamesComponentIndex,dep:this})}let n=[],r=[];for(let f of t)"object"==typeof f?(this.replacementPrimitives.push(null),n.push(f.componentName),r.push(f.componentType)):this.replacementPrimitives.push(f);return{success:!0,downstreamComponentNames:n,downstreamComponentTypes:r}}async getValue({verbose:e}={}){let t=await super.getValue({verbose:e,skipProxy:!0}),n=[],r=0;for(let e of this.replacementPrimitives)null===e?(n.push(t.value[r]),r++):n.push(e);return t.value=n,(this.replacementPrimitives.length!==this.previousReplacementPrimitives.length||this.replacementPrimitives.some(((e,t)=>e!==this.previousReplacementPrimitives[t])))&&(t.changes.componentIdentitiesChanged=!0,this.previousReplacementPrimitives=[...this.replacementPrimitives]),t}deleteFromUpdateTriggers(){if(this.compositesFound)for(let e of this.compositesFound){let t=this.dependencyHandler.updateTriggers.replacementDependenciesByComposite[e];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ReplacementDependency);class SourceCompositeStateVariableDependency extends Dependency{static dependencyType="sourceCompositeStateVariable";setUpParameters(){if(this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.definition.compositeComponentType&&(this.compositeComponentType=this.definition.compositeComponentType),this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;if(this.compositeComponentType)for(;!this.dependencyHandler.componentInfoObjects.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:this.compositeComponentType});){if(!t.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};t=t.replacementOf}return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeStateVariableDependency);class SourceCompositeIdentityDependency extends Dependency{static dependencyType="sourceCompositeIdentity";setUpParameters(){this.definition.replacementName?(this.replacementName=this.definition.replacementName,this.specifiedComponentName=this.replacementName):this.replacementName=this.upstreamComponentName,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.replacementName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.replacementName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.replacementName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.replacementOf)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.replacementOf;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SourceCompositeIdentityDependency);class ShadowSourceDependency extends Dependency{static dependencyType="shadowSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.shadows)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.shadows.componentName,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(ShadowSourceDependency);class UnlinkedCopySourceDependency extends Dependency{static dependencyType="unlinkedCopySource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.unlinkedCopySource)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.unlinkedCopySource,n=this.dependencyHandler._components[t];return n?{success:!0,downstreamComponentNames:[n.componentName],downstreamComponentTypes:[n.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(UnlinkedCopySourceDependency);class PrimaryShadowDependency extends Dependency{static dependencyType="primaryShadow";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName];if(t||(t=this.dependencyHandler.updateTriggers.primaryShadowDependencies[this.componentName]=[]),t.includes(this)||t.push(this),!e.primaryShadow)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let n=e.primaryShadow,r=this.dependencyHandler._components[n];return r?{success:!0,downstreamComponentNames:[r.componentName],downstreamComponentTypes:[r.componentType]}:{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(PrimaryShadowDependency);class AdapterSourceStateVariableDependency extends Dependency{static dependencyType="adapterSourceStateVariable";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,!this.definition.variableName)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: must have a variableName`);this.originalDownstreamVariableNames=[this.definition.variableName],this.returnSingleVariableValue=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceStateVariableDependency);class AdapterSourceDependency extends Dependency{static dependencyType="adapterSource";setUpParameters(){if(this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0,this.variablesOptional=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.adaptedFrom)return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};let t=e.adaptedFrom;return{success:!0,downstreamComponentNames:[t.componentName],downstreamComponentTypes:[t.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(AdapterSourceDependency);class CountAmongSiblingsDependency extends Dependency{static dependencyType="countAmongSiblingsOfSameType";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(!e.parentName)return console.warn(`component ${this.componentName} does not have a parent for state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}.`),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]};this.parentName=e.parentName;let t=this.dependencyHandler._components[this.parentName];if(!t){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}let n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(n||(n=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName]=[]),n.includes(this)||n.push(this),!t.childrenMatched){if(!t.childrenMatchedWithPlaceholders){let e=t.unexpandedCompositesNotReady.length>0;if(!e&&t.unexpandedCompositesReady.length>0){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}if(e){for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"childMatches",blockerStateVariable:e,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});for(let e of t.unexpandedCompositesNotReady)for(let t of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:e,blockerType:"stateVariable",blockerStateVariable:"readyToExpandWhenResolved",componentNameBlocked:this.upstreamComponentName,typeBlocked:"childMatches",stateVariableBlocked:t});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}}}return{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.childDependenciesByParent[this.parentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}let t=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];if(t){let e=t.indexOf(this);-1!==e&&t.splice(e,1)}}async getValue(){let e=this.dependencyHandler.components[this.upstreamComponentName].componentType,t=this.dependencyHandler.components[this.parentName].activeChildren.filter((t=>t.componentType===e)),n=t.map((e=>e.componentName)).indexOf(this.upstreamComponentName)+1;if(this.parentName===this.dependencyHandler.core.documentName){let t=this.dependencyHandler.core.previousComponentTypeCounts[e];t&&(n+=t)}return{value:n,changes:{}}}}dependencyTypeArray.push(CountAmongSiblingsDependency);class AttributeTargetComponentNamesDependency extends StateVariableDependency{static dependencyType="attributeTargetComponentNames";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.targetComponentNames:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributeTargetComponentNamesDependency);class TargetComponentDependency extends Dependency{static dependencyType="targetComponent";setUpParameters(){let e=this.dependencyHandler._components[this.upstreamComponentName];if(this.target=e.doenetAttributes.target,this.target&&(this.targetComponentName=this.specifiedComponentName=e.doenetAttributes.targetComponentName),this.definition.variableNames){if(!Array.isArray(this.definition.variableNames))throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames must be an array`);this.originalDownstreamVariableNames=this.definition.variableNames}else this.originalDownstreamVariableNames=[];this.returnSingleComponent=!0}async determineDownstreamComponents(){if(!this.target)return{downstreamComponentNames:[],downstreamComponentTypes:[]};let e=this.dependencyHandler._components[this.targetComponentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.targetComponentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.targetComponentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.targetComponentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}dependencyTypeArray.push(TargetComponentDependency);class ValueDependency extends Dependency{static dependencyType="value";setUpParameters(){this.value=this.definition.value}async getValue(){return{value:this.value,changes:{}}}}dependencyTypeArray.push(ValueDependency);class FlagDependency extends ValueDependency{static dependencyType="flag";setUpParameters(){this.flagName=this.definition.flagName,this.value=this.dependencyHandler.core.flags[this.flagName]}}dependencyTypeArray.push(FlagDependency);class DoenetAttributeDependency extends StateVariableDependency{static dependencyType="doenetAttribute";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){e=this.dependencyHandler.components[this.downstreamComponentNames[0]].doenetAttributes[this.attributeName]}return{value:e,changes:t}}}dependencyTypeArray.push(DoenetAttributeDependency);class AttributePrimitiveDependency extends StateVariableDependency{static dependencyType="attributePrimitive";setUpParameters(){this.attributeName=this.definition.attributeName,this.definition.parentName?(this.componentName=this.definition.parentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async getValue(){let e=null,t={};if(this.componentIdentitiesChanged&&(t.componentIdentitiesChanged=!0,this.componentIdentitiesChanged=!1),1===this.downstreamComponentNames.length){let t=this.dependencyHandler.components[this.componentName];t&&(e=t.attributes[this.attributeName],e=e?e.primitive:null)}return{value:e,changes:t}}}dependencyTypeArray.push(AttributePrimitiveDependency);class SerializedChildrenDependency extends Dependency{static dependencyType="serializedChildren";setUpParameters(){this.definition.parentName?(this.parentName=this.definition.parentName,this.specifiedComponentName=this.parentName):this.parentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.parentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.parentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.parentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.parentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.parentName].serializedChildren,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(SerializedChildrenDependency);class DoenetMLDependency extends Dependency{static dependencyType="doenetML";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName,this.displayOnlyChildren=this.definition.displayOnlyChildren}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler.core.requestComponentDoenetML(this.componentName,this.displayOnlyChildren),changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(DoenetMLDependency);class VariantsDependency extends Dependency{static dependencyType="variants";setUpParameters(){this.definition.componentName?(this.componentName=this.definition.componentName,this.specifiedComponentName=this.componentName):this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].variants,changes:{}}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}}dependencyTypeArray.push(VariantsDependency);class CounterDependency extends Dependency{static dependencyType="counter";setUpParameters(){this.counterName=this.definition.counterName,this.componentName=this.upstreamComponentName}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName],t=e.counters[this.counterName];return t||(t=e.counters[this.counterName]={dependencies:[],componentList:[],value:null}),t.dependencies.includes(this)||t.dependencies.push(this),await this.dependencyHandler.collateCountersAndPropagateToAncestors(e),{success:!0,downstreamComponentNames:[],downstreamComponentTypes:[]}}async getValue(){return{value:this.dependencyHandler._components[this.componentName].counters[this.counterName].value,changes:{}}}}dependencyTypeArray.push(CounterDependency);class DetermineDependenciesDependency extends Dependency{static dependencyType="determineDependencies";setUpParameters(){if(this.recalculateDependencies=!0,this.definition.componentName?this.componentName=this.definition.componentName:this.componentName=this.upstreamComponentName,void 0===this.definition.variableNames)throw Error(`Invalid state variable ${this.representativeStateVariable} of ${this.upstreamComponentName}, dependency ${this.dependencyName}: variableNames is not defined`);this.originalDownstreamVariableNames=this.definition.variableNames,this.returnSingleComponent=!0}async determineDownstreamComponents(){let e=this.dependencyHandler._components[this.componentName];if(!e){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName];e||(e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.componentName]=[]),e.includes(this)||e.push(this);for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.componentName,blockerType:"componentIdentity",componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:e,dependencyBlocked:this.dependencyName}),await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"recalculateDownstreamComponents",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!1,downstreamComponentNames:[],downstreamComponentTypes:[]}}for(let e of this.upstreamVariableNames)await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:e,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:e});return{success:!0,downstreamComponentNames:[this.componentName],downstreamComponentTypes:[e.componentType]}}deleteFromUpdateTriggers(){if(this.specifiedComponentName){let e=this.dependencyHandler.updateTriggers.dependenciesMissingComponentBySpecifiedName[this.specifiedComponentName];if(e){let t=e.indexOf(this);-1!==t&&e.splice(t,1)}}}async markStale(){let e=this.dependencyHandler._components[this.upstreamComponentName];for(let t of this.upstreamVariableNames)if(!(e&&e.state[t]&&e.state[t].currentlyResolving)){await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"stateVariable",stateVariableBlocked:t});for(let e in this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t]){"determineDependencies"!==this.dependencyHandler.downstreamDependencies[this.upstreamComponentName][t][e].dependencyType&&await this.dependencyHandler.addBlocker({blockerComponentName:this.upstreamComponentName,blockerType:"determineDependencies",blockerStateVariable:t,blockerDependency:this.dependencyName,componentNameBlocked:this.upstreamComponentName,typeBlocked:"recalculateDownstreamComponents",stateVariableBlocked:t,dependencyBlocked:e})}}}}dependencyTypeArray.push(DetermineDependenciesDependency);class FileDependency extends Dependency{static dependencyType="file";setUpParameters(){this.cid=this.definition.cid,this.uri=this.definition.uri,this.fileType=this.definition.fileType}async getValue(){let e;if(this.cid){if("csv"!==this.fileType.toLowerCase())return{value:null,changes:{}};return e="csv",{value:await retrieveTextFileForCid(this.cid,e),changes:{}}}{let e=await fetch(this.uri);if(e.ok){return{value:await e.text(),changes:{}}}return{value:null,changes:{}}}}}dependencyTypeArray.push(FileDependency);var appliedFunctionSymbolsDefault=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","re","im","det","trace","nPr","nCr"],appliedFunctionSymbolsDefaultLatex=["abs","exp","log","ln","log10","sign","sqrt","erf","cos","cosh","acos","acosh","arccos","arccosh","cot","coth","acot","acoth","arccot","arccoth","csc","csch","acsc","acsch","arccsc","arccsch","sec","sech","asec","asech","arcsec","arcsech","sin","sinh","asin","asinh","arcsin","arcsinh","tan","tanh","atan","atan2","atanh","arctan","arctanh","arg","min","max","mean","median","floor","ceil","round","sum","prod","variance","std","count","mod","Re","Im","det","trace","nPr","nCr"];let allowedLatexSymbols=["alpha","beta","gamma","Gamma","delta","Delta","epsilon","zeta","eta","theta","Theta","iota","kappa","lambda","Lambda","mu","nu","xi","Xi","pi","Pi","rho","sigma","Sigma","tau","Tau","upsilon","Upsilon","phi","Phi","chi","psi","Psi","omega","Omega","partial","varnothing","emptyset","angle","circ","$","%"];var textToAst$1=new me$3.converters.textToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefault});function getFromText({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefault,splitSymbols:n=!0,parseScientificNotation:r=!1}){return a=>me$3.fromAst(new me$3.converters.textToAstObj({appliedFunctionSymbols:t,functionSymbols:e,splitSymbols:n,parseScientificNotation:r}).convert(a))}var latexToAst=new me$3.converters.latexToAstObj({appliedFunctionSymbols:appliedFunctionSymbolsDefaultLatex,allowedLatexSymbols:allowedLatexSymbols});function getFromLatex({functionSymbols:e,appliedFunctionSymbols:t=appliedFunctionSymbolsDefaultLatex,splitSymbols:n=!0,parseScientificNotation:r=!1}){return n?n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordIncludingNumberWithVar(n,r))):n=>me$3.fromAst(new me$3.converters.latexToAstObj({appliedFunctionSymbols:t,functionSymbols:e,allowedLatexSymbols:allowedLatexSymbols,parseScientificNotation:r}).convert(wrapWordWithVar(n,r)))}function normalizeMathExpression({value:e,simplify:t,expand:n=!1,createVectors:r=!1,createIntervals:a=!1}){return r&&(e=e.tuples_to_vectors()),a&&(e=e.to_intervals()),n&&(e=e.expand()),"full"===t?e.simplify():"numbers"===t?e.evaluate_numbers():"numberspreserveorder"===t?e.evaluate_numbers({skip_ordering:!0}):e}function findFiniteNumericalValue(e){if(void 0!==e)return Number.isFinite(e)||void 0!==e.evaluate_to_constant&&(e=e.evaluate_to_constant(),Number.isFinite(e))?e:null}function convertValueToMathExpression(e){return e instanceof me$3.class?e:"number"==typeof e||"string"==typeof e||Array.isArray(e)?me$3.fromAst(e):me$3.fromAst("_")}function returnNVariables(e,t){if(!Number.isInteger(e)||e<1)return[];let n=t.length;if(0===n){if(1===e)return[me$3.fromAst("x")];if(2===e)return[me$3.fromAst("x"),me$3.fromAst("y")];if(3===e)return[me$3.fromAst("x"),me$3.fromAst("y"),me$3.fromAst("z")];{let t=[];for(let n=1;n<=e;n++)t.push(me$3.fromAst(textToAst$1.convert(`x_${n}`)));return t}}if(new Set(t.map((e=>e.toString()))).sizee.toString()))],a=[...t];for(let t=n+1;t<=e;t++){let n;n=1==t?e>3?["x_1"]:["x"]:2==t?e>3?["x_2","y_2"]:["y","x_2"]:3==t?e>3?["x_3","y_3","z_3"]:["z","x_3","z_3"]:["x","y","z","u","v","w","X","Y","Z"].map((e=>`${e}_${t}`));let i=!1;for(let e of n)if(!r.includes(e)){a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),i=!0;break}if(!i){let e=n[0];a.push(me$3.fromAst(textToAst$1.convert(e))),r.push(e),console.warn("Variables added were not unique")}}return a}async function preprocessMathInverseDefinition({desiredValue:e,stateValues:t,variableName:n="value",arrayKey:r,workspace:a}){if(!vectorOperators.includes(e.tree[0])||!e.tree.includes())return{desiredValue:e};let i,s=n+"Ast";if(void 0!==r&&(s+=`_${r}`),a[s])i=a[s].slice(0,e.tree.length);else{let a=await t[n];a&&void 0!==r&&(a=a[r]),a&&vectorOperators.includes(a.tree[0])&&(i=a.tree.slice(0,e.tree.length))}if(i){let t=[],n=!1;for(let[r,a]of e.tree.entries())void 0===a?(n=!0,t.push(r)):i[r]=a;return e=me$3.fromAst(i),a[s]=i,n?{desiredValue:e,vectorComponentsNotAffected:t}:{desiredValue:e}}{let t=[];for(let n of e.tree.slice(1))void 0===n?t.push("_"):t.push(n);return{desiredValue:e=me$3.fromAst([e.tree[0],...t])}}}function normalizeLatexString(e,{unionFromU:t=!1}={}){let n=[["α","\\alpha "],["β","\\beta "],["ϐ","\\beta "],["Γ","\\Gamma "],["γ","\\gamma "],["Δ","\\Delta "],["δ","\\delta "],["ε","\\epsilon "],["ϵ","\\epsilon "],["ζ","\\zeta "],["η","\\eta "],["Θ","\\Theta "],["ϴ","\\Theta "],["θ","\\theta "],["ᶿ","\\theta "],["ϑ","\\theta "],["ι","\\iota "],["κ","\\kappa "],["Λ","\\Lambda "],["λ","\\lambda "],["μ","\\mu "],["µ","\\mu "],["ν","\\nu "],["Ξ","\\Xi "],["ξ","\\xi "],["Π","\\Pi "],["π","\\pi "],["ϖ","\\pi "],["ρ","\\rho "],["ϱ","\\rho "],["Σ","\\Sigma "],["σ","\\sigma "],["ς","\\sigma "],["τ","\\tau "],["Υ","\\Upsilon "],["υ","\\upsilon "],["Φ","\\Phi "],["φ","\\phi "],["ϕ","\\phi "],["Ψ","\\Psi "],["ψ","\\psi "],["Ω","\\Omega "],["ω","\\omega "],["−","-"],["⋅"," \\cdot "],["·"," \\cdot "],["∪"," \\cup "],["∩"," \\cap "],["∞"," \\infty "],["∅"," \\emptyset "]];for(let t of n)e=e.replaceAll(t[0],t[1]);let r=e.match(/^(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*(.*)$/);if(r){let t=r[6];e=","!==t[0]?"\\ldots,"+t:"\\ldots"+t}let a=e.match(/^(.*?)(\\ )*(\\ldots|\.(\\ )*\.(\\ )*\.)(\\ )*$/);if(a){let t=a[1];e=","!==t[t.length-1]?t+",\\ldots":t+"\\ldots"}return e=(e=e.replaceAll(/(\b|\\ )or(\b|\\ )/g,"$1\\lor$2")).replaceAll(/(\b|\\ )and(\b|\\ )/g,"$1\\land$2"),t&&(e=e.replaceAll(/(\b|\\ )U(\b|\\ )/g,"$1\\cup$2")),e}function isValidVariable(e){let t=e.tree,n=!0;return"string"==typeof t?"_"===t&&(n=!1):(!Array.isArray(t)||"_"!==t[0]||"string"!=typeof t[1]||"string"!=typeof t[2]&&"number"!=typeof t[2])&&(n=!1),n}function mathStateVariableFromNumberStateVariable({numberVariableName:e="number",mathVariableName:t="math",isPublic:n=!1}={}){let r={returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:e}}),definition:function({dependencyValues:e}){return{setValue:{[t]:numberToMathExpression(e.number)}}},inverseDefinition:function({desiredStateVariableValues:e}){let n=e[t].evaluate_to_constant();return null===n&&(n=NaN),{success:!0,instructions:[{setDependency:"number",desiredValue:n}]}}};return n&&(r.public=!0,r.shadowingInstructions={createComponentOfType:"math"}),r}function numberToMathExpression(e){let t;if("number"==typeof e?.re&&"number"==typeof e?.im)if(0===e.im)t=e.re;else{let n;n=1===e.im?"i":-1===e.im?["-","i"]:["*",e.im,"i"],t=0===e.re?n:["+",e.re,n]}else t=e;return me$3.fromAst(t)}function roundForDisplay({value:e,dependencyValues:t,usedDefault:n}){let r;return!n.displayDigits&&t.displayDigits>=1||n.displayDecimals||!Number.isFinite(t.displayDecimals)?(r=t.displayDigits>=1?me$3.round_numbers_to_precision(e,t.displayDigits):me$3.round_numbers_to_precision(e,10),t.displaySmallAsZero>0&&(r=me$3.evaluate_numbers(r,{skip_ordering:!0,set_small_zero:t.displaySmallAsZero}))):r=me$3.round_numbers_to_decimals(e,t.displayDecimals),r}function mergeListsWithOtherContainers(e){if(!Array.isArray(e))return e;let t=e[0],n=e.slice(1);return[...vectorOperators,"list","set"].includes(t)&&(n=n.reduce(((e,t)=>Array.isArray(t)&&"list"===t[0]?[...e,...t.slice(1)]:[...e,t]),[])),n=n.map((e=>mergeListsWithOtherContainers(e))),[t,...n]}function wrapWordWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordWithVarSub(e,t),n}function wrapWordWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9]?)([a-zA-Z][a-zA-Z0-9]+)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function wrapWordIncludingNumberWithVar(e,t){let n="",r=/\\operatorname\s*{[^{}]*}/,a=e.match(r);for(;a;){let i=a.index,s=i+a[0].length;n+=wrapWordIncludingNumberWithVarSub(e.substring(0,i),t),n+=e.substring(i,s),a=(e=e.substring(s)).match(r)}return n+=wrapWordIncludingNumberWithVarSub(e,t),n}function wrapWordIncludingNumberWithVarSub(e,t){let n="";const r=/([^a-zA-Z0-9\s]?\s*)([a-zA-Z][a-zA-Z0-9]*[0-9][a-zA-Z0-9]*)([^a-zA-Z0-9]?)/;let a;if(t){const e="(E[+\\-]?[0-9]+\\s*($|(?=\\,|&|\\||\\\\\\||\\)|\\}|\\\\}|\\]|\\\\\\\\|\\\\end)))";a=new RegExp("([0-9]+(\\.[0-9]*)?"+e+")|(\\.[0-9]+"+e+")")}let i=e.match(r);for(;i;){let s=i.index,o=s+i[0].length-i[3].length;if(t){let t=e.match(a);if(t&&t.indexs){n+=e.substring(0,o),i=(e=e.substring(o)).match(r);continue}}if("\\"===i[1]||"^"===i[1][0]||"_"===i[1][0])n+=e.substring(0,o),e=e.substring(o);else{let t=s+i[1].length;n+=e.substring(0,t),n+=`\\operatorname{${i[2]}}`,e=e.substring(o)}i=e.match(r)}return n+=e,n}function stripLatex(e){return e.replaceAll("\\,","").replaceAll(/\\operatorname{([^{}]*)}/g,"$1")}function superSubscriptsToUnicode(e){let t={0:"₀",1:"₁",2:"₂",3:"₃",4:"₄",5:"₅",6:"₆",7:"₇",8:"₈",9:"₉","+":"₊","-":"₋"," ":""},n={0:"⁰",1:"¹",2:"²",3:"³",4:"⁴",5:"⁵",6:"⁶",7:"⁷",8:"⁸",9:"⁹","+":"⁺","-":"⁻"," ":""};function r(e,n){let r="";for(let e of n)r+=t[e];return r}function a(e,t){let r="";for(let e of t)r+=n[e];return r}return e=(e=(e=(e=e.replaceAll(/_(\d+)/g,r)).replaceAll(/_\(([\d +-]+)\)/g,r)).replaceAll(/\^(\d+)/g,a)).replaceAll(/\^\(([\d +-]+)\)/g,a)}function unicodeToSuperSubscripts(e){let t={"₀":"0","₁":"1","₂":"2","₃":"3","₄":"4","₅":"5","₆":"6","₇":"7","₈":"8","₉":"9","₊":"+","₋":"-"},n={"⁰":"0","¹":"1","²":"2","³":"3","⁴":"4","⁵":"5","⁶":"6","⁷":"7","⁸":"8","⁹":"9","⁺":"+","⁻":"-"};return e=(e=e.replaceAll(/([\u2080\u2081\u2082\u2083\u2084\u2085\u2086\u2087\u2088\u2089\u208A\u208B]+)/g,(function(e,n){let r="";for(let e of n)r+=t[e];return"_("+r+")"}))).replaceAll(/([\u2070\u00B9\u00B2\u00B3\u2074\u2075\u2076\u2077\u2078\u2079\u207A\u207B]+)/g,(function(e,t){let r="";for(let e of t)r+=n[e];return"^("+r+")"}))}const vectorOperators=["vector","altvector","tuple"];function renameStateVariable({stateVariableDefinitions:e,oldName:t,newName:n}){let r=e[n]=e[t];if(delete e[t],r.additionalStateVariablesDefined){let e=r.additionalStateVariablesDefined.indexOf(t);-1!==e&&(r.additionalStateVariablesDefined[e]=n)}let a=r.definition,i=["setValue","useEssentialOrDefaultValue","setEssentialValue"],s=["noChanges"];r.definition=function(e){let r=a(e);for(let e of i)r[e]&&t in r[e]&&(r[e][n]=r[e][t],delete r[e][t]);for(let e of s)if(r[e]){let a=r[e].indexOf(t);-1!==a&&(r[e][a]=n)}return r};let o=r.inverseDefinition;o&&(r.inverseDefinition=async function(e){let r=e.desiredStateVariableValues;r[t]=r[n],delete r[n];let a=await o(e);if(a.success)for(let e of a.instructions)e.setEssentialValue===t&&(e.setEssentialValue=n);return a})}function returnDefaultGetArrayKeysFromVarName(e){return e>1?function({arrayEntryPrefix:e,varEnding:t,arraySize:n,nDimensions:r}){let a=t.split("_").map((e=>Number(e)-1));return a.length===r&&a.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?a.every(((e,t)=>e=0?n?rcrypto.getRandomValues(new Uint8Array(e)).reduce(((e,t)=>e+=(t&=63)<36?t.toString(36):t<62?(t-26).toString(36).toUpperCase():t>62?"-":"_"),""),core,queuedRequestActions=[];async function createCore(e){core=new Core(e),core.getInitializedPromise().then((()=>{for(let e of queuedRequestActions)core.requestAction(e);queuedRequestActions=[]}))}async function returnAllStateVariables(e){if(!e.components)return{};let t={};for(let n in e.components){let r=e.components[n],a=t[n]={componentName:n,componentType:r.componentType,stateValues:{}};for(let e in r.state)a.stateValues[e]=removeFunctionsMathExpressionClass(await r.state[e].value);a.activeChildren=r.activeChildren.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),r.replacements&&(a.replacements=r.replacements.map((e=>e.componentName?{componentName:e.componentName,componentType:e.componentType}:e)),void 0!==r.replacementsToWithhold&&(a.replacementsToWithhold=r.replacementsToWithhold)),a.sharedParameters=removeFunctionsMathExpressionClass(r.sharedParameters)}return t}function removeFunctionsMathExpressionClass(e){if(e instanceof me$3.class)e=e.tree;else if("function"==typeof e)e=void 0;else if(Array.isArray(e))e=e.map((e=>removeFunctionsMathExpressionClass(e)));else if("object"==typeof e&&null!==e){let t={};for(let n in e)t[n]=removeFunctionsMathExpressionClass(e[n]);e=t}return e}onmessage=function(e){"createCore"===e.data.messageType?createCore(e.data.args):"requestAction"===e.data.messageType?core?.initialized?core.requestAction(e.data.args):queuedRequestActions.push(e.data.args):"returnAllStateVariables"===e.data.messageType?(console.log("all components"),console.log(core._components),returnAllStateVariables(core).then((e=>{postMessage({messageType:"returnAllStateVariables",args:e})}))):"visibilityChange"===e.data.messageType?core.handleVisibilityChange(e.data.args):"terminate"===e.data.messageType?core.terminate().then((()=>{postMessage({messageType:"terminated"})})):"navigatingToComponent"===e.data.messageType?core.handleNavigatingToComponent(e.data.args.componentName):"submitAllAnswers"===e.data.messageType&&core.requestAction({componentName:core.documentName,actionName:"submitAllAnswers",args:e.data.args})};let styleAttributes={lineColor:{componentType:"text"},lineColorWord:{componentType:"text"},lineOpacity:{componentType:"number"},lineWidth:{componentType:"number"},lineWidthWord:{componentType:"text"},lineStyle:{componentType:"text"},lineStyleWord:{componentType:"text"},markerColor:{componentType:"text"},markerColorWord:{componentType:"text"},markerStyle:{componentType:"text"},markerStyleWord:{componentType:"text"},markerSize:{componentType:"number"},fillColor:{componentType:"text"},fillColorWord:{componentType:"text"},fillOpacity:{componentType:"number"}},defaultStyle={lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3};function returnDefaultStyleDefinitions(){return{1:{lineColor:"#648FFF",lineColorWord:"blue",lineOpacity:.7,lineWidth:4,lineWidthWord:"thick",lineStyle:"solid",lineStyleWord:"",markerColor:"#648FFF",markerColorWord:"blue",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"#648FFF",fillColorWord:"blue",fillOpacity:.3},2:{lineColor:"#D4042D",lineColorWord:"red",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#D4042D",markerColorWord:"red",markerStyle:"square",markerStyleWord:"square",markerSize:5,fillColor:"#D4042D",fillColorWord:"red",fillOpacity:.3},3:{lineColor:"#F19143",lineColorWord:"orange",lineOpacity:.7,lineWidth:3,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#F19143",markerColorWord:"orange",markerStyle:"triangle",markerStyleWord:"triangle",markerSize:5,fillColor:"#F19143",fillColorWord:"orange",fillOpacity:.3},4:{lineColor:"#644CD6",lineColorWord:"purple",lineOpacity:.7,lineWidth:2,lineWidthWord:"",lineStyle:"solid",lineStyleWord:"",markerColor:"#644CD6",markerColorWord:"purple",markerStyle:"diamond",markerStyleWord:"diamond",markerSize:5,fillColor:"#644CD6",fillColorWord:"purple",fillOpacity:.3},5:{lineColor:"black",lineColorWord:"black",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"solid",lineStyleWord:"",markerColor:"black",markerColorWord:"black",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"black",fillColorWord:"black",fillOpacity:.3},6:{lineColor:"gray",lineColorWord:"gray",lineOpacity:.7,lineWidth:1,lineWidthWord:"thin",lineStyle:"dotted",lineStyleWord:"dotted",markerColor:"gray",markerColorWord:"gray",markerStyle:"circle",markerStyleWord:"point",markerSize:5,fillColor:"gray",fillColorWord:"gray",fillOpacity:.3}}}function returnStyleDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.styleDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`styleDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["styleDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithStyle&&(t=e.ancestorWithStyle.stateValues.styleDefinitions),t||(t=returnDefaultStyleDefinitions());for(let e in t)n[e]=Object.assign({},t[e]);let r=[];for(let t of e.setupChildren)r.push(...e[`styleDefinitionsOf${t.componentName}`]);for(let e of r){let t=e.stateValues.value;for(let e in t){let r=n[e];r||(r=n[e]=Object.assign({},defaultStyle));let a=Object.assign({},t[e]);"markerColor"in a&&!("markerColorWord"in a)&&(a.markerColorWord=a.markerColor),"markerStyle"in a&&!("markerStyleWord"in a)&&(a.markerStyleWord=a.markerStyle,"circle"===a.markerStyleWord?a.markerStyleWord="point":"triangle"===a.markerStyleWord.slice(0,8)&&(a.markerStyleWord="triangle")),"lineColor"in a&&!("lineColorWord"in a)&&(a.lineColorWord=a.lineColor),"fillColor"in a&&!("fillColorWord"in a)&&(a.fillColorWord=a.fillColor),"lineWidth"in a&&!("lineWidthWord"in a)&&(a.lineWidth>=4?a.lineWidthWord="thick":a.lineWidth<=1?a.lineWidthWord="thin":a.lineWidthWord=""),"lineStyle"in a&&!("lineStyleWord"in a)&&("dashed"===a.lineStyle?a.lineStyleWord="dashed":"dotted"===a.lineStyle?a.lineStyleWord="dotted":a.lineStyleWord=""),Object.assign(r,a)}}return{setValue:{styleDefinitions:n}}}},e}function returnSelectedStyleStateVariableDefinition(){return{selectedStyle:{forRenderer:!0,willNeverBeEssential:!0,returnDependencies:()=>({styleNumber:{dependencyType:"stateVariable",variableName:"styleNumber"},ancestorWithStyle:{dependencyType:"ancestor",variableNames:["styleDefinitions"]}}),definition:function({dependencyValues:e}){let t=e.ancestorWithStyle.stateValues.styleDefinitions;t||(t=returnDefaultStyleDefinitions());let n=t[e.styleNumber];return void 0===n&&(n=defaultStyle),{setValue:{selectedStyle:n}}}}}}function enumerateSelectionCombinations({numberOfIndices:e,numberOfOptions:t,maxNumber:n=1/0,withReplacement:r=!1,skipZero:a=!1}){if(1===e){let e=[...Array(t).keys()];return e=e.slice(1),a||(e=[...e,0]),e=e.slice(0,n),e=e.map((e=>[e])),e}let i=enumerateSelectionCombinations({numberOfIndices:e-1,numberOfOptions:t,maxNumber:n,withReplacement:r,skipZero:!r}),s=[],o=0;for(let e of i)for(let r=1;r<=t;r++){let i=[r%t,...e.map((e=>(r+e)%t))];if((!a||!i.includes(0))&&(s.push(i),o++,o>=n))return s}return s}function enumerateCombinations({numberOfOptionsByIndex:e,maxNumber:t=1/0}){let n=e.length;if(0===n)return[];let r=[];for(let t=0;t[...t,...e]),[]).reduce(((e,t)=>Math.max(e,t)),1);if(1===a){let n=e.reduce(((e,t)=>e*t));n=Math.min(n,t);let r=[];for(let t=0;tt%e));r.push(n)}return r}if(2===n){let n=a,r=me$3.math.lcm(...e),i=[],s=0;for(let a=0;a=t)return i}return i}let i=[];for(let t=0;t1?n.push(me$3.math.lcm(e[t],e[a])):n.push(null);i.push(n)}let s,o=i.reduce(((e,t)=>[...t,...e]),[]).filter((e=>null!==e)).reduce(((e,t)=>Math.min(e,t)),1/0);for(let e=0;e{if(0===e.length)n.push(a);else for(let i=0;i=t)return}};return r(e),n}function returnStandardSequenceAttributes(){return{type:{createPrimitiveOfType:"string",createStateVariable:"type",defaultPrimitiveValue:"number",toLowerCase:!0,validValues:["number","math","letters"]},from:{createComponentOfType:"_componentWithSelectableType"},to:{createComponentOfType:"_componentWithSelectableType"},step:{createComponentOfType:"math"},length:{createComponentOfType:"number"},exclude:{createComponentOfType:"_componentListWithSelectableType"}}}function returnStandardSequenceStateVariableDefinitions(){let e={specifiedFrom:{returnDependencies:()=>({fromAttr:{dependencyType:"attributeComponent",attributeName:"from",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"from",definition:function({dependencyValues:e}){return null===e.fromAttr?{useEssentialOrDefaultValue:{specifiedFrom:!0}}:null===e.fromAttr.stateValues.value?{setValue:{specifiedFrom:NaN}}:{setValue:{specifiedFrom:e.fromAttr.stateValues.value}}}},specifiedTo:{returnDependencies:()=>({toAttr:{dependencyType:"attributeComponent",attributeName:"to",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"to",definition:function({dependencyValues:e}){return null===e.toAttr?{useEssentialOrDefaultValue:{specifiedTo:!0}}:null===e.toAttr.stateValues.value?{setValue:{specifiedTo:NaN}}:{setValue:{specifiedTo:e.toAttr.stateValues.value}}}},specifiedLength:{returnDependencies:()=>({lengthAttr:{dependencyType:"attributeComponent",attributeName:"length",variableNames:["value"]}}),defaultValue:null,hasEssential:!0,essentialVarName:"length",definition:function({dependencyValues:e}){return null===e.lengthAttr?{useEssentialOrDefaultValue:{specifiedLength:!0}}:null===e.lengthAttr.stateValues.value?{setValue:{specifiedLength:NaN}}:{setValue:{specifiedLength:e.lengthAttr.stateValues.value}}}},specifiedStep:{returnDependencies:()=>({stepAttr:{dependencyType:"attributeComponent",attributeName:"step",variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),defaultValue:null,hasEssential:!0,essentialVarName:"step",definition:function({dependencyValues:e}){if(null===e.stepAttr)return{useEssentialOrDefaultValue:{specifiedStep:!0}};let t=e.stepAttr.stateValues.value;return null===t?{setValue:{specifiedStep:NaN}}:{setValue:{specifiedStep:t}}}},specifiedExclude:{returnDependencies:()=>({excludeAttr:{dependencyType:"attributeComponent",attributeName:"exclude",variableNames:["values"]}}),defaultValue:[],hasEssential:!0,essentialVarName:"exclude",definition:function({dependencyValues:e}){return null===e.excludeAttr?{useEssentialOrDefaultValue:{specifiedExclude:!0}}:{setValue:{specifiedExclude:e.excludeAttr.stateValues.values}}}},lowercase:{returnDependencies:()=>({specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"}}),definition:function({dependencyValues:e}){let t=/^[A-Z]*$/,n=!0;return null!==e.specifiedFrom?t.test(e.specifiedFrom)&&(n=!1):null!==e.specifiedTo&&t.test(e.specifiedTo)&&(n=!1),{setValue:{lowercase:n}}}}};return e.validSequence={returnDependencies:()=>({specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},type:{dependencyType:"stateVariable",variableName:"type"},lowercase:{dependencyType:"stateVariable",variableName:"lowercase"}}),definition:function({dependencyValues:e}){let t=!0;if(null!==e.specifiedLength&&(!Number.isInteger(e.specifiedLength)||e.specifiedLength<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),t=!1),null!==e.specifiedStep&&"math"!==e.type){let n=findFiniteNumericalValue(e.specifiedStep);Number.isFinite(n)||(console.warn("Invalid step of sequence. Must be a number for sequence of type "+e.type+"."),t=!1)}if(null!==e.specifiedFrom)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedFrom);Number.isFinite(n)||(console.warn("Invalid from of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedFrom)&&(console.warn("Invalid from of sequence"),t=!1);if(null!==e.specifiedTo)if("number"===e.type){let n=findFiniteNumericalValue(e.specifiedTo);Number.isFinite(n)||(console.warn("Invalid to of number sequence. Must be a number"),t=!1)}else Number.isNaN(e.specifiedTo)&&(console.warn("Invalid to of sequence"),t=!1);return{setValue:{validSequence:t}}}},e.from={additionalStateVariablesDefined:["step","length","exclude"],returnDependencies:()=>({specifiedFrom:{dependencyType:"stateVariable",variableName:"specifiedFrom"},specifiedTo:{dependencyType:"stateVariable",variableName:"specifiedTo"},specifiedLength:{dependencyType:"stateVariable",variableName:"specifiedLength"},specifiedStep:{dependencyType:"stateVariable",variableName:"specifiedStep"},type:{dependencyType:"stateVariable",variableName:"type"},specifiedExclude:{dependencyType:"stateVariable",variableName:"specifiedExclude"},validSequence:{dependencyType:"stateVariable",variableName:"validSequence"}}),definition:function({dependencyValues:e}){let t=e.specifiedFrom,n=e.specifiedTo,r=e.specifiedStep,a=e.specifiedLength,i=[...e.specifiedExclude],s=e.type;if("math"===e.type)null!==n&&(n instanceof me$3.class||(n=me$3.fromAst(n))),null!==t&&(t instanceof me$3.class||(t=me$3.fromAst(t))),null!==r&&(r instanceof me$3.class||(r=me$3.fromAst(r)));else if(null!==r&&r instanceof me$3.class&&(r=r.evaluate_to_constant()),"letters"===e.type)null!==t&&(t=lettersToNumber$1(t)),null!==n&&(n=lettersToNumber$1(n)),i=i.map(lettersToNumber$1);else if("number"===e.type){null!==n&&(n=n instanceof me$3.class?n.evaluate_to_constant():Number(n)),null!==t&&(t=t instanceof me$3.class?t.evaluate_to_constant():Number(t));for(let[e,t]of i.entries())t instanceof me$3.class?i[e]=t.evaluate_to_constant():i[e]=Number(t)}if(e.validSequence){let e=calculateSequenceParameters({from:t,to:n,step:r,length:a,type:s});return e.exclude=i,{setValue:e}}return(!Number.isInteger(a)||a<0)&&(a=0),{setValue:{from:t,step:r,length:a,exclude:i}}}},e}function calculateSequenceParameters({from:e,to:t,step:n,length:r,type:a}){if(null===e)null===t?(e="math"===a?me$3.fromAst(1):1,null===n?(n="math"===a?me$3.fromAst(1):1,null===r&&(r=10)):null===r&&(r=10)):(null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r="math"===a?Math.floor((t.subtract(1).divide(n).evaluate_to_constant()+1)*(1+1e-14)):Math.floor(((t-1)/n+1)*(1+1e-14))),"math"===a?e=t.subtract(n.multiply(r-1)).simplify():(e=t-n*(r-1),"letters"===a&&e<1&&(e=t-n*((r=Math.floor(((t-1)/n+1)*(1+1e-14)))-1))));else if(null===t)null===n&&(n="math"===a?me$3.fromAst(1):1),null===r&&(r=10);else if(null===n)null===r?"math"===a?(n=me$3.fromAst(1),r=Math.floor(t.subtract(e).add(1).evaluate_to_constant()*(1+1e-14))):(n=1,r=Math.floor((t-e+1)*(1+1e-14))):"math"===a?n=t.subtract(e).divide(r-1):(n=(t-e)/(r-1),"letters"===a&&(n=Math.floor(n)));else{if(null!==r)throw Error("Can't define from, to, step, and length for sequence");r="math"===a?Math.floor(t.subtract(e).divide(n).add(1).evaluate_to_constant()*(1+1e-14)):Math.floor(((t-e)/n+1)*(1+1e-14))}return(!Number.isInteger(r)||r<0)&&(console.warn("Invalid length of sequence. Must be a non-negative integer."),r=0),{from:e,step:n,length:r}}function returnSequenceValues({from:e,step:t,length:n,exclude:r,type:a,lowercase:i,maxNum:s},o=!1){let l=[],u=0;for(let c=0;c0&&("math"===a?n=n.add(t.multiply(me$3.fromAst(c))).expand().simplify():n+=t*c),"math"===a){if(r.some((e=>e&&e.equals(n))))continue}else if("number"===a){if(r.some((e=>Math.abs(e-n)<=1e-14*Math.max(Math.abs(e),Math.abs(n)))))continue}else if(r.includes(n))continue;if("letters"===a&&(n=numberToLetters(n,i)),o?l.push({value:n,originalIndex:c}):l.push(n),u++,u===s)break}return l}function returnSequenceValueForIndex({index:e,from:t,step:n,length:r,exclude:a,type:i,lowercase:s}){if(!(e>=0&&(void 0===r||e0&&("math"===i?o=o.add(n.multiply(me$3.fromAst(e))).expand().simplify():o+=n*e),"math"===i){if(a.some((e=>e&&e.equals(o))))return null}else if("number"===i){if(a.some((e=>Math.abs(e-o)<=1e-14*Math.max(Math.abs(e),Math.abs(o)))))return null}else if(a.includes(o))return null;return"letters"===i&&(o=numberToLetters(o,s)),o}function lettersToNumber$1(e){try{e=e.toUpperCase()}catch(t){return void console.warn("Cannot convert "+e+" to a number")}let t=0,n=e.length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t}function numberToLetters(e,t){e--;let n=65;t&&(n=97);let r="";for(;;){let t=e%26;if(r=String.fromCharCode(n+t)+r,e<26)break;e=Math.floor(e/26)-1}return r}function getVariantsForDescendantsForUniqueVariants({variantIndex:e,serializedComponent:t,componentInfoObjects:n}){let r=t.variants?.descendantVariantComponents;if(void 0===r)return{success:!1};let a=r.map((e=>e.variants.numberOfVariants)),i=enumerateCombinations({numberOfOptionsByIndex:a,maxNumber:e})[e-1],s=[];for(let[e,t]of r.entries()){let r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:i[e]+1,componentInfoObjects:n});if(!r.success)return{succss:!1};s.push(r.desiredVariant)}return{success:!0,desiredVariants:s}}function setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:r=!1}){let a,i;if(e.variants&&(i=e.variants.desiredVariant),a=void 0!==i?.seed?i.seed.toString():r?t.subpartVariantRng().toString().slice(2):t.variantRng().toString().slice(2),t.variantSeed=a,t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}function gatherVariantComponents({serializedComponents:e,componentInfoObjects:t}){let n=[];for(let r of e){if("object"!=typeof r)continue;if(r.variants||(r.variants={}),r.variants.isVariantComponent){n.push(r);continue}if(r.componentType in t.componentTypesCreatingVariants){r.variants.isVariantComponent=!0,n.push(r);continue}if(!r.children)continue;if(r.children.some((e=>"variantControl"===e.componentType))){r.variants.isVariantComponent=!0,n.push(r);continue}let e=gatherVariantComponents({serializedComponents:r.children,componentInfoObjects:t});e.length>0&&(r.variants.descendantVariantComponents=e,n.push(...e))}return n}function getNumberOfVariants({serializedComponent:e,componentInfoObjects:t}){let n;e.variants||(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){n=t;break}let r="document"===e.componentType;if(!n){if(!r)return{success:!1};let n=e.children.filter((e=>e.componentType||""!==e.trim()));if(1===n.length&&t.isInheritedComponentType({inheritedComponentType:n[0].componentType,baseComponentType:"_sectioningComponent"})){let r=n[0],a=getNumberOfVariants({serializedComponent:r,componentInfoObjects:t});if(a.success)return e.variants.descendantVariantComponents=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t}),e.variants.uniqueVariants=!0,e.variants.numberOfVariants=r.variants.numberOfVariants,e.variants.allPossibleVariants=r.variants.allPossibleVariants,e.variants.allVariantNames=r.variants.allVariantNames,e.variants.allPossibleVariantUniqueIndices=[...r.variants.allPossibleVariants.keys()].map((e=>e+1)),e.variants.allPossibleVariantSeeds=[...r.variants.allPossibleVariants.keys()].map((e=>(e+1).toString())),a}}return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:r})}function determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:n=!1}){let r;void 0===e.variants&&(e.variants={});for(let t of e.children)if("variantControl"===t.componentType){r=t;break}if(!r&&!n){return t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t})}let a=[];if(r?.attributes.variantNames&&(a=r.attributes.variantNames.component.children.map((e=>e.toLowerCase()))),a.length!==[...new Set(a)].length)throw Error("Duplicate variant names specified");let i=r?.attributes.nVariants?.primitive;Number.isFinite(i)||(i=100),i=Math.min(Math.max(i,1),1e3);let s=[...a];if(s.lengthe.toLowerCase())),o=[...new Set(o)];for(let e of o)if(!s.includes(e))throw Error(`Cannot include variant ${e} as ${e} is a not variant name`)}let l=r?.attributes.variantsToExclude?.component.children;if(l){l=l.map((e=>e.toLowerCase()));for(let e of l)if(!s.includes(e))throw Error(`Cannot exclude variant ${e} as ${e} is not a variant name`)}else l=[];o=o?o.filter((e=>!l.includes(e))):[...s].filter((e=>!l.includes(e)));let u=o.map((e=>s.indexOf(e)+1)),c=[];r?.attributes.seeds&&(c=r.attributes.seeds.component.children);let p=[...c];if(p.lengthp[e-1])),h=void 0!==r?.attributes.uniqueVariants,f=r?.attributes.uniqueVariants?.primitive;if(f||!h){d=t.allComponentClasses._base.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}),f=!!d.success&&(f||d.numberOfVariants<=i)}let y=[],g=[],b=[];if(f)for(let[e,t]of u.entries())t<=d.numberOfVariants&&(g.push(t),y.push(o[e]),b.push(m[e]));else y=o,g=u,b=m;let v=y.length;if(0===v)throw Error("No variants selected based on variantsToInclude, variantsToExclude, and the number of variants available");return e.variants.uniqueVariants=f,e.variants.numberOfVariants=v,e.variants.allPossibleVariants=y,e.variants.allVariantNames=s,e.variants.allPossibleVariantUniqueIndices=g,e.variants.allPossibleVariantSeeds=b,{success:!0,numberOfVariants:v}}function indexToLowercaseLetters(e){return numberToLetters(e,!0)}class BaseComponent{constructor({componentName:e,ancestors:t,serializedComponent:n,definingChildren:r,serializedChildren:a,attributes:i,stateVariableDefinitions:s,componentInfoObjects:o,coreFunctions:l,flags:u,shadow:c,numerics:p,parentSharedParameters:d,sharedParameters:m}){this.numerics=p,this.parentSharedParameters=d,this.sharedParameters=m,this.componentName=e,this.ancestors=t,this.counters={},this.componentInfoObjects=o,this.coreFunctions=l,this.flags=u,!0===c&&(this.isShadow=!0),this.definingChildren=r,void 0===this.definingChildren&&(this.definingChildren=[]),this.serializedChildren=a,this.attributes=i,this.state={};for(let e in s)this.state[e]=Object.assign({},s[e]);this.stateValues=new Proxy(this.state,createStateProxyHandler()),this.essentialState={},n.state&&(this.essentialState=deepClone(n.state)),this.doenetAttributes={},void 0!==n.doenetAttributes&&Object.assign(this.doenetAttributes,n.doenetAttributes),void 0!==n.variants&&(this.variants=n.variants),n.range&&(this.doenetMLrange=n.range),this.actions={copyDoenetMLToClipboard:this.copyDoenetMLToClipboard.bind(this)}}static componentType="_base";static get rendererType(){return this.componentType}get componentType(){return this.constructor.componentType}get componentOrAdaptedName(){return this.adaptedFrom?this.adaptedFrom.componentOrAdaptedName:this.componentName}get rendererType(){return this.constructor.rendererType}get allPotentialRendererTypes(){let e=[];this.rendererType&&e.push(this.rendererType);for(let t in this.state){let n=this.state[t];if(n.public){let t=n.componentType;Array.isArray(t)||(t=[t]),n.wrappingComponents&&t.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let n of t){let t=this.componentInfoObjects.allComponentClasses[n];if(t){let n=t.rendererType;n&&!e.includes(n)&&e.push(n)}}}}if(this.constructor.adapters)for(let t of this.constructor.adapters){let n;n="string"==typeof t?t:t.componentType;let r=this.componentInfoObjects.allComponentClasses[n];if(r){let t=r.rendererType;t&&!e.includes(t)&&e.push(t)}}if(!this.rendererType)return e;for(let t in this.allChildren){let n=this.allChildren[t].component;if("object"==typeof n)for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}return e}potentialRendererTypesFromSerializedComponents(e){let t=[];for(let n of e){let e=this.componentInfoObjects.allComponentClasses[n.componentType];if(e){let n=e.rendererType;n&&!t.includes(n)&&t.push(n);let r=e.returnStateVariableInfo({onlyPublic:!0}).stateVariableDescriptions;for(let e in r){let n=r[e],a=n.shadowingInstructions?.createComponentOfType;Array.isArray(a)||(a=[a]),n.wrappingComponents&&a.push(...flattenDeep(n.wrappingComponents).map((e=>"object"==typeof e?e.componentType:e)));for(let e of a){let n=this.componentInfoObjects.allComponentClasses[e];if(n){let e=n.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(e.adapters)for(let n of e.adapters){let e;e="string"==typeof n?n:n.componentType;let r=this.componentInfoObjects.allComponentClasses[e];if(r){let e=r.rendererType;e&&!t.includes(e)&&t.push(e)}}}if(n.children){let e=this.potentialRendererTypesFromSerializedComponents(n.children);for(let n of e)t.includes(n)||t.push(n)}}return t}get childrenMatched(){return this.childrenMatchedWithPlaceholders&&!this.placeholderActiveChildrenIndices}static createAttributesObject(){return{hide:{createComponentOfType:"boolean",createStateVariable:"hide",defaultValue:!1,public:!0},disabled:{createComponentOfType:"boolean"},fixed:{createComponentOfType:"boolean",ignoreFixed:!0},modifyIndirectly:{createComponentOfType:"boolean",createStateVariable:"modifyIndirectly",defaultValue:!0,public:!0,propagateToProps:!0},styleNumber:{createComponentOfType:"number",createStateVariable:"styleNumber",defaultValue:1,public:!0,fallBackToParentStateVariable:"styleNumber"},isResponse:{createPrimitiveOfType:"boolean",createStateVariable:"isResponse",defaultValue:!1,public:!0},newNamespace:{createPrimitiveOfType:"boolean",createStateVariable:"newNamespace",defaultValue:!1,public:!0}}}static returnSugarInstructions(){return[]}static returnChildGroups(){return[]}static get childGroups(){return this.hasOwnProperty("childGroupsData")||(this.childGroupsData=this.returnChildGroups()),this.childGroupsData}static childGroupOfComponentTypeData;static get childGroupOfComponentType(){return this.hasOwnProperty("childGroupOfComponentTypeData")||(this.childGroupOfComponentTypeData={}),this.childGroupOfComponentTypeData}static childGroupIndsByNameData;static get childGroupIndsByName(){if(this.hasOwnProperty("childGroupIndsByNameData"))return Object.assign({},this.childGroupIndsByNameData);this.childGroupIndsByNameData={};for(let[e,t]of this.childGroups.entries()){if(t.group in this.childGroupIndsByNameData)throw Error(`Invalid childGroups for componentClass ${this.componentType}: ${t} is repeated`);this.childGroupIndsByNameData[t.group]=e}return Object.assign({},this.childGroupIndsByNameData)}returnMatchedChildIndices(e){let t=[];for(let n of e){let e=this.childMatchesByGroup[n];if(!e)return;t.push(...e)}return t.sort(((e,t)=>e-t))}static returnStateVariableDefinitions(){let e={};return e.hidden={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({hide:{dependencyType:"stateVariable",variableName:"hide",variablesOptional:!0},parentHidden:{dependencyType:"parentStateVariable",variableName:"hidden"},sourceCompositeHidden:{dependencyType:"sourceCompositeStateVariable",variableName:"hidden"},adapterSourceHidden:{dependencyType:"adapterSourceStateVariable",variableName:"hidden"}}),definition:({dependencyValues:e})=>({setValue:{hidden:Boolean(e.parentHidden||e.sourceCompositeHidden||e.adapterSourceHidden||e.hide)}}),markStale:()=>({updateParentRenderedChildren:!0}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"hide",desiredValue:e.hidden}]})},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,doNotShadowEssential:!0,defaultValue:!1,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({disabledAttr:{dependencyType:"attributeComponent",attributeName:"disabled",variableNames:["value"]},readOnly:{dependencyType:"flag",flagName:"readOnly"},parentDisabled:{dependencyType:"parentStateVariable",variableName:"disabled"},sourceCompositeDisabled:{dependencyType:"sourceCompositeStateVariable",variableName:"disabled"},adapterSourceDisabled:{dependencyType:"adapterSourceStateVariable",variableName:"disabled"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(e.readOnly)return{setValue:{disabled:!0}};if(null!==e.disabledAttr)return{setValue:{disabled:e.disabledAttr.stateValues.value}};if(void 0!==n.disabled)return{useEssentialOrDefaultValue:{disabled:!0}};let r=!1,a=!0;return null===e.parentDisabled||t.parentDisabled||(r=r||e.parentDisabled,a=!1),null===e.sourceCompositeDisabled||t.sourceCompositeDisabled||(r=r||e.sourceCompositeDisabled,a=!1),null===e.adapterSourceDisabled||t.adapterSourceDisabled||(r=r||e.adapterSourceDisabled,a=!1),a?{useEssentialOrDefaultValue:{disabled:!0}}:{setValue:{disabled:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.disabledAttr?{success:!0,instructions:[{setDependency:"disabledAttr",desiredValue:t.disabled,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"disabled",value:t.disabled}]}},e.fixed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,ignoreFixed:!0,provideEssentialValuesInDefinition:!0,returnDependencies:()=>({fixedAttr:{dependencyType:"attributeComponent",attributeName:"fixed",variableNames:["value"]},parentFixed:{dependencyType:"parentStateVariable",variableName:"fixed"},sourceCompositeFixed:{dependencyType:"sourceCompositeStateVariable",variableName:"fixed"},adapterSourceFixed:{dependencyType:"adapterSourceStateVariable",variableName:"fixed"},ignoreParentFixed:{dependencyType:"doenetAttribute",attributeName:"ignoreParentFixed"}}),definition({dependencyValues:e,usedDefault:t,essentialValues:n}){if(null!==e.fixedAttr)return{setValue:{fixed:e.fixedAttr.stateValues.value}};if(void 0!==n.fixed)return{useEssentialOrDefaultValue:{fixed:!0}};let r=!1,a=!0;return null===e.parentFixed||t.parentFixed||e.ignoreParentFixed||(r=r||e.parentFixed,a=!1),null===e.sourceCompositeFixed||t.sourceCompositeFixed||(r=r||e.sourceCompositeFixed,a=!1),null===e.adapterSourceFixed||t.adapterSourceFixed||(r=r||e.adapterSourceFixed,a=!1),a?{useEssentialOrDefaultValue:{fixed:!0}}:{setValue:{fixed:r}}},inverseDefinition:({dependencyValues:e,desiredStateVariableValues:t})=>null!==e.fixedAttr?{success:!0,instructions:[{setDependency:"fixedAttr",desiredValue:t.fixed,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"fixed",value:t.fixed}]}},e.isInactiveCompositeReplacement={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{isInactiveCompositeReplacement:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:{variableName:"isInactiveCompositeReplacement",value:e.isInactiveCompositeReplacement}}]})},e.doenetML={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({doenetML:{dependencyType:"doenetML"}}),definition({dependencyValues:e}){let t=e.doenetML;return t||(t=""),{setValue:{doenetML:t}}}},e}static returnNormalizedStateVariableDefinitions({attributeNames:e,numerics:t}){let n=this.returnStateVariableDefinitions({attributeNames:e,numerics:t});if(!n)throw Error(`Error in state variable definitions of ${this.componentType}: returnStateVariableDefinitions did not return anything`);let r=function(e){for(let[t,n]of e.entries())"object"==typeof n&&(e[t]=n.variableName)},a=["returnDependencies","definition","inverseDefinition","stateVariablesDeterminingDependencies","stateVariablesDeterminingArraySizeDependencies","isArray","nDimensions","returnArraySizeDependencies","returnArraySize","returnArrayDependenciesByKey","arrayDefinitionByKey","inverseArrayDefinitionByKey","basedOnArrayKeyStateVariables","markStale","getPreviousDependencyValuesForMarkStale","determineDependenciesImmediately","createWorkspace","workspace","provideEssentialValuesInDefinition","providePreviousValuesInDefinition"],i={};for(let e in n){let t=n[e];if(i[e]=t,t.createWorkspace&&(t.workspace={}),t.additionalStateVariablesDefined){for(let[n,s]of t.additionalStateVariablesDefined.entries()){let o={};for(let e of a)e in t&&(o[e]=t[e]);o.additionalStateVariablesDefined=[...t.additionalStateVariablesDefined],o.additionalStateVariablesDefined[n]=e,r(o.additionalStateVariablesDefined);let l=s;"object"==typeof s&&(l=s.variableName,s=Object.assign({},s),delete s.variableName,Object.assign(o,s)),i[l]=o}r(t.additionalStateVariablesDefined)}}return i}static returnStateVariableInfo({onlyPublic:e=!1,onlyForRenderer:t=!1}={}){let n=this.createAttributesObject(),r={},a={},i={};for(let a in n){let i=n[a],s=i.createStateVariable;if(s&&(!e||i.public)&&(!t||i.forRenderer))if(i.public){let e;!i.createComponentOfType?(e=i.createPrimitiveOfType,"string"===e&&(e="text")):e=i.createComponentOfType,r[s]={createComponentOfType:e,public:!0}}else r[s]={}}let s=this.returnNormalizedStateVariableDefinitions({attributeNames:Object.keys(r)});for(let n in s){let o=s[n];if(o.isAlias)i[n]=o.targetVariableName;else if((!e||o.public)&&(!t||o.forRenderer)&&(o.public?r[n]={createComponentOfType:o.shadowingInstructions.createComponentOfType,public:!0}:r[n]={},o.isArray)){let e;r[n].isArray=!0,r[n].nDimensions=void 0===o.nDimensions?1:o.nDimensions,r[n].wrappingComponents=o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents():[],e=o.entryPrefixes?o.entryPrefixes:[n];for(let t of e)a[t]={arrayVariableName:n,nDimensions:o.returnEntryDimensions?o.returnEntryDimensions(t):1,wrappingComponents:o.shadowingInstructions?.returnWrappingComponents?o.shadowingInstructions.returnWrappingComponents(t):[]};o.getArrayKeysFromVarName?r[n].getArrayKeysFromVarName=o.getArrayKeysFromVarName:r[n].getArrayKeysFromVarName=returnDefaultGetArrayKeysFromVarName(r[n].nDimensions)}}return{stateVariableDescriptions:r,arrayEntryPrefixes:a,aliases:i}}get parentName(){if(void 0!==this.ancestors&&0!==this.ancestors.length)return this.ancestors[0].componentName}getAllChildrenDownstreamComponentNames(e=!1){const t=Object.keys(this.allChildren);let n=Object.keys(this.downstreamDependencies);return!0!==e&&(n=n.filter((e=>!0!==this.downstreamDependencies[e].inactive))),[...t,...n]}get allDescendants(){let e=[];for(let t in this.allChildren){let n=this.allChildren[t].component;e=[...e,t,...n.allDescendants]}return e}async serialize(e={}){let t,n={componentType:this.componentType},r=[],a={...e};t=e.sourceAttributesToIgnoreRecursively?[...e.sourceAttributesToIgnoreRecursively]:[],e.sourceAttributesToIgnore&&(t.push(...e.sourceAttributesToIgnore),delete a.sourceAttributesToIgnore);for(let e of this.definingChildren)"object"!=typeof e?r.push(e):r.push(await e.serialize(a));if(void 0!==this.serializedChildren)for(let e of this.serializedChildren)r.push(this.copySerializedComponent(e));r.length>0&&(n.children=r),n.attributes={};for(let r in this.attributes){let i=this.attributes[r];i.component?e.copyAll&&(n.attributes[r]={component:await i.component.serialize(a)}):t.includes(r)&&!e.copyAll||(n.attributes[r]=JSON.parse(JSON.stringify(i)))}return this.essentialState&&Object.keys(this.essentialState).length>0&&(n.state=deepClone(this.essentialState)),e.copyVariants&&this.state.generatedVariantInfo&&(n.variants={desiredVariant:await this.stateValues.generatedVariantInfo}),n.originalName=this.componentName,n.originalDoenetAttributes=deepClone(this.doenetAttributes),n.doenetAttributes=deepClone(this.doenetAttributes),n.originalAttributes=deepClone(n.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames,n}copySerializedComponent(e){if("object"!=typeof e)return e;let t=[];if(void 0!==e.children)for(let n of e.children)t.push(this.copySerializedComponent(n));let n={componentType:e.componentType,originalName:e.componentName,originalNameFromSerializedComponent:!0,children:t,state:{},doenetAttributes:{}};return void 0!==e.doenetAttributes&&(n.originalDoenetAttributes=deepClone(e.doenetAttributes),n.doenetAttributes=deepClone(e.doenetAttributes),n.originalAttributes=deepClone(e.attributes),n.attributes=deepClone(e.attributes),delete n.doenetAttributes.prescribedName,delete n.doenetAttributes.assignNames),void 0!==e.state&&Object.assign(n.state,e.state),n}static adapters=[];static get nAdapters(){return this.adapters.length}getAdapter(e){if(e>=this.constructor.adapters.length)return;let t,n,r,a,i=this.constructor.adapters[e];"string"==typeof i?t=i:(t=i.stateVariable,n=i.componentType,r=i.substituteForPrimaryStateVariable,a=i.stateVariablesToShadow);let s=this.state[t];if(void 0===s||!s.public&&!n)throw Error("Invalid adapter "+t+" in "+this.componentType);return void 0===n&&(n=s.shadowingInstructions.createComponentOfType),{componentType:n,downstreamDependencies:{[this.componentName]:[{dependencyType:"adapter",adapterVariable:t,adapterTargetIdentity:{componentName:this.componentName,componentType:this.componentType},substituteForPrimaryStateVariable:r,stateVariablesToShadow:a}]}}}static getAdapterComponentType(e,t){if(e>=this.adapters.length)return;let n,r,a=this.adapters[e];if("string"==typeof a?n=a:(n=a.stateVariable,r=a.componentType),void 0===r){let e=t[this.componentType].stateVariableDescriptions[n];if(!e)throw Error("Invalid adapter "+n+" in "+this.componentType);if(r=e.createComponentOfType,!r)throw Error(`Couldn't get adapter component type for ${n} of componentType ${this.componentType}`)}return r}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){let n=e.variants?.numberOfVariants;if(void 0!==n)return{success:!0,numberOfVariants:n};let r=[];e.children&&(r=gatherVariantComponents({serializedComponents:e.children,componentInfoObjects:t})),void 0===e.variants&&(e.variants={}),e.variants.descendantVariantComponents=r,n=1;let a=[];for(let e of r){let r=t.allComponentClasses[e.componentType].determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!r.success)return{success:!1};a.push(r.numberOfVariants),n*=r.numberOfVariants}return e.variants.numberOfVariants=n,e.variants.uniqueVariantData={numberOfVariantsByDescendant:a},{success:!0,numberOfVariants:n}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};let a=!1,i=e.variants.uniqueVariantData.numberOfVariantsByDescendant,s=e.variants.descendantVariantComponents,o=[];if(s.length>0){let e=enumerateCombinations({numberOfOptionsByIndex:i,maxNumber:t})[t-1].map((e=>e+1));for(let t=0;t1){let r=s[t],i=n.allComponentClasses[r.componentType].getUniqueVariant({serializedComponent:r,variantIndex:e[t],componentInfoObjects:n});if(!i.success)return{success:!1};o.push(i.desiredVariant),a=!0}else o.push({})}let l={index:t};return a&&(l.subvariants=o),{success:!0,desiredVariant:l}}async copyDoenetMLToClipboard({actionId:e}){let t=await this.stateValues.doenetML;t?this.coreFunctions.copyToClipboard(t,e):this.coreFunctions.resolveAction({actionId:e})}}class InlineComponent extends BaseComponent{static componentType="_inline"}class Text extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveText:this.moveText.bind(this)})}static componentType="text";static includeBlankStringChildren=!0;static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"textLike",componentTypes:["string","text","_singleCharacterInline","_inlineRenderInlineChildren"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,returnDependencies:()=>({textLikeChildren:{dependencyType:"child",childGroups:["textLike"],variableNames:["text"]}}),defaultValue:"",set:e=>null===e?"":String(e),definition:function({dependencyValues:e}){if(0===e.textLikeChildren.length)return{useEssentialOrDefaultValue:{value:!0}};let t="";for(let n of e.textLikeChildren)t+="string"==typeof n?n:n.stateValues.text;return{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=t.textLikeChildren.length;return n>1?{success:!1}:1===n?{success:!0,instructions:[{setDependency:"textLikeChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:null===e.value?"":String(e.value)}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.text}]})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveText({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class TextOrInline extends InlineComponent{static componentType="_textOrInline";static renderChildren=!0;static rendererType="containerInline";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{value:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}}class CompositeComponent extends BaseComponent{constructor(e){super(e),this.replacementsWorkspace={}}static componentType="_composite";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.replacements={returnDependencies:()=>({replacements:{dependencyType:"replacement"}}),definition:({dependencyValues:e})=>({setValue:{replacements:e.replacements}})},e.recursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0}}),definition:({dependencyValues:e})=>({setValue:{recursiveReplacements:e.recursiveReplacements}})},e.fullRecursiveReplacements={returnDependencies:()=>({recursiveReplacements:{dependencyType:"replacement",recursive:!0,recurseNonStandardComposites:!0}}),definition:({dependencyValues:e})=>({setValue:{fullRecursiveReplacements:e.recursiveReplacements}})},e}static createSerializedReplacements(){return{replacements:[]}}static calculateReplacementChanges(){return[]}replacements=[];replacementsToWithhold=0;get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;for(let t in this.allChildren){let n=this.allChildren[t].component;for(let t of n.allPotentialRendererTypes)e.includes(t)||e.push(t)}if(this.replacements)for(let t of this.replacements)if("object"==typeof t)for(let n of t.allPotentialRendererTypes)e.includes(n)||e.push(n);return e}}class Template extends CompositeComponent{static componentType="template";static treatAsComponentForRecursiveReplacements=!0;static includeBlankStringChildren=!0;static renderedDefault=!1;static assignNamesToReplacements=!0;static createsVariants=!0;static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static createAttributesObject(){let e=super.createAttributesObject();return e.rendered={createComponentOfType:"boolean",createStateVariable:"rendered",defaultValue:this.renderedDefault,public:!0},e.isResponse={leaveRaw:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.serializedChildren={returnDependencies:()=>({serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return{setValue:{serializedChildren:e.serializedChildren}}}},e.newNamespace={returnDependencies:()=>({newNamespace:{dependencyType:"attributePrimitive",attributeName:"newNamespace"}}),definition:({dependencyValues:e})=>({setValue:{newNamespace:e.newNamespace}})},e.readyToExpandWhenResolved={returnDependencies:()=>({}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:n}){let r;if(e.typeAttr){if(!(n.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in n.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);r=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error(`You must specify createComponentOfType when specifying nComponents for a ${t.componentType}.`);r=null}return{setValue:{nComponentsSpecified:r}}}},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,alwaysCreateReplacements:n,flags:r}){if(await e.stateValues.nComponentsSpecified,await e.stateValues.rendered||n){let n=deepClone(await e.state.serializedChildren.value),a=e.attributes.newNamespace?.primitive;if("isResponse"in e.attributes)for(let i of n){if("object"!=typeof i)continue;let n=convertAttributesForComponentType({attributes:{isResponse:e.attributes.isResponse},componentType:i.componentType,componentInfoObjects:t,compositeCreatesNewNamespace:a,flags:r});i.attributes||(i.attributes={}),Object.assign(i.attributes,n)}let i=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:n,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:t,originalNamesAreConsistent:!0});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:i.serializedComponents,assignNames:e.doenetAttributes.assignNames,componentInfoObjects:t,compositeAttributesObj:this.createAttributesObject(),flags:r})).replacements}}return{replacements:[]}}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n);return e}}const vectorAndListOperators=["list",...vectorOperators];class MathComponent extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="math";static primaryStateVariableForDefinition="unnormalizedValue";static primaryEssentialStateVariable="value";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0,toLowerCase:!0,validValues:["text","latex"]},e.simplify={createComponentOfType:"text",createStateVariable:"simplify",defaultValue:"none",public:!0,toLowerCase:!0,valueTransformations:{true:"full",false:"none"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expand",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"inline",public:!0,forRenderer:!0},e.unordered={createComponentOfType:"boolean"},e.createVectors={createComponentOfType:"boolean",createStateVariable:"createVectors",defaultValue:!1,public:!0},e.createIntervals={createComponentOfType:"boolean",createStateVariable:"createIntervals",defaultValue:!1,public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.sourcesAreFunctionSymbols={createComponentOfType:"textList",createStateVariable:"sourcesAreFunctionSymbols",defaultValue:[]},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.groupCompositeReplacements={createPrimitiveOfType:"boolean",createStateVariable:"groupCompositeReplacements",defaultValue:!0},e.displayBlanks={createComponentOfType:"boolean",createStateVariable:"displayBlanks",defaultValue:!0,public:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"strings",componentTypes:["string"]},{group:"displayedMaths",componentTypes:["m","me","men"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDigits"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displayDecimals"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.mathChildren[0].stateValues.displayDecimals}};r=!0,n=e.mathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["displaySmallAsZero"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.mathChildren.length&&0===e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.mathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["padZeros"]},stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.mathChildren.length&&0==e.stringChildren.length){if(!t.mathChildren[0]||!t.mathChildren[0].padZeros)return{setValue:{padZeros:e.mathChildren[0].stateValues.padZeros}};r=!0,n=e.mathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.valueShadow={defaultValue:me$3.fromAst("_"),hasEssential:!0,essentialVarName:"value",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]}}},e.unordered={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,returnDependencies:()=>({unorderedAttr:{dependencyType:"attributeComponent",attributeName:"unordered",variableNames:["value"]},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["unordered"]}}),definition({dependencyValues:e}){if(null===e.unorderedAttr){if(e.mathChildren.length>0){let t=e.mathChildren.every((e=>e.stateValues.unordered));return{setValue:{unordered:t}}}return{useEssentialOrDefaultValue:{unordered:!0}}}return{setValue:{unordered:e.unorderedAttr.stateValues.value}}}},e.codePre={returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition({dependencyValues:e}){let t="math",n=!1;do{n=!1;for(let r of e.stringChildren)if(!0===r.includes(t)){n=!0,t+="m";break}}while(n);return{setValue:{codePre:t}}}},e.mathChildrenFunctionSymbols={returnDependencies:()=>({sourcesAreFunctionSymbols:{dependencyType:"stateVariable",variableName:"sourcesAreFunctionSymbols"},mathChildren:{dependencyType:"child",childGroups:["maths"]}}),definition({dependencyValues:e}){let t=[];if(e.mathChildren.compositeReplacementRange)for(let n of e.mathChildren.compositeReplacementRange)if(e.sourcesAreFunctionSymbols.includes(n.target))for(let e=n.firstInd;e<=n.lastInd;e++)t.push(e);return{setValue:{mathChildrenFunctionSymbols:t}}}},e.expressionWithCodes={hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"],variableNames:["latex"]},format:{dependencyType:"stateVariable",variableName:"format"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},mathChildrenFunctionSymbols:{dependencyType:"stateVariable",variableName:"mathChildrenFunctionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"},groupCompositeReplacements:{dependencyType:"stateVariable",variableName:"groupCompositeReplacements"}}),set:e=>null===e?null:convertValueToMathExpression(e),definition:calculateExpressionWithCodes,async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,componentName:r}){let a=e.expressionWithCodes,i=[{setEssentialValue:"expressionWithCodes",value:a}],s=t.stringChildren.length;if(0===s)return{success:!1};if(0===t.mathChildren.length){let e;e="latex"===await n.format?a.toLatex():a.toString(),i.push({setDependency:"stringChildren",desiredValue:e,childIndex:0,variableIndex:0,ignoreChildChangeForComponent:!0});for(let e=1;e({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value","canBeModified"]}}),definition:({dependencyValues:e})=>({setValue:{mathChildrenWithCanBeModified:e.mathChildren}})},e.unnormalizedValue={returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},codePre:{dependencyType:"stateVariable",variableName:"codePre"},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),set:convertValueToMathExpression,defaultValue:me$3.fromAst("_"),definition:calculateMathValue,inverseDefinition:invertMath},e.value={public:!0,shadowingInstructions:{createComponentOfType:this.componentType,attributesToShadow:["unordered","displayDigits","displayDecimals","displaySmallAsZero","padZeros","simplify","expand"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},returnDependencies:()=>({unnormalizedValue:{dependencyType:"stateVariable",variableName:"unnormalizedValue"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},createVectors:{dependencyType:"stateVariable",variableName:"createVectors"},createIntervals:{dependencyType:"stateVariable",variableName:"createIntervals"}}),definition:function({dependencyValues:e}){let t=e.unnormalizedValue,{simplify:n,expand:r,createVectors:a,createIntervals:i}=e;return t=normalizeMathExpression({value:t,simplify:n,expand:r,createVectors:a,createIntervals:i}),{setValue:{value:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"unnormalizedValue",desiredValue:e.value}]}}},e.number={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=e.value.evaluate_to_constant();return null===t&&(t=NaN),{setValue:{number:t}}},inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setDependency:"value",desiredValue:me$3.fromAst(e.number)}]}}},e.isNumber={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{isNumber:Number.isFinite(e.value.tree)}}}},e.isNumeric={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({number:{dependencyType:"stateVariable",variableName:"number"}}),definition:function({dependencyValues:e}){return{setValue:{isNumeric:Number.isFinite(e.number)}}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:normalizeMathExpression({value:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}),simplify:e.simplify,expand:e.expand})}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:e.valueForDisplay}]})},e.latex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toLatex(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{latex:n}}},inverseDefinition({desiredStateVariableValues:e}){let t;try{t=me$3.fromLatex(e.latex)}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"valueForDisplay",desiredValue:t}]}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"},displayBlanks:{dependencyType:"stateVariable",variableName:"displayBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n,r={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.displayBlanks||(r.showBlanks=!1);try{n=e.valueForDisplay.toString(r)}catch(t){n=e.displayBlanks?"_":""}return{setValue:{text:superSubscriptsToUnicode(n.toString())}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n,r=getFromText({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(unicodeToSuperSubscripts(e.text))}catch(e){return{success:!1}}return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}}},e.codesAdjacentToStrings={returnDependencies:()=>({stringMathChildren:{dependencyType:"child",childGroups:["strings","maths"]},codePre:{dependencyType:"stateVariable",variableName:"codePre"},format:{dependencyType:"stateVariable",variableName:"format"}}),definition:calculateCodesAdjacentToStrings},e.canBeModified={additionalStateVariablesDefined:["constantChildIndices","codeForExpression","inverseMaps","template","mathChildrenMapped"],returnDependencies:()=>({mathChildrenModifiable:{dependencyType:"child",childGroups:["maths"],variableNames:["canBeModified"]},displayedMathChildren:{dependencyType:"child",childGroups:["displayedMaths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition:determineCanBeModified},e.mathChildrenByVectorComponent={returnDependencies:()=>({codePre:{dependencyType:"stateVariable",variableName:"codePre"},mathChildren:{dependencyType:"child",childGroups:["maths"]},expressionWithCodes:{dependencyType:"stateVariable",variableName:"expressionWithCodes"}}),definition:function({dependencyValues:e}){if(null===e.expressionWithCodes)return{setValue:{mathChildrenByVectorComponent:null}};let t=e.expressionWithCodes.tree,n=e.mathChildren.length;if(0===n||!Array.isArray(t)||!vectorOperators.includes(t[0]))return{setValue:{mathChildrenByVectorComponent:null}};let r={},a=0,i=e.codePre+a;for(let s=1;s=n)break}return{setValue:{mathChildrenByVectorComponent:r}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=1,n=e.value.tree;if(Array.isArray(n))if(vectorAndListOperators.includes(n[0]))t=n.length-1;else if("matrix"===n[0]){let e=n[1].slice(1);1===e[0]?t=e[1]:1===e[1]&&(t=e[0])}else vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=n[1].length-1);return{setValue:{nDimensions:t}}}},e.vector={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;ee.tree))]);else if("matrix"===s[0]){let e=s[1].slice(1);if(1===e[0]){let e=["tuple"];for(let t=0;te.tree))]],s[2]&&i.push(s[2]),i=me$3.fromAst(i));return i||(i=r.desiredVector[0]),{success:!0,instructions:[{setDependency:"value",desiredValue:i}]}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.matrixSize={public:!0,shadowingInstructions:{createComponentOfType:"numberList"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition({dependencyValues:e}){let t=[1,1],n=e.value.tree;return Array.isArray(n)&&(vectorAndListOperators.includes(n[0])?t=[n.length-1,1]:"matrix"===n[0]?t=n[1].slice(1):vectorOperators.includes(n[1][0])&&("^"===n[0]&&"T"===n[2]||"prime"===n[0])&&(t=[1,n[1].length-1])),{setValue:{matrixSize:t}}}},e.nRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nRows:e.matrixSize[0]}})},e.nColumns={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),definition:({dependencyValues:e})=>({setValue:{nColumns:e.matrixSize[1]}})},e.matrix={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"matrixEntry"===e?[]:"row"===e?[["matrix","matrixRow"]]:"column"===e?[["matrix","matrixColumn"]]:[["matrixRow"],["matrix"]]},isArray:!0,nDimensions:2,entryPrefixes:["matrixEntry","row","column","rows","columns"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("matrixEntry"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}if("column"===e){let e=Number(t)-1;return Number.isInteger(e)&&e>=0?n?en+","+e)):[]:["0,"+e]:[]}if("rows"===e||"columns"===e){if(!n)return["0,0"];let e=[];for(let t=0;tt+","+n)));return e}},arrayVarNameFromPropIndex(e,t){if("matrix"===t||"rows"===t)return 1===e.length?"row"+e[0]:`matrixEntry${e[0]}_${e[1]}`;if("columns"===t)return 1===e.length?"column"+e[0]:`matrixEntry${e[1]}_${e[0]}`;if("row"===t.slice(0,3)){let n=Number(t.slice(3));if(Number.isInteger(n)&&n>0)return`matrixEntry${n}_${e[0]}`}if("column"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`matrixEntry${e[0]}_${n}`}return null},returnArraySizeDependencies:()=>({matrixSize:{dependencyType:"stateVariable",variableName:"matrixSize"}}),returnArraySize:({dependencyValues:e})=>e.matrixSize,returnArrayDependenciesByKey:()=>({globalDependencies:{value:{dependencyType:"stateVariable",variableName:"value"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t,arraySize:n}){let r=e.value.tree,a=!1,i={};if(Array.isArray(r))if(vectorAndListOperators.includes(r[0])){for(let e=0;e({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=[{stateVariable:"number",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text",{componentType:"subsetOfReals",stateVariable:"value",substituteForPrimaryStateVariable:"subsetValue"}];async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function calculateExpressionWithCodes({dependencyValues:e,changes:t}){if(!("stringMathChildren"in t&&t.stringMathChildren.componentIdentitiesChanged||"displayedMathChildren"in t||"format"in t||"splitSymbols"in t||"parseScientificNotation"in t||"functionSymbols"in t||"mathChildrenFunctionSymbols"in t))return{useEssentialOrDefaultValue:{expressionWithCodes:!0}};if(0===e.stringMathChildren.length){if(e.displayedMathChildren.length>0){let t;try{t=me$3.fromLatex(e.displayedMathChildren[0].stateValues.latex)}catch(e){t=me$3.fromAst("_")}return{setValue:{expressionWithCodes:t},setEssentialValue:{expressionWithCodes:t}}}return{setValue:{expressionWithCodes:null},setEssentialValue:{expressionWithCodes:null}}}let n,r,a,i,s="",o=0,l="",u=e.stringMathChildren.compositeReplacementRange;e.groupCompositeReplacements&&u.length>0&&(a=0,i=u[a].firstInd);for(let[t,c]of e.stringMathChildren.entries()){if(void 0===n&&t===i){n=a,r=u[a].lastInd,l="";let s=r===t;if(!s)for(let n=t;n<=r;n++)if("string"==typeof e.stringMathChildren[n]){s=!0;break}s&&(u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0)}if("string"==typeof c)s+=" "+c+" ";else{let t,r=e.codePre+o;o++,t="latex"===e.format?"\\operatorname{"+r+"}":" "+r+" ",void 0!==n?(l&&(l+=","),l+=t):s+=t}if(t===r){let o=s.trimEnd(),c=!1;if(0===o.length)c=!0;else{let n=o[o.length-1];if(["{","[","(","|",","].includes(n)){let n=e.stringMathChildren[t+1];if("string"!=typeof n)c=!0;else{let t=n.trimStart();if(0===t.length)c=!0;else{let n=t[0];"latex"===e.format&&"\\"===n&&t.length>1&&(n=t[1]),["}","]",")","|",","].includes(n)||(c=!0)}}}else c=!0}c&&(l="("+l+")"),s+=l,l="",u.length>n+1?(a=n+1,i=u[a].firstInd):(a=void 0,i=void 0),n=void 0,r=void 0}}let c=null,p=[...e.functionSymbols];if(p.push(...e.mathChildrenFunctionSymbols.map((t=>e.codePre+t))),""===s)c=me$3.fromAst("_");else if("text"===e.format){let t=getFromText({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of text format: "+s)}}else if("latex"===e.format){let t=getFromLatex({functionSymbols:p,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation});try{c=t(s)}catch(e){c=me$3.fromAst("_"),console.log("Invalid value for a math of latex format: "+s)}}return{setValue:{expressionWithCodes:c},setEssentialValue:{expressionWithCodes:c}}}function calculateMathValue({dependencyValues:e}={}){if(null===e.expressionWithCodes)return{setValue:{unnormalizedValue:e.valueShadow}};let t={};for(let[n,r]of e.mathChildren.entries())t[e.codePre+n]=r.stateValues.value;let n=e.expressionWithCodes;return e.mathChildren.length>0&&(n=n.substitute(t)),n=me$3.fromAst(mergeListsWithOtherContainers(n.tree)),{setValue:{unnormalizedValue:n}}}function calculateCodesAdjacentToStrings({dependencyValues:e}){let t,n=[];for(let[r,a]of e.stringMathChildren.entries())if("string"==typeof a){let a=e.stringMathChildren[r+1];if(void 0!==a&&"string"==typeof a)continue;let i={};if(void 0!==t&&("latex"===e.format?i.prevCode="\\operatorname{"+e.codePre+t+"}":i.prevCode=e.codePre+t),void 0!==a){let n=0;void 0!==t&&(n=t+1),"latex"===e.format?i.nextCode="\\operatorname{"+e.codePre+n+"}":i.nextCode=e.codePre+n}n.push(i)}else void 0===t?t=0:t++;return{setValue:{codesAdjacentToStrings:n}}}function determineCanBeModified({dependencyValues:e}){if(!e.modifyIndirectly||e.fixed)return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};if(0===e.mathChildrenModifiable.length)return e.displayedMathChildren.length>0?{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}:{setValue:{canBeModified:!0,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}};let t=[],n=[],r=[],a={};for(let[i,s]of e.mathChildrenModifiable.entries()){let o=e.codePre+i;!0===s.stateValues.canBeModified?(t.push(i),n.push(o)):(r.push(o),a[o]=i)}let i=e.codePre+"expr",s=checkForLinearExpression(me$3.utils.unflattenLeft(e.expressionWithCodes.tree),n,i,r);if(s.foundLinear){let e={},r=s.template,o=new Set;for(let r in s.mappings){e[r]=s.mappings[r];let a=e[r].mathChildSub;if(a){let i=t[n.indexOf(a)];e[r].mathChildInd=i,o.add(Number(i))}}return o.has=o.has.bind(o),{setValue:{canBeModified:!0,constantChildIndices:a,codeForExpression:i,inverseMaps:e,template:r,mathChildrenMapped:o}}}return{setValue:{canBeModified:!1,constantChildIndices:null,codeForExpression:null,inverseMaps:null,template:null,mathChildrenMapped:null}}}function checkForLinearExpression(e,t,n,r=[],a=[]){let i=me$3.variables(e);if(i.every((e=>!t.includes(e)))&&i.every((e=>!r.includes(e)))){let e={},t="x"+a.join("_");return e[t]={result:me$3.fromAst(n).simplify(),components:a},{foundLinear:!0,mappings:e,template:t}}if(!Array.isArray(e))return checkForScalarLinearExpression(e,t,n,a);let s=e[0],o=e.slice(1);if(vectorAndListOperators.includes(s)){let e={mappings:{},template:[s]},i=0;for(let s=0;s!t.includes(e)))?(n=["+",n,["-",i[0]]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["+",n,["-",i[1]]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"*"===a?me$3.variables(i[0]).every((e=>!t.includes(e)))?(n=["/",n,i[0]],checkForScalarLinearExpression(i[1],t,n,r)):me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["/",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}:"/"===a&&me$3.variables(i[1]).every((e=>!t.includes(e)))?(n=["*",n,i[1]],checkForScalarLinearExpression(i[0],t,n,r)):{foundLinear:!1}}async function invertMath({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r,overrideFixed:a,componentName:i}){if(!await n.canBeModified&&!a)return{success:!1};let s=t.mathChildren,o=t.stringChildren.length;if(1===s.length&&0===o)return{success:!0,instructions:[{setDependency:"mathChildren",desiredValue:e.unnormalizedValue,childIndex:0,variableIndex:0}]};let l=convertValueToMathExpression(e.unnormalizedValue),u=await preprocessMathInverseDefinition({desiredValue:l,stateValues:n,variableName:"value",workspace:r}),c=u.vectorComponentsNotAffected;if(l=u.desiredValue,0===s.length){let f=[];return o>0?f.push({setDependency:"expressionWithCodes",desiredValue:l}):f.push({setDependency:"valueShadow",desiredValue:l}),{success:!0,instructions:f}}let p=await getExpressionPieces({expression:l,stateValues:n});if(!p)return{success:!1};let d=[],m=[];if(c&&await n.mathChildrenByVectorComponent){let y=await n.mathChildrenByVectorComponent;for(let g of c)y[g]&&m.push(...y[g])}let h=await n.mathChildrenWithCanBeModified;for(let[b,v]of s.entries())if(n.mathChildrenMapped.has(b)&&h[b].stateValues.canBeModified){if(!m.includes(b)){let N=p[b],T={},C=!1,A=await n.constantChildIndices;for(let V in A){let x=A[V];T[V]=s[x].stateValues.value,C=!0}C&&(N=N.substitute(T)),N=N.simplify(),d.push({setDependency:"mathChildren",desiredValue:N,childIndex:b,variableIndex:0})}delete p[b]}if(o>0){let S=t.expressionWithCodes,w=t.codePre,E=w.length;function D(e){return"string"==typeof e&&e.substring(0,E)===w}function O(e){return Array.isArray(e)?flattenDeep(e.slice(1)).some(D):D(e)}if(vectorAndListOperators.includes(S.tree[0])&&!S.tree.slice(1).every(O)){let I=await n.inverseMaps;for(let R in p){let _=I[R];if(void 0!==_.mathChildInd)continue;let M=_.components;S=S.substitute_component(M,p[R])}d.push({setDependency:"expressionWithCodes",desiredValue:S})}}return{success:!0,instructions:d}}async function getExpressionPieces({expression:e,stateValues:t}){let n=await t.template,r=me$3.utils.match(e.tree,n);if(!(r||(r=me$3.utils.match(e.tuples_to_vectors().tree,me$3.fromAst(n).tuples_to_vectors().tree),r||(r=me$3.utils.match(e.to_intervals().tree,me$3.fromAst(n).to_intervals().tree),r||(r=me$3.utils.match(e.tuples_to_vectors().to_intervals().tree,me$3.fromAst(n).tuples_to_vectors().to_intervals().tree),r)))))return!1;let a={};for(let e in r){let n={};n[await t.codeForExpression]=r[e];let i=(await t.inverseMaps)[e];if(void 0!==i){let r=e;void 0!==i.mathChildInd&&(r=i.mathChildInd),a[r]=i.result.substitute(n),a[r]=normalizeMathExpression({value:a[r],simplify:await t.simplify,expand:await t.expand,createVectors:await t.createVectors,createIntervals:await t.createIntervals})}}return a}class Label extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveLabel:this.moveLabel.bind(this)})}static componentType="label";static renderChildren=!0;static rendererType="label";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="valueShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.forObject={createTargetComponentNames:!0},e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.valueShadow={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{valueShadow:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"valueShadow",value:e.valueShadow}]})},e.hasLatex={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow;return{setValue:{hasLatex:Boolean(/\\\(.*\\\)/.exec(t))}}}for(let t of e.inlineChildren)if("object"!=typeof t);else if("boolean"==typeof t.stateValues.hasLatex&&"string"==typeof t.stateValues.value&&"string"==typeof t.stateValues.text){if(t.stateValues.hasLatex)return{setValue:{hasLatex:!0}}}else if("boolean"==typeof t.stateValues.renderAsMath&&"string"==typeof t.stateValues.latex&&"string"==typeof t.stateValues.text){if(t.stateValues.renderAsMath)return{setValue:{hasLatex:!0}}}else if("string"==typeof t.stateValues.latex)return{setValue:{hasLatex:!0}};return{setValue:{hasLatex:!1}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"latex",public:!0,shadowingInstructions:{createComponentOfType:"text"}},{variableName:"value",public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"hasLatex"}}}}],returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text","latex","value","hasLatex","renderAsMath"],variablesOptional:!0},valueShadow:{dependencyType:"stateVariable",variableName:"valueShadow"},hasLatex:{dependencyType:"stateVariable",variableName:"hasLatex"}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length&&null!==e.valueShadow){let t=e.valueShadow,n=t;return e.hasLatex&&(n=n.replace(/\\\(/g,""),n=n.replace(/\\\)/g,"")),{setValue:{text:n,latex:n,value:t}}}let t="",n="";for(let r of e.inlineChildren)if("object"!=typeof r){let e=r.toString();t+=e,n+=e}else"boolean"==typeof r.stateValues.hasLatex&&"string"==typeof r.stateValues.value&&"string"==typeof r.stateValues.text?(t+=r.stateValues.text,n+=r.stateValues.value):"boolean"==typeof r.stateValues.renderAsMath&&"string"==typeof r.stateValues.latex&&"string"==typeof r.stateValues.text?r.stateValues.renderAsMath?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):(t+=r.stateValues.text,n+=r.stateValues.text):"string"==typeof r.stateValues.latex?(t+=r.stateValues.latex,n+="\\("+r.stateValues.latex+"\\)"):"string"==typeof r.stateValues.text&&(t+=r.stateValues.text,n+=r.stateValues.text);return{setValue:{text:t,latex:t,value:n}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n;if("string"==typeof e.value)n=e.value;else if("string"==typeof e.text)n=e.text;else{if("string"!=typeof e.latex)return{success:!1};n=e.latex}if(0===t.inlineChildren.length&&null!==t.valueShadow)return{success:!0,instructions:[{setDependency:"valueShadow",desiredValue:n}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0],r=e.value;if("object"!=typeof n)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0}]};if("boolean"==typeof n.stateValues.hasLatex&&"string"==typeof n.stateValues.value&&"string"==typeof n.stateValues.text)return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:2}]};if("boolean"==typeof n.stateValues.renderAsMath&&"string"==typeof n.stateValues.latex&&"string"==typeof n.stateValues.text){if(n.stateValues.renderAsMath){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}}if("string"==typeof n.stateValues.latex){let e=r.match(/^\\\((.*)\\\)/);return e&&(r=e[1]),{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:1}]}}return"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:r,childIndex:0,variableIndex:0}]}:{success:!1}}return{success:!1}}},e.forObjectComponentName={returnDependencies:()=>({forObject:{dependencyType:"attributeTargetComponentNames",attributeName:"forObject"}}),definition({dependencyValues:e}){let t;return t=1===e.forObject?.length?e.forObject[0].absoluteName:null,{setValue:{forObjectComponentName:t}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}static adapters=["text"];async moveLabel({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}function returnGroupIntoComponentTypeSeparatedBySpaces({componentType:e,forceComponentType:t=!1}){return function({matchedChildren:n,componentInfoObjects:r}){let a=[],i=[];function s(){let n=!1;if(t){if(1===i.length){let t=i[0],s=t.componentType;"copy"===s&&t.attributes?.createComponentOfType&&(t.attributes.nComponents&&1!==t.attributes.nComponents.primitive||(s=t.attributes.createComponentOfType.primitive)),r.isInheritedComponentType({inheritedComponentType:s,baseComponentType:e})&&(a.push(t),n=!0)}}else 1===i.length&&"string"!=typeof i[0]&&(a.push(i[0]),n=!0);!n&&i.length>0&&a.push({componentType:e,children:i}),i=[]}for(let e of n)if("string"!=typeof e)i.push(e);else{let t=e.split(/\s+/),n=t[0];""===n?s():i.push(n);for(let e of t.slice(1))s(),""!==e&&i.push(e)}return s(),{success:!0,newChildren:a}}}function returnBreakStringsIntoComponentTypeBySpaces({componentType:e}){return function({matchedChildren:t}){let n=t.reduce((function(t,n){return"string"==typeof n?[...t,...n.split(/\s+/).filter((e=>e)).map((t=>({componentType:e,children:[t]})))]:[...t,n]}),[]);return{success:!0,newChildren:n}}}class MathList extends InlineComponent{static componentType="mathList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="maths";static primaryStateVariableForDefinition="mathsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.mergeMathLists={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"math"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"math"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"mathLists",componentTypes:["mathList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{mathsShadow:!0}})},e.mergeMathLists={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({mergeMathListsAttr:{dependencyType:"attributeComponent",attributeName:"mergeMathLists",variableNames:["value"]},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],skipComponentNames:!0},mathChildren:{dependencyType:"child",childGroups:["maths"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{mergeMathLists:e.mergeMathListsAttr?.stateValues.value||0===e.mathListChildren.length&&1===e.mathChildren.length}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["mergeMathLists"],additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies({stateValues:e}){let t={maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}};return e.mergeMathLists?t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","nComponents"],variablesOptional:!0}:(t.mathListChildren={dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},t.mathAndMathListChildren={dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0}),t},definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.mathAndMathListChildren.length>0)if(e.mergeMathLists)for(let[a,i]of e.mathAndMathListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})){for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.maths={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["math"],stateVariablesDeterminingDependencies:["mergeMathLists","childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["value","math"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].mathAndMathListChildren[0];if(n)if(void 0!==n.stateValues.value){let t=n.stateValues.value;if(e.mergeMathLists&&Array.isArray(t.tree)&&"list"===t.tree[0]){let n=e.childIndexByArrayKey[a][1];r[a]=t.get_component(n)}else r[a]=t}else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["math"+t]}else null!==e.mathsShadow&&(r[a]=e.mathsShadow[a])}return{setValue:{maths:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.mergeMathLists){let t=[],s=await a.childIndexByArrayKey,o=[];for(let l in e.maths){if(!n[l])continue;if(o.includes(l))continue;let u;if(void 0!==s[l][2]){let t=Number(l)-s[l][1],n=t+s[l][2]-1;i.desiredMaths||(i.desiredMaths=[]);let r=["list"];for(let s=t;s<=n;s++)void 0!==e.maths[s]?i.desiredMaths[s]=convertValueToMathExpression(e.maths[s]):void 0===i.desiredMaths[s]&&(i.desiredMaths[s]=(await a.maths)[s]),r.push(i.desiredMaths[s].tree),o.push(s.toString());u=me$3.fromAst(r)}else u=e.maths[l];let c=n[l].mathAndMathListChildren[0];c&&(void 0!==c.stateValues.value?t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:0}):t.push({setDependency:r[l].mathAndMathListChildren,desiredValue:u,childIndex:0,variableIndex:1}))}return{success:!0,instructions:t}}let s=[];for(let t in e.maths){if(!n[t])continue;let a=n[t].mathAndMathListChildren[0];a&&(void 0!==a.stateValues.value?s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:0}):s.push({setDependency:r[t].mathAndMathListChildren,desiredValue:e.maths[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:s}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({maths:{dependencyType:"stateVariable",variableName:"maths"}}),definition({dependencyValues:e}){let t;return t=0===e.maths.length?me$3.fromAst("_"):1===e.maths.length?e.maths[0]:me$3.fromAst(["list",...e.maths.map((e=>e.tree))]),{setValue:{math:t}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"maths"},e.latex={additionalStateVariablesDefined:["latexs"],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","latex","latexs"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.mathAndMathListChildren.length>0)for(let t of e.mathAndMathListChildren)if(t.stateValues.valueForDisplay){let a=t.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(a.tree)&&"list"===a.tree[0])for(let e=0;eroundForDisplay({value:n,dependencyValues:e,usedDefault:t}).toLatex(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{latex:n.join(", "),latexs:n}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},mergeMathLists:{dependencyType:"stateVariable",variableName:"mergeMathLists"},mathsShadow:{dependencyType:"stateVariable",variableName:"mathsShadow"}}),definition:function({dependencyValues:e}){let t=[];if(e.mathAndMathListChildren.length>0)for(let n of e.mathAndMathListChildren)if(n.stateValues.valueForDisplay){let r=n.stateValues.valueForDisplay;if(e.mergeMathLists&&Array.isArray(r.tree)&&"list"===r.tree[0])for(let e=0;ee.toString())));let n=e.maximumNumber;return null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),{setValue:{text:t.join(", "),texts:t}}}},e.componentNamesInList={returnDependencies:()=>({mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.mathAndMathListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"mathList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["nComponents"]},mathAndMathListChildren:{dependencyType:"child",childGroups:["maths","mathLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.mathAndMathListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"mathList"})){let t=e.mathListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Columns extends Text{static componentType="columns";static rendererType="text"}class Title extends TextOrInline{static componentType="title"}class RightHandSide extends MathComponent{static componentType="rightHandSide";static rendererType="math"}class Description extends TextOrInline{static componentType="description";static rendererType=void 0}class Else extends Template{static componentType="else"}class Xlabel extends Label{static componentType="xlabel";static rendererType="label"}class Ylabel extends Label{static componentType="ylabel";static rendererType="label"}class MatrixRow extends MathList{static componentType="matrixRow";static rendererType="mathList"}class MatrixColumn extends MathList{static componentType="matrixColumn";static rendererType="mathList"}var Aliases=Object.freeze({__proto__:null,Columns:Columns,Title:Title,RightHandSide:RightHandSide,Description:Description,Else:Else,Xlabel:Xlabel,Ylabel:Ylabel,MatrixRow:MatrixRow,MatrixColumn:MatrixColumn});class M$3 extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="m";static rendererType="math";static includeBlankStringChildren=!0;static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){if(0===e.inlineChildren.length)return{useEssentialOrDefaultValue:{latex:!0}};let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n:"string"==typeof n.stateValues.latex?t+=n.stateValues.latex:"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{latex:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.latex)return{success:!1};if(0===t.inlineChildren.length)return{success:!0,instructions:[{setEssentialValue:"latex",value:e.latex}]};if(1===t.inlineChildren.length){let n=t.inlineChildren[0];return"object"!=typeof n?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0}]}:"string"==typeof n.stateValues.latex?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:0}]}:"string"==typeof n.stateValues.text?{success:!0,instructions:[{setDependency:"inlineChildren",desiredValue:e.latex,childIndex:0,variableIndex:1}]}:{success:!1}}return{success:!1}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["latex","text"],variablesOptional:!0},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.inlineChildren.length)return{setValue:{latexWithInputChildren:[e.latex]}};let n=[],r="",a=0;for(let i of e.inlineChildren)"object"!=typeof i?r+=i:t.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"input"})?(r.length>0&&(n.push(r),r=""),n.push(a),a++):"string"==typeof i.stateValues.latex?r+=i.stateValues.latex:"string"==typeof i.stateValues.text&&(r+=i.stateValues.text);return r.length>0&&n.push(r),{setValue:{latexWithInputChildren:n}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"inline"}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=me$3.fromAst(latexToAst.convert(e.latex))}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Me$2 extends M$3{static componentType="me";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e}}class Men extends M$3{static componentType="men";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"numbered"}}),e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({equationCounter:{dependencyType:"counter",counterName:"equation"}}),definition:({dependencyValues:e})=>({setValue:{equationTag:String(e.equationCounter)}})},e}}var MMeMen=Object.freeze({__proto__:null,M:M$3,Me:Me$2,Men:Men});class Md extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{moveMath:this.moveMath.bind(this)})}static componentType="md";static rendererType="math";static primaryStateVariableForDefinition="latex";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.anchor={createComponentOfType:"point"},e.positionFromAnchor={createComponentOfType:"text",createStateVariable:"positionFromAnchor",defaultValue:"center",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right","center"]},e.styleNumber.defaultValue=0,e}static returnChildGroups(){return[{group:"mrows",componentTypes:["mrow"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();return Object.assign(e,t),e.mrowChildNames={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"]}}),definition:({dependencyValues:e})=>({setValue:{mrowChildNames:e.mrowChildren.map((e=>e.componentName))}})},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},defaultValue:"",hasEssential:!0,shadowVariable:!0,forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latex","hide","equationTag","numbered"]}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t="";for(let n of e.mrowChildren)n.stateValues.hide||(t.length>0&&(t+="\\\\"),n.stateValues.numbered?t+=`\\tag{${n.stateValues.equationTag}}`:t+="\\notag ",t+=n.stateValues.latex);return{setValue:{latex:t}}}return{useEssentialOrDefaultValue:{latex:!0}}}},e.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({mrowChildren:{dependencyType:"child",childGroups:["mrows"],variableNames:["latexWithInputChildren","hide","equationTag","numbered"]},latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){if(e.mrowChildren.length>0){let t=[],n=0,r="";for(let a of e.mrowChildren)if(!a.stateValues.hide){r.length>0&&(r+="\\\\"),a.stateValues.numbered?r+=`\\tag{${a.stateValues.equationTag}}`:r+="\\notag ";for(let e of a.stateValues.latexWithInputChildren)"number"==typeof e?(r.length>0&&(t.push(r),r=""),t.push(n),n++):r+=e}return r.length>0&&t.push(r),{setValue:{latexWithInputChildren:t}}}return{setValue:{latexWithInputChildren:[e.latex]}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){let t;try{t=e.latex.replaceAll("\\notag","").replaceAll("\\amp","").split("\\\\").map((e=>me$3.fromAst(latexToAst.convert(e)).toString())).join("\\\\\n")}catch(t){return{setValue:{text:e.latex}}}return{setValue:{text:superSubscriptsToUnicode(t.toString())}}}},e.renderMode={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{renderMode:"align"}})},e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e.anchor={defaultValue:me$3.fromText("(0,0)"),public:!0,forRenderer:!0,hasEssential:!0,shadowingInstructions:{createComponentOfType:"point"},returnDependencies:()=>({anchorAttr:{dependencyType:"attributeComponent",attributeName:"anchor",variableNames:["coords"]}}),definition:({dependencyValues:e})=>e.anchorAttr?{setValue:{anchor:e.anchorAttr.stateValues.coords}}:{useEssentialOrDefaultValue:{anchor:!0}},inverseDefinition:async({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,initialChange:r})=>r&&!await n.draggable?{success:!1}:t.anchorAttr?{success:!0,instructions:[{setDependency:"anchorAttr",desiredValue:e.anchor,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"anchor",value:e.anchor}]}},e}async moveMath({x:e,y:t,z:n,transient:r,actionId:a}){let i=["vector"];return void 0!==e&&(i[1]=e),void 0!==t&&(i[2]=t),void 0!==n&&(i[3]=n),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"anchor",value:me$3.fromAst(i)}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}}class Mdn extends Md{static componentType="mdn";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e}}class Mrow extends M$3{static componentType="mrow";static createAttributesObject(){let e=super.createAttributesObject();return e.number={createComponentOfType:"boolean"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.renderMode.definition=()=>({setValue:{renderMode:"display"}}),e.numbered={forRenderer:!0,returnDependencies:()=>({parentNumbered:{dependencyType:"parentStateVariable",variableName:"numbered"},numberAttr:{dependencyType:"attributeComponent",attributeName:"number",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=null!==e.numberAttr?e.numberAttr.stateValues.value:e.parentNumbered,{setValue:{numbered:t}}}},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["numbered"],returnDependencies:({stateValues:e})=>e.numbered?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e}}var MdMdnMrow=Object.freeze({__proto__:null,Md:Md,Mdn:Mdn,Mrow:Mrow});function periodicSetEquality(e,t,{min_elements_match:n=3,match_partial:r=!1}={}){if(!is_periodic_set(e))return!1;if(is_periodic_set(t)){if(r){let n=contained_in(e.tree,t.tree,r);if(!1===n)return 0;let a=contained_in(t.tree,e.tree,r);return!1===a?0:!0===n?!0===a?1:a:!0===a?n:Math.min(n,a)}return contained_in(e.tree,t.tree,r)&&contained_in(t.tree,e.tree,r)}{let a=e.tree.slice(1);if(a.length>1)return!1;let i=me$3.fromAst(a[0][1]).evaluate_to_constant(),s=me$3.fromAst(["apply","abs",a[0][2]]).evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return!1;let o=a[0][3],l=a[0][4];if(o!==-1/0||l!==1/0)return!1;if("list"!==t.tree[0])return!1;let u=t.tree.slice(1),c=0;if("ldots"===u[0][0])c++,u=u.slice(1);else if(!r)return!1;if("ldots"===u[u.length-1][0])c++,u=u.slice(0,u.length-1);else if(!r)return!1;let p=u.length;if(0===p)return!1;if(!r&&pme$3.fromAst(e).evaluate_to_constant())).map((e=>Number.isFinite(e)?e:NaN));let d=me$3.math.mod(u[0]-i,s);if(!(me$3.math.min(d,s-d)<1e-10*s))return!1;let m=1;for(let e=1;e=n)return!0;let h=m/Math.max(p,n);return h*=(9+c/2)/10,h}}function is_periodic_set(e){var t=e.tree;if(!Array.isArray(t))return!1;if("periodic_set"!==t[0])return!1;var n=t.slice(1);for(var r of n){if(!Array.isArray(r))return!1;if("tuple"!==r[0])return!1;if(5!==r.length)return!1}return!0}function contained_in(e,t,n){if("periodic_set"===e[0]){if(n){let r=0;for(let a of e.slice(1)){let e=contained_in(a,t,n);!0===e?r++:!1!==e&&(r+=e)}let a=e.length-1;return r===a||0!==r&&r/a}return e.slice(1).every((e=>contained_in(e,t)))}var r=e[1],a=e[2],i=e[3],s=e[4];if(i!==-1/0||s!==1/0)return!1;r=me$3.fromAst(["/",r,a]).evaluate_to_constant();var o=t.slice(1),l=[];for(let e=0;e1e3)return!1;let c=s.d;l.push([u,c,r,i])}for(l.sort();;){if(1!==l[0][0])break;let e=l[0][2],t=l[0][3],n=me$3.fromAst(["+",e,["-",r]]).evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t)&&(n=me$3.math.mod(n,t),me$3.math.min(n,t-n)<1e-10*t))return!0;if(l.splice(0,1),0===l.length)return!1}var u=[...new Set(l.map((e=>e[0])))];let c=0;for(let e of u){let t=l.map((function(t,n){let r=e/t[0];return Number.isInteger(r)?[t[0],r,n]:void 0})).filter((e=>e)),a=[];for(let n of t){let t=n[0],i=n[1],s=n[2],o=l[s][2],u=l[s][3];for(let n=0;nc&&(c=t)}}return!!(n&&c>0)&&c}const nonTupleVectorOperators=["vector","altvector"];function checkEquality({object1:e,object2:t,isUnordered:n=!1,partialMatches:r=!1,matchByExactPositions:a=!1,symbolicEquality:i=!1,simplify:s="none",expand:o=!1,allowedErrorInNumbers:l=0,includeErrorInNumberExponents:u=!1,allowedErrorIsAbsolute:c=!1,nSignErrorsMatched:p=0,nPeriodicSetMatchesRequired:d=3,caseInsensitiveMatch:m=!1,matchBlanks:h=!1}){let f=!1;if(e instanceof me$3.class){if(f=!0,!(t instanceof me$3.class)){if("number"!=typeof t&&"string"!=typeof t)return{fraction_equal:0};t=me$3.fromAst(t)}}else if(t instanceof me$3.class){if(f=!0,"number"!=typeof e&&"string"!=typeof e)return{fraction_equal:0};e=me$3.fromAst(e)}let y,g=function(e,t=!1){e instanceof me$3.class||(e=me$3.fromAst(e)),e=e.normalize_function_names().normalize_applied_functions(),m&&(e=me$3.fromAst(setStringsInTreeToLowerCase(e.tree)));let n=s,r=o;return t&&(n="full",r=!0),"none"===n?l>0&&(e=e.constants_to_floats()):e="numberspreserveorder"===n?e.evaluate_numbers({max_digits:1/0,skip_ordering:!0}):"number"===n?e.evaluate_numbers({max_digits:1/0}):e.evaluate_numbers({max_digits:1/0,evaluate_functions:!0}),normalizeMathExpression({value:e,simplify:n,expand:r})};y=f?i?function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return!e.variables().includes("_")&&!t.variables().includes("_")&&(e=g(e)).equalsViaSyntax(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.variables().includes("_")||r.variables().includes("_"))return{fraction_equal:0};if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equalsViaSyntax(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:function(e,t){let n=e,r=t;if(e instanceof me$3.class||(n=me$3.fromAst(e)),t instanceof me$3.class||(r=me$3.fromAst(t)),m&&(n=me$3.fromAst(setStringsInTreeToLowerCase(n.tree)),r=me$3.fromAst(setStringsInTreeToLowerCase(r.tree))),p>0){r=JSON.parse(JSON.stringify(r),me$3.reviver);let e=function(e,t){return e.equals(t,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})};return n.tree.im||r.tree.im?{fraction_equal:0}:{fraction_equal:me$3.equalSpecifiedSignErrors(r,n,{equalityFunction:e,n_sign_errors:p})?1:0}}if(n.tree.im||r.tree.im)return{fraction_equal:0};return{fraction_equal:n.equals(r,{allowed_error_in_numbers:l,include_error_in_number_exponents:u,allowed_error_is_absolute:c,allow_blanks:h})?1:0}}:(e,t)=>(m&&(e=convertStringsToLowerCase(e),t=convertStringsToLowerCase(t)),{fraction_equal:deepCompare(e,t)?1:0});let b=!1,v=!1;if(f){e=g(e,!i),t=g(t,!i);let s=e.tree[0],o=t.tree[0];if("periodic_set"===s||"periodic_set"===o){let n=e,a=t;"periodic_set"!==s&&(n=t,a=e);let i=periodicSetEquality(n,a,{match_partial:r,min_elements_match:d});return!0===i?{fraction_equal:1}:!1===i?{fraction_equal:0}:{fraction_equal:i}}if("list"===s)e=e.tree.slice(1),t="list"===o?t.tree.slice(1):[t.tree];else if("list"===o)t=t.tree.slice(1),e=[e.tree];else if(nonTupleVectorOperators.includes(s)){if(e=e.tree.slice(1),"interval"===o||"matrix"===o||"array"===o||"set"===o)return{fraction_equal:0};t=vectorOperators.includes(o)?t.tree.slice(1):[t.tree]}else if(nonTupleVectorOperators.includes(o)){if(t=t.tree.slice(1),"interval"===s||"matrix"===s||"array"===s||"set"===s)return{fraction_equal:0};e="tuple"===s?e.tree.slice(1):[e.tree]}else if("interval"===s){a=!0;let n=e.tree[2],r=n[1],i=n[2];if(e=e.tree[1].slice(1),"matrix"===o||"set"===o)return{fraction_equal:0};if("tuple"===o){let e=t.tree.slice(1);if(2!==e.length||!1!==r||!1!==i)return{fraction_equal:0};t=e}else if("array"===o){let e=t.tree.slice(1);if(2!==e.length||!0!==r||!0!==i)return{fraction_equal:0};t=e}else{if("interval"!==o)return{fraction_equal:0};{let e=t.tree[2];if(e[1]!==r||e[2]!==i)return{fraction_equal:0};t=t.tree[1].slice(1)}}}else if("interval"===o){a=!0;let n=t.tree[2],r=n[1],i=n[2];if(t=t.tree[1].slice(1),"matrix"===s||"set"===s)return{fraction_equal:0};if("tuple"===s){let t=e.tree.slice(1);if(2!==t.length||!1!==r||!1!==i)return{fraction_equal:0};e=t}else{if("array"!==s)return{fraction_equal:0};{let t=e.tree.slice(1);if(2!==t.length||!0!==r||!0!==i)return{fraction_equal:0};e=t}}}else if("matrix"===s){if("matrix"!==o)return{fraction_equal:0};e=convertMatrixToArrayOfTuples(e.tree.slice(1)),t=convertMatrixToArrayOfTuples(t.tree.slice(1)),a=!0,v=!0,b=!0}else{if("matrix"===o)return{fraction_equal:0};if("set"===s){let r=[];for(let t of e.tree.slice(1))r.some((e=>1===y(e,t).fraction_equal))||r.push(t);if(e=r,n=!0,"tuple"===o||"array"===o)return{fraction_equal:0};if("set"===o){r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);t=r}else t=[t.tree]}else if("set"===o){let r=[];for(let e of t.tree.slice(1))r.some((t=>1===y(t,e).fraction_equal))||r.push(e);if(t=r,n=!0,"tuple"===s||"array"===s)return{fraction_equal:0};e=[e.tree]}else if("tuple"===s){if(e=e.tree.slice(1),"array"===o)return{fraction_equal:0};t="tuple"===o?t.tree.slice(1):[t.tree]}else if("tuple"===o){if(t=t.tree.slice(1),"array"===s)return{fraction_equal:0};e=[e.tree]}else if("array"===s)e=e.tree.slice(1),t="array"===o?t.tree.slice(1):[t.tree];else{if("array"!==o)return y(e.tree,t.tree);t=t.tree.slice(1),e=[e.tree]}}}else if(Array.isArray(e))Array.isArray(t)||(t="string"==typeof t&&e.every((e=>"string"==typeof e&&!e.includes(",")))?t.split(",").map((e=>e.trim())):[t]);else{if(!Array.isArray(t))return y(e,t);e="string"==typeof e&&t.every((e=>"string"==typeof e&&!e.includes(",")))?e.split(",").map((e=>e.trim())):[e]}let N=e.length,T=t.length,C={fraction_equal:0};if(a&&(n=!1),!n){let n=0,u=Math.min(N,T);for(let r=0;rArray(T+1).fill(0)));for(let n=0;nr&&(r=t.fraction_equal,e=a)}-1!==e&&(V+=r,A.add(e))}return N===T&&N===V?(C.fraction_equal=1,C):r?(C.fraction_equal=V/Math.max(N,T),C):C}function setStringsInTreeToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?[e[0],...e.slice(1).map(setStringsInTreeToLowerCase)]:e}function convertStringsToLowerCase(e){return"string"==typeof e?e.toLowerCase():Array.isArray(e)?e.map(convertStringsToLowerCase):e}function convertMatrixToArrayOfTuples(e){let t=e[0][1],n=e[0][2];if(!Number.isInteger(t)||!Number.isInteger(n))return e;let r=[];for(let a=0;aevaluateLogic({logicTree:e,canOverrideUnorderedCompare:t,dependencyValues:n,valueOnInvalid:r});if(!Array.isArray(e)){if("string"==typeof e){let t=n.booleanChildrenByCode[e];if(t)return n.matchPartial&&void 0!==t.stateValues.fractionSatisfied?t.stateValues.fractionSatisfied:t.stateValues.value?1:0;{let t=n.mathChildrenByCode[e];if(t){let e=t.stateValues.value.simplify().evaluate_to_constant();return Number.isFinite(e)&&0!==e?1:0}{let t=n.numberChildrenByCode[e];if(t){let e=t.stateValues.value;return Number.isFinite(e)&&0!==e?1:0}if("true"===e.toLowerCase())return 1;if("false"===e.toLowerCase())return 0}}}else if("number"==typeof e)return 0===e?0:1;return console.warn("Invalid format for boolean condition"),r}let i=e[0],s=e.slice(1);if("not"===i)return 1!==s.length?(console.warn("Invalid format for boolean condition"),r):0===a(s[0])?1:0;if("and"===i)return n.matchPartial?s.reduce(((e,t)=>e+a(t)),0)/s.length:s.every((e=>1===a(e)))?1:0;if("or"===i)return n.matchPartial?s.reduce(((e,t)=>Math.max(a(t),e)),0):s.some((e=>1===a(e)))?1:0;let o=!1,l=!1,u=!1,c=!1;s.forEach((function(e){"string"==typeof e&&(e in n.mathChildrenByCode||e in n.mathListChildrenByCode||e in n.numberChildrenByCode||e in n.numberListChildrenByCode?o=!0:e in n.textChildrenByCode||e in n.textListChildrenByCode?l=!0:e in n.booleanChildrenByCode||e in n.booleanListChildrenByCode?u=!0:e in n.otherChildrenByCode&&(c=!0))}));let p,d=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?t.stateValues.value.tree:(t=n.mathListChildrenByCode[e],void 0!==t?["list",...t.stateValues.maths.map((e=>e.tree))]:(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?["list",...t.stateValues.numbers]:e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(d)]:e};if("apply"===i&&["isnumber","isinteger"].includes(s[0])){if(l||u||c)return 0;let e=me$3.fromAst(d(s[1])).simplify().evaluate_to_constant();if(!Number.isFinite(e))return 0;if("isnumber"===s[0])return 1;{let t=Math.round(e);return Math.abs(t-e)<=1e-15*Math.abs(e)?1:0}}if(!["=","ne","<",">","le","ge","lts","gts","in","notin"].includes(i)){if(l||u||c)return console.warn("Invalid format for boolean condition"),r;let t=me$3.fromAst(d(e)).simplify().evaluate_to_constant();return Number.isFinite(t)&&0!==t?1:0}if(u){if(o||l||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1;if(s=s.map((function(t){if("string"==typeof t){let i=n.booleanChildrenByCode[t];return void 0!==i?i.stateValues.value:(i=n.booleanListChildrenByCode[t],void 0!==i?(i.stateValues.unordered&&(a=!0),i.stateValues.booleans):"true"===(t=t.toLowerCase().trim())||"t"===t||"false"!==t&&"f"!==t&&(console.warn("Invalid format for boolean condition"),e=!0,r))}return console.warn("Invalid format for boolean condition"),e=!0,r})),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),r;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(l){if(o||c)return console.warn("Invalid format for boolean condition"),r;let e=!1,a=!1,l=function(t,r=!1){if("string"==typeof t){let e=n.textChildrenByCode[t];return void 0!==e?e.stateValues.value.trim().replace(/\s+/," "):(e=n.textListChildrenByCode[t],void 0!==e?(e.stateValues.unordered&&(a=!0),e.stateValues.texts.map((e=>e.trim().replace(/\s+/," ")))):t.trim())}return"number"==typeof t?t.toString():r&&Array.isArray(t)&&"*"===t[0]?t.slice(1).map(l).join(" "):(console.warn("Invalid format for boolean condition"),e=!0,"")};if(s=s.map((e=>l(e,!0))),e)return r;let u=n.unorderedCompare;if(t&&a&&(u=!0),"="===i){let e=s[0];if(n.matchPartial){let t=s.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return s.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal))?1:0}if("ne"===i){if(2!==s.length)return console.warn("Invalid format for boolean condition"),0;return 0===checkEquality({object1:s[0],object2:s[1],isUnordered:u,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,caseInsensitiveMatch:n.caseInsensitiveMatch}).fraction_equal?1:0}return console.warn("Invalid format for boolean condition"),r}if(c){if(o)return console.warn("Invalid format for boolean condition"),r;let e=!1;return s=s.map((function(t){if("string"==typeof t){let e=n.otherChildrenByCode[t];if(void 0!==e)return e.stateValues.value}return console.warn("Invalid format for boolean condition"),e=!0,null})),e?r:"="===i?s.slice(1).every((e=>deepCompare(e,s[0])))?1:0:"ne"===i?2!==s.length?(console.warn("Invalid format for boolean condition"),0):deepCompare(s[0],s[1])?0:1:(console.warn("Invalid format for boolean condition"),0)}"lts"!==i&&"gts"!==i||(p=s[1].slice(1),s=s[0].slice(1));let m=!1,h=function(e){if("string"==typeof e){let t=n.mathChildrenByCode[e];return void 0!==t?(t.stateValues.unordered&&(m=!0),t.stateValues.value.tree):(t=n.mathListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.maths.map((e=>e.tree))]):(t=n.numberChildrenByCode[e],void 0!==t?numberToMathExpression(t.stateValues.value).tree:(t=n.numberListChildrenByCode[e],void 0!==t?(t.stateValues.unordered&&(m=!0),["list",...t.stateValues.numbers]):e)))}return Array.isArray(e)?[e[0],...e.slice(1).map(h)]:e},f=s.map((function(e){return me$3.fromAst(h(e))})),y=n.unorderedCompare;if(t&&m&&(y=!0),"="===i){let e=f[0];if(Number.isNaN(e.tree))return f.slice(1).every((e=>Number.isNaN(e.tree)))?1:0;if(n.matchPartial){let t=f.slice(1).map((t=>checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),r=t.reduce(((e,t)=>e+t.fraction_equal),0);return r/t.length}return f.slice(1).every((t=>1===checkEquality({object1:e,object2:t,isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal))?1:0}if("ne"===i){return 0===checkEquality({object1:f[0],object2:f[1],isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal?1:0}if("in"===i||"notin"===i){let e=f[0],t=f[1].tree;if(!Array.isArray(t)||"set"!==t[0])return console.warn("Invalid format for boolean condition"),r;if(n.matchPartial){let r=t.slice(1).map((t=>checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}))),a=r.reduce(((e,t)=>Math.max(e,t.fraction_equal)),0);return"in"===i?a:1-a}{let r=t.slice(1).some((t=>1===checkEquality({object1:e,object2:me$3.fromAst(t),isUnordered:y,partialMatches:n.matchPartial,matchByExactPositions:n.matchByExactPositions,symbolicEquality:n.symbolicEquality,simplify:n.simplifyOnCompare,expand:n.expandOnCompare,allowedErrorInNumbers:n.allowedErrorInNumbers,includeErrorInNumberExponents:n.includeErrorInNumberExponents,allowedErrorIsAbsolute:n.allowedErrorIsAbsolute,nSignErrorsMatched:n.nSignErrorsMatched,nPeriodicSetMatchesRequired:n.nPeriodicSetMatchesRequired,caseInsensitiveMatch:n.caseInsensitiveMatch,matchBlanks:n.matchBlanks}).fraction_equal));return"in"===i?r?1:0:r?0:1}}let g=f.map((e=>e.simplify().evaluate_to_constant()));if(g.some((e=>null===e||Number.isNaN(e))))return 0;if("<"===i)return g[0]"===i)return g[0]>g[1]?1:0;if("le"===i)return g[0]<=g[1]?1:0;if("ge"===i)return g[0]>=g[1]?1:0;for(let e=0;eg[e+1]))return 0}else if(!(g[e]>=g[e+1]))return 0;return 1}function splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n=!1,init:r=!0}){if(!Array.isArray(e))return"string"!=typeof e||n||r?e:fromTextSplit(e).tree;let a=e[0],i=e.slice(1);if(["and","not","or"].includes(a))return[a,...i.map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:r})))];if(i.some((e=>t.includes(e)))&&(n=!0),"apply"===a){i=[i[0],...i.slice(1).map((e=>splitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))];let e=!1;if("int"===i[0]?e=!0:Array.isArray(i[0])&&("^"===i[0][0]?("int"===i[0][1]||Array.isArray(i[0][1])&&"_"===i[0][1][0]&&"int"===i[0][1][1])&&(e=!0):"_"===i[0][0]&&"int"===i[0][1]&&(e=!0)),e){i=me$3.fromAst([a,...i]).tree.slice(1);let e=i[1];if(Array.isArray(e)&&"*"===e[0]){let t=[];for(let n=0;nsplitSymbolsIfMath({logicTree:e,nonMathCodes:t,foundNonMath:n,init:!1})))]}class BooleanComponent extends InlineComponent{static componentType="boolean";static variableForPlainMacro="value";static descendantCompositesMustHaveAReplacement=!0;static descendantCompositesDefaultReplacementType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numbersepreserveorder"],public:!0},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"comparableTypes",componentTypes:["math","mathList","number","numberList","text","textList","boolean","booleanList","orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["mathListChildrenByCode","numberChildrenByCode","numberListChildrenByCode","textChildrenByCode","textListChildrenByCode","booleanChildrenByCode","booleanListChildrenByCode","otherChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value","texts","maths","numbers","booleans","fractionSatisfied","unordered"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s={},o={},l={},u={},c={},p=0,d=e.codePre;for(let m of e.allChildren)if("string"!=typeof m){let e=d+p;t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"math"})?n[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"mathList"})?r[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"number"})?a[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"numberList"})?i[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"text"})?s[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"textList"})?o[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"boolean"})?l[e]=m:t.isInheritedComponentType({inheritedComponentType:m.componentType,baseComponentType:"booleanList"})?u[e]=m:c[e]=m,p+=1}return{setValue:{mathChildrenByCode:n,mathListChildrenByCode:r,numberChildrenByCode:a,numberListChildrenByCode:i,textChildrenByCode:s,textListChildrenByCode:o,booleanChildrenByCode:l,booleanListChildrenByCode:u,otherChildrenByCode:c}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean",attributesToShadow:["fixed"]},forRenderer:!0,hasEssential:!0,defaultValue:!1,set:Boolean,returnDependencies:()=>({symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","comparableTypes"],variableNames:["value"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(0===e.allChildren.length)return{useEssentialOrDefaultValue:{value:!0}};if(null===e.parsedExpression)return{setValue:{value:!1}};let n=t.unorderedCompare;return{setValue:{value:1===evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e})}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.allChildren.length)return{success:!0,instructions:[{setEssentialValue:"value",value:Boolean(e.value)}]};if(1===t.allChildren.length){let r=t.allChildren[0];if("string"==typeof r)return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value.toString(),childIndex:0,variableIndex:0}]};if(n.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"boolean"}))return{success:!0,instructions:[{setDependency:"allChildren",desiredValue:e.value,childIndex:0,variableIndex:0}]}}return{success:!1}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=String(e.text).toLowerCase();return"true"===n?t=!0:"false"===n&&(t=!1),void 0!==t?{success:!0,instructions:[{setDependency:"value",desiredValue:t}]}:{success:!1}}},e}static adapters=["text"]}class BooleanOperator extends BooleanComponent{static componentType="_booleanOperator";static rendererType="boolean";static descendantCompositesMustHaveAReplacement=!1;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"boolean",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();delete e.parsedExpression,delete e.mathChildrenByCode;let t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({booleanChildren:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.booleanChildren.map((e=>e.stateValues.value)))}}}},e}}class BooleanOperatorOneInput extends BooleanComponent{static componentType="_booleanOperatorOneInput";static rendererType="boolean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreOperator"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"valuePreOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyBooleanOperator(e.value)}}}},e}}class Not extends BooleanOperatorOneInput{static componentType="not";static applyBooleanOperator(e){return!e}}class And extends BooleanOperator{static componentType="and";static applyBooleanOperator(e){return e.every((e=>e))}}class Or$1 extends BooleanOperator{static componentType="or";static applyBooleanOperator(e){return e.some((e=>e))}}class Xor extends BooleanOperator{static componentType="xor";static applyBooleanOperator(e){return 1===e.reduce(((e,t)=>e+t),0)}}var BooleanOperators=Object.freeze({__proto__:null,Not:Not,And:And,Or:Or$1,Xor:Xor});class BooleanBaseOperatorOfMath extends BooleanComponent{static componentType="_booleanOperatorOfMath";static rendererType="boolean";static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return e.every((e=>"string"==typeof e||e.doenetAttributes&&e.doenetAttributes.createdFromMacro))?1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}:{success:!1}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.parsedExpression,delete e.mathChildrenByCode,e.booleanOperator={returnDependencies:()=>({}),definition:()=>({setValue:{booleanOperator:e=>!1}})},e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},booleanOperator:{dependencyType:"stateVariable",variableName:"booleanOperator"}}),definition:function({dependencyValues:e}){return{setValue:{value:e.booleanOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class IsInteger extends BooleanBaseOperatorOfMath{static componentType="isInteger";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsInteger requires exactly one math child"),null;let t=e[0].evaluate_to_constant();if(!Number.isFinite(t))return!1;let n=Math.round(t);return Math.abs(n-t)<=1e-15*Math.abs(t)}}}),e}}class IsNumber extends BooleanBaseOperatorOfMath{static componentType="isNumber";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator.definition=()=>({setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsNumber requires exactly one math child"),null;let t=e[0].evaluate_to_constant();return Number.isFinite(t)}}}),e}}class IsBetween extends BooleanBaseOperatorOfMath{static componentType="isBetween";static createAttributesObject(){let e=super.createAttributesObject();return e.limits={createComponentOfType:"numberList",createStateVariable:"limits",defaultValue:[],public:!0},e.strict={createComponentOfType:"boolean",createStateVariable:"strict",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.booleanOperator={returnDependencies:()=>({limits:{dependencyType:"stateVariable",variableName:"limits"},strict:{dependencyType:"stateVariable",variableName:"strict"}}),definition({dependencyValues:e}){let t,n,r=e.limits[0],a=e.limits[1];if(r!1}};n=a,t=r}let i=e.strict;return{setValue:{booleanOperator:function(e){if(0===e.length)return!1;if(1!==e.length)return console.warn("IsBetween requires exactly one math child"),null;let r=e[0].evaluate_to_constant();return i?r>n&&r=n&&r<=t}}}}},e}}var BooleanOperatorsOfMath=Object.freeze({__proto__:null,IsInteger:IsInteger,IsNumber:IsNumber,IsBetween:IsBetween});class MathOperator extends MathComponent{static componentType="_mathOperator";static rendererType="math";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.forceSymbolic={createComponentOfType:"boolean",createStateVariable:"forceSymbolic",defaultValue:!1,public:!0},e.forceNumeric={createComponentOfType:"boolean",createStateVariable:"forceNumeric",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:Number.isFinite(Number(e))?"number":"math",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDigits"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDigitsAttr?{setValue:{displayDigits:e.displayDigitsAttr.stateValues.value}}:null!==e.displayDecimalsAttr||1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDigits?{useEssentialOrDefaultValue:{displayDigits:!0}}:{setValue:{displayDigits:e.mathLikeChildren[0].stateValues.displayDigits}}},e.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:null,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displayDecimals?{useEssentialOrDefaultValue:{displayDecimals:!0}}:{setValue:{displayDecimals:e.mathLikeChildren[0].stateValues.displayDecimals}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].displaySmallAsZero?{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}:{setValue:{displaySmallAsZero:e.mathLikeChildren[0].stateValues.displaySmallAsZero}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},mathLikeChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:1!==e.mathLikeChildren.length||t.mathLikeChildren[0]&&t.mathLikeChildren[0].padZeros?{useEssentialOrDefaultValue:{padZeros:!0}}:{setValue:{padZeros:e.mathLikeChildren[0].stateValues.padZeros}}},e.isNumericOperator={returnDependencies:()=>({forceNumeric:{dependencyType:"stateVariable",variableName:"forceNumeric"},forceSymbolic:{dependencyType:"stateVariable",variableName:"forceSymbolic"},mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["isNumber"],variablesOptional:!0},mathListChildren:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths"]}}),definition({dependencyValues:e}){let t;return t=!!e.forceNumeric||!e.forceSymbolic&&(0===e.mathChildren.length&&0===e.mathListChildren.length||e.mathChildren.every((e=>e.stateValues.isNumber))&&e.mathListChildren.every((e=>e.stateValues.maths.every((e=>Number.isFinite(e.tree)))))),{setValue:{isNumericOperator:t}}}},delete e.codePre,delete e.expressionWithCodes,delete e.mathChildrenFunctionSymbols,delete e.codesAdjacentToStrings,delete e.mathChildrenByVectorComponent,e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me$3.fromAst("_")}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:e=>me$3.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:null}})},e.unnormalizedValue={returnDependencies:()=>({mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers","mathLists","numberLists"],variableNames:["value","maths","numbers","canBeModified"],variablesOptional:!0},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},numericOperator:{dependencyType:"stateVariable",variableName:"numericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){if(0===e.mathNumberChildren.length)return{setValue:{unnormalizedValue:me$3.fromAst("_")}};if(e.isNumericOperator){let n=[];for(let r of e.mathNumberChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})){let e=r.stateValues.value.evaluate_to_constant();Number.isFinite(e)||(e=NaN),n.push(e)}else if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"}))n.push(...r.stateValues.numbers);else{let e=r.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));n.push(...e)}return{setValue:{unnormalizedValue:me$3.fromAst(e.numericOperator(n))}}}{let n=[];for(let r of e.mathNumberChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"})?n.push(me$3.fromAst(r.stateValues.value)):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"math"})?n.push(r.stateValues.value):t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.numbers.map((e=>me$3.fromAst(e)))):n.push(...r.stateValues.maths);return{setValue:{unnormalizedValue:e.mathOperator(n)}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentInfoObjects:n}){if(0===t.mathNumberChildren.length)return{success:!1};if(t.isNumericOperator){if(t.inverseNumericOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"}))r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e);else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})){let t=s.stateValues.value.evaluate_to_constant();Number.isFinite(t)||(t=NaN),r.push(t),a.push(s.stateValues.canBeModified),i.push(e)}else if(n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"}))r.push(...s.stateValues.numbers),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN));else{let t=s.stateValues.maths.map((e=>{let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}));r.push(...t),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN))}let s=t.inverseNumericOperator({desiredValue:e.unnormalizedValue.evaluate_to_constant(),inputs:r,canBeModified:a,desiredMathValue:e.unnormalizedValue});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}if(t.inverseMathOperator){let r=[],a=[],i=[];for(let[e,s]of t.mathNumberChildren.entries())n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"number"})?(r.push(me$3.fromAst(s.stateValues.value)),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"math"})?(r.push(s.stateValues.value),a.push(s.stateValues.canBeModified),i.push(e)):n.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})?(r.push(...s.stateValues.numbers.map((e=>me$3.fromAst(e)))),a.push(...Array(s.stateValues.numbers.length).fill(s.stateValues.canBeModified)),1===s.stateValues.numbers.length?i.push(e):i.push(...Array(s.stateValues.numbers.length).fill(NaN))):(r.push(...s.stateValues.maths),a.push(...Array(s.stateValues.maths.length).fill(s.stateValues.canBeModified)),1===s.stateValues.maths.length?i.push(e):i.push(...Array(s.stateValues.maths.length).fill(NaN)));let s=t.inverseMathOperator({desiredValue:e.unnormalizedValue,inputs:r,canBeModified:a});if(s.success){let e=i[s.inputNumber];if(Number.isFinite(e)){let r=s.inputValue,a=0,i=t.mathNumberChildren[e];return n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"numberList"})?(a=2,r={0:r}):n.isInheritedComponentType({inheritedComponentType:i.componentType,baseComponentType:"mathList"})&&(a=1,r={0:r}),{success:!0,instructions:[{setDependency:"mathNumberChildren",desiredValue:r,childIndex:e,variableIndex:a}]}}return{success:!1}}return{success:!1}}return{success:!1}}},e.canBeModified={returnDependencies:()=>({modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},mathNumberChildren:{dependencyType:"child",childGroups:["maths","numbers"],variableNames:["canBeModified"]},mathNumberListChildren:{dependencyType:"child",childGroups:["mathLists","numberLists"],variableNames:["nComponents"]},isNumericOperator:{dependencyType:"stateVariable",variableName:"isNumericOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseNumericOperator:{dependencyType:"stateVariable",variableName:"inverseNumericOperator"}}),definition:function({dependencyValues:e}){let t=e.modifyIndirectly&&!e.fixed&&Boolean(e.isNumericOperator?e.inverseNumericOperator:e.inverseMathOperator);if(t&&e.mathNumberChildren.length+e.mathNumberListChildren.length>0){let n=e.mathNumberChildren.filter((e=>e.stateValues.canBeModified)).length+e.mathNumberListChildren.reduce(((e,t)=>e+t.stateValues.nComponents),0);1!==n&&(t=!1)}return{setValue:{canBeModified:t}}}},e}}class MathOperatorOneInput extends MathComponent{static componentType="_mathOperatorOneInput";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:e=>me.fromAst("_")}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:null}})},renameStateVariable({stateVariableDefinitions:e,oldName:"unnormalizedValue",newName:"unnormalizedValuePreOperator"}),e.unnormalizedValue={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"unnormalizedValuePreOperator"},mathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"inverseMathOperator"}}),definition:function({dependencyValues:e}){return{setValue:{unnormalizedValue:e.mathOperator(e.value)}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t,componentName:n}){if(t.inverseMathOperator){return{success:!0,instructions:[{setDependency:"value",desiredValue:t.inverseMathOperator(e.unnormalizedValue)}]}}return{success:!1}}},renameStateVariable({stateVariableDefinitions:e,oldName:"canBeModified",newName:"canBeModifiedPreOperator"}),e.canBeModified={returnDependencies:()=>({canBeModifiedPreOperator:{dependencyType:"stateVariable",variableName:"canBeModifiedPreOperator"},inverseMathOperator:{dependencyType:"stateVariable",variableName:"mathOperator"}}),definition:function({dependencyValues:e}){let t=e.canBeModifiedPreOperator;return e.inverseMathOperator||(t=!1),{setValue:{canBeModified:t}}}},e}}class Sum extends MathOperator{static componentType="sum";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e+t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t)))}}})},e}}class Product extends MathOperator{static componentType="product";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>e*t))}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.multiply(t)))}}})},e}}class ClampNumber extends MathOperatorOneInput{static componentType="clampNumber";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return clamp({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function clamp({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?me$3.fromAst(Math.max(t,Math.min(n,r))):me$3.fromAst(NaN)}class WrapNumberPeriodic extends MathOperatorOneInput{static componentType="wrapNumberPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.mathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e.inverseMathOperator={returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:({dependencyValues:e})=>({setValue:{inverseMathOperator:function(t){return makePeriodic({value:t,lowerValue:e.lowerValue,upperValue:e.upperValue})}}})},e}}function makePeriodic({value:e,lowerValue:t,upperValue:n}){let r=e;return r instanceof me$3.class&&(r=r.evaluate_to_constant()),Number.isFinite(r)?t===n?me$3.fromAst(t):(t>n&&([n,t]=[t,n]),me$3.fromAst(t+me$3.math.mod(r-t,n-t))):me$3.fromAst(NaN)}class Round extends MathOperatorOneInput{static componentType="round";static createAttributesObject(){let e=super.createAttributesObject();return e.numberDecimals={createComponentOfType:"number",createStateVariable:"numberDecimals",defaultValue:0,public:!0},e.numberDigits={createComponentOfType:"number",createStateVariable:"numberDigits",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({numberDecimals:{dependencyType:"stateVariable",variableName:"numberDecimals"},numberDigits:{dependencyType:"stateVariable",variableName:"numberDigits"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){let n=t.evaluate_numbers({max_digits:1/0,evaluate_functions:!0});return null!==e.numberDigits?n.round_numbers_to_precision(e.numberDigits):n.round_numbers_to_decimals(e.numberDecimals)}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class setSmallToZero extends MathOperatorOneInput{static componentType="setSmallToZero";static createAttributesObject(){let e=super.createAttributesObject();return e.threshold={createComponentOfType:"number",createStateVariable:"threshold",defaultValue:1e-14,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return t.evaluate_numbers({skip_ordering:!0,set_small_zero:e.threshold})}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class ConvertSetToList extends MathOperatorOneInput{static componentType="convertSetToList";static createAttributesObject(){let e=super.createAttributesObject();return delete e.unordered,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.unordered={returnDependencies:()=>({}),definition:()=>({setValue:{unordered:!0}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){if(void 0!==e&&Array.isArray(e.tree)&&"set"===e.tree[0]){let t=[];for(let n of e.tree.slice(1))t.some((t=>e.context.equalsViaSyntax(e.context.fromAst(t),e.context.fromAst(n))))||t.push(n);return e.context.fromAst(["list",...t])}return e}}})},e}}class Ceil extends MathOperatorOneInput{static componentType="ceil";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","ceil",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.ceil(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Floor extends MathOperatorOneInput{static componentType="floor";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();if(!Number.isFinite(t))return me$3.fromAst(["apply","floor",e.tree]);let n=Math.round(t);return Math.abs((n-t)/t)<1e-15?me$3.fromAst(n):me$3.fromAst(Math.floor(t))}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:e=>e}})},e}}class Abs extends MathOperatorOneInput{static componentType="abs";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.abs(t)):me$3.fromAst(["apply","abs",e.tree])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function(e){let t=e,n=e.evaluate_to_constant();return Number.isFinite(n)?n<0&&(t=me$3.fromAst(0)):Array.isArray(e.tree)&&"apply"===e.tree[0]&&"abs"===e.tree[1]&&(t=me$3.fromAst(e.tree[2])),t}}})},e}}class Sign extends MathOperatorOneInput{static componentType="sign";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){let t=e.evaluate_to_constant();return Number.isFinite(t)?me$3.fromAst(Math.sign(t)):me$3.fromAst(["apply","sign",e.tree])}}})},e}}class Mean extends MathOperator{static componentType="mean";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){let t=e.reduce(((e,t)=>e+t));return t/=e.length,t}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return e.reduce(((e,t)=>e.add(t))).divide(e.length)}}})},e}}class Variance extends MathOperator{static componentType="variance";static createAttributesObject(){let e=super.createAttributesObject();return e.population={createComponentOfType:"boolean",createStateVariable:"population",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{numericOperator:function(t){return calculateNumericVariance(t,e.population)}}})},e.mathOperator={returnDependencies:()=>({population:{dependencyType:"stateVariable",variableName:"population"}}),definition:({dependencyValues:e})=>({setValue:{mathOperator:function(t){return calculateSymbolicVariance(t,e.population)}}})},e}}function calculateNumericVariance(e,t){let n=0,r=0;for(let t of e)n+=t,r+=t*t;let a=e.length;return r-=n**2/a,r/=t?a:a-1,r}function calculateSymbolicVariance(e,t){let n=e.length,r=e.reduce(((e,t)=>e.add(t))),a=e.slice(1).reduce(((e,t)=>e.add(t.pow(2))),e[0].pow(2)).subtract(r.pow(2).divide(n));return a=t?a.divide(n):a.divide(n-1),a}class StandardDeviation extends Variance{static componentType="standardDeviation";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator.definition=({dependencyValues:e})=>({setValue:{numericOperator:function(t){return Math.sqrt(calculateNumericVariance(t,e.population))}}}),e.mathOperator.definition=({dependencyValues:e})=>({setValue:{mathOperator:function(t){return me$3.fromAst(["apply","sqrt",calculateSymbolicVariance(t,e.population).tree])}}}),e}}class Count extends MathOperator{static componentType="count";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.isNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{isNumericOperator:!0}})},e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.length}}})},e}}class Min extends MathOperator{static componentType="min";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.min(e,t)),1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","min",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Max extends MathOperator{static componentType="max";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.reduce(((e,t)=>Math.max(e,t)),-1/0)}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","max",["tuple",...e.map((e=>e.tree))]])}}})},e.inverseMathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseMathOperator:function({desiredValue:e,canBeModified:t}){if(1===t.filter((e=>e)).length){let n=t.indexOf(!0);if(n>=0)return{success:!0,inputValue:e,inputNumber:n}}return{success:!1}}}})},e.inverseNumericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{inverseNumericOperator:function({desiredValue:e,canBeModified:t,desiredMathValue:n}){if(1===t.filter((e=>e)).length){let r=t.indexOf(!0);if(r>=0)return Number.isFinite(e)||(e=n),{success:!0,inputValue:e,inputNumber:r}}return{success:!1}}}})},e}}class Mod extends MathOperator{static componentType="mod";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return 2!==e.length?NaN:me$3.math.mod(e[0],e[1])}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return 2!==e.length?me$3.fromAst("_"):me$3.fromAst(["apply","mod",["tuple",...e.map((e=>e.tree))]])}}})},e}}class Gcd extends MathOperator{static componentType="gcd";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numericOperator={returnDependencies:()=>({}),definition:()=>({setValue:{numericOperator:function(e){return e.every(Number.isInteger)?gcd(...e):NaN}}})},e.mathOperator={returnDependencies:()=>({}),definition:()=>({setValue:{mathOperator:function(e){return me$3.fromAst(["apply","gcd",["tuple",...e.map((e=>e.tree))]])}}})},e}}class ExtractMath extends MathOperatorOneInput{static componentType="extractMath";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createComponentOfType:"text",createStateVariable:"type",defaultValue:null,toLowerCase:!0,validValues:["operand","function","functionargument","numberofoperands"]},e.operandNumber={createComponentOfType:"number",createStateVariable:"operandNumber",defaultValue:null,public:!0},e.argumentNumber={createComponentOfType:"number",createStateVariable:"argumentNumber",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.mathOperator={returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},operandNumber:{dependencyType:"stateVariable",variableName:"operandNumber"},argumentNumber:{dependencyType:"stateVariable",variableName:"argumentNumber"}}),definition:({dependencyValues:e})=>"operand"===e.type?null===e.operandNumber?(console.warn("Must specify a operandNumber when extracting a math operand"),{setValue:{mathOperator:e=>me$3.fromAst("_")}}):{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return 1===e.operandNumber?t:me$3.fromAst("_");if("apply"===n[0])return 1===e.operandNumber?t:me$3.fromAst("_");let r=n[e.operandNumber];return void 0===r?me$3.fromAst("_"):me$3.fromAst(r)}}}:"function"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"!==t[0]?me$3.fromAst("_"):me$3.fromAst(t[1]):me$3.fromAst("_")}}}:"functionargument"===e.type?{setValue:{mathOperator:function(t){let n=t.tree;if(!Array.isArray(n))return me$3.fromAst("_");if("apply"!==n[0])return me$3.fromAst("_");let r=n[2];if(null===e.argumentNumber)return me$3.fromAst(r);if(1===e.argumentNumber)return Array.isArray(r)&&"tuple"===r[0]?me$3.fromAst(r[1]):me$3.fromAst(r);if(Array.isArray(r)&&"tuple"===r[0]){let t=r[e.argumentNumber];return void 0===t?me$3.fromAst("_"):me$3.fromAst(t)}return me$3.fromAst("_")}}}:"numberofoperands"===e.type?{setValue:{mathOperator:function(e){let t=e.tree;return Array.isArray(t)?"apply"===t[0]?me$3.fromAst(1):me$3.fromAst(t.length-1):me$3.fromAst(1)}}}:{setValue:{mathOperator:e=>me$3.fromAst("_")}}},e}}function gcd(e,t,...n){return!t&&n.length>0?gcd(e,...n):t?gcd(t,e%t,...n):e}var MathOperators=Object.freeze({__proto__:null,Sum:Sum,Product:Product,ClampNumber:ClampNumber,WrapNumberPeriodic:WrapNumberPeriodic,Round:Round,setSmallToZero:setSmallToZero,ConvertSetToList:ConvertSetToList,Ceil:Ceil,Floor:Floor,Abs:Abs,Sign:Sign,Mean:Mean,Variance:Variance,StandardDeviation:StandardDeviation,Count:Count,Min:Min,Max:Max,Mod:Mod,Gcd:Gcd,ExtractMath:ExtractMath});function returnLabelStateVariableDefinitions(){let e={};return e.componentNameAndShadowSourceNames={returnDependencies:()=>({shadowSource:{dependencyType:"shadowSource",variableNames:["componentNameAndShadowSourceNames"]},unlinkedCopySource:{dependencyType:"unlinkedCopySource",variableNames:["componentNameAndShadowSourceNames"]}}),definition({dependencyValues:e,componentName:t}){let n=[t];return e.shadowSource?.stateValues.componentNameAndShadowSourceNames?n.push(...e.shadowSource.stateValues.componentNameAndShadowSourceNames):e.unlinkedCopySource?.stateValues.componentNameAndShadowSourceNames&&n.push(...e.unlinkedCopySource.stateValues.componentNameAndShadowSourceNames),{setValue:{componentNameAndShadowSourceNames:n}}}},e.label={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"labelHasLatex"}}},hasEssential:!0,doNotShadowEssential:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,additionalStateVariablesDefined:[{variableName:"labelHasLatex",forRenderer:!0}],returnDependencies:()=>({labelChild:{dependencyType:"child",childGroups:["labels"],variableNames:["value","hasLatex"]},labelIsName:{dependencyType:"stateVariable",variableName:"labelIsName"},labelIsNameAttr:{dependencyType:"attributeComponent",attributeName:"labelIsName"},componentNameAndShadowSourceNames:{dependencyType:"stateVariable",variableName:"componentNameAndShadowSourceNames"},shadowSource:{dependencyType:"shadowSource",variableNames:["label","labelHasLatex"]}}),definition({dependencyValues:e,essentialValues:t}){let n=e.labelChild[e.labelChild.length-1];if(n&&!n.shadowDepth)return{setValue:{label:n.stateValues.value,labelHasLatex:n.stateValues.hasLatex}};if(void 0!==t.label)return{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}};if(e.labelIsName&&!e.labelIsNameAttr.shadowDepth){let t="__",n=e.componentNameAndShadowSourceNames;for(let e of n){let n=e.lastIndexOf("/");if(t=e.substring(n+1),"__"!==t.slice(0,2))break}return"__"===t.slice(0,2)?{setValue:{label:"",labelHasLatex:!1}}:("_"!==t[0]&&(t.includes("_")||t.includes("-")?t=t.replace(/[_\-]/g," "):t.match(/^[a-z]/)?t.match(/[A-Z]/)&&(t=t.replace(/([A-Z])/g," $1").toLowerCase()):t.match(/^[A-Z]/)&&t.match(/[a-z]/)&&(t=t.replace(/([A-Z])/g," $1"),t=t.slice(1))),{setValue:{label:t,labelHasLatex:!1}})}return"string"==typeof e.shadowSource?.stateValues.label?{setValue:{label:e.shadowSource.stateValues.label,labelHasLatex:Boolean(e.shadowSource.stateValues.labelHasLatex)}}:{useEssentialOrDefaultValue:{label:!0},setValue:{labelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.label)return{success:!1};let n=t.labelChild.length-1,r=t.labelChild[n];return r&&!r.shadowDepth?{success:!0,instructions:[{setDependency:"labelChild",desiredValue:e.label,childIndex:n,variableIndex:0}]}:t.labelIsName&&!t.labelIsNameAttr.shadowDepth?{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}:"string"==typeof t.shadowSource?.stateValues.label?{success:!0,instructions:[{setDependency:"shadowSource",desiredValue:e.label,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"label",value:e.label}]}}},e.labelForGraph={forRenderer:!0,returnDependencies:()=>({label:{dependencyType:"stateVariable",variableName:"label"},labelHasLatex:{dependencyType:"stateVariable",variableName:"labelHasLatex"}}),definition({dependencyValues:e}){let t;if(e.labelHasLatex){let n=0;t="";for(let r of e.label)"("===r?n++:")"===r?n--:0===n&&("_"===r?r="_":"^"===r&&(r="^")),t+=r}else t=e.label.replaceAll("_","_").replaceAll("^","^");return{setValue:{labelForGraph:t}}}},e}class GraphicalComponent extends BaseComponent{static componentType="_graphical";static createAttributesObject(){let e=super.createAttributesObject();return e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.layer={createComponentOfType:"integer",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnSelectedStyleStateVariableDefinition();Object.assign(e,t);let n=returnLabelStateVariableDefinitions();return Object.assign(e,n),e}}function returnNumericalFunctionFromFormula({formula:e,nInputs:t,variables:n,domain:r,component:a=0}){let i;if(a=Number(a),Array.isArray(e.tree)&&vectorOperators.includes(e.tree[0]))try{e=e.get_component(Number(a))}catch(e){return()=>NaN}else if(0!==a)return()=>NaN;try{i=e.subscripts_to_strings().f()}catch(e){return()=>NaN}if(1===t){let e=n[0].subscripts_to_strings().tree,t=-1/0,a=1/0,s=!1,o=!1;if(null!==r){let e=r[0];if(void 0!==e)try{t=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)?s=!e.tree[2][1]:t=-1/0,a=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(a)?o=!e.tree[2][2]:a=1/0}catch(e){}}return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=t)||!(n<=a)||s&&n===t||o&&n===a)return NaN;try{return i({[e]:n})}catch(e){return NaN}}}let s=[];for(let e=0;eme$3.fromAst("_")}else if("0"!==t)return e=>me$3.fromAst("_");let r=e.simplify,a=e.expand,i=n.subscripts_to_strings();if(1===e.nInputs){let t=e.variables[0].subscripts_to_strings().tree;return e=>normalizeMathExpression({value:i.substitute({[t]:e}).strings_to_subscripts(),simplify:r,expand:a})}let s=[];for(let t=0;tNaN;let l=e-1;t[0][o];let u,c,p=t[l][o],d=n.map((e=>e[o]));return i&&(u=s[o]),r&&(c=a[o]),function(e){if(isNaN(e))return NaN;if(e<0)return i?(u[2]*e+u[1])*e+u[0]:NaN;if(e>=l)return r?(e-=l,(c[2]*e+c[1])*e+c[0]):e===l?p:NaN;let t=Math.floor(e);e-=t;let n=d[t];return((n[3]*e+n[2])*e+n[1])*e+n[0]}}function returnInterpolatedFunction({xs:e,coeffs:t,interpolationPoints:n,domain:r}){let a=[];if(n&&(a=n.map((e=>e.y))),null===e)return e=>NaN;let i=-1/0,s=1/0,o=!1,l=!1;if(null!==r){let e=r[0];if(void 0!==e)try{i=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(i)?o=!e.tree[2][1]:i=-1/0,s=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(s)?l=!e.tree[2][2]:s=1/0}catch(e){}}let u=e[0],c=e[e.length-1];return function(n,r=!1){if(r){if(isNaN(n))return NaN}else if(!(n>=i)||!(n<=s)||o&&n===i||l&&n===s)return NaN;if(n<=u){n-=u;let e=t[0];return((e[3]*n+e[2])*n+e[1])*n+e[0]}if(n>=c){let r=e.length-2;n-=e[r];let a=t[r];return((a[3]*n+a[2])*n+a[1])*n+a[0]}for(var p,d=0,m=e.length-1;d<=m;){p=Math.floor(.5*(d+m));let t=e[p];if(tn))return a[p];m=p-1}}let h=Math.max(0,m);n-=e[h];let f=t[h];return((f[3]*n+f[2])*n+f[1])*n+f[0]}}function returnReturnDerivativesOfInterpolatedFunction({xs:e,coeffs:t,variables:n}){if(!e)return e=>NaN;let r=n[0].subscripts_to_strings().tree,a=e[0],i=e[e.length-1];return function(n){let s=n.map((e=>e.subscripts_to_strings().tree)),o=s.length;return o>3||!s.every((e=>e===r))||s.includes("_")?e=>0:0===o||null===e?e=>NaN:function(n){if(isNaN(n))return NaN;if(n<=a){n-=a;let e=t[0];return 1===o?(3*e[3]*n+2*e[2])*n+e[1]:2===o?6*e[3]*n+2*e[2]:6*e[3]}if(n>=i){let r=e.length-2;n-=e[r];let a=t[r];return 1===o?(3*a[3]*n+2*a[2])*n+a[1]:2===o?6*a[3]*n+2*a[2]:6*a[3]}for(var r,s=0,l=e.length-1;s<=l;){r=Math.floor(.5*(s+l));let a=e[r];if(an))return 1===o?t[r][1]:2===o?2*t[r][2]:6*t[r][3];l=r-1}}let u=Math.max(0,l);n-=e[u];let c=t[u];return 1===o?(3*c[3]*n+2*c[2])*n+c[1]:2===o?6*c[3]*n+2*c[2]:6*c[3]}}}var functionOperatorDefinitions={clampFunction:function(e,t){return function(n){return Number.isFinite(n)?Math.max(e,Math.min(t,n)):NaN}},wrapFunctionPeriodic:function(e,t){return function(n){if(!Number.isFinite(n))return NaN;let r=e,a=t;return r===a?r:(r>a&&([a,r]=[r,a]),r+me$3.math.mod(n-r,a-r))}},derivative:function(e,t){if("interpolatedFunction"===e.derivativeType){let n=returnReturnDerivativesOfInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,variables:e.variables.map(convertValueToMathExpression)}),r=t.map(convertValueToMathExpression);if(e.additionalDerivVariables){r=[...e.additionalDerivVariables.map(convertValueToMathExpression),...r]}if(e.variableMappings)for(let t of e.variableMappings){let e=[];for(let n of r){let r=t[n.subscripts_to_strings().tree];r?e.push(convertValueToMathExpression(r)):e.push(me$3.fromAst("_"))}r=e}return n(r)}return e=>NaN}};class Function$1 extends InlineComponent{static componentType="function";static rendererType="math";static primaryStateVariableForDefinition="numericalfShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.simplify={createComponentOfType:"text",createStateVariable:"simplifySpecified",defaultValue:"none",toLowerCase:!0,valueTransformations:{true:"full"},validValues:["none","full","numbers","numberspreserveorder"]},e.expand={createComponentOfType:"boolean",createStateVariable:"expandSpecified",defaultValue:!1,public:!0},e.xscale={createComponentOfType:"number",createStateVariable:"xscale",defaultValue:1,public:!0},e.yscale={createComponentOfType:"number",createStateVariable:"yscale",defaultValue:1,public:!0},e.nInputs={createComponentOfType:"integer"},e.nOutputs={createComponentOfType:"integer"},e.domain={createComponentOfType:"_intervalListComponent"},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showLabel={createComponentOfType:"boolean",createStateVariable:"showLabel",defaultValue:!0,public:!0,forRenderer:!0},e.applyStyleToLabel={createComponentOfType:"boolean",createStateVariable:"applyStyleToLabel",defaultValue:!1,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.layer={createComponentOfType:"number",createStateVariable:"layer",defaultValue:0,public:!0,forRenderer:!0},e.minima={createComponentOfType:"extrema"},e.maxima={createComponentOfType:"extrema"},e.extrema={createComponentOfType:"extrema"},e.through={createComponentOfType:"_pointListComponent"},e.throughSlopes={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.symbolic={createComponentOfType:"boolean"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurve",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[],i=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a=e.slice(0,t),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),i=e.slice(t))}return 1===r.length&&"string"!=typeof r[0]||0===r.length?{success:!1}:{success:!0,newChildren:[...a,{componentType:"math",children:r},...i]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]},{group:"functions",componentTypes:["function"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions({numerics:e}){let t=GraphicalComponent.returnStateVariableDefinitions();return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" function"}}}},t.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:10,hasEssential:!0,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDigits"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth0){let n=t.functionChild[0],r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;return n||r||(n=!0),n?{useEssentialOrDefaultValue:{displayDigits:{defaultValue:e.functionChild[0].stateValues.displayDigits}}}:{setValue:{displayDigits:e.functionChild[0].stateValues.displayDigits}}}return{useEssentialOrDefaultValue:{displayDigits:!0}}}},t.displayDecimals={public:!0,shadowingInstructions:{createComponentOfType:"integer"},defaultValue:null,hasEssential:!0,returnDependencies:()=>({displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displayDecimals"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displayDecimalsAttr?{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displayDecimals:e.functionChild[0].stateValues.displayDecimals}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}},t.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["displaySmallAsZero"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.displaySmallAsZeroAttr?{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{displaySmallAsZero:e.functionChild[0].stateValues.displaySmallAsZero}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}},t.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["padZeros"]}}),definition:({dependencyValues:e,usedDefault:t})=>null!==e.padZerosAttr?{setValue:{padZeros:e.padZerosAttr.stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0]?{setValue:{padZeros:e.functionChild[0].stateValues.padZeros}}:{useEssentialOrDefaultValue:{padZeros:!0}}},t.isInterpolatedFunction={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through"},minima:{dependencyType:"attributeComponent",attributeName:"minima"},maxima:{dependencyType:"attributeComponent",attributeName:"maxima"},extrema:{dependencyType:"attributeComponent",attributeName:"extrema"}}),definition:({dependencyValues:e})=>({setValue:{isInterpolatedFunction:e.through||e.minima||e.maxima||e.extrema}})},t.nInputs={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{nInputs:1}};if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}return null!==e.variablesAttr?{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}}:e.functionChild.length>0?{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}}:{setValue:{nInputs:1}}}},t.nOutputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({nOutputsAttr:{dependencyType:"attributeComponent",attributeName:"nOutputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nOutputs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition({dependencyValues:e}){if(e.functionChild.length>0)return{setValue:{nOutputs:e.functionChild[0].stateValues.nOutputs}};if(null!==e.nOutputsAttr){let t=e.nOutputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nOutputs:t}}}if(e.mathChild.length>0){let t=e.mathChild[0].stateValues.value,n=1;return Array.isArray(t.tree)&&vectorOperators.includes(t.tree[0])&&(n=t.tree.length-1),{setValue:{nOutputs:n}}}return{useEssentialOrDefaultValue:{nOutputs:!0}}}},t.domain={returnDependencies:()=>({domainAttr:{dependencyType:"attributeComponent",attributeName:"domain",variableNames:["intervals"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),definition({dependencyValues:e}){if(null!==e.domainAttr){let t=e.nInputs,n=e.domainAttr.stateValues.intervals.slice(0,t);return n.length!==t?{setValue:{domain:null}}:n.every((e=>Array.isArray(e.tree)&&"interval"===e.tree[0]))?{setValue:{domain:n}}:{setValue:{domain:null}}}return e.functionChild.length>0?{setValue:{domain:e.functionChild[0].stateValues.domain}}:{setValue:{domain:null}}}},t.simplify={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({simplifySpecified:{dependencyType:"stateVariable",variableName:"simplifySpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["simplify"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.simplifySpecified&&e.functionChild.length>0?{setValue:{simplify:e.functionChild[0].stateValues.simplify}}:{setValue:{simplify:e.simplifySpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.simplifySpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.simplify,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"simplifySpecified",desiredValue:e.simplify}]}},t.expand={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({expandSpecified:{dependencyType:"stateVariable",variableName:"expandSpecified"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["expand"]}}),definition:({dependencyValues:e,usedDefault:t})=>t.expandSpecified&&e.functionChild.length>0?{setValue:{expand:e.functionChild[0].stateValues.expand}}:{setValue:{expand:e.expandSpecified}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t,usedDefault:n})=>n.expandSpecified&&t.functionChild.length>0?{success:!0,instructions:[{setDependency:"functionChild",desiredValue:e.expand,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setDependency:"expandSpecified",desiredValue:e.expand}]}},t.numericalfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{numericalfShadow:!0}})},t.symbolicfShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{symbolicfShadow:!0}})},t.symbolic={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({symbolicAttr:{dependencyType:"attributeComponent",attributeName:"symbolic",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolic"]},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"}}),definition:({dependencyValues:e})=>null!==e.symbolicAttr?{setValue:{symbolic:e.symbolicAttr.stateValues.value}}:e.functionChild.length>0?{setValue:{symbolic:e.functionChild[0].stateValues.symbolic}}:e.numericalfShadow?{setValue:{symbolic:!1}}:e.symbolicfShadow?{setValue:{symbolic:!0}}:{useEssentialOrDefaultValue:{symbolic:!0}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(n)+1)]}};return{globalDependencies:{variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},functionChild:{dependencyType:"child",childGroups:["functions"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.functionChild.length>0){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.variable={isAlias:!0,targetVariableName:"variable1"},t.unnormalizedFormula={defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"}}),definition:function({dependencyValues:e,usedDefault:t}){return e.isInterpolatedFunction?{setValue:{unnormalizedFormula:me$3.fromAst("_")}}:e.mathChild.length>0?{setValue:{unnormalizedFormula:e.mathChild[0].stateValues.value}}:e.functionChild.length>0&&!t.functionChild[0].formula?{setValue:{unnormalizedFormula:e.functionChild[0].stateValues.formula}}:{useEssentialOrDefaultValue:{unnormalizedFormula:!0}}}},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},defaultValue:me$3.fromAst(0),hasEssential:!0,returnDependencies:()=>({unnormalizedFormula:{dependencyType:"stateVariable",variableName:"unnormalizedFormula"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"}}),definition:function({dependencyValues:e,usedDefault:t}){if(t.unnormalizedFormula)return{useEssentialOrDefaultValue:{formula:!0}};return{setValue:{formula:normalizeMathExpression({value:e.unnormalizedFormula,simplify:e.simplify,expand:e.expand})}}}},t.nPrescribedPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nPrescribedPoints:t}}}},t.prescribedPoints={isArray:!0,entryPrefixes:["prescribedPoint"],returnArraySizeDependencies:()=>({nPrescribedPoints:{dependencyType:"stateVariable",variableName:"nPrescribedPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nPrescribedPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["point"+e]},throughSlopes:{dependencyType:"attributeComponent",attributeName:"throughSlopes",variableNames:["math"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].through;if(null!==t){let a=Number(r)+1,i=t.stateValues["point"+a],s=null,o=e[r].throughSlopes;null!==o&&(s=o.stateValues["math"+a],void 0===s&&(s=null)),n[r]={x:i[0],y:i[1],slope:s}}}return{setValue:{prescribedPoints:n}}}},t.prescribedMinima={returnDependencies:()=>({minima:{dependencyType:"attributeComponent",attributeName:"minima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.minima&&(t=e.minima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMinima:t}}}},t.prescribedMaxima={returnDependencies:()=>({maxima:{dependencyType:"attributeComponent",attributeName:"maxima",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.maxima&&(t=e.maxima.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedMaxima:t}}}},t.prescribedExtrema={returnDependencies:()=>({extrema:{dependencyType:"attributeComponent",attributeName:"extrema",variableNames:["extrema"]}}),definition({dependencyValues:e}){let t=[];return null!==e.extrema&&(t=e.extrema.stateValues.extrema.map((e=>({x:e[0],y:e[1]})))),{setValue:{prescribedExtrema:t}}}},t.interpolationPoints={returnDependencies:()=>({xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"},prescribedPoints:{dependencyType:"stateVariable",variableName:"prescribedPoints"},prescribedMinima:{dependencyType:"stateVariable",variableName:"prescribedMinima"},prescribedMaxima:{dependencyType:"stateVariable",variableName:"prescribedMaxima"},prescribedExtrema:{dependencyType:"stateVariable",variableName:"prescribedExtrema"}}),definition:({dependencyValues:t})=>calculateInterpolationPoints({dependencyValues:t,numerics:e})},t.xs={additionalStateVariablesDefined:["coeffs"],returnDependencies:()=>({interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"}}),definition:computeSplineParamCoeffs},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)if("0"===r){let n=returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain});t[r]=function(e){me$3.fromAst(n(e.evaluate_to_constant()))}}else t[r]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.symbolicfs[r];return{setValue:{symbolicfs:t}}}if(e.symbolicfShadow){let t={};for(let r of n)t[r]="0"===r?e.symbolicfShadow:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?function(t){let n=t.evaluate_to_constant();return null===n?NaN:me$3.fromAst(e.numericalfShadow(n))}:e=>me$3.fromAst("_");return{setValue:{symbolicfs:t}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)t[r]=returnSymbolicFunctionFromFormula(e,r);return{setValue:{symbolicfs:t}}}}},t.symbolicf={isAlias:!0,targetVariableName:"symbolicf1"},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?returnInterpolatedFunction({xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}):e=>me$3.fromAst("_");return{setValue:{numericalfs:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.numericalfs[r];return{setValue:{numericalfs:t}}}if(e.numericalfShadow){let t={};for(let r of n)t[r]="0"===r?e.numericalfShadow:()=>NaN;return{setValue:{numericalfs:t}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]="0"===t?function(e){let t=dependencyValues.symbolicfShadow(me$3.fromAst(e)).evaluate_to_constant();return null===t&&(t=NaN),t}:()=>NaN;return{setValue:{numericalfs:e}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r});return{setValue:{numericalfs:t}}}}},t.numericalf={returnDependencies:()=>({numericalf1:{dependencyType:"stateVariable",variableName:"numericalf1"}}),definition:({dependencyValues:e})=>({setValue:{numericalf:e.numericalf1}})},t.fDefinitions={isArray:!0,entryPrefixes:["fDefinition"],stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:({stateValues:e})=>e.isInterpolatedFunction?{globalDependencies:{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},interpolationPoints:{dependencyType:"stateVariable",variableName:"interpolationPoints"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}:{globalDependencies:{formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinitions"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},symbolicfShadow:{dependencyType:"stateVariable",variableName:"symbolicfShadow"},numericalfShadow:{dependencyType:"stateVariable",variableName:"numericalfShadow"},domain:{dependencyType:"stateVariable",variableName:"domain"}}},arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n}){if(e.isInterpolatedFunction){let t={};for(let r of n)t[r]="0"===r?{functionType:"interpolated",xs:e.xs,coeffs:e.coeffs,interpolationPoints:e.interpolationPoints,domain:e.domain}:{};return{setValue:{fDefinitions:t}}}if(t.formula||"_"===e.formula.tree&&0!==e.functionChild.length){if(e.functionChild.length>0){let t={};for(let r of n)t[r]=e.functionChild[0].stateValues.fDefinitions[r];return{setValue:{fDefinitions:t}}}if(e.numericalfShadow){let e={};for(let t of n)e[t]={};return{setValue:{fDefinitions:e}}}if(e.symbolicfShadow){let e={};for(let t of n)e[t]={};return{setValue:{fDefinitions:e}}}{let t={};for(let r of n)t[r]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:r};return{setValue:{fDefinitions:t}}}}{let t={};for(let r of n)t[r]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:r};return{setValue:{fDefinitions:t}}}}},t.fDefinition={isAlias:!0,targetVariableName:"fDefinition1"},t.fs={isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={symbolicf:{dependencyType:"stateVariable",variableName:"symbolicf"+e},numericalf:{dependencyType:"stateVariable",variableName:"numericalf"+e}}}return{globalDependencies:{symbolic:{dependencyType:"stateVariable",variableName:"symbolic"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};if(e.symbolic)for(let e of n)r[e]=t[e].symbolicf;else for(let e of n)r[e]=t[e].numericalf;return{setValue:{fs:r}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({formula:{dependencyType:"stateVariable",variableName:"formula"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.formula,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},t.latexWithInputChildren={forRenderer:!0,returnDependencies:()=>({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},t.allMinima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMinima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMinima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]>0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)0){let t=-d[1]/(2*d[2]);if(t+n[e]>=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]+r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)0){let e=-d[1]/(2*d[2]);e+n[n.length-2]>=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]+t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMinima:t.functionChild[0].stateValues.allMinima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMinima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}),definition:({dependencyValues:e})=>({setValue:{numberMinima:e.allMinima.length},checkForActualChange:{numberMinima:!0}})},t.minima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"minimum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["minimum","minimumLocations","minimumLocation","minimumValues","minimumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["minimum","minimumLocation","minimumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"minimumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"minimumLocation"+(Number(t)+1):"minimumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("minima"===t){if(1===e.length)return"minimum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"minimumLocation"+t;if(2===e[1])return"minimumValue"+t}return null}}if("minimumLocations"===t)return"minimumLocation"+e[0];if("minimumValues"===t)return"minimumValue"+e[0];if("minimum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"minimumLocation"+n;if(2===e[0])return"minimumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMinima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMinima:{dependencyType:"stateVariable",variableName:"allMinima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},domain:{dependencyType:"stateVariable",variableName:"domain"}}:{numericalf:{dependencyType:"stateVariable",variableName:"numericalf"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["allMaxima"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},domain:{dependencyType:"stateVariable",variableName:"domain"}},definition:function({dependencyValues:t}){if(t.isInterpolatedFunction){let n=t.xs,r=t.coeffs,a=e.eps,i=[];if(null===n)return{setValue:{allMaxima:i}};let s=!1,o=-1/0,l=1/0,u=!1,c=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{o=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(o)?u=!e.tree[2][1]:o=-1/0,l=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][2]:l=1/0}catch(e){}}let p=1e-14*Math.max(Math.abs(o),Math.abs(l)),d=r[0],m=n[1]-n[0];if(0===d[3]){if(d[2]<0){let e=-d[1]/(2*d[2]);e+n[0]>=o-p&&e+n[0]<=l+p&&(e<=m-a?u&&Math.abs(e+n[0]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[0]>=o-p&&r+n[0]<=l+p&&(r<=m-a?u&&Math.abs(r+n[0]-o)=o-p){if(!(t+n[e]<=l+p)){s=!1;continue}Math.abs(t)=a&&t<=m-a&&(u&&Math.abs(t+n[e]-o)0){let r=Math.sqrt(t),h=(-2*d[2]-r)/(6*d[3]);if(h+n[e]>=o-p){if(!(h+n[e]<=l+p)){s=!1;continue}Math.abs(h)=a&&h<=m-a&&(u&&Math.abs(h+n[e]-o)=o-p&&e+n[n.length-2]<=l+p&&(Math.abs(e)=a&&(u&&Math.abs(e+n[n.length-2]-o)0){let t=Math.sqrt(e),r=(-2*d[2]-t)/(6*d[3]);r+n[n.length-2]>=o-p&&r+n[n.length-2]<=l+p&&(r>=a||Math.abs(r)0)return{setValue:{allMaxima:t.functionChild[0].stateValues.allMaxima}};if(1!==t.nInputs||1!==t.nOutputs)return{setValue:{allMaxima:[]}};let n,r,a=t.variables[0].subscripts_to_strings().tree,i=t.formula.subscripts_to_strings().derivative(a),s=!0;try{n=i.subscripts_to_strings().f()}catch(e){s=!1,r=()=>NaN}s&&(r=function(e){try{return n({[a]:e})}catch(e){return NaN}});let o=e=>-t.numericalf(e,!0),l=-100*t.xscale,u=100*t.xscale,c=!1,p=!1;if(null!==t.domain){let e=t.domain[0];if(void 0!==e)try{l=me$3.fromAst(e.tree[1][1]).evaluate_to_constant(),Number.isFinite(l)?c=!e.tree[2][1]:l=-100*t.xscale,u=me$3.fromAst(e.tree[1][2]).evaluate_to_constant(),Number.isFinite(u)?p=!e.tree[2][2]:u=100*t.xscale}catch(e){}}let d=1e3,m=(u-l)/d,h=1e-10*Math.max(Math.abs(l),Math.abs(u)),f=[],y=!1,g=!1,b=o(l-m),v=r(l-m);for(let t=-1;t0&&r(t+i)<0&&(N=!0,y=!1,!(t>=l-h&&t<=u+h)||c&&Math.abs(t-l)({allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition:({dependencyValues:e})=>({setValue:{numberMaxima:e.allMaxima.length},checkForActualChange:{numberMaxima:!0}})},t.maxima={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"maximum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["maximum","maximumLocations","maximumLocation","maximumValues","maximumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["maximum","maximumLocation","maximumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"maximumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"maximumLocation"+(Number(t)+1):"maximumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("maxima"===t){if(1===e.length)return"maximum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"maximumLocation"+t;if(2===e[1])return"maximumValue"+t}return null}}if("maximumLocations"===t)return"maximumLocation"+e[0];if("maximumValues"===t)return"maximumValue"+e[0];if("maximum"===t.slice(0,7)){let n=Number(t.slice(7));if(Number.isInteger(n)&&n>0){if(1===e[0])return"maximumLocation"+n;if(2===e[0])return"maximumValue"+n}}return null},returnArraySizeDependencies:()=>({numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),returnArraySize:({dependencyValues:e})=>[e.numberMaxima,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({numberMinima:{dependencyType:"stateVariable",variableName:"numberMinima"},numberMaxima:{dependencyType:"stateVariable",variableName:"numberMaxima"}}),definition:function({dependencyValues:e}){return{setValue:{numberExtrema:e.numberMinima+e.numberMaxima},checkForActualChange:{numberExtrema:!0}}}},t.allExtrema={returnDependencies:()=>({allMinima:{dependencyType:"stateVariable",variableName:"allMinima"},allMaxima:{dependencyType:"stateVariable",variableName:"allMaxima"}}),definition({dependencyValues:e}){let t=[...e.allMinima,...e.allMaxima].sort(((e,t)=>e[0]-t[0]));return{setValue:{allExtrema:t}}}},t.extrema={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"extremum"===e||void 0===e?[["point",{componentType:"mathList",isAttribute:"xs"}]]:[]},isArray:!0,nDimensions:2,entryPrefixes:["extremum","extremumLocations","extremumLocation","extremumValues","extremumValue"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if(["extremum","extremumLocation","extremumValue"].includes(e)){let r=Number(t)-1;return Number.isInteger(r)&&r>=0&&(!n||rt+",0")):["0,0"]:"extremumValues"===e?""!==t?[]:n?Array.from(Array(n[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[t,n]=e.split(",");return"0"===n?"extremumLocation"+(Number(t)+1):"extremumValue"+(Number(t)+1)},arrayVarNameFromPropIndex(e,t){if("extrema"===t){if(1===e.length)return"extremum"+e[0];{let t=Number(e[0]);if(Number.isInteger(t)&&t>0){if(1===e[1])return"extremumLocation"+t;if(2===e[1])return"extremumValue"+t}return null}}if("extremumLocations"===t)return"extremumLocation"+e[0];if("extremumValues"===t)return"extremumValue"+e[0];if("extremum"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0){if(1===e[0])return"extremumLocation"+n;if(2===e[0])return"extremumValue"+n}}return null},returnArraySizeDependencies:()=>({numberExtrema:{dependencyType:"stateVariable",variableName:"numberExtrema"}}),returnArraySize:({dependencyValues:e})=>[e.numberExtrema,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allExtrema:{dependencyType:"stateVariable",variableName:"allExtrema"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;ne.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{returnNumericalDerivatives:returnReturnDerivativesOfInterpolatedFunction(e)}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.returnNumericalDerivatives){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{returnNumericalDerivatives:e.functionChild[0].stateValues.returnNumericalDerivatives}};return{setValue:{returnNumericalDerivatives:function(t){let n=[];for(let e of t){let t=a[e.subscripts_to_strings().tree];t?n.push(t):n.push(me$3.fromAst("_"))}return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}return{setValue:{returnNumericalDerivatives:null}}}},t.numericalDerivativesDefinition={stateVariablesDeterminingDependencies:["isInterpolatedFunction"],returnDependencies:({stateValues:e})=>e.isInterpolatedFunction?{xs:{dependencyType:"stateVariable",variableName:"xs"},coeffs:{dependencyType:"stateVariable",variableName:"coeffs"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}}:{functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition","variables"]},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},variables:{dependencyType:"stateVariable",variableName:"variables"}},definition:function({dependencyValues:e}){if(e.isInterpolatedFunction)return{setValue:{numericalDerivativesDefinition:{derivativeType:"interpolatedFunction",xs:e.xs,coeffs:e.coeffs,variables:e.variables}}};if(e.functionChild.length>0&&e.functionChild[0].stateValues.numericalDerivativesDefinition){let t=e.variables.map((e=>e.subscripts_to_strings().tree)),n=e.functionChild[0].stateValues.variables,r=n.map((e=>e.subscripts_to_strings().tree)),a={};for(let[e,i]of t.entries())r[e]&&r[e]!==i&&(a[i]=n[e]);if(0===Object.keys(a).length)return{setValue:{numericalDerivativesDefinition:e.functionChild[0].stateValues.numericalDerivativesDefinition}};{let t={...e.functionChild[0].stateValues.numericalDerivativesDefinition};return t.variableMappings?t.variableMappings=[a,...t.variableMappings]:t.variableMappings=[a],{setValue:{numericalDerivativesDefinition:t}}}}return{setValue:{numericalDerivativesDefinition:{}}}}},t}static adapters=[{stateVariable:"numericalf",componentType:"curve",stateVariablesToShadow:["label","labelHasLatex"]},{stateVariable:"formula",componentType:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}]}function calculateInterpolationPoints({dependencyValues:e,numerics:t}){let n=[],r=[],a={maximum:e.prescribedMaxima,minimum:e.prescribedMinima,extremum:e.prescribedExtrema,point:e.prescribedPoints};for(let e in a)for(let t of a[e]){let a=null,i=null,s=null;if(null===t.x||(a=t.x.evaluate_to_constant(),Number.isFinite(a)))if(null===t.y||(i=t.y.evaluate_to_constant(),Number.isFinite(i)))if(null!==t.slope&&void 0!==t.slope&&(s=t.slope.evaluate_to_constant(),Number.isFinite(s)||(console.warn("Ignoring non-numerical slope"),s=null)),null===a){if(null===i){console.warn(`Ignoring empty ${e}`);continue}r.push({type:e,y:i,slope:s})}else n.push({type:e,x:a,y:i,slope:s});else console.warn(`Ignoring non-numerical ${e}`);else console.warn(`Ignoring non-numerical ${e}`)}n.sort(((e,t)=>e.x-t.x)),r.sort(((e,t)=>e.y-t.y));let i=-1/0,s=t.eps;for(let e=0;e0;){let e,t;void 0===l?e=v({allowedTypes:["maximum","minimum","extremum"],comparison:"atLeast",value:-1/0}):"maximum"===l?e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}):"minimum"===l?e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}):"point"===l&&(e=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:o+c}),!0!==e.success&&(e=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:o-c}))),!0===e.success?(t=e.point,r.splice(e.ind,1),m?(t.x=0,m=!1):t.x=i+u):(t=r.pop(),m?(t.x=0,m=!1):t.x=i+2*u);let n=y({p:t,typePrev:l,xPrev:i,yPrev:o});l=n.type,i=n.x,o=n.y}if(0===p.length&&p.push({type:"point",x:0,y:0,slope:0}),m=p[0],"maximum"===m.type){let e={type:"point",x:m.x-u,y:m.y-c,slope:2*c/u};p.splice(0,0,e)}else if("minimum"===m.type){let e={type:"point",x:m.x-u,y:m.y+c,slope:-2*c/u};p.splice(0,0,e)}else if("point"===m.type)if(1===p.length)null===m.slope&&(m.slope=0);else{let e=p[1],t=(e.y-m.y)/(e.x-m.x);if("maximum"===e.type||"minimum"===e.type)null===m.slope&&(m.slope=2*t);else{2===p.length?null===m.slope&&(m.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:m,nextPoint:p[2]})),null===m.slope&&(m.slope=2*(m.y-e.y)/(m.x-e.x)-e.slope));let n={x:m.x-u,y:m.y-u*m.slope,slope:m.slope};p.splice(0,0,n)}}let h=p[p.length-1];if("maximum"===h.type){let e={type:"point",x:h.x+u,y:h.y-c,slope:-2*c/u};p.push(e)}else if("minimum"===h.type){let e={type:"point",x:h.x+u,y:h.y+c,slope:2*c/u};p.push(e)}else if("point"===h.type)if(1===p.length){let e={type:"point",x:h.x+u,y:h.y+m.slope*u,slope:m.slope};p.push(e)}else{let e=p[p.length-2],t=(e.y-h.y)/(e.x-h.x);if("maximum"===e.type||"minimum"===e.type)null===h.slope&&(h.slope=2*t);else{2===p.length?null===h.slope&&(h.slope=t):(null===e.slope&&(e.slope=f({point:e,prevPoint:p[p.length-3],nextPoint:h})),null===h.slope&&(h.slope=2*(e.y-h.y)/(e.x-h.x)-e.slope));let n={x:h.x+u,y:h.y+u*h.slope,slope:h.slope};p.push(n)}}for(let e=1;ei-c||void 0!==r&&null!==e.y&&e.y>t.y-c?g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("minimum"===n||"minimum"===r)return null!==e.y&&e.yt.y+c?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t});if("point"===n||"point"===r){let o="maximum";return(null===e.y&&void 0!==t&&t.type===maximum||null!==e.y&&e.y<=i-c||void 0!==r&&null!==e.y&&e.y>=t.y-c)&&(o="minimum"),"minimum"===o?b({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t}):g({x:e.x,y:e.y,typePrev:n,xPrev:a,yPrev:i,yNext:s,pNext:t})}return null!==e.y&&e.ys-c){let n,a,o=(e+i)/2,l=null,u=v({allowedTypes:["minimum","extremum"],comparison:"atMost",value:Math.min(s,t)-c});!0===u.success?(a="minimum",n=u.point.y,r.splice(u.ind,1),l=0):(a="point",n=s-c),p.push({type:a,x:o,y:n,slope:l})}}else if("minimum"===a&&ti-c){let n=[(2*a+e)/3,(a+2*e)/3],s=[i-c,t+c],o=["atMost","atLeast"],l=[["minimum","extremum"],["maximum","extremum"]];for(let e=0;e<2;e++){let t,a,i=n[e],u=null,c=v({allowedTypes:l[e],comparison:o[e],value:s[e]});!0===c.success?(a=l[e][0],t=c.point.y,r.splice(c.ind,1),u=0):(a="point",t=s[e],u=null),p.push({type:a,x:i,y:t,slope:u})}}}else if("minimum"===n){null===t&&(t=void 0===s?i:"minimum"===o.type?Math.min(i,s):Math.min(i,s-c));let n,l,u=Math.max(i,t)+c,d=(e+a)/2,m=null,h=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:u});!0===h.success?(l="maximum",n=h.point.y,r.splice(h.ind,1),m=0):(l="point",n=u),p.push({type:l,x:d,y:n,slope:m})}else if("point"===n)if(null===t)t=void 0===s?i-c:"minimum"===o.type?Math.min(i-c,s):Math.min(i,s)-c;else if(t>i-c){let n,i,s=(e+a)/2,o=null,l=v({allowedTypes:["maximum","extremum"],comparison:"atLeast",value:t+c});!0===l.success?(i="maximum",n=l.point.y,r.splice(l.ind,1),o=0):(i="point",n=t+c),p.push({type:i,x:s,y:n,slope:o})}let l={type:"minimum",x:e,y:t,slope:0};return p.push(l),l}function v({allowedTypes:e,comparison:t,value:n}){let a=[];if("atMost"===t)a=Object.keys(r).reverse();else{if("atLeast"!==t)return{success:!1};a=Object.keys(r)}for(let i of e)for(let e of a){let a=r[e];if(a.type===i)if("atMost"===t){if(a.y<=n)return{success:!0,ind:e,point:a}}else if(a.y>=n)return{success:!0,ind:e,point:a}}return{success:!1}}}function computeSplineParamCoeffs({dependencyValues:e}){let t=e.interpolationPoints;if(null===t)return{setValue:{xs:null,coeffs:null}};let n,r=[],a=[],i=t[0];a.push(i.x);for(let e=1;et.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}return 0===a.length||1===a.length&&"string"!=typeof a[0]?{success:!1}:{success:!0,newChildren:[...i,{componentType:"math",children:a},...s]}}}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this.componentType;t.isInterpolatedFunction={returnDependencies:()=>({}),definition:()=>({setValue:{isInterpolatedFunction:!1}})},delete t.nPrescribedPoints,delete t.prescribedPoints,delete t.prescribedMinima,delete t.prescribedMaxima,delete t.prescribedExtrema,delete t.interpolationPoints,delete t.xs,t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!1}})},t.formula.returnDependencies=()=>({}),t.formula.definition=()=>({setValue:{formula:me$3.fromAst("_")}}),t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!0}})},t.symbolicFunctionOperator={returnDependencies:()=>({}),definition:()=>({setValue:{symbolicFunctionOperator:e=>me$3.fromAst("_")}})},t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperator:e=>NaN,numericalFunctionOperatorArguments:[]}})},t.numericalFunctionOperatorArguments={returnDependencies:()=>({}),definition:()=>({setValue:{numericalFunctionOperatorArguments:{}}})},t.formulaOperator={returnDependencies:()=>({}),definition:()=>({setValue:{formulaOperator:e=>me$3.fromAst("_")}})},t.returnNumericalDerivatives={returnDependencies:()=>({}),definition:()=>({setValue:{returnNumericalDerivatives:null}})},t.formula={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalStateVariablesDefined:["operatorBasedOnFormula"],returnDependencies:()=>({operatorBasedOnFormulaIfAvailable:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormulaIfAvailable"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["formula"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},formulaOperator:{dependencyType:"stateVariable",variableName:"formulaOperator"}}),definition:function({dependencyValues:e}){if(!e.operatorBasedOnFormulaIfAvailable||(0===e.functionChild.length||"_"===e.functionChild[0].stateValues.formula.tree)&&(0===e.mathChild.length||"_"===e.mathChild[0].stateValues.value.tree))return{setValue:{formula:me$3.fromAst("_"),operatorBasedOnFormula:!1}};let t;return t=0===e.functionChild.length?e.mathChild[0].stateValues.value:e.functionChild[0].stateValues.formula,{setValue:{formula:e.formulaOperator(t),operatorBasedOnFormula:!0}}}},t.symbolicfs={isArray:!0,entryPrefixes:["symbolicf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},simplify:{dependencyType:"stateVariable",variableName:"simplify"},expand:{dependencyType:"stateVariable",variableName:"expand"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["symbolicfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},symbolicFunctionOperator:{dependencyType:"stateVariable",variableName:"symbolicFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>me$3.fromAst("_");return{setValue:{symbolicfs:e}}}{let t=Object.assign({},e);t.formula=e.mathChild[0].stateValues.value;let a=[];for(let e=0;ee.symbolicFunctionOperator(...a.map((e=>e(...t))));return{setValue:{symbolicfs:i}}}}{let t=[];for(let n=0;ne.symbolicFunctionOperator(...t.map((e=>e(...n))));return{setValue:{symbolicfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.symbolicFunctionOperator(...t);return{setValue:{symbolicfs:t}}}}{let t={};for(let r of n)return t[r]=returnSymbolicFunctionFromFormula(e,r),{setValue:{symbolicfs:t}}}}},t.numericalfs={isArray:!0,entryPrefixes:["numericalf"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalfs"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:n,arraySize:r}){if(!e.operatorBasedOnFormula){if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let e={};for(let t of n)e[t]=e=>NaN;return{setValue:{numericalfs:e}}}{Object.assign({},e).formula=e.mathChild[0].stateValues.value;let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t=[];for(let n=0;ne.numericalFunctionOperator(...t.map((e=>e(...n))));return{setValue:{numericalfs:a}}}}{let t={};for(let r of n)t[r]=(...t)=>e.numericalFunctionOperator(...t);return{setValue:{numericalfs:t}}}}{let t={};for(let r of n)return t[r]=returnNumericalFunctionFromFormula({formula:e.formula,nInputs:e.nInputs,variables:e.variables,domain:e.domain,component:r}),{setValue:{numericalfs:t}}}}},t.fDefinitions={isArray:!0,entryPrefixes:["fDefinition"],returnArraySizeDependencies:()=>({nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"}}),returnArraySize:({dependencyValues:e})=>[e.nOutputs],returnArrayDependenciesByKey:()=>({globalDependencies:{operatorBasedOnFormula:{dependencyType:"stateVariable",variableName:"operatorBasedOnFormula"},formula:{dependencyType:"stateVariable",variableName:"formula"},variables:{dependencyType:"stateVariable",variableName:"variables"},nInputs:{dependencyType:"stateVariable",variableName:"nInputs"},nOutputs:{dependencyType:"stateVariable",variableName:"nOutputs"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["fDefinitions"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"},numericalFunctionOperatorArguments:{dependencyType:"stateVariable",variableName:"numericalFunctionOperatorArguments"},operatorComposesWithOriginal:{dependencyType:"stateVariable",variableName:"operatorComposesWithOriginal"},domain:{dependencyType:"stateVariable",variableName:"domain"}}}),arrayDefinitionByKey:function({globalDependencyValues:e,usedDefault:t,arrayKeys:r,arraySize:a}){if(e.operatorBasedOnFormula){let t={};for(let n of r)t[n]={functionType:"formula",formula:e.formula.tree,variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain,component:n};return{setValue:{fDefinitions:t}}}if(e.operatorComposesWithOriginal){if(0===e.functionChild.length){if(0===e.mathChild.length){let t={};for(let n of r)t[n]={functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain};return{setValue:{fDefinitions:t}}}throw Error("function operator with math child not implemented yet")}{let t={};for(let a of r)t[a]={functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!0,originalFDefinition:e.functionChild[0].stateValues.fDefinitions[a]};return{setValue:{fDefinitions:t}}}}if(0===e.functionChild.length){if(0===e.mathChild.length){let t={};for(let n of r)t[n]={functionType:"formula",formula:"_",variables:e.variables.map((e=>e.tree)),nInputs:e.nInputs,nOutputs:e.nOutputs,domain:e.domain};return{setValue:{fDefinitions:t}}}throw Error("function operator with math child not implemented yet")}{let t={};for(let a of r)t[a]={functionType:"functionOperator",componentType:n,nOutputs:e.nOutputs,functionOperatorArguments:e.numericalFunctionOperatorArguments,operatorComposesWithOriginal:!1,originalFDefinition:e.functionChild[0].stateValues.fDefinitions[a]};return{setValue:{fDefinitions:t}}}}};let r=t.allMinima.returnDependencies;t.allMinima.returnDependencies=function(e){let t=r(e);return delete t.functionChild,t};let a=t.allMaxima.returnDependencies;return t.allMaxima.returnDependencies=function(e){let t=a(e);return delete t.functionChild,t},t}}class ClampFunction extends FunctionOperator{static componentType="clampFunction";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.clampFunction(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class WrapFunctionPeriodic extends FunctionOperator{static componentType="wrapFunctionPeriodic";static createAttributesObject(){let e=super.createAttributesObject();return e.lowerValue={createComponentOfType:"number",createStateVariable:"lowerValue",defaultValue:0,public:!0},e.upperValue={createComponentOfType:"number",createStateVariable:"upperValue",defaultValue:1,public:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.numericalFunctionOperator={additionalStateVariablesDefined:["numericalFunctionOperatorArguments"],returnDependencies:()=>({lowerValue:{dependencyType:"stateVariable",variableName:"lowerValue"},upperValue:{dependencyType:"stateVariable",variableName:"upperValue"}}),definition:function({dependencyValues:e}){return{setValue:{numericalFunctionOperator:functionOperatorDefinitions.wrapFunctionPeriodic(e.lowerValue,e.upperValue),numericalFunctionOperatorArguments:[e.lowerValue,e.upperValue]}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}class Derivative extends FunctionOperator{static componentType="derivative";static createAttributesObject(){let e=super.createAttributesObject();return e.derivVariables={createComponentOfType:"variables"},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.operatorBasedOnFormulaIfAvailable={returnDependencies:()=>({}),definition:()=>({setValue:{operatorBasedOnFormulaIfAvailable:!0}})},t.operatorComposesWithOriginal={returnDependencies:()=>({}),definition:()=>({setValue:{operatorComposesWithOriginal:!1}})},t.haveFunctionChild={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"]}}),definition:({dependencyValues:e})=>({setValue:{haveFunctionChild:e.functionChild.length>0}})},t.nInputs={defaultValue:1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},stateVariablesDeterminingDependencies:["haveFunctionChild"],returnDependencies({stateValues:e}){let t={nInputsAttr:{dependencyType:"attributeComponent",attributeName:"nInputs",variableNames:["value"]},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nInputs"]},variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["nComponents"]}};return e.haveFunctionChild||(t.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]}),t},definition({dependencyValues:e}){if(null!==e.nInputsAttr){let t=e.nInputsAttr.stateValues.value;return t>=0||(t=1),{setValue:{nInputs:t}}}if(null!==e.variablesAttr)return{setValue:{nInputs:Math.max(1,e.variablesAttr.stateValues.nComponents)}};if(e.functionChild.length>0)return{setValue:{nInputs:e.functionChild[0].stateValues.nInputs}};if(null!==e.derivVariablesAttr){let t=[...new Set(e.derivVariablesAttr.stateValues.variables.map((e=>e.subscripts_to_strings().tree)))].length;return{setValue:{nInputs:t}}}return{useEssentialOrDefaultValue:{nInputs:!0}}}},t.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["variable"],returnArraySizeDependencies:()=>({nInputs:{dependencyType:"stateVariable",variableName:"nInputs"}}),returnArraySize:({dependencyValues:e})=>[e.nInputs],stateVariablesDeterminingDependencies:["haveFunctionChild"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={variablesAttr:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]},parentVariableForChild:{dependencyType:"parentStateVariable",variableName:"variableForChild"},isInterpolatedFunction:{dependencyType:"stateVariable",variableName:"isInterpolatedFunction"},haveFunctionChild:{dependencyType:"stateVariable",variableName:"haveFunctionChild"}},r={};if(t.haveFunctionChild)for(let t of e)r[t]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["variable"+(Number(t)+1)]}};else n.derivVariablesAttr={dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]};return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arraySize:n,arrayKeys:r,usedDefault:a}){if(null!==e.variablesAttr){let t=e.variablesAttr.stateValues.variables;return{setValue:{variables:returnNVariables(n[0],t)}}}if(e.haveFunctionChild){let e={};for(let n of r)e[n]=t[n].functionChild[0].stateValues["variable"+(Number(n)+1)];return{setValue:{variables:e}}}if(null!==e.derivVariablesAttr){let t=[],r=[];for(let n of e.derivVariablesAttr.stateValues.variables){let e=n.subscripts_to_strings().tree;r.includes(e)||(t.push(n),r.push(e))}return{setValue:{variables:returnNVariables(n[0],t)}}}return e.parentVariableForChild&&!a.parentVariableForChild?{setValue:{variables:Array(n[0]).fill(e.parentVariableForChild)}}:{setValue:{variables:returnNVariables(n[0],[])}}}},t.nDerivatives={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["nComponents"]}}),definition:({dependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{nDerivatives:e.derivVariablesAttr.stateValues.nComponents}}:{setValue:{nDerivatives:1}}},t.derivVariables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["derivVariable"],returnArraySizeDependencies:()=>({nDerivatives:{dependencyType:"stateVariable",variableName:"nDerivatives"}}),returnArraySize:({dependencyValues:e})=>[e.nDerivatives],returnArrayDependenciesByKey:()=>({globalDependencies:{derivVariablesAttr:{dependencyType:"attributeComponent",attributeName:"derivVariables",variableNames:["variables"]},variable1:{dependencyType:"stateVariable",variableName:"variable1"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>null!==e.derivVariablesAttr?{setValue:{derivVariables:e.derivVariablesAttr.stateValues.variables}}:{setValue:{derivVariables:{0:e.variable1}}}},t.formulaOperator={returnDependencies:()=>({derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),definition:({dependencyValues:e})=>({setValue:{formulaOperator:function(t){let n=t.subscripts_to_strings();for(let t of e.derivVariables)n=n.derivative(t.subscripts_to_strings().tree);return n.strings_to_subscripts()}}})},t.numericalFunctionOperator={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["returnNumericalDerivatives"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["returnNumericalDerivatives"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.returnNumericalDerivatives)return{setValue:{numericalFunctionOperator:e=>NaN,returnNumericalDerivatives:null}};return{setValue:{numericalFunctionOperator:e.functionChild[0].stateValues.returnNumericalDerivatives(e.derivVariables),returnNumericalDerivatives:function(t){let n=[...e.derivVariables,...t];return e.functionChild[0].stateValues.returnNumericalDerivatives(n)}}}}},t.numericalFunctionOperatorArguments={returnDependencies:()=>({functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalDerivativesDefinition"],variablesOptional:!0},derivVariables:{dependencyType:"stateVariable",variableName:"derivVariables"}}),additionalStateVariablesDefined:["numericalDerivativesDefinition"],definition:function({dependencyValues:e}){if(0===e.functionChild.length||!e.functionChild[0].stateValues.numericalDerivativesDefinition)return{setValue:{numericalFunctionOperatorArguments:[],numericalDerivativesDefinition:{}}};let t=e.functionChild[0].stateValues.numericalDerivativesDefinition,n={...t};return n.additionalDerivVariables?n.additionalDerivVariables=[...e.derivVariables,...n.additionalDerivVariables]:n.additionalDerivVariables=[...e.derivVariables],{setValue:{numericalFunctionOperatorArguments:[t,e.derivVariables],numericalDerivativesDefinition:n}}}},t.symbolicFunctionOperator={returnDependencies:()=>({numericalFunctionOperator:{dependencyType:"stateVariable",variableName:"numericalFunctionOperator"}}),definition:({dependencyValues:e})=>({setValue:{symbolicFunctionOperator:t=>me$3.fromAst(e.numericalFunctionOperator(t.evaluate_to_constant()))}})},t}}var FunctionOperators=Object.freeze({__proto__:null,ClampFunction:ClampFunction,WrapFunctionPeriodic:WrapFunctionPeriodic,Derivative:Derivative});class TextBaseOperatorOfMath extends Text{static componentType="_textOperatorOfMath";static rendererType="text";static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({mathChildren:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]}}),definition:function({dependencyValues:e}){return{setValue:{value:t.applyTextOperator(e.mathChildren.map((e=>e.stateValues.value)))}}}},e}}class ExtractMathOperator extends TextBaseOperatorOfMath{static componentType="extractMathOperator";static applyTextOperator(e){return 0===e.length?"":1!==e.length?(console.warn("MathOperator requires exactly one math child"),""):Array.isArray(e[0].tree)?e[0].tree[0]:""}}var TextOperatorsOfMath=Object.freeze({__proto__:null,ExtractMathOperator:ExtractMathOperator});class Extremum extends BaseComponent{static componentType="extremum";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.location={createComponentOfType:"math"},e.value={createComponentOfType:"math"},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/s+(.*s)?/,replacementFunction:function({matchedChildren:e}){let t=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),n=t({matchedChildren:e});if(!n.success&&1===e.length)return{success:!0,newAttributes:{value:{component:{componentType:"math",children:e}}}};if(n.success){if(1===n.newChildren.length)return{success:!0,newAttributes:{value:{component:n.newChildren[0]}}};if(2===n.newChildren.length){let e=n.newChildren[0],t=n.newChildren[1],r={location:{component:e},value:{component:t}};return(0===e.children.length||1===e.children.length&&"string"==typeof e.children[0]&&""===e.children[0].trim())&&delete r.location,(0===t.children.length||1===t.children.length&&"string"==typeof t.children[0]&&""===t.children[0].trim())&&delete r.value,{success:!0,newAttributes:r}}return{success:!1}}return n}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e}),n=this;return t.value={public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"location",public:!0,shadowingInstructions:{createComponentOfType:"math"},defaultValue:null,hasEssential:!0}],returnDependencies:()=>({extremumChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions","xs"]},location:{dependencyType:"attributeComponent",attributeName:"location",variableNames:["value"]},value:{dependencyType:"attributeComponent",attributeName:"value",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t,r;if(e.extremumChild.length>0){let a=e.extremumChild[0];2!==a.stateValues.nDimensions?(console.log("Cannot determine "+n.componentType+" from a point that isn't 2D"),t=null,r=null):(t=a.stateValues.xs[0],r=a.stateValues.xs[1])}else null!==e.location&&(t=e.location.stateValues.value),null!==e.value&&(r=e.value.stateValues.value);let a={},i={},s=!1,o=!1;void 0===t?(i.location=!0,o=!0):(a.location=t,s=!0),void 0===r?(i.value=!0,o=!0):(a.value=r,s=!0);let l={};return s&&(l.setValue=a),o&&(l.useEssentialOrDefaultValue=i),l}},t}}class Extrema extends BaseComponent{static componentType="extrema";static rendererType=void 0;static componentTypeSingular="extremum";static get componentTypeCapitalized(){return this.componentType.charAt(0).toUpperCase()+this.componentType.slice(1)}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=this;return e.push({replacementFunction:function({matchedChildren:e}){let n=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==n.success?{success:!1}:{success:!0,newChildren:n.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:t.componentTypeSingular,children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"extrema",componentTypes:[this.componentTypeSingular]},{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e["n"+t.componentTypeCapitalized]={additionalStateVariablesDefined:["childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["extrema","points"]}}),definition:function({dependencyValues:e}){return{setValue:{["n"+t.componentTypeCapitalized]:e.children.length,childIdentities:e.children}}}},e[t.componentType]={isArray:!0,nDimensions:2,entryPrefixes:[t.componentTypeSingular,t.componentTypeSingular+"Locations",t.componentTypeSingular+"Location",t.componentTypeSingular+"Values",t.componentTypeSingular+"Value"],stateVariablesDeterminingDependencies:["childIdentities"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:n,arraySize:r}){if([t.componentTypeSingular,t.componentTypeSingular+"Location",t.componentTypeSingular+"Value"].includes(e)){let a=Number(n)-1;return Number.isInteger(a)&&a>=0&&(!r||at+",0")):["0,0"]:e===t.componentTypeSingular+"Values"?""!==n?[]:r?Array.from(Array(r[0]),((e,t)=>t+",1")):["0,1"]:[]},arrayVarNameFromArrayKey(e){let[n,r]=e.split(",");return"0"===r?t.componentTypeSingular+"Location"+(Number(n)+1):t.componentTypeSingular+"Value"+(Number(n)+1)},arrayVarNameFromPropIndex(e,n){if(n===t.componentType){if(1===e.length)return t.componentTypeSingular+e[0];{let n=Number(e[0]);if(Number.isInteger(n)&&n>0){if(1===e[1])return t.componentTypeSingular+"Location"+n;if(2===e[1])return t.componentTypeSingular+"Value"+n}return null}}if(n===t.componentTypeSingular+"Locations")return t.componentTypeSingular+"Location"+e[0];if(n===t.componentTypeSingular+"Values")return t.componentTypeSingular+"Value"+e[0];let r=t.componentTypeSingular.length;if(n.slice(0,r)===t.componentTypeSingular){let a=Number(n.slice(r));if(Number.isInteger(a)&&a>0){if(1===e[0])return t.componentTypeSingular+"Location"+a;if(2===e[0])return t.componentTypeSingular+"Value"+a}}return null},returnArraySizeDependencies:()=>({nChildren:{dependencyType:"stateVariable",variableName:"n"+t.componentTypeCapitalized}}),returnArraySize:({dependencyValues:e})=>[e.nChildren,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:n}){let r={};for(let a of e){let e,[i,s]=a.split(",");e=n.childIdentities[i].componentType===t.componentTypeSingular?0===Number(s)?"location":"value":"x"+(Number(s)+1),r[a]={child:{dependencyType:"child",childGroups:["extrema","points"],variableNames:[e],childIndices:[i]}}}return{dependenciesByKey:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:n}){let r={};for(let t of n){let n=e[t].child[0];if(n){let e=t.split(",")[1],a=0===Number(e)?"location":"value";a in n.stateValues?r[t]=n.stateValues[a]:r[t]=n.stateValues["x"+(Number(e)+1)]}}return{setValue:{[t.componentType]:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:n}){let r=[];for(let a in e[t.componentType])r.push({setDependency:n[a].extremumChild,desiredValue:e[t.componentType][a],childIndex:0,variableIndex:0});return{success:!0,instructions:r}}},e}}var Extrema$1=Object.freeze({__proto__:null,Extremum:Extremum,Extrema:Extrema});class InlineRenderInlineChildren extends InlineComponent{static componentType="_inlineRenderInlineChildren";static renderChildren=!0;static includeBlankStringChildren=!0;static beginTextDelimiter="";static endTextDelimiter="";static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=this;return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let n="";for(let t of e.inlineChildren)"object"!=typeof t?n+=t.toString():"string"==typeof t.stateValues.text?n+=t.stateValues.text:n+=" ";return n=t.beginTextDelimiter+n+t.endTextDelimiter,{setValue:{text:n}}}},e}}class Em extends InlineRenderInlineChildren{static componentType="em"}class Alert extends InlineRenderInlineChildren{static componentType="alert"}class Q$2 extends InlineRenderInlineChildren{static componentType="q";static beginTextDelimiter='"';static endTextDelimiter='"'}class SQ extends InlineRenderInlineChildren{static componentType="sq";static beginTextDelimiter="'";static endTextDelimiter="'"}class Term extends InlineRenderInlineChildren{static componentType="term";static rendererType="alert"}class C$2 extends InlineRenderInlineChildren{static componentType="c"}class Tag extends InlineRenderInlineChildren{static componentType="tag";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter=">"}class Tage extends InlineRenderInlineChildren{static componentType="tage";static rendererType="tag";static beginTextDelimiter="<";static endTextDelimiter="/>";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.selfClosed={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{selfClosed:!0}})},e}}class Attr extends InlineRenderInlineChildren{static componentType="attr";static rendererType="c"}var ParagraphMarkup=Object.freeze({__proto__:null,Em:Em,Alert:Alert,Q:Q$2,SQ:SQ,Term:Term,C:C$2,Tag:Tag,Tage:Tage,Attr:Attr});class SingleCharacter extends InlineComponent{static componentType="_singleCharacterInline";static unicodeCharacter="";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({}),definition:()=>({setValue:{text:this.unicodeCharacter}})},e}}class Ndash extends SingleCharacter{static componentType="ndash";static unicodeCharacter="–"}class Mdash extends SingleCharacter{static componentType="mdash";static unicodeCharacter="—"}class NBSP extends SingleCharacter{static componentType="nbsp";static unicodeCharacter=" "}class Ellipsis extends SingleCharacter{static componentType="ellipsis";static unicodeCharacter="…"}var SingleCharacterComponents=Object.freeze({__proto__:null,Ndash:Ndash,Mdash:Mdash,NBSP:NBSP,Ellipsis:Ellipsis});class BlockComponent extends BaseComponent{static componentType="_block"}function returnDefaultFeedbackDefinitions(){return{numericalerror:"Credit reduced because numbers in your answer weren't quite right. Did you round too much?",goodjob:"Good job!",onesignerror:"Credit reduced because it appears that you made a sign error.",twosignerrors:"Credit reduced because it appears that you made two sign errors."}}function returnFeedbackDefinitionStateVariables(){let e={setupChildren:{returnDependencies:()=>({setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}}),definition:({dependencyValues:e})=>({setValue:{setupChildren:e.setupChildren}})}};return e.feedbackDefinitions={stateVariablesDeterminingDependencies:["setupChildren"],returnDependencies({stateValues:e}){let t={ancestorWithFeedback:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},setupChildren:{dependencyType:"child",childGroups:["setups"],proceedIfAllChildrenNotMatched:!0}};for(let n of e.setupChildren)t[`feedbackDefinitionsOf${n.componentName}`]={dependencyType:"child",parentName:n.componentName,childGroups:["feedbackDefinitions"],variableNames:["value"]};return t},definition({dependencyValues:e}){let t,n={};e.ancestorWithFeedback&&(t=e.ancestorWithFeedback.stateValues.feedbackDefinitions),t||(t=returnDefaultFeedbackDefinitions()),Object.assign(n,t);let r=[];for(let t of e.setupChildren)r.push(...e[`feedbackDefinitionsOf${t.componentName}`]);for(let e of r)Object.assign(n,e.stateValues.value);return{setValue:{feedbackDefinitions:n}}}},e}class SectioningComponent extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),revealSection:this.revealSection.bind(this),closeSection:this.closeSection.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="_sectioningComponent";static renderChildren=!0;static includeBlankStringChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores={createComponentOfType:"boolean",createStateVariable:"aggregateScores",defaultValue:!1,public:!0},e.weight={createComponentOfType:"number",createStateVariable:"weight",defaultValue:1,public:!0},e.sectionWideCheckWork={createComponentOfType:"boolean",createStateVariable:"sectionWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.boxed={createComponentOfType:"boolean",createStateVariable:"boxed",defaultValue:!1,public:!0,forRenderer:!0},e.suppressAutoName={createComponentOfType:"boolean",createStateVariable:"suppressAutoName",defaultValue:!1,public:!0},e.suppressAutoNumber={createComponentOfType:"boolean",createStateVariable:"suppressAutoNumber",defaultValue:!1,public:!0},e.includeAutoName={createComponentOfType:"boolean",createStateVariable:"includeAutoName",defaultValue:!1,public:!0},e.includeAutoNumber={createComponentOfType:"boolean",createStateVariable:"includeAutoNumber",defaultValue:!1,public:!0},e.includeAutoNameNumberIfNoTitle={createComponentOfType:"boolean",createStateVariable:"includeAutoNameNumberIfNoTitle",defaultValue:!0,public:!0},e.includeParentNumber={createComponentOfType:"boolean",createStateVariable:"includeParentNumber",defaultValue:!1,public:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"variantControls",componentTypes:["variantControl"]},{group:"titles",componentTypes:["title"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.enumeration={additionalStateVariablesDefined:[{variableName:"sectionNumber",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["enumeration"]},includeParentNumber:{dependencyType:"stateVariable",variableName:"includeParentNumber"}}),definition({dependencyValues:e}){let t=[];return e.includeParentNumber&&e.sectionAncestor&&t.push(...e.sectionAncestor.stateValues.enumeration),t.push(e.countAmongSiblings),{setValue:{enumeration:t,sectionNumber:t.join(".")}}}},e.sectionName={returnDependencies:()=>({}),definition:()=>({setValue:{sectionName:"Section"}})},e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["titles"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[e.titleChild.length-1].componentName),{setValue:{titleChildName:t}}}},e.childIndicesToRender={returnDependencies:()=>({titleChildren:{dependencyType:"child",childGroups:["titles"]},allChildren:{dependencyType:"child",childGroups:["anything","variantControls","titles","setups"]},titleChildName:{dependencyType:"stateVariable",variableName:"titleChildName"}}),definition({dependencyValues:e}){let t=[],n=e.titleChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())"object"==typeof a&&n.includes(a.componentName)&&a.componentName!==e.titleChildName||t.push(r);return{setValue:{childIndicesToRender:t}}}},e.title={additionalStateVariablesDefined:[{variableName:"titlePrefix",forRenderer:!0,alwaysUpdateRenderer:!0}],public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,alwaysUpdateRenderer:!0,returnDependencies:({sharedParameters:e})=>({titleChild:{dependencyType:"child",childGroups:["titles"],variableNames:["text"]},sectionName:{dependencyType:"stateVariable",variableName:"sectionName"},sectionNumber:{dependencyType:"stateVariable",variableName:"sectionNumber"},includeAutoName:{dependencyType:"stateVariable",variableName:"includeAutoName"},includeAutoNumber:{dependencyType:"stateVariable",variableName:"includeAutoNumber"},prerender:{dependencyType:"value",value:e.prerender},includeAutoNameNumberIfNoTitle:{dependencyType:"stateVariable",variableName:"includeAutoNameNumberIfNoTitle"}}),definition({dependencyValues:e}){let t="",n="";const r=e.titleChild.length>0;let a=(e.includeAutoNumber||!r&&e.includeAutoNameNumberIfNoTitle)&&!e.prerender,i=e.includeAutoName||!r&&e.includeAutoNameNumberIfNoTitle;return a?(i&&(t=e.sectionName+" "),t+=e.sectionNumber):i&&(t=e.sectionName),r?(t&&(e.includeAutoName?t+=": ":t+=". "),n=e.titleChild[e.titleChild.length-1].stateValues.text):n=t,{setValue:{title:n,titlePrefix:t}}}},e.containerTag={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{containerTag:"section"}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.displayDigitsForCreditAchieved={returnDependencies:()=>({}),definition:()=>({setValue:{displayDigitsForCreditAchieved:3}})},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},forRenderer:!0,defaultValue:0,hasEssential:!0,additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},defaultValue:0,hasEssential:!0}],stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchieved"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchieved"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchieved:0,percentCreditAchieved:0}};let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e["creditAchieved"+t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["aggregateScores","scoredDescendants"],returnDependencies({stateValues:e}){let t={aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"}};if(e.aggregateScores){t.scoredDescendants={dependencyType:"stateVariable",variableName:"scoredDescendants"};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"}}return t},definition({dependencyValues:e}){if(!e.aggregateScores)return{setValue:{creditAchievedIfSubmit:0}};let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={};e.variantName?(n.index=e.variantIndex,n.name=e.variantName):n.seed=e.variantSeed,n.meta={createdBy:t};let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.collapsible={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{collapsible:!1}})},e.open={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{open:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"open",value:e.open}]})},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({sectionWideCheckWork:{dependencyType:"stateVariable",variableName:"sectionWideCheckWork"},aggregateScores:{dependencyType:"stateVariable",variableName:"aggregateScores"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor&&e.sectionAncestor.stateValues.suppressAnswerSubmitButtons?r=!0:e.sectionWideCheckWork&&(e.aggregateScores?(n=!0,r=!0):console.warn(`Cannot create submit all button for ${t} because it doesn't aggegrate scores`)),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{creditAchieved:await this.stateValues.creditAchievedIfSubmit}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}async revealSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!0}],overrideReadOnly:!0,actionId:e,event:{verb:"viewed",object:{componentName:this.componentName,componentType:this.componentType}}})}async closeSection({actionId:e}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"open",value:!1}],overrideReadOnly:!0,actionId:e,event:{verb:"closed",object:{componentName:this.componentName,componentType:this.componentType}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){if(!e.variants?.allPossibleVariants)return void setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0});let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r){let e=t.variantRng();r=Math.floor(e*a)+1}if(t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){if(!e.variants.allPossibleVariants)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};if(!e.variants.uniqueVariants)return{success:!0,desiredVariant:{index:t}};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?(e.variants.selectedUniqueVariant=!0,{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}):(console.log("Failed to get unique variant for section."),{success:!1})}}class Section extends SectioningComponent{static componentType="section";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeParentNumber.defaultValue=!0,e}}class Subsection extends Section{static componentType="subsection"}class Subsubsection extends Section{static componentType="subsubsection"}class Paragraphs extends SectioningComponent{static componentType="paragraphs";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:4}}),e.sectionName.definition=()=>({setValue:{sectionName:"Paragraphs"}}),e}}class Aside extends SectioningComponent{static componentType="aside";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.collapsible={createComponentOfType:"boolean",createStateVariable:"collapsible",defaultValue:!0,public:!0,forRenderer:!0},e.startOpen={createComponentOfType:"boolean",createStateVariable:"startOpen",defaultValue:!1},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.collapsible,e.open.returnDependencies=()=>({startOpen:{dependencyType:"stateVariable",variableName:"startOpen"}}),e.open.definition=({dependencyValues:e})=>({useEssentialOrDefaultValue:{open:{defaultValue:e.startOpen}}}),e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e.sectionName.definition=()=>({setValue:{sectionName:"Aside"}}),e}}class Problem extends SectioningComponent{static componentType="problem";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.aggregateScores.defaultValue=!0,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Problem"}}),e}}class Exercise extends Problem{static componentType="exercise";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Exercise"}}),e}}class Example extends SectioningComponent{static componentType="example";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.sectionName.definition=()=>({setValue:{sectionName:"Example"}}),e}}class StandinForFutureLayoutTag extends SectioningComponent{static componentType="standinForFutureLayoutTag";static rendererType="section";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.level.definition=()=>({setValue:{level:3}}),e.containerTag.definition=()=>({setValue:{containerTag:"aside"}}),e}}class externalContent extends SectioningComponent{static componentType="externalContent";static rendererType="section";static createAttributesObject(){let e=super.createAttributesObject();return e.includeAutoNameNumberIfNoTitle.defaultValue=!1,e}}var Sectioning=Object.freeze({__proto__:null,Section:Section,Subsection:Subsection,Subsubsection:Subsubsection,Paragraphs:Paragraphs,Aside:Aside,Problem:Problem,Exercise:Exercise,Example:Example,StandinForFutureLayoutTag:StandinForFutureLayoutTag,externalContent:externalContent});class Ol extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="ol";static rendererType="list";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.label={createComponentOfType:"text",createStateVariable:"label",defaultValue:null,public:!0,forRenderer:!0},e.level={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"lis",componentTypes:["li"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!0}})},e.level={forRenderer:!0,returnDependencies:()=>({ancestorLevel:{dependencyType:"ancestor",componentType:"ol",variableNames:["level"]},levelAttr:{dependencyType:"attributeComponent",attributeName:"level",variableNames:["value"]}}),definition({dependencyValues:e}){let t=e.levelAttr?.stateValues.value;return t>0||(t=(e.ancestorLevel?.stateValues.level||0)+1),{setValue:{level:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Ul extends Ol{static componentType="ul";static rendererType="list";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numbered={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{numbered:!1}})},e}}class Li$1 extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="li";static rendererType="list";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.item={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{item:!0}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Lists=Object.freeze({__proto__:null,Ol:Ol,Ul:Ul,Li:Li$1});class ODESystem extends InlineComponent{static componentType="odesystem";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.independentVariable={createComponentOfType:"variable",createStateVariable:"independentVariable",defaultValue:me$3.fromAst("t"),public:!0},e.initialIndependentVariableValue={createComponentOfType:"math",createStateVariable:"initialIndependentVariableValue",defaultValue:me$3.fromAst(0),public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:14,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.renderMode={createComponentOfType:"text",createStateVariable:"renderMode",defaultValue:"align",public:!0,forRenderer:!0},e.chunkSize={createComponentOfType:"number",createStateVariable:"chunkSize",defaultValue:10,public:!0},e.tolerance={createComponentOfType:"number",createStateVariable:"tolerance",defaultValue:1e-6,public:!0},e.maxIterations={createComponentOfType:"number",createStateVariable:"maxIterations",defaultValue:1e3,public:!0},e.hideInitialCondition={createComponentOfType:"boolean",createStateVariable:"hideInitialCondition",defaultValue:!1,public:!0},e.initialConditions={createComponentOfType:"mathList"},e.variables={createComponentOfType:"variables"},e.number={createComponentOfType:"boolean",createStateVariable:"number",defaultValue:!1,public:!0},e}static returnChildGroups(){return[{group:"rightHandSides",componentTypes:["rightHandSide"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validIndependentVariable={returnDependencies:()=>({independentVarAttr:{dependencyType:"attributeComponent",attributeName:"independentVariable",variableNames:["validVariable"]}}),definition({dependencyValues:e}){let t=!0;return e.independentVarAttr&&(t=e.independentVarAttr.stateValues.validVariable),{setValue:{validIndependentVariable:t}}}},e.nDimensions={returnDependencies:()=>({rhsChildren:{dependencyType:"child",childGroups:["rightHandSides"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nDimensions:e.rhsChildren.length},checkForActualChange:{nDimensions:!0}}}},e.variables={additionalStateVariablesDefined:[{variableName:"validVariables",isArray:!0,entryPrefixes:["validVar"]}],isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables","validVariables"]},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[],n=[],r=e.nDimensions;null!==e.variables&&(t=e.variables.stateValues.variables,n=[...e.variables.stateValues.validVariables].slice(0,r));let a=returnNVariables(r,t);return a.some((t=>t.equals(e.independentVariable)))&&console.warn("Variables of odesystem must be different than independent variable."),n.length({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={rhsChild:{dependencyType:"child",childGroups:["rightHandSides"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].rhsChild[0].stateValues.value;return{setValue:{rhss:n}}}},e.rhs={isAlias:!0,targetVariableName:"rhs1"},e.righthandside={isAlias:!0,targetVariableName:"rhs1"},e.righthandsides={isAlias:!0,targetVariableName:"rhss"},e.initialConditions={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["initialCondition"],defaultValueByArrayKey:()=>me$3.fromAst(0),returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={initialConditionAttr:{dependencyType:"attributeComponent",attributeName:"initialConditions",variableNames:[`math${Number(n)+1}`]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=!1;if(e[a].initialConditionAttr){let r=e[a].initialConditionAttr.stateValues[`math${Number(a)+1}`];void 0!==r&&(t=!0,n[a]=r)}t||(r[a]=!0)}let a={};return Object.keys(n).length>0&&(a.setValue={initialConditions:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialConditions:r}),a}},e.initialCondition={isAlias:!0,targetVariableName:"initialCondition1"},e.equationTag={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["number"],returnDependencies:({stateValues:e})=>e.number?{equationCounter:{dependencyType:"counter",counterName:"equation"}}:{},definition:({dependencyValues:e})=>void 0!==e.equationCounter?{setValue:{equationTag:String(e.equationCounter)}}:{setValue:{equationTag:null}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},variables:{dependencyType:"stateVariable",variableName:"variables"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"},hideInitialCondition:{dependencyType:"stateVariable",variableName:"hideInitialCondition"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},rhss:{dependencyType:"stateVariable",variableName:"rhss"},number:{dependencyType:"stateVariable",variableName:"number"},equationTag:{dependencyType:"stateVariable",variableName:"equationTag"}}),definition({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=[],a=e.independentVariable.toLatex();for(let i=0;i({latex:{dependencyType:"stateVariable",variableName:"latex"}}),definition:function({dependencyValues:e}){return{setValue:{latexWithInputChildren:[e.latex]}}}},e.numericalRHSf={additionalStateVariablesDefined:["numericalRHSfDefinitions"],returnDependencies:()=>({validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},rhss:{dependencyType:"stateVariable",variableName:"rhss"}}),definition({dependencyValues:e}){let t=!0;e.validIndependentVariable||(console.warn("Can't define ODE RHS functions with invalid independent variable."),t=!1),e.validVariables.every((e=>e))||(console.warn("Can't define ODE RHS functions with an invalid variable."),t=!1);let n,r=e.independentVariable.subscripts_to_strings().tree,a=e.variables.map((e=>e.subscripts_to_strings().tree));a.includes(r)&&(console.warn("Can't define ODE RHS functions when independent variable is a dependent variable"),t=!1),[...new Set(a)].length!==a.length&&(console.warn("Can't define ODE RHS functions with duplicate dependent variable names"),t=!1);try{n=e.rhss.map((e=>e.subscripts_to_strings().f()))}catch(e){console.warn("Cannot define ODE RHS function. Error creating mathjs function"),t=!1}if(!t){let t=e.rhss.length;return{setValue:{numericalRHSf:()=>NaN,numericalRHSfDefinitions:Array(t).fill({})}}}return{setValue:{numericalRHSf:function(e,t){let i={[r]:e};Array.isArray(t)?t.forEach(((e,t)=>i[a[t]]=e)):i[a[0]]=t;try{return n.map((e=>e(i)))}catch(e){return NaN}},numericalRHSfDefinitions:e.rhss.map((e=>({functionType:"formula",formula:e,nInputs:a.length+1,variables:[r,...a]})))}}}},e.haveNumericalInitialConditions={additionalStateVariablesDefined:["t0","x0s"],returnDependencies:()=>({initialIndependentVariableValue:{dependencyType:"stateVariable",variableName:"initialIndependentVariableValue"},initialConditions:{dependencyType:"stateVariable",variableName:"initialConditions"}}),definition({dependencyValues:e}){let t=e.initialIndependentVariableValue.evaluate_to_constant(),n=e.initialConditions.map((e=>e.evaluate_to_constant())),r=Number.isFinite(t)&&n.every((e=>Number.isFinite(e)));return{setValue:{t0:t,x0s:n,haveNumericalInitialConditions:r}}}},e.numericalSolutions={isArray:!0,entryPrefixes:["numericalSolution"],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinitions:{stateVariableToShadow:"numericalSolutionFDefinitions"}}},createWorkspace:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSf:{dependencyType:"stateVariable",variableName:"numericalRHSf"}}}),arrayDefinitionByKey({globalDependencyValues:e,workspace:t,componentName:n}){let r={};if(t.calculatedNumericSolutions=[],t.endingNumericalValues=[],t.maxPossibleTime=void 0,!e.haveNumericalInitialConditions){for(let t=0;tNaN;return{setValue:{numericalSolutions:r}}}let a=e.t0,i=e.x0s,s=e.chunkSize,o=e.tolerance,l=e.numericalRHSf,u=e.maxIterations;for(let c=0;c=r)for(let e=r;e<=p;e++){let r=t.endingNumericalValues[e-1];void 0===r&&(r=i);let c=a+e*s,p=me$3.math.dopri(c,c+s,r,l,o,u);t.endingNumericalValues.push(p.y[p.y.length-1]),t.calculatedNumericSolutions.push(p.at.bind(p));let d=p.x[p.x.length-1];if(d<.999999*(c+s)){t.maxPossibleTime=d;let e="For chunksize "+s+" and tolerance "+o+", odesystem";void 0!==n&&(e+=" ("+n+")"),e+=" hit maxiterations ("+u+") at t = "+t.maxPossibleTime+". Will not calculate solution beyond that time. Decrease chunksize, increase maxiterations, or increase tolerance to calculate further.";break}}return e>t.maxPossibleTime?NaN:t.calculatedNumericSolutions[p](e)[c]};return{setValue:{numericalSolutions:r}}}},e.numericalSolution={isAlias:!0,targetVariableName:"numericalSolution1"},e.numericalSolutionFDefinitions={forRenderer:!0,isArray:!0,entryPrefixes:["numericalSolutionFDefinition"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},validIndependentVariable:{dependencyType:"stateVariable",variableName:"validIndependentVariable"},independentVariable:{dependencyType:"stateVariable",variableName:"independentVariable"},validVariables:{dependencyType:"stateVariable",variableName:"validVariables"},variables:{dependencyType:"stateVariable",variableName:"variables"},chunkSize:{dependencyType:"stateVariable",variableName:"chunkSize"},tolerance:{dependencyType:"stateVariable",variableName:"tolerance"},maxIterations:{dependencyType:"stateVariable",variableName:"maxIterations"},haveNumericalInitialConditions:{dependencyType:"stateVariable",variableName:"haveNumericalInitialConditions"},t0:{dependencyType:"stateVariable",variableName:"t0"},x0s:{dependencyType:"stateVariable",variableName:"x0s"},numericalRHSfDefinitions:{dependencyType:"stateVariable",variableName:"numericalRHSfDefinitions"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>e.haveNumericalInitialConditions?{setValue:{numericalSolutionFDefinitions:[...Array(e.nDimensions).keys()].map((t=>({functionType:"ODESolution",nDimensions:e.nDimensions,t0:e.t0,x0s:e.x0s,chunkSize:e.chunkSize,tolerance:e.tolerance,numericalRHSfDefinitions:e.numericalRHSfDefinitions,maxIterations:e.maxIterations,component:t})))}}:{setValue:{numericalSolutionFDefinitions:Array(e.nDimensions).fill({})}}},e}}class Polyline extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePolyline:this.movePolyline.bind(this),finalizePolylinePosition:this.finalizePolylinePosition.bind(this),polylineClicked:this.polylineClicked.bind(this),mouseDownOnPolyline:this.mouseDownOnPolyline.bind(this)})}static componentType="polyline";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.verticesDraggable={createComponentOfType:"boolean"},e.vertices={createComponentOfType:"_pointListComponent"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" polyline"}}}},e.verticesDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({verticesDraggableAttr:{dependencyType:"attributeComponent",attributeName:"verticesDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.verticesDraggableAttr?{setValue:{verticesDraggable:e.verticesDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{verticesDraggable:{defaultValue:e.draggable}}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.vertices?{setValue:{nVertices:e.vertices.stateValues.nPoints}}:{setValue:{nVertices:0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.vertices){return{setValue:{nDimensions:e.vertices.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},getAllArrayKeys(e,t=!0,n){function r(e){if(1===e.length)return Array.from(Array(e[0]),((e,t)=>String(t)));{let n=e[0],a=r(e.slice(1)),i=[];for(let e=0;ee+","+t))):i.push(a.map((t=>e+","+t)));return i}}if(n){if(0!==n.length&&e){let t=[...e];return t[0]=n[0],r(t)}return[]}return e&&0!==e.length?r(e):[]},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={vertices:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].vertices;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{vertices:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].vertices||!t[r].vertices.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0})}return{success:!0,instructions:i}}},e.numericalVertices={isArray:!0,entryPrefixes:["numericalVertex"],forRenderer:!0,returnArraySizeDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={vertex:{dependencyType:"stateVariable",variableName:"vertex"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalVertices:n}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[0]?.[0],l=i[0]?.[1];for(let e=1;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}async movePolyline({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){if(1===Object.keys(e).length){if(!await this.stateValues.verticesDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};for(let t in e)a[t+",0"]=me$3.fromAst(e[t][0]),a[t+",1"]=me$3.fromAst(e[t][1]);return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:a,sourceInformation:n}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}async finalizePolylinePosition(){return await this.actions.movePolyline({pointCoords:await this.stateValues.numericalVertices,transient:!1})}async polylineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPolyline({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class CobwebPolyline extends Polyline{static componentType="cobwebPolyline";static rendererType="cobwebPolyline";static createAttributesObject(){let e=super.createAttributesObject();return e.attractThreshold={createComponentOfType:"number",createStateVariable:"attractThreshold",defaultValue:.5,public:!0},e.nPoints={createComponentOfType:"number",createStateVariable:"nPoints",defaultValue:1,public:!0,clamp:[0,1/0],forRenderer:!0},e.variable={createComponentOfType:"variable",createStateVariable:"variable",defaultValue:me$3.fromAst("x"),public:!0,forRenderer:!0},e.nIterationsRequired={createComponentOfType:"number",createStateVariable:"nIterationsRequired",defaultValue:0,public:!0},e.initialPoint={createComponentOfType:"point"},e.function={createComponentOfType:"function"},e.lockToSolution={createComponentOfType:"boolean",createStateVariable:"lockToSolution",defaultValue:!1},e.defaultPoint={createComponentOfType:"point"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nDimensions.returnDependencies=()=>({}),e.nDimensions.definition=()=>({setValue:{nDimensions:2}}),e.initialPoint={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"initialPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["initialPointX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={initialPointAttr:{dependencyType:"attributeComponent",attributeName:"initialPoint",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=Number(a)+1;e[a].initialPointAttr?n[a]=e[a].initialPointAttr.stateValues["x"+t]:r[a]=!0}let a={};return Object.keys(n).length>0&&(a.setValue={initialPoint:n}),Object.keys(r).length>0&&(a.useEssentialOrDefaultValue={initialPoint:r}),a},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.initialPoint)t[a].initialPointAttr&&t[a].initialPointAttr.stateValues["x"+(Number(a)+1)]?r.push({setDependency:n[a].initialPointAttr,desiredValue:e.initialPoint[a],variableIndex:0}):r.push({setEssentialValue:"initialPoint",value:{[a]:e.initialPoint[a]}});return{success:!0,instructions:r}}},e.f={additionalStateVariablesDefined:[{variableName:"fDefinition",forRenderer:!0}],returnDependencies:()=>({functionAttr:{dependencyType:"attributeComponent",attributeName:"function",variableNames:["numericalf","fDefinition"]}}),definition:({dependencyValues:e})=>e.functionAttr?{setValue:{f:e.functionAttr.stateValues.numericalf,fDefinition:e.functionAttr.stateValues.fDefinition}}:{setValue:{f:null,fDefinition:null}}},e.nVertices={isAlias:!0,targetVariableName:"nPoints"},e.nOriginalVertices={providePreviousValuesInDefinition:!0,returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e,previousValues:t}){let n=e.nVertices;return t.nOriginalVertices>n&&(n=t.nOriginalVertices),{setValue:{nOriginalVertices:n}}}},e.originalVertices={isArray:!0,nDimensions:2,hasEssential:!0,entryPrefixes:["originalVertexX","originalVertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("originalVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("originalVertices"===t)return 1===e.length?"originalVertex"+e[0]:`originalVertexX${e[0]}_${e[1]}`;if("originalVertex"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`originalVertexX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nOriginalVertices:{dependencyType:"stateVariable",variableName:"nOriginalVertices"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nOriginalVertices-1,e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},defaultPoint:{dependencyType:"attributeComponent",attributeName:"defaultPoint",variableNames:["xs"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",").map(Number);n[r]={get defaultValue(){if(e.defaultPoint){let n=e.defaultPoint.stateValues.xs;if(2===n.length&&t[1]<2)return n[t[1]]}if(e.graphAncestor){if(0===t[1]){let t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax;return me$3.fromAst((t+n)/2)}if(1===t[1]){let t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax;return me$3.fromAst((t+n)/2)}}return me$3.fromAst(0)}}}return{useEssentialOrDefaultValue:{originalVertices:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.originalVertices)t.push({setEssentialValue:"originalVertices",value:{[n]:e.originalVertices[n]}});return{success:!0,instructions:t}}},e.vertices.additionalStateVariablesDefined=[{variableName:"prelimCorrectVertices",entryPrefixes:["prelimCorrectVertexX","prelimCorrectVertex"],getArrayKeysFromVarName:function({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("prelimCorrectVertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}}}],e.vertices.basedOnArrayKeyStateVariables=!0,e.vertices.returnArrayDependenciesByKey=function({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]="0"===e?{initialPoint:{dependencyType:"stateVariable",variableName:"initialPointX"+(Number(r)+1)}}:{originalVertexX1:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_1"},originalVertexX2:{dependencyType:"stateVariable",variableName:"originalVertexX"+e+"_2"},previousVertexX1:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_1"},previousVertexX2:{dependencyType:"stateVariable",variableName:"vertexX"+e+"_2"}}}return{globalDependencies:{f:{dependencyType:"stateVariable",variableName:"f"},attractThreshold:{dependencyType:"stateVariable",variableName:"attractThreshold"},lockToSolution:{dependencyType:"stateVariable",variableName:"lockToSolution"}},dependenciesByKey:t}},e.vertices.arrayDefinitionByKey=function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let[n,s]=i.split(",");if("0"===n)r[i]=t[i].initialPoint,a[i]=null;else{let s,o,l;try{s=[t[i].originalVertexX1.evaluate_to_constant(),t[i].originalVertexX2.evaluate_to_constant()],o=[t[i].previousVertexX1.evaluate_to_constant(),t[i].previousVertexX2.evaluate_to_constant()]}catch(e){r[n+",0"]=me$3.fromAst(0),r[n+",1"]=me$3.fromAst(0),a[n+",0"]=!1;continue}if(Number(n)%2==1){let t=e.f(o[0]);l=[o[0],t]}else l=[o[1],o[1]];Math.pow(s[0]-l[0],2)+Math.pow(s[1]-l[1],2)({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),returnArraySize:({dependencyValues:e})=>[e.nVertices-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={prelimCorrectVertex:{dependencyType:"stateVariable",variableName:"prelimCorrectVertexX"+(Number(n)+2)+"_1"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].prelimCorrectVertex;return{setValue:{correctVertices:n}}}},e.fractionCorrectVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"nCorrectVertices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({correctVertices:{dependencyType:"stateVariable",variableName:"correctVertices"}}),definition({dependencyValues:e}){let t,n,r=e.correctVertices.length;return 0===r?(t=0,n=0):(n=e.correctVertices.reduce(((e,t)=>e+t),0),t=n/r),{setValue:{fractionCorrectVertices:t,nGradedVertices:r,nCorrectVertices:n}}}},e.fractionCorrectVerticesAdjusted={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"nGradedVerticesAdjusted",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({nCorrectVertices:{dependencyType:"stateVariable",variableName:"nCorrectVertices"},nGradedVertices:{dependencyType:"stateVariable",variableName:"nGradedVertices"},nIterationsRequired:{dependencyType:"stateVariable",variableName:"nIterationsRequired"}}),definition({dependencyValues:e}){let t=0;e.nIterationsRequired>0&&(t=2*e.nIterationsRequired-1);let n,r=Math.max(e.nGradedVertices,t);return n=0===r?0:e.nCorrectVertices/r,{setValue:{fractionCorrectVerticesAdjusted:n,nGradedVerticesAdjusted:r}}}},e.nIterateValues={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition:({dependencyValues:e})=>({setValue:{nIterateValues:Math.ceil((e.nVertices+1)/2)}})},e.iterateValues={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math"},entryPrefixes:["iterateValue"],returnArraySizeDependencies:()=>({nIterateValues:{dependencyType:"stateVariable",variableName:"nIterateValues"}}),returnArraySize:({dependencyValues:e})=>[e.nIterateValues],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]="0"===n?{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX1_1"}}:{iterateValue:{dependencyType:"stateVariable",variableName:"vertexX"+2*Number(n)+"_2"}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].iterateValue;return{setValue:{iterateValues:n}}}},e}}class Point extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{movePoint:this.movePoint.bind(this),switchPoint:this.switchPoint.bind(this),pointClicked:this.pointClicked.bind(this),mouseDownOnPoint:this.mouseDownOnPoint.bind(this)})}static componentType="point";static primaryStateVariableForDefinition="coordsShadow";static stateVariableForAttributeValue="coords";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.coords={createComponentOfType:"coords"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"constraints")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{coords:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:[{componentType:"math",children:e}]}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]},{group:"constraints",componentTypes:["constraints"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescription:e.selectedStyle.markerColorWord}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.selectedStyle.markerColorWord+" "+e.selectedStyle.markerStyleWord}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{coordsShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,workspace:n}){return{success:!0,instructions:[{setEssentialValue:"coordsShadow",value:e.coordsShadow}]}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]},x:{dependencyType:"attributeComponent",attributeName:"x"},y:{dependencyType:"attributeComponent",attributeName:"y"},z:{dependencyType:"attributeComponent",attributeName:"z"},xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){let t,n,r=!1;if(n=null!==e.z?3:null!==e.y?2:0,null!==e.coords?(r=!0,t=e.coords.stateValues.value):e.coordsShadow&&(r=!0,t=e.coordsShadow),r){let e=t.tree;return n=Array.isArray(e)&&vectorOperators.includes(e[0])?Math.max(e.length-1,n):Math.max(1,n),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}}}return null!==e.xs?{setValue:{nDimensions:Math.max(e.xs.stateValues.nComponents,n)}}:e.pointChild.length>0?{setValue:{nDimensions:Math.max(e.pointChild[0].stateValues.nDimensions,n)}}:e.vectorChild.length>0?{setValue:{nDimensions:Math.max(e.vectorChild[0].stateValues.nDimensions,n)}}:(0===n&&(n=2),{setValue:{nDimensions:n},checkForActualChange:{nDimensions:!0}})}},e.arrayVariableForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayVariableForConstraints:"unconstrainedXs"}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{arrayEntryPrefixForConstraints:"unconstrainedX"}})},e.nDimensionsForConstraints={isAlias:!0,targetVariableName:"nDimensions"},e.unconstrainedXs={isArray:!0,entryPrefixes:["unconstrainedX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={xs:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===n?t[n].component={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===n&&(t[n].component={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]})}return{globalDependencies:{coordsShadow:{dependencyType:"stateVariable",variableName:"coordsShadow"},coords:{dependencyType:"attributeComponent",attributeName:"coords",variableNames:["value"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r,a={},i={},s=!1;if(null!==e.coords?(s=!0,r=e.coords.stateValues.value):e.coordsShadow&&(s=!0,r=e.coordsShadow),s){let e=r.tree;if(Array.isArray(e)&&vectorOperators.includes(e[0]))for(let t of n){let n=Number(t);(n>=0||n0)a[e]=r[0].stateValues["x"+n];else{let r=t[e].vectorChild;r.length>0&&(a[e]=r[0].stateValues["x"+n])}}}for(let e of n){let n=t[e].component;n?a[e]=n.stateValues.value.simplify():void 0===a[e]&&(i[e]=!0)}let o={};return Object.keys(a).length>0&&(o.setValue={unconstrainedXs:a}),Object.keys(i).length>0&&(o.useEssentialOrDefaultValue={unconstrainedXs:i}),o},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i,s,o=[],l=!1,u=!1;null!==t.coords?(l=!0,i="coords",s=Array(a[0]+1)):null!==t.coordsShadow&&(l=!0,i="coordsShadow",s=Array(a[0]+1));for(let t of Object.keys(e.unconstrainedXs).reverse()){let a=convertValueToMathExpression(e.unconstrainedXs[t]);if(null!==n[t].component)o.push({setDependency:r[t].component,desiredValue:a,childIndex:0,variableIndex:0});else if(l)s[Number(t)+1]=a.tree,u=!0;else{if(null!==n[t].xs)o.push({setDependency:r[t].xs,desiredValue:a,childIndex:0,variableIndex:0});else{if(n[t].pointChild.length>0)o.push({setDependency:r[t].pointChild,desiredValue:a,childIndex:0,variableIndex:0});else{n[t].vectorChild.length>0?o.push({setDependency:r[t].vectorChild,desiredValue:a,childIndex:0,variableIndex:0}):o.push({setEssentialValue:"unconstrainedXs",value:{[t]:a}})}}}}if(u){let e;1===a[0]?e=me$3.fromAst(s[1]):(s[0]="vector",e=me$3.fromAst(s));let t={setDependency:i,desiredValue:e};"coords"===i&&(t.childIndex=0,t.variableIndex=0),o.push(t)}return{success:!0,instructions:o}}},e.xs={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["x"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r={};r.unconstrainedX={dependencyType:"stateVariable",variableName:`unconstrainedX${e}`},r.constraintsChild={dependencyType:"child",childGroups:["constraints"],variableNames:[`constraintResult${e}`]},t[n]=r}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)if(e[r].constraintsChild.length>0){let t=Number(r)+1;n[r]=convertValueToMathExpression(e[r].constraintsChild[0].stateValues["constraintResult"+t])}else n[r]=convertValueToMathExpression(e[r].unconstrainedX);return t.length>0?{setValue:{xs:n}}:{}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r of Object.keys(e.xs).reverse())t[r]&&(t[r].constraintsChild.length>0?i.push({setDependency:n[r].constraintsChild,desiredValue:e.xs[r],childIndex:0,variableIndex:0}):i.push({setDependency:n[r].unconstrainedX,desiredValue:e.xs[r]}));return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.coords={public:!0,shadowingInstructions:{createComponentOfType:"coords",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({xs:{dependencyType:"stateVariable",variableName:"xs"}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.xs)n?t.push(n.tree):t.push("_");return t=t.length>1?["vector",...t]:1===t.length?t[0]:"_",{setValue:{coords:me$3.fromAst(t)}}},inverseDefinition:async function({desiredStateVariableValues:e,stateValues:t,initialChange:n}){if(n&&!await t.draggable)return{success:!1};let r=[],a={},i=e.coords.tree;if(Array.isArray(i)&&vectorOperators.includes(i[0]))for(let t=0;t({coords:{dependencyType:"stateVariable",variableName:"coords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.coords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.value={isAlias:!0,targetVariableName:"coords"},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintsChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["constraintUsed"]}}),definition:function({dependencyValues:e}){return 0===e.constraintsChild.length?{setValue:{constraintUsed:!1}}:{setValue:{constraintUsed:e.constraintsChild[0].stateValues.constraintUsed}}}},e.numericalXs={isArray:!0,entryPrefixes:["numericalX"],forRenderer:!0,returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={x:{dependencyType:"stateVariable",variableName:`x${e}`}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].x;t?(t=e[r].x.evaluate_to_constant(),Number.isFinite(t)?n[r]=t:n[r]=NaN):n[r]=NaN}return{setValue:{numericalXs:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,initialChange:n,stateValues:r}){if(n&&!await r.draggable)return{success:!1};let a=[];for(let n in e.numericalXs)dependencyValuesByKey[n]&&a.push({setDependency:t[n].xs,desiredValue:e.numericalXs[n]});return{success:!0,instructions:a}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalXs:{dependencyType:"stateVariable",variableName:"numericalXs"}}),definition:({dependencyValues:e})=>({setValue:{nearestPoint:function(){let t={};for(let n=1;n<=e.nDimensions;n++){let r=e.numericalXs[n-1];if(!Number.isFinite(r))return{};t["x"+n]=r}return t}}})},e}static adapters=[{stateVariable:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async movePoint({x:e,y:t,z:n,transient:r,actionId:a}){let i={};return void 0!==e&&(i[0]=me$3.fromAst(e)),void 0!==t&&(i[1]=me$3.fromAst(t)),void 0!==n&&(i[2]=me$3.fromAst(n)),r?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],transient:r,actionId:a}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"xs",value:i}],actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{x:e,y:t,z:n}}})}switchPoint(){}async pointClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnPoint({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class EquilibriumPoint extends Point{static componentType="equilibriumPoint";static rendererType="point";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.open={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{open:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.open}]})},e}async switchPoint({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Line extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLine:this.moveLine.bind(this),switchLine:this.switchLine.bind(this),lineClicked:this.lineClicked.bind(this),mouseDownOnLine:this.mouseDownOnLine.bind(this)})}static componentType="line";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.equation={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.slope={createComponentOfType:"number"},e.variables={createComponentOfType:"variables"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){if(0===e.length)return{success:!1};let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{equation:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line"}}}},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){let n=null===e.displayDigitsAttr||t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nPointsPrescribed:0}}:{setValue:{nPointsPrescribed:e.throughAttr.stateValues.nPoints}}}},e.basedOnSlope={returnDependencies:()=>({slopeAttr:{dependencyType:"attributeComponent",attributeName:"slope"},nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:({dependencyValues:e})=>({setValue:{basedOnSlope:e.nPointsPrescribed<2&&null!==e.slopeAttr&&2===e.nDimensions}})},e.dForSlope={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dForSlope:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dForSlope",value:e.dForSlope}]})},e.variables={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"variable"},entryPrefixes:["var"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey:()=>({globalDependencies:{variables:{dependencyType:"attributeComponent",attributeName:"variables",variableNames:["variables"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arraySize:t}){let n=[];return null!==e.variables&&(n=e.variables.stateValues.variables),{setValue:{variables:returnNVariables(t[0],n)}}}},e.equationIdentity={returnDependencies:()=>({equation:{dependencyType:"attributeComponent",attributeName:"equation"}}),definition:function({dependencyValues:e}){return null!==e.equation?{setValue:{equationIdentity:e.equation}}:{setValue:{equationIdentity:null}}}},e.essentialPoints={isArray:!0,nDimensions:"2",hasEssential:!0,entryPrefixes:["essentialPointX","essentialPoint"],set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("essentialPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialPoints:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialPoints)t.push({setEssentialValue:"essentialPoints",value:{[n]:convertValueToMathExpression(e.essentialPoints[n])}});return{success:!0,instructions:t}}},e.points={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"pointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["equationIdentity","nPointsPrescribed","basedOnSlope"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({stateValues:e,arrayKeys:t}){if(null===e.equationIdentity){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1);n[r]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+i]}},e.basedOnSlope?("1"===t&&(1===e.nPointsPrescribed&&n[r].through.variableNames.push("pointX1_"+(Number(a)+1)),n[r].dForSlope={dependencyType:"stateVariable",variableName:"dForSlope"},n[r].slopeAttr={dependencyType:"attributeComponent",attributeName:"slope",variableNames:["value"]}),0===e.nPointsPrescribed&&(n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX2_"+(Number(a)+1)})):n[r].essentialPoint={dependencyType:"stateVariable",variableName:"essentialPointX"+i}}return{dependenciesByKey:n,globalDependencies:{nPointsPrescribed:{dependencyType:"stateVariable",variableName:"nPointsPrescribed"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},basedOnSlope:{dependencyType:"stateVariable",variableName:"basedOnSlope"}}}}return{globalDependencies:{coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"},variables:{dependencyType:"stateVariable",variableName:"variables"},lastPointsFromInverting:{dependencyType:"stateVariable",variableName:"lastPointsFromInverting"}}}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r,componentName:a}){if("coeff0"in e){let t=calculatePointsFromCoeffs(e);if(t.success)return{setValue:{points:t.points}};{let e={};for(let t=0;te.toString()))];for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){if(Number.isNaN(e.nDimensions))return{};let a={};for(let r of n){let n=t[r].point;Array.isArray(n)||(n=[n]);let i=[];for(let t=0;t({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){let t=e.coeff0.evaluate_to_constant();Number.isFinite(t)||(t=NaN);let n=e.coeffvar1.evaluate_to_constant();Number.isFinite(n)||(n=NaN);let r=e.coeffvar2.evaluate_to_constant();return Number.isFinite(r)||(r=NaN),{setValue:{numericalCoeff0:t,numericalCoeffvar1:n,numericalCoeffvar2:r}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:function({dependencyValues:e}){return{setValue:{slope:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeffvar1,b:e.coeffvar2}).simplify()}}}},e.xintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar1:{dependencyType:"stateVariable",variableName:"coeffvar1"}}),definition:({dependencyValues:e})=>({setValue:{xintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar1}).simplify()}})},e.yintercept={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({coeff0:{dependencyType:"stateVariable",variableName:"coeff0"},coeffvar2:{dependencyType:"stateVariable",variableName:"coeffvar2"}}),definition:({dependencyValues:e})=>({setValue:{yintercept:me$3.fromAst(["-",["/","a","b"]]).substitute({a:e.coeff0,b:e.coeffvar2}).simplify()}})},e.lastPointsFromInverting={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{lastPointsFromInverting:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"lastPointsFromInverting",value:e.lastPointsFromInverting}]})},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({equation:{dependencyType:"stateVariable",variableName:"equation"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.equation,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalCoeff0:{dependencyType:"stateVariable",variableName:"numericalCoeff0"},numericalCoeffvar1:{dependencyType:"stateVariable",variableName:"numericalCoeffvar1"},numericalCoeffvar2:{dependencyType:"stateVariable",variableName:"numericalCoeffvar2"}}),definition({dependencyValues:e}){let t=e.numericalCoeffvar1,n=e.numericalCoeffvar2,r=e.numericalCoeff0,a=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r),i=2!==e.nDimensions||!a||0===t&&0===n;return{setValue:{nearestPoint:function({variables:e,scales:a=[1,1]}){if(i)return{};let s=a[0],o=a[1],l=t*s,u=n*o,c=l*l+u*u,p=e.x1?.evaluate_to_constant(),d=e.x2?.evaluate_to_constant();if(!Number.isFinite(p)||!Number.isFinite(d))return{};let m=p/s,h=d/o,f={};return f.x1=(u*(u*m-l*h)-l*r)*s/c,f.x2=(l*(-u*m+l*h)-u*r)*o/c,void 0!==e.x3&&(f.x3=0),f}}}}},e}static adapters=[{stateVariable:"equation",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveLine({point1coords:e,point2coords:t,transient:n,actionId:r}){let a={"0,0":me$3.fromAst(e[0]),"0,1":me$3.fromAst(e[1])};return await this.stateValues.basedOnSlope||(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"points",value:a}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{point1:e,point2:t}}})}switchLine(){}async lineClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLine({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}function calculateCoeffsFromEquation({equation:e,variables:t}){let n=t[0],r=t[1],a=n.toString(),i=r.toString();if(e=e.expand().simplify(),!Array.isArray(e.tree)||"="!==e.tree[0]||3!==e.tree.length)return{success:!1};let s=me$3.fromAst(["+",e.tree[2],["-",e.tree[1]]]).expand().simplify(),o=[];o=Array.isArray(s.tree)&&"+"===s.tree[0]?s.tree.slice(1):[s.tree];let l=me$3.fromAst(0),u=me$3.fromAst(0),c=me$3.fromAst(0);for(let e of o){let t=p(e);if(!t.success)return{success:!1};l=l.add(t.coeffvar1),u=u.add(t.coeffvar2),c=c.add(t.coeff0)}return l=l.simplify(),u=u.simplify(),c=c.simplify(),{success:!0,coeff0:c,coeffvar1:l,coeffvar2:u};function p(e){let t=0,s=0,o=0;if("string"==typeof e)e===a?t=1:e===i?s=1:o=e;else if("number"==typeof e)o=e;else{if(!Array.isArray(e))return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};{let a=e[0],i=e.slice(1);if("-"===a){let e=p(i[0]);if(!e.success)return{success:!1};t=["-",e.coeffvar1.tree],s=["-",e.coeffvar2.tree],o=["-",e.coeff0.tree]}else{if("+"===a)return console.warn("Invalid format for equation of line in variables "+n+" and "+r),{success:!1};if("*"===a){let a=-1,l=-1;for(let e=0;e({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},e}async switchLine({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}class Curve extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveControlVector:this.moveControlVector.bind(this),moveThroughPoint:this.moveThroughPoint.bind(this),changeVectorControlDirection:this.changeVectorControlDirection.bind(this),switchCurve:this.switchCurve.bind(this),curveClicked:this.curveClicked.bind(this),mouseDownOnCurve:this.mouseDownOnCurve.bind(this)})}static componentType="curve";static rendererType="curve";static primaryStateVariableForDefinition="fShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft","top","bottom","left","right"]},e.flipFunction={createComponentOfType:"boolean",createStateVariable:"flipFunction",defaultValue:!1,public:!0,forRenderer:!0},e.nDiscretizationPoints={createComponentOfType:"number",createStateVariable:"nDiscretizationPoints",defaultValue:1e3,public:!0},e.periodic={createComponentOfType:"boolean",createStateVariable:"periodic",defaultValue:!1,public:!0},e.splineTension={createComponentOfType:"number",createStateVariable:"splineTension",defaultValue:.8,clamp:[0,1],public:!0},e.extrapolateBackward={createComponentOfType:"boolean",createStateVariable:"extrapolateBackward",defaultValue:!1,public:!0,forRenderer:!0},e.extrapolateForward={createComponentOfType:"boolean",createStateVariable:"extrapolateForward",defaultValue:!1,public:!0,forRenderer:!0},e.splineForm={createComponentOfType:"text",createStateVariable:"splineForm",defaultValue:"centripetal",public:!0,toLowerCase:!0,validValues:["centripetal","uniform"]},e.variable={createComponentOfType:"variable",createStateVariable:"variableForChild",defaultValue:me$3.fromAst("x")},e.through={createComponentOfType:"_pointListComponent"},e.parMin={createComponentOfType:"math"},e.parMax={createComponentOfType:"math"},e.nearestPointAsCurve={createComponentOfType:"boolean",createStateVariable:"nearestPointAsCurvePrelim",defaultValue:!1},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e=>t.componentIsSpecifiedType(e,"label");if(0===e.length||!e.every((e=>"string"==typeof e||e.doenetAttributes?.createdFromMacro||n(e))))return{success:!1};let r=e.map(n),a=[],i=[],s=[];if(0===r.filter((e=>e)).length)a=e;else{if(r[0]){let t=r.indexOf(!1);-1!==t&&(i=e.slice(0,t),e=e.slice(t),r=r.slice(t))}let t=r.indexOf(!0);-1===t?a=e:(a=e.slice(0,t),s=e.slice(t))}if(0===a.length)return{success:!1};let o=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"function",children:e}),mustStripOffOuterParentheses:!0}),l=o({matchedChildren:a}),u=[];return u=l.success?l.newChildren:[{componentType:"function",children:a}],{success:!0,newChildren:[...i,...u,...s]}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"functions",componentTypes:["function"]},{group:"bezierControls",componentTypes:["bezierControls"]}),e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" curve"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},through:{dependencyType:"attributeComponent",attributeName:"through"}}),definition({dependencyValues:e}){let t="function";return null!==e.through?t="bezier":e.functionChildren.length>1&&(t="parameterization"),{setValue:{curveType:t}}}},t.fShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fShadow:!0}})},t.graphXmin={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"graphXmax",forRenderer:!0},{variableName:"graphYmin",forRenderer:!0},{variableName:"graphYmax",forRenderer:!0}],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>e.graphAncestor?{setValue:{graphXmin:e.graphAncestor.stateValues.xmin,graphXmax:e.graphAncestor.stateValues.xmax,graphYmin:e.graphAncestor.stateValues.ymin,graphYmax:e.graphAncestor.stateValues.ymax}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMaxAttr:{dependencyType:"attributeComponent",attributeName:"parMax",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=e.nThroughPoints-1,e.extrapolateForward&&(t*=2);else if(null!==e.parMaxAttr)t=e.parMaxAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][2]).evaluate_to_constant(),Number.isFinite(t)||t===1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?r+.1*(r-n):Math.min(t,r+.1*(r-n))),void 0===t&&(t=1/0)}else t=10;return{setValue:{parMax:t}}}},t.parMin={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},parMinAttr:{dependencyType:"attributeComponent",attributeName:"parMin",variableNames:["value"]},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["domain"]},adapterSourceDomain:{dependencyType:"adapterSourceStateVariable",variableName:"domain"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"}}),definition:function({dependencyValues:e}){let t;if("bezier"===e.curveType)t=0,e.extrapolateBackward&&(t=-(e.nThroughPoints-1));else if(null!==e.parMinAttr)t=e.parMinAttr.stateValues.value.evaluate_to_constant(),Number.isFinite(t)||(t=NaN);else if("function"===e.curveType){let n,r,a=null;if(a=1===e.functionChild.length?e.functionChild[0].stateValues.domain:e.adapterSourceDomain,null!==a){a=a[0];try{t=me$3.fromAst(a.tree[1][1]).evaluate_to_constant(),Number.isFinite(t)||t===-1/0||(t=NaN)}catch(e){}}e.flipFunction?(r=e.graphYmax,n=e.graphYmin):(r=e.graphXmax,n=e.graphXmin),null!==r&&null!==n&&(t=void 0===t?n+.1*(n-r):Math.max(t,n+.1*(n-r))),void 0===t&&(t=-1/0)}else t=-10;return{setValue:{parMin:t}}}},t.domainForFunctions={returnDependencies:()=>({parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"}}),definition:({dependencyValues:e})=>({setValue:{domainForFunctions:[me$3.fromAst(["interval",["tuple",e.parMin,e.parMax],["tuple",!0,!0]])]}})},t.nThroughPoints={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition({dependencyValues:e}){let t=0;return null!==e.through&&(t=e.through.stateValues.nPoints),{setValue:{nThroughPoints:t}}}},t.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.through){return{setValue:{nDimensions:e.through.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].through;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst(0)}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].through||!t[r].through.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].through,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,entryPrefixes:["numericalThroughPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.evaluate_to_constant()));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}}},t.haveBezierControls={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"]}}),definition:({dependencyValues:e})=>({setValue:{haveBezierControls:e.controlChild.length>0}})},t.bezierControlsAlwaysVisible={forRenderer:!0,returnDependencies:()=>({controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["alwaysVisible"]}}),definition:({dependencyValues:e})=>({setValue:{bezierControlsAlwaysVisible:e.controlChild.length>0&&e.controlChild[0].stateValues.alwaysVisible}})},t.vectorControlDirections={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["vectorControlDirection"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["direction"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["direction"+(Number(r)+1)]:n[r]="none"}return{setValue:{vectorControlDirections:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.vectorControlDirections){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.vectorControlDirections[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.hiddenControls={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["hiddenControl"],forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["hiddenControl"+(Number(n)+1)]}};return{dependenciesByKey:t,globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"}}}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlChild;t&&t.length>0?n[r]=t[0].stateValues["hiddenControl"+(Number(r)+1)]:n[r]=!1}return{setValue:{hiddenControls:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls)return{success:!1};let a=[];for(let r in e.hiddenControls){let i=n[r].controlChild;i&&i.length>0&&a.push({setDependency:t[r].controlChild,desiredValue:e.hiddenControls[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:a}}},t.controlVectors={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlVectorX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlVectorX","controlVector"],nDimensions:3,stateVariablesDeterminingDependencies:["vectorControlDirections","nThroughPoints"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlVectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1)),i=a.join("_");n[r]={direction:{dependencyType:"stateVariable",variableName:"vectorControlDirection"+a[0]},controlChild:{dependencyType:"child",childGroups:["bezierControls"],variableNames:["control"+i]}};let s=e[0],o=t.vectorControlDirections[s],l=[];"none"===o?l=[s-1,s,s+1]:"previous"===o?l=[s,s+1]:"next"===o&&(l=[s-1,s]);for(let e of l)e>=0&&eNumber(e))),s=r.map((e=>e+1)),o=s.join("_"),l=r[0],u=r[1],c=n[i].direction;if("none"===c){let r,s,o=n[i]["throughPoint"+(l+1)];l>0&&(r=n[i]["throughPoint"+l]),lNumber(e))),s=i.map((e=>e+1)),o=s.join("_"),l=n[r].controlChild;if(l.length>0){l[0].stateValues["control"+o]&&a.push({setDependency:t[r].controlChild,desiredValue:e.controlVectors[r],childIndex:0,variableIndex:0})}}return{success:!0,instructions:a}}},t.numericalControlVectors={isArray:!0,entryPrefixes:["numericalControlVector"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlVector:{dependencyType:"stateVariable",variableName:"controlVector"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlVector.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlVectors:n}}}},t.controlPoints={isArray:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"controlPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},entryPrefixes:["controlPointX","controlPoint"],nDimensions:3,getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("controlPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 3===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eNumber(e)-1));return 2===e.length&&e.every((e=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>eString(e)+","+n)):[]:[String(e)+",0"]:[]}},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={throughPointX:{dependencyType:"stateVariable",variableName:"throughPointX"+r[0]+"_"+r[2]},controlVectorX:{dependencyType:"stateVariable",variableName:"controlVectorX"+a}}}return{globalDependencies:{haveBezierControls:{dependencyType:"stateVariable",variableName:"haveBezierControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(2!==e.nDimensions)r[a]=me$3.fromAst(NaN);else{let e=t[a].controlVectorX;if(e){let n=t[a].throughPointX.evaluate_to_constant();Number.isFinite(n)||(n=NaN),r[a]=me$3.fromAst(n+e.tree)}else r[a]=null}return{setValue:{controlPoints:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r}){if(!r.haveBezierControls||2!==r.nDimensions)return{success:!1};let a=[];for(let r in e.controlPoints){if(n[r].controlVectorX){let i=n[r].throughPointX,s=e.controlPoints[r];s.tree&&(s=s.tree);let o=me$3.fromAst(["+",s,["-",i.tree]]);a.push({setDependency:t[r].controlVectorX,desiredValue:o})}}return{success:!0,instructions:a}}},t.numericalControlPoints={isArray:!0,entryPrefixes:["numericalControlPoint"],forRenderer:!0,nDimensions:2,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=n.split(",").map((e=>Number(e))),r=e.map((e=>e+1)),a=r.join("_");t[n]={controlPoint:{dependencyType:"stateVariable",variableName:"controlPoint"+a}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].controlPoint.map((e=>e.tree));n[r]=t}return{setValue:{numericalControlPoints:n}}}},t.splineCoeffs={isArray:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints-1],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1,r=e+1;t[n]={previousPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+e},nextPoint:{dependencyType:"stateVariable",variableName:"numericalThroughPoint"+r},previousVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+e+"_2"},nextVector:{dependencyType:"stateVariable",variableName:"numericalControlVector"+r+"_1"}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].previousPoint,a=e[r].nextPoint,i=e[r].previousVector,s=e[r].nextVector,o=[];for(let e=0;e<2;e++)o.push(initCubicPoly(t[e],a[e],3*i[e],-3*s[e]));n[r]=o}return{setValue:{splineCoeffs:n}}}},t.extrapolateBackwardCoeffs={stateVariablesDeterminingDependencies:["extrapolateBackward"],additionalStateVariablesDefined:[{variableName:"extrapolateBackwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateBackward&&(t.firstSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs1"},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateBackward||!e.firstSplineCoeffs)return{setValue:{extrapolateBackwardCoeffs:null,extrapolateBackwardMode:""}};let t=e.firstSplineCoeffs[0],n=e.firstSplineCoeffs[1],r=t[0],a=t[1],i=2*t[2],s=n[0],o=n[1],l=a*a+o*o,u=(o*i-a*(2*n[2]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateBackwardCoeffs:[[r,t,0],[s,n,0]],extrapolateBackwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a>0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateBackwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateBackwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateBackwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateBackwardMode:"parabolaHorizontal"}}}}},t.extrapolateForwardCoeffs={stateVariablesDeterminingDependencies:["nThroughPoints","extrapolateForward"],additionalStateVariablesDefined:[{variableName:"extrapolateForwardMode",public:!0,shadowingInstructions:{createComponentOfType:"text"}}],returnDependencies({stateValues:e}){let t={extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}};return e.extrapolateForward&&e.nThroughPoints>=2&&(t.lastSplineCoeffs={dependencyType:"stateVariable",variableName:"splineCoeffs"+(e.nThroughPoints-1)},t.graphXmin={dependencyType:"stateVariable",variableName:"graphXmin"},t.graphXmax={dependencyType:"stateVariable",variableName:"graphXmax"},t.graphYmin={dependencyType:"stateVariable",variableName:"graphYmin"},t.graphYmax={dependencyType:"stateVariable",variableName:"graphYmax"}),t},definition({dependencyValues:e}){if(!e.extrapolateForward||!e.lastSplineCoeffs)return{setValue:{extrapolateForwardCoeffs:null,extrapolateForwardMode:""}};let t=e.lastSplineCoeffs[0],n=e.lastSplineCoeffs[1],r=t[0]+t[1]+t[2]+t[3],a=t[1]+2*t[2]+3*t[3],i=2*t[2]+6*t[3],s=n[0]+n[1]+n[2]+n[3],o=n[1]+2*n[2]+3*n[3],l=a*a+o*o,u=(o*i-a*(2*n[2]+6*n[3]))/(l*l);if(Math.abs(u)<1e-12||Math.abs(a)<1e-12||Math.abs(o)<1e-12){let t=a,n=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,i=e.nThroughPoints-1,s=r/i/Math.abs(t),o=a/i/Math.abs(n),l=Math.min(s,o);l>1&&(t*=l,n*=l)}return{setValue:{extrapolateForwardCoeffs:[[r,t,0],[s,n,0]],extrapolateForwardMode:"line"}}}let c=o*u,p=-a*u;if(c*a<0){let t=c/p,n=(1+t*t)**2,i=a;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,a=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=r/s,l=1/0;if(0!==p){let e=p*n/2*s*s,r=-t*s,i=Math.sqrt(r*r+4*Math.abs(e)*a);l=(Math.abs(r)+i)/(2*Math.abs(e))}let u=Math.min(o,l);u>Math.abs(i)&&(i*=u/Math.abs(i))}return{setValue:{extrapolateForwardCoeffs:[[r,i,0],[s,-i*t,p*i*i*n/2]],extrapolateForwardMode:"parabolaVertical"}}}{let t=p/c,n=(1+t*t)**2,a=o;if(null!==e.graphXmin&&null!==e.graphXmax&&null!==e.graphYmin&&null!==e.graphYmax){let r=e.graphXmax-e.graphXmin,i=e.graphYmax-e.graphYmin,s=e.nThroughPoints-1,o=i/s,l=1/0;if(0!==c){let e=c*n/2*s*s,a=-t*s,i=Math.sqrt(a*a+4*Math.abs(e)*r);l=(Math.abs(a)+i)/(2*Math.abs(e))}let u=Math.min(l,o);u>Math.abs(a)&&(a*=u/Math.abs(a))}return{setValue:{extrapolateForwardCoeffs:[[r,-a*t,c*a*a*n/2],[s,a,0]],extrapolateForwardMode:"parabolaHorizontal"}}}}},t.fs={isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0,entryPrefixes:["fDefinition"]}],public:!0,shadowingInstructions:{createComponentOfType:"function",addStateVariablesShadowingStateVariables:{fDefinitions:{stateVariableToShadow:"fDefinitions"},domain:{stateVariableToShadow:"domainForFunctions"}}},returnArraySizeDependencies:()=>({functionChildren:{dependencyType:"child",childGroups:["functions"]},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),returnArraySize:({dependencyValues:e})=>"bezier"===e.curveType?[2]:[Math.max(1,e.functionChildren.length)],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["numericalf","fDefinition"],childIndices:[n]}},0===Number(n)&&(t[n].fShadow={dependencyType:"stateVariable",variableName:"fShadow"},t[n].fDefinitionAdapted={dependencyType:"adapterSourceStateVariable",variableName:"fDefinition"});return{globalDependencies:{curveType:{dependencyType:"stateVariable",variableName:"curveType"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},extrapolateBackward:{dependencyType:"stateVariable",variableName:"extrapolateBackward"},extrapolateBackwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateBackwardCoeffs"},extrapolateForward:{dependencyType:"stateVariable",variableName:"extrapolateForward"},extrapolateForwardCoeffs:{dependencyType:"stateVariable",variableName:"extrapolateForwardCoeffs"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if("bezier"===e.curveType){let t={functionType:"bezier",nThroughPoints:e.nThroughPoints,numericalThroughPoints:e.numericalThroughPoints,splineCoeffs:e.splineCoeffs,extrapolateForward:e.extrapolateForward,extrapolateForwardCoeffs:e.extrapolateForwardCoeffs,extrapolateBackward:e.extrapolateBackward,extrapolateBackwardCoeffs:e.extrapolateBackwardCoeffs},n={},r={};return t.component=0,n[0]=returnBezierFunctions(t),r[0]=t,t={...t},t.component=1,n[1]=returnBezierFunctions(t),r[1]=t,{setValue:{fs:n,fDefinitions:r}}}let r={},a={};for(let e of n){let n=t[e].functionChild;1===n.length?(r[e]=n[0].stateValues.numericalf,a[e]=n[0].stateValues.fDefinition):0===Number(e)&&t[e].fShadow?(r[e]=t[e].fShadow,a[e]=t[e].fDefinitionAdapted):(r[e]=()=>0,a[e]={functionType:"zero"})}return{setValue:{fs:r,fDefinitions:a}}}},t.f={isAlias:!0,targetVariableName:"f1"},t.allXCriticalPoints={returnDependencies:()=>({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allXCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[0],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allXCriticalPoints:t}}}},t.nXCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nXCriticalPoints:e.allXCriticalPoints.length}})},t.xCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"xCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["xCriticalPointX","xCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("xCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("xCriticalPoints"===t)return 1===e.length?"xCriticalPoint"+e[0]:`xCriticalPointX${e[0]}_${e[1]}`;if("xCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`xCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nXCriticalPoints:{dependencyType:"stateVariable",variableName:"nXCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nXCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allXCriticalPoints:{dependencyType:"stateVariable",variableName:"allXCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allYCriticalPoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let e=n[1],r=3*e[3],s=2*e[2],o=e[1];if(Math.abs(r)<1e-14){i=addTimePointBezier({t:-o/s,ind:t,ts:a,ignoreLeft:i})}else{let e=s*s-4*r*o;if(0==e){i=addTimePointBezier({t:-s/(2*r),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),o=[(-s-n)/(2*r),(-s+n)/(2*r)];r<0&&(o=[o[1],o[0]]);let l=!1;for(let e of o){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(l=!0)}i=l}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allYCriticalPoints:t}}}},t.nYCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}),definition:({dependencyValues:e})=>({setValue:{nYCriticalPoints:e.allYCriticalPoints.length}})},t.yCriticalPoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"yCriticalPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["yCriticalPointX","yCriticalPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("yCriticalPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("yCriticalPoints"===t)return 1===e.length?"yCriticalPoint"+e[0]:`yCriticalPointX${e[0]}_${e[1]}`;if("yCriticalPoint"===t.slice(0,14)){let n=Number(t.slice(14));if(Number.isInteger(n)&&n>0)return`yCriticalPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nYCriticalPoints:{dependencyType:"stateVariable",variableName:"nYCriticalPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nYCriticalPoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allYCriticalPoints:{dependencyType:"stateVariable",variableName:"allYCriticalPoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({splineCoeffs:{dependencyType:"stateVariable",variableName:"splineCoeffs"},fs:{dependencyType:"stateVariable",variableName:"fs"},curveType:{dependencyType:"stateVariable",variableName:"curveType"}}),definition({dependencyValues:e}){let t=[];if("bezier"!==e.curveType)return{setValue:{allCurvatureChangePoints:t}};let n=e.fs[0],r=e.fs[1],a=[],i=!1;for(let[t,n]of e.splineCoeffs.entries()){let[e,r,s,o]=n[0],[l,u,c,p]=n[1],d=3*(s*p-c*o),m=3*(r*p-u*o),h=r*c-u*s;if(Math.abs(d)<1e-14){i=addTimePointBezier({t:-h/m,ind:t,ts:a,ignoreLeft:i})}else{let e=m*m-4*d*h;if(0==e){i=addTimePointBezier({t:-m/(2*d),ind:t,ts:a,ignoreLeft:i})}else if(e>0){let n=Math.sqrt(e),r=[(-m-n)/(2*d),(-m+n)/(2*d)];d<0&&(r=[r[1],r[0]]);let s=!1;for(let e of r){addTimePointBezier({t:e,ind:t,ts:a,ignoreLeft:i})&&(s=!0)}i=s}else i=!1}}for(let e of a)t.push([n(e),r(e)]);return{setValue:{allCurvatureChangePoints:t}}}},t.nCurvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}),definition:({dependencyValues:e})=>({setValue:{nCurvatureChangePoints:e.allCurvatureChangePoints.length}})},t.curvatureChangePoints={public:!0,shadowingInstructions:{createComponentOfType:"number",returnWrappingComponents:e=>"curvatureChangePointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["curvatureChangePointX","curvatureChangePoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("curvatureChangePointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("curvatureChangePoints"===t)return 1===e.length?"curvatureChangePoint"+e[0]:`curvatureChangePointX${e[0]}_${e[1]}`;if("curvatureChangePoint"===t.slice(0,20)){let n=Number(t.slice(20));if(Number.isInteger(n)&&n>0)return`curvatureChangePointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"nCurvatureChangePoints"}}),returnArraySize:({dependencyValues:e})=>[e.nCurvatureChangePoints,2],returnArrayDependenciesByKey:()=>({globalDependencies:{allCurvatureChangePoints:{dependencyType:"stateVariable",variableName:"allCurvatureChangePoints"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({nearestPointAsCurvePrelim:{dependencyType:"stateVariable",variableName:"nearestPointAsCurvePrelim"},functionChild:{dependencyType:"child",childGroups:["functions"],variableNames:["nearestPointAsCurve"]},adapterSourceValue:{dependencyType:"adapterSourceStateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.nearestPointAsCurvePrelim;return t.nearestPointAsCurvePrelim&&(e.functionChild.length>0?n=e.functionChild[0].stateValues.nearestPointAsCurve:null!==e.adapterSourceValue&&(n=e.adapterSourceValue)),{setValue:{nearestPointAsCurve:n}}}},t.nearestPoint={returnDependencies:()=>({curveType:{dependencyType:"stateVariable",variableName:"curveType"},fs:{dependencyType:"stateVariable",variableName:"fs"},flipFunction:{dependencyType:"stateVariable",variableName:"flipFunction"},nDiscretizationPoints:{dependencyType:"stateVariable",variableName:"nDiscretizationPoints"},parMin:{dependencyType:"stateVariable",variableName:"parMin"},parMax:{dependencyType:"stateVariable",variableName:"parMax"},periodic:{dependencyType:"stateVariable",variableName:"periodic"},graphXmin:{dependencyType:"stateVariable",variableName:"graphXmin"},graphXmax:{dependencyType:"stateVariable",variableName:"graphXmax"},graphYmin:{dependencyType:"stateVariable",variableName:"graphYmin"},graphYmax:{dependencyType:"stateVariable",variableName:"graphYmax"},nearestPointAsCurve:{dependencyType:"stateVariable",variableName:"nearestPointAsCurve"}}),definition({dependencyValues:t}){let n=null;return"function"===t.curveType?n=getNearestPointFunctionCurve({dependencyValues:t,numerics:e}):["parameterization","bezier"].includes(t.curveType)&&(n=getNearestPointParametrizedCurve({dependencyValues:t,numerics:e})),{setValue:{nearestPoint:n}}}},t}async moveControlVector({controlVector:e,controlVectorInds:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"controlVectors",value:a,sourceInformation:{controlVectorMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["controlVector"+t.join("_")]:e}}})}async moveThroughPoint({throughPoint:e,throughPointInd:t,transient:n,actionId:r}){let a={[t+",0"]:me$3.fromAst(e[0]),[t+",1"]:me$3.fromAst(e[1])};return n?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],transient:n,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"throughPoints",value:a,sourceInformation:{throughPointMoved:t}}],actionId:r,event:{verb:"interacted",object:{componentId:this.componentName},result:{["throughPoint"+t]:e}}})}async changeVectorControlDirection({direction:e,throughPointInd:t,actionId:n}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"vectorControlDirection",value:{[t]:e}}],actionId:n})}switchCurve(){}async curveClicked({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnCurve({actionId:e,name:t}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:t}),this.coreFunctions.resolveAction({actionId:e})}}function getNearestPointFunctionCurve({dependencyValues:e,numerics:t}){let n=e.flipFunction,r=e.fs[0],a=e.nDiscretizationPoints,i=e.parMax,s=e.parMin;return function({variables:o,scales:l}){let u,c,p,d,m=o.x1?.evaluate_to_constant(),h=o.x2?.evaluate_to_constant(),f=l[0],y=l[1];if(s!==-1/0){if(u=s,c=r(s),!Number.isFinite(c)){let e=.99999*s+1e-5*i,t=r(e);Number.isFinite(t)&&(u=e,c=t)}if(n){let e=u;u=c,c=e}}if(i!==1/0){if(p=i,d=r(i),!Number.isFinite(d)){let e=1e-5*s+.99999*i,t=r(e);Number.isFinite(t)&&(p=e,d=t)}if(n){let e=p;p=d,d=e}}if(!e.nearestPointAsCurve||!Number.isFinite(m)||!Number.isFinite(h)){let e,t;if(n?(t=h,e=r(t)):(e=m,t=r(e)),!Number.isFinite(e)||!Number.isFinite(t)){let r,a;n?(r=Math.abs(s-h),a=Math.abs(i-h)):(r=Math.abs(s-m),a=Math.abs(i-m)),re.evaluate_to_constant())),a)l=a.map((e=>e.evaluate_to_constant())),s=n?n.map((e=>e.evaluate_to_constant())):[2*o[0]-l[0],2*o[1]-l[1]];else{if(!n)return{coordsNumeric:[me$3.fromAst(NaN),me$3.fromAst(NaN)],numericEntries:!1};s=n.map((e=>e.evaluate_to_constant())),l=[2*o[0]-s[0],2*o[1]-s[1]]}let c=[];if("centripetal"===i){let n=u(s,o),r=u(o,l);n=Math.sqrt(n),r=Math.sqrt(r),rme$3.fromAst(e)));return{coordsNumeric:p,numericEntries:Number.isFinite(c[0])&&Number.isFinite(c[1])}}function initCubicPoly(e,t,n,r){return[e,n,-3*e+3*t-2*n-r,2*e-2*t+n+r]}function addTimePointBezier({t:e,ind:t,ts:n,ignoreLeft:r=!1}){const a=1e-14;let i=!1;return e>=a?e<=.99999999999999?n.push(t+e):e<1.00000000000001&&(n.push(t+1),i=!0):e>-a&&!r&&n.push(t),i}class EquilibriumCurve extends Curve{static componentType="equilibriumCurve";static rendererType="curve";static createAttributesObject(){let e=super.createAttributesObject();return e.stable={createComponentOfType:"boolean",createStateVariable:"stable",defaultValue:!0,public:!0},e.switchable={createComponentOfType:"boolean",createStateVariable:"switchable",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions({numerics:e}){let t=super.returnStateVariableDefinitions({numerics:e});return t.dashed={forRenderer:!0,returnDependencies:()=>({stable:{dependencyType:"stateVariable",variableName:"stable"}}),definition:({dependencyValues:e})=>({setValue:{dashed:!e.stable}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"stable",desiredValue:!e.dashed}]})},t}async switchCurve({actionId:e}){if(await this.stateValues.switchable)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"stable",value:!this.stateValues.stable}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{stable:!this.stateValues.stable}}});this.coreFunctions.resolveAction({actionId:e})}}var DynamicalSystems=Object.freeze({__proto__:null,ODESystem:ODESystem,CobwebPolyline:CobwebPolyline,EquilibriumPoint:EquilibriumPoint,EquilibriumLine:EquilibriumLine,EquilibriumCurve:EquilibriumCurve});class Atom extends InlineComponent{static componentType="atom";static rendererType="math";static primaryStateVariableForDefinition="atomicNumberShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.atomicNumberShadow={defaultValue:null,hasEssential:!0,essentialVarName:"atomicNumber",returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Name:null,{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.atomicMass={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Mass"]:null,{setValue:{atomicMass:t}}}},e.phaseAtSTP={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Phase at STP"]:null,{setValue:{phaseAtSTP:t}}}},e.chargeOfCommonIon={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Charge of Common Ion"]:null,{setValue:{chargeOfCommonIon:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.ionizationEnergy={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Ionization Energy"]:null,{setValue:{ionizationEnergy:t}}}},e.meltingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Melting Point"]:null,{setValue:{meltingPoint:t}}}},e.boilingPoint={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Boiling Point"]:null,{setValue:{boilingPoint:t}}}},e.atomicRadius={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Radius"]:null,{setValue:{atomicRadius:t}}}},e.density={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Density:null,{setValue:{density:t}}}},e.electronegativity={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Electronegativity:null,{setValue:{electronegativity:t}}}},e.electronConfiguration={public:!0,shadowingInstructions:{createComponentOfType:"electronConfiguration"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Electron Configuration"]:null,{setValue:{electronConfiguration:t}}}},e.orbitalDiagram={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({electronConfiguration:{dependencyType:"stateVariable",variableName:"electronConfiguration"}}),definition({dependencyValues:e}){let t;return t=e.electronConfiguration?electronConfigurationToOrbitalDiagram(e.electronConfiguration):null,{setValue:{orbitalDiagram:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?["^",e.symbol]:"_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"}}),definition({dependencyValues:e}){let t;return t=e.symbol?`\\text{${e.symbol}}`:"[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name",{stateVariable:"atomicNumber",componentType:"ion"}]}function electronConfigurationToOrbitalDiagram(e){let t=e.tree;if(!Array.isArray(t)||"*"!==t[0])return null;t=t.slice(1);let n=t.length/2;if(!Number.isInteger(n))return null;let r=[];for(let e=0;e0))return null;let a=t[2*e+1];if(!Array.isArray(a)||"^"!==a[0])return null;let i=a[1],s=a[2];if(!(["s","p","d","f"].includes(i)&&Number.isInteger(s)&&s>0))return null;let o,l=`${n}${i}`;o="s"===i?1:"p"===i?3:"d"===i?5:7;let u=Array(o).fill("");for(let e=0;e({}),definition:()=>({useEssentialOrDefaultValue:{atomicNumberShadow:!0}}),inverseDefinition:async function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"atomicNumberShadow",value:e.atomicNumberShadow}]}}},e.dataForAtom={returnDependencies:()=>({fileContents:{dependencyType:"file",cid:"bafkreibilal4glrbpo7p7oodtwtnzkfhiylfoqa2td4ij6h6iqva57kzcy",fileType:"csv"},symbolAttr:{dependencyType:"attributeComponent",attributeName:"symbol",variableNames:["value"]},atomicNumberAttr:{dependencyType:"attributeComponent",attributeName:"atomicNumber",variableNames:["value"]},atomChild:{dependencyType:"child",childGroups:["atoms"],variableNames:["atomicNumber"]},atomicNumberShadow:{dependencyType:"stateVariable",variableName:"atomicNumberShadow"}}),definition:function({dependencyValues:e}){let t=null,n=null;if(e.atomChild.length>0)n=e.atomChild[0].stateValues.atomicNumber;else if(e.symbolAttr)t=e.symbolAttr.stateValues.value.toLowerCase();else if(e.atomicNumberAttr)n=e.atomicNumberAttr.stateValues.value;else{if(!e.atomicNumberShadow)return{setValue:{dataForAtom:null}};n=e.atomicNumberShadow}let r,a=e.fileContents.trim().split("\n");r=null!==n?n-1:["h","he","li","be","b","c","n","o","f","ne","na","mg","al","si","p","s","cl","ar","k","ca","sc","ti","v","cr","mn","fe","co","ni","cu","zn","ga","ge","as","se","br","kr","rb","sr","y","zr","nb","mo","tc","ru","rh","pd","ag","cd","in","sn","sb","te","i","xe","cs","ba","la","ce","pr","nd","pm","sm","eu","gd","tb","dy","ho","er","tm","yb","lu","hf","ta","w","re","os","ir","pt","au","hg","tl","pb","bi","po","at","rn","fr","ra","ac","th","pa","u","np","pu","am","cm","bk","cf","es","fm","md","no","lr","rf","db","sg","bh","hs","mt","ds","rg","cn","nh","fl","mc","lv","ts","og"].indexOf(t?.toLowerCase());let i=a.slice(1)[r];if(!i)return{setValue:{dataForAtom:null}};i=i.trim().split(",").map((e=>e.trim()));let s=a[0].trim().split(",").map((e=>e.trim())).map((e=>(['"',"'"].includes(e[0])&&e[e.length-1]===e[0]&&(e=e.substring(1,e.length-1).trim()),e))),o=s.length,l=["number","string","string","number","number","string","number","string","string","number","number","number","number","number","number","number","string"],u={};for(let e=0;e({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Atomic Number"]:null,{setValue:{atomicNumber:t}}}},e.symbol={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Symbol:null,{setValue:{symbol:t}}}},e.charge={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},chargeAttr:{dependencyType:"attributeComponent",attributeName:"charge",variableNames:["value"]}}),definition({dependencyValues:e}){let t;return e.chargeAttr?(t=e.chargeAttr.stateValues.value,Number.isFinite(t)||(t=0)):t=e.dataForAtom&&e.dataForAtom["Charge of Common Ion"]||0,{setValue:{charge:t}}}},e.name={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"},charge:{dependencyType:"stateVariable",variableName:"charge"},group:{dependencyType:"stateVariable",variableName:"group"},atomicNumber:{dependencyType:"stateVariable",variableName:"atomicNumber"}}),definition({dependencyValues:e}){let t;if(e.dataForAtom){if(t=e.dataForAtom.Name,e.charge<0){let e={Hydrogen:"Hydride",Oxygen:"Oxide",Sulfur:"Sulfide",Nitrogen:"Nitride",Phosphorus:"Phosphide",Carbon:"Carbide"},n=t.length;"ine"===t.substring(n-3,n)?t=t.substring(0,n-3)+"ide":t in e&&(t=e[t])}else if(e.charge>0&&(e.group>=3&&e.group<=12||101===e.group||102===e.group||[13,31,49,50,81,82,83,84].includes(e.atomicNumber))){let n="";switch(e.charge){case 1:n=" (I)";break;case 2:n=" (II)";break;case 3:n=" (III)";break;case 4:n=" (IV)";break;case 5:n=" (V)";break;case 6:n=" (VI)";break;case 7:n=" (VII)";break;case 8:n=" (VIII)"}t+=n}}else t=null;return{setValue:{name:t}}}},e.group={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Group:null,{setValue:{group:t}}}},e.metalCategory={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Metal/Nonmetal/Metalloid"]:null,{setValue:{metalCategory:t}}}},e.groupName={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom["Group Name"]:null,{setValue:{groupName:t}}}},e.period={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({dataForAtom:{dependencyType:"stateVariable",variableName:"dataForAtom"}}),definition({dependencyValues:e}){let t;return t=e.dataForAtom?e.dataForAtom.Period:null,{setValue:{period:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=["^",e.symbol],-1===e.charge?t.push("-"):1===e.charge?t.push("+"):e.charge<0?t.push(Math.abs(e.charge)+"-"):e.charge>0&&t.push(Math.abs(e.charge)+"+")):t="_",{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({symbol:{dependencyType:"stateVariable",variableName:"symbol"},charge:{dependencyType:"stateVariable",variableName:"charge"}}),definition({dependencyValues:e}){let t;return e.symbol?(t=`\\text{${e.symbol}}`,-1===e.charge?t+="^-":1===e.charge?t+="^+":e.charge<0?t+=`^{${Math.abs(e.charge)}-}`:e.charge>0&&(t+=`^{${Math.abs(e.charge)}+}`)):t="[\\text{Invalid Chemical Symbol}]",{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math","name"]}class IonicCompound extends InlineComponent{static componentType="ionicCompound";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return e.symbol={createComponentOfType:"text"},e.atomicNumber={createComponentOfType:"integer"},e.charge={createComponentOfType:"integer"},e}static returnChildGroups(){return[{group:"ions",componentTypes:["ion"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.ionicCompound={returnDependencies:()=>({ionChildren:{dependencyType:"child",childGroups:["ions"],variableNames:["symbol","charge","atomicNumber","name"]}}),definition({dependencyValues:e}){let t=e.ionChildren.map((e=>e.stateValues.charge));if(2!==t.length)return console.warn("have not implemented ionic compound for anything other than two ions"),{setValue:{ionicCompound:null}};if(!(t[0]*t[1]<0))return console.warn("ionic compound implemented only for one cation and one anion"),{setValue:{ionicCompound:null}};let n=Math.abs(t[1]),r=Math.abs(t[0]),a=me$3.math.gcd(n,r);return n/=a,r/=a,{setValue:{ionicCompound:[{symbol:e.ionChildren[0].stateValues.symbol,atomicNumber:e.ionChildren[0].stateValues.atomicNumber,name:e.ionChildren[0].stateValues.name,charge:t[0],count:n},{symbol:e.ionChildren[1].stateValues.symbol,atomicNumber:e.ionChildren[1].stateValues.atomicNumber,name:e.ionChildren[1].stateValues.name,charge:t[1],count:r}]}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t=[];for(let n of e.ionicCompound){let e=n.symbol;n.count>1&&(e=["_",e,n.count]),t.push(e)}t=t.length>1?["*",...t]:1===t.length?t[0]:"_"}else t="_";return{setValue:{math:me$3.fromAst(t)}}}},e.latex={additionalStateVariablesDefined:[{variableName:"latexWithInputChildren",forRenderer:!0}],returnDependencies:()=>({ionicCompound:{dependencyType:"stateVariable",variableName:"ionicCompound"}}),definition({dependencyValues:e}){let t;if(e.ionicCompound){t="";for(let n of e.ionicCompound)t+=`\\text{${n.symbol}}`,n.count>1&&(t+=`_{${n.count}}`)}else t="[\\text{Invalid Ionic Compound}]";return{setValue:{latex:t,latexWithInputChildren:[t]}}}},e}static adapters=["math"]}class ElectronConfiguration extends MathComponent{static componentType="electronConfiguration";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;try{n=e.valueForDisplay.toLatex()}catch(e){n="_"}return n=n.replaceAll("\\,",""),n=n.replaceAll("\\cdot","~"),{setValue:{latex:n}}}},e}}class OrbitalDiagram extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagram";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.labels={createComponentOfType:"textList",createStateVariable:"labels",defaultValue:[]},e}static returnSugarInstructions(){return[{replacementFunction:function({matchedChildren:e}){return 1===e.length&&"string"!=typeof e[0]?{success:!1}:{success:!0,newChildren:[{componentType:"tupleList",children:e}]}}}]}static returnChildGroups(){return[{group:"tupleLists",componentTypes:["tupleList"]},{group:"orbitalDiagrams",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({orbitalDiagramChildren:{dependencyType:"child",childGroups:["orbitalDiagrams"],variableNames:["value"]},tupleListChildren:{dependencyType:"child",childGroups:["tupleLists"],variableNames:["maths"]},labels:{dependencyType:"stateVariable",variableName:"labels"}}),definition:function({dependencyValues:e}){return{setValue:{value:function(){function t(e){if("u"===e||"U"===e)return"U";if("d"===e||"D"===e)return"D";if("e"===e||"E"===e)return"";if(Array.isArray(e)&&"*"===e[0]){let t="";for(let n of e.slice(1))if("u"===n||"U"===n)t+="U";else{if("d"!==n&&"D"!==n)return"";t+="D"}return t}return""}if(1===e.orbitalDiagramChildren.length)return e.orbitalDiagramChildren[0].stateValues.value;let n=[];if(e.tupleListChildren[0]?.stateValues.maths.length>0){let r=e.tupleListChildren[0].stateValues.maths;for(let[a,i]of r.entries()){let r="";e.labels[a]&&(r=e.labels[a]);let s=[];if(Array.isArray(i.tree)&&"tuple"===i.tree[0])for(let e of i.tree.slice(1))s.push(t(e));else s.push(t(i.tree));n.push({orbitalText:r,boxes:s})}return n}return[{orbitalText:"",boxes:[]}]}()}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class OrbitalDiagramInput extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{addRow:this.addRow.bind(this),removeRow:this.removeRow.bind(this),addBox:this.addBox.bind(this),removeBox:this.removeBox.bind(this),addUpArrow:this.addUpArrow.bind(this),addDownArrow:this.addDownArrow.bind(this),removeArrow:this.removeArrow.bind(this),updateRowText:this.updateRowText.bind(this),selectRow:this.selectRow.bind(this),selectBox:this.selectBox.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="orbitalDiagramInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"orbitalDiagram",createStateVariable:"prefill",defaultValue:[]},e.prefillLabel={createComponentOfType:"textList",createStateVariable:"prefillLabel",defaultValue:[]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={defaultValue:[{orbitalText:"",boxes:[]}],hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},returnDependencies:()=>({prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLabel:{dependencyType:"stateVariable",variableName:"prefillLabel"}}),definition:function({dependencyValues:e}){return{useEssentialOrDefaultValue:{value:{get defaultValue(){return function(){if(e.prefill?.length>0){let t=JSON.parse(JSON.stringify(e.prefill));for(let[n,r]of t.entries())e.prefillLabel[n]&&(r.orbitalText=e.prefillLabel[n]);return t}return[{orbitalText:"",boxes:[]}]}()}}}}},inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"value",value:e.value}]})},e.rows={public:!0,shadowingInstructions:{createComponentOfType:"orbitalDiagram"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{rows:[...e.value].reverse()}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setDependency:"value",desiredValue:[...e.rows].reverse()}]})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({rows:{dependencyType:"stateVariable",variableName:"rows"}}),definition:function({dependencyValues:e}){return{setValue:{numRows:e.rows.length}}}},e.selectedRowIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedRowIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=await t.numRows,r=e.selectedRowIndex;return r=Number.isFinite(r)?Math.min(n,Math.max(0,Math.round(r))):0,{success:!0,instructions:[{setEssentialValue:"selectedRowIndex",value:r}]}}},e.selectedBoxIndex={defaultValue:0,hasEssential:!0,forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({}),definition:function(){return{useEssentialOrDefaultValue:{selectedBoxIndex:!0}}},async inverseDefinition({desiredStateVariableValues:e}){let t=e.selectedBoxIndex;return t=Number.isFinite(t)?Math.max(0,Math.round(t)):0,{success:!0,instructions:[{setEssentialValue:"selectedBoxIndex",value:t}]}}},e}async addRow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t));t.length<20&&(n=[{orbitalText:"",boxes:[]},...t]);let r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==await this.stateValues.selectedRowIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0}),-1!==await this.stateValues.selectedBoxIndex-1&&r.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:r,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeRow({actionId:e}){let t=await this.stateValues.rows,n=await this.stateValues.selectedRowIndex-1,r=JSON.parse(JSON.stringify(t));if(t.length>1){let e=t.length-1-n;-1===n&&(e=0),r.splice(e,1)}return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}],actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async addBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0),n[a].boxes.length<17&&n[a].boxes.push("");let i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];if(-1!==r){let e=0;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e})}return await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeBox({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.splice(s,1);let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return-1!==i&&o.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:0}),await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addUpArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"U");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async addDownArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length<3&&(n[a].boxes[s]=n[a].boxes[s]+"D");let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async removeArrow({actionId:e}){let t=await this.stateValues.rows,n=JSON.parse(JSON.stringify(t)),r=await this.stateValues.selectedRowIndex-1,a=t.length-r-1;-1===r&&(a=0);let i=await this.stateValues.selectedBoxIndex-1,s=i;-1===i&&(s=n[a].boxes.length-1),n[a].boxes.length>0&&n[a].boxes[s].length>0&&(n[a].boxes[s]=n[a].boxes[s].slice(0,-1));let o=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:n}];return await this.coreFunctions.performUpdate({updateInstructions:o,actionId:e,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:n}}})}async updateRowText({newValue:e,actionId:t}){let n=await this.stateValues.rows,r=JSON.parse(JSON.stringify(n)),a=await this.stateValues.selectedRowIndex-1,i=n.length-a-1;-1===a&&(i=0),r[i].orbitalText=e;let s=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rows",value:r}];return await this.coreFunctions.performUpdate({updateInstructions:s,actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{rows:r}}})}async selectRow({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedRowIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedRowIndex:e}}})}async selectBox({index:e,actionId:t}){return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"selectedBoxIndex",value:e}],actionId:t,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{selectedBoxIndex:e}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Chemistry=Object.freeze({__proto__:null,Atom:Atom,Ion:Ion,IonicCompound:IonicCompound,ElectronConfiguration:ElectronConfiguration,OrbitalDiagram:OrbitalDiagram,OrbitalDiagramInput:OrbitalDiagramInput});class FeedbackDefinition extends BaseComponent{static componentType="feedbackDefinition";static createAttributesObject(){let e=super.createAttributesObject();return e.code={createComponentOfType:"text"},e.text={createComponentOfType:"text"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.feedbackDefinition={returnDependencies:()=>({codeAttr:{dependencyType:"attributeComponent",attributeName:"code",variableNames:["value"]},textAttr:{dependencyType:"attributeComponent",attributeName:"text",variableNames:["value"]}}),definition({dependencyValues:e}){if(null!==e.codeAttr&&null!==e.textAttr){return{setValue:{feedbackDefinition:{[e.codeAttr.stateValues.value.toLowerCase()]:e.textAttr.stateValues.value}}}}return{setValue:{feedbackDefinition:null}}}},e}}class FeedbackDefinitions extends BaseComponent{static componentType="feedbackDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"feedbackDefinition",componentTypes:["feedbackDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({feedbackDefinitionChildren:{dependencyType:"child",childGroups:["feedbackDefinition"],variableNames:["feedbackDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.feedbackDefinitionChildren)n.stateValues.feedbackDefinition&&Object.assign(t,n.stateValues.feedbackDefinition);return{setValue:{value:t}}}},e}}var FeedbackDefinitions$1=Object.freeze({__proto__:null,FeedbackDefinition:FeedbackDefinition,FeedbackDefinitions:FeedbackDefinitions});class StyleDefinition extends BaseComponent{static componentType="styleDefinition";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();e.styleNumber={createPrimitiveOfType:"number",createStateVariable:"styleNumber",defaultValue:1};for(let t in styleAttributes)e[t]={createComponentOfType:styleAttributes[t].componentType};return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDefinition={returnDependencies:function(){let e={};for(let t in styleAttributes)e[t]={dependencyType:"attributeComponent",attributeName:t,variableNames:["value"]};return e},definition:function({dependencyValues:e}){let t={};for(let n in styleAttributes)null!==e[n]&&(t[n]=e[n].stateValues.value,"string"==typeof t[n]&&(t[n]=t[n].toLowerCase()));return{setValue:{styleDefinition:t}}}},e}}class StyleDefinitions extends BaseComponent{static componentType="styleDefinitions";static rendererType=void 0;static returnChildGroups(){return[{group:"styleDefinition",componentTypes:["styleDefinition"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({styleDefinitionChildren:{dependencyType:"child",childGroups:["styleDefinition"],variableNames:["styleNumber","styleDefinition"]}}),definition({dependencyValues:e}){let t={};for(let n of e.styleDefinitionChildren){let e=n.stateValues.styleNumber,r=t[e];r||(r=t[e]={}),Object.assign(r,n.stateValues.styleDefinition)}return{setValue:{value:t}}}},e}}var StyleDefinitions$1=Object.freeze({__proto__:null,StyleDefinition:StyleDefinition,StyleDefinitions:StyleDefinitions});class ComponentWithSelectableType extends BaseComponent{static componentType="_componentWithSelectableType";static rendererType=void 0;static includeBlankStringChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=t.type;r||(r=n.type),r?["number","letters","math","text","boolean"].includes(r)||(console.warn(`Invalid type ${r}, setting type to number`),r="number"):r="number";let a="letters"===r?"text":r;return"text"!==a&&(e=e.filter((e=>"string"!=typeof e||""!==e.trim()))),{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.type={shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"doenetAttribute",attributeName:"type"},parentType:{dependencyType:"parentStateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentName:t}){let n=e.type;return n||(n=e.parentType),n?["number","letters","math","text","boolean"].includes(n)||(console.warn(`Invalid type ${n}, setting type to number`),n="number"):n="number",{setValue:{type:n}}}},e.value={public:!0,shadowingInstructions:{hasVariableComponentType:!0},shadowVariable:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},atMostOneChild:{dependencyType:"child",childGroups:["anything"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;return t=e.atMostOneChild.length>0?e.atMostOneChild[0].stateValues.value:"text"===e.type||"letters"===e.type?"":"boolean"!==e.type&&("number"===e.type?NaN:me$3.fromAst("_")),{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.atMostOneChild.length>0?{success:!0,instructions:[{setDependency:"atMostOneChild",desiredValue:e.value,childIndex:0,variableIndex:0}]}:{success:!1}},e}}class ComponentListWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListWithSelectableType";static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n,isAttributeComponent:r=!1,createdFromMacro:a=!1,componentInfoObjects:i}){let s=t.type;s||(s=n.type),s?["number","letters","math","text","boolean"].includes(s)||(console.warn(`Invalid type ${s}, setting type to number`),s="number"):s="number";let o="letters"===s?"text":s;if(r&&!a){return returnGroupIntoComponentTypeSeparatedBySpaces({componentType:o})({matchedChildren:e})}return returnBreakStringsIntoComponentTypeBySpaces({componentType:o})({matchedChildren:e})}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nValues={additionalStateVariablesDefined:["childForValue"],returnDependencies:()=>({anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["nValues"],variablesOptional:!0}}),definition({dependencyValues:e}){let t=0,n=[];for(let[r,a]of e.anythingForSelectedType.entries()){let e=Number.isInteger(a.stateValues.nValues)?a.stateValues.nValues:1;t+=e;for(let t=0;t({nValues:{dependencyType:"stateVariable",variableName:"nValues"}}),returnArraySize:({dependencyValues:e})=>[e.nValues],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.childForValue[r];n[r]={anythingForSelectedType:{dependencyType:"child",childGroups:["anything"],variableNames:["value","values"],childIndices:[e.child],variablesOptional:!0},valueIndex:{dependencyType:"value",value:e.valueIndex}}}return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,componentName:r}){let a={};for(let r of n)if(t[r].anythingForSelectedType&&1===t[r].anythingForSelectedType.length){let n,i=t[r].anythingForSelectedType[0];n=i.stateValues.values?i.stateValues.values[t[r].valueIndex]:i.stateValues.value,a[r]=convertValueToType(n,e.type)}return{setValue:{values:a},setCreateComponentOfType:{values:e.type}}}},e}}class ComponentListOfListsWithSelectableType extends ComponentWithSelectableType{static componentType="_componentListOfListsWithSelectableType";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string"},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t,parentAttributes:n}){let r=breakEmbeddedStringsIntoParensPieces({componentList:e,removeParens:!0});if(!0!==r.success)return{success:!1};let a=t.type;return a||(a=n.type),a?["number","letters","math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}, setting type to number`),a="number"):a="number",{success:!0,newChildren:r.pieces.map((e=>({componentType:"_componentListWithSelectableType",attributes:{type:{primitive:a}},children:e})))}}}),e}static returnChildGroups(){return[{group:"lists",componentTypes:["_componentListWithSelectableType"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return delete e.value,e.nLists={returnDependencies:()=>({listChildren:{dependencyType:"child",childGroups:["lists"]}}),definition:({dependencyValues:e})=>({setValue:{nLists:e.listChildren.length}})},e.lists={isArray:!0,entryPrefixes:["list"],returnArraySizeDependencies:()=>({nLists:{dependencyType:"stateVariable",variableName:"nLists"}}),returnArraySize:({dependencyValues:e})=>[e.nLists],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={listChildren:{dependencyType:"child",childGroups:["lists"],variableNames:["values","type"],childIndices:[n]}};return{globalDependencies:{type:{dependencyType:"stateVariable",variableName:"type"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(t[a].listChildren&&1===t[a].listChildren.length){let n=t[a].listChildren[0];n.stateValues.type===e.type?r[a]=n.stateValues.values:r[a]=n.stateValues.values.map((t=>convertValueToType(t,e.type)))}return{setValue:{lists:r}}}},e}}function convertValueToType(e,t){if(Array.isArray(e)&&(e=e[0]),"number"===t){if(e instanceof me$3.class){let t=e.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),t}return Number(e)}if("math"===t){if("string"==typeof e)try{return me$3.fromAst(textToAst$1.convert(e))}catch(e){}return convertValueToMathExpression(e)}return"boolean"===t?Boolean(e):String(e)}var ComponentWithSelectableType$1=Object.freeze({__proto__:null,ComponentWithSelectableType:ComponentWithSelectableType,ComponentListWithSelectableType:ComponentListWithSelectableType,ComponentListOfListsWithSelectableType:ComponentListOfListsWithSelectableType});class SideBySide extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="sideBySide";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.width={createComponentOfType:"_componentSize"},e.widths={createComponentOfType:"_componentSizeList"},e.margins={createComponentOfType:"_componentSizeList"},e.valign={createComponentOfType:"text"},e.valigns={createComponentOfType:"textList"},e}static returnChildGroups(){return[{group:"blocks",componentTypes:["_block"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPanels={forRenderer:!0,returnDependencies:()=>({blockChildren:{dependencyType:"child",childGroups:["blocks"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nPanels:e.blockChildren.length},checkForActualChange:{nPanels:!0}})},e.essentialWidths={isArray:!0,entryPrefixes:["essentialWidth"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialWidths:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialWidths)t[n]=e.essentialWidths[n];return{success:!0,instructions:[{setEssentialValue:"essentialWidths",value:t}]}}},e.allWidthsSpecified={additionalStateVariablesDefined:["widthsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents","componentSizes"]},parentWidths:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedWidths"},parentWidthsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"widthsAbsolute"},essentialWidth:{dependencyType:"stateVariable",variableName:"essentialWidths"}}),definition({dependencyValues:e}){let t,n=[],r=null,a=!1;null!==e.widthsAttr?t=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(t=e.nPanels,a=!0):t=0;for(let i=0;iNumber.isFinite(e)?e:null)),{setValue:{allWidthsSpecified:n,widthsAbsolute:r}}}},e.essentialMargins={isArray:!0,entryPrefixes:["essentialMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialMargins:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialMargins)t[n]=e.essentialMargins[n];return{success:!0,instructions:[{setEssentialValue:"essentialMargins",value:t}]}}},e.allMarginsSpecified={additionalStateVariablesDefined:["marginsAbsolute"],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["nComponents","componentSizes"]},parentMargins:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"specifiedMargins"},parentMarginsAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:"marginsAbsolute"},essentialMargins:{dependencyType:"stateVariable",variableName:"essentialMargins"}}),definition({dependencyValues:e}){let t=[],n=null;if(null===e.marginsAttr)if(e.parentMargins){n=e.parentMarginsAbsolute;for(let n=0;n<2;n++)null===e.essentialMargins[n]?t[n]=e.parentMargins[n]:t[n]=e.essentialMargins[n]}else for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(0===e.marginsAttr.stateValues.nComponents)for(let n=0;n<2;n++)t[n]=e.essentialMargins[n];else if(1===e.marginsAttr.stateValues.nComponents){let r=null;e.marginsAttr.stateValues.componentSizes[0]&&(r=e.marginsAttr.stateValues.componentSizes[0].size,Number.isFinite(r)||(r=null),n=Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute)),t=[r,r]}else{let r;if(n=!!e.marginsAttr.stateValues.componentSizes[0]&&Boolean(e.marginsAttr.stateValues.componentSizes[0].isAbsolute),r=!!e.marginsAttr.stateValues.componentSizes[1]&&Boolean(e.marginsAttr.stateValues.componentSizes[1].isAbsolute),r!==n)throw Error("SideBySide is not implemented for absolute measurements");t=e.marginsAttr.stateValues.componentSizes.slice(0,2).map((e=>e&&Number.isFinite(e.size)?e.size:null))}return{setValue:{allMarginsSpecified:t,marginsAbsolute:n}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SideBySide is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SideBySide is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0}],returnDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"},allWidthsSpecified:{dependencyType:"stateVariable",variableName:"allWidthsSpecified"},allMarginsSpecified:{dependencyType:"stateVariable",variableName:"allMarginsSpecified"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.allWidthsSpecified],r=[...e.allMarginsSpecified],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.nPanels);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.nPanels>1?t=(100-(a+s))/(e.nPanels-1):1===e.nPanels?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]},essentialWidth:{dependencyType:"stateVariable",variableName:`essentialWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n,globalDependencyValues:r,arraySize:a}){let i,s=!1;null!==r.widthsAttr?i=r.widthsAttr.stateValues.nComponents:null!==r.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.widths){Number(n)({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"},marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}},n={};for(let t of e){let e=Number(t)+1;n[t]={essentialMargin:{dependencyType:"stateVariable",variableName:`essentialMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyNamesByKey:n}){let r=[];if(null===t.marginsAttr)for(let t in e.margins)r.push({setDependency:n[t].essentialMargin,desiredValue:e.margins[t]});else if(t.marginsAttr.stateValues.componentSize1&&Number.isFinite(t.marginsAttr.stateValues.componentSize1.size)){let n=1===t.marginsAttr.stateValues.nComponents;for(let a in e.margins)n?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[a],isAbsolute:t.absoluteMeasurements},variableIndex:a})}else"0"in e.margins?r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[0],isAbsolute:t.absoluteMeasurements},variableIndex:0}):r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:0}),"1"in e.margins&&t.marginsAttr.stateValues.nComponents>1&&r.push({setDependency:"marginsAttr",desiredValue:{size:e.margins[1],isAbsolute:t.absoluteMeasurements},variableIndex:1});return{success:!0,instructions:r}}},e.essentialValigns={isArray:!0,entryPrefixes:["essentialValign"],defaultValueByArrayKey:()=>null,hasEssential:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialValigns:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t={};for(let n in e.essentialValigns)t[n]=e.essentialValigns[n];return{success:!0,instructions:[{setEssentialValue:"essentialValigns",value:t}]}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],forRenderer:!0,returnArraySizeDependencies:()=>({nPanels:{dependencyType:"stateVariable",variableName:"nPanels"}}),returnArraySize:({dependencyValues:e})=>[e.nPanels],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]},parentValign:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valign${e}`},parentValignAbsolute:{dependencyType:"parentStateVariable",parentComponentType:"sbsGroup",variableName:`valignAbsolute${e}`},essentialValign:{dependencyType:"stateVariable",variableName:`essentialValign${e}`}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],s=!0):a=0;for(let r of n){let n=Number(r);if(n({sideBySideChildren:{dependencyType:"child",childGroups:["sideBySides"],variableNames:["nPanels"]}}),definition:({dependencyValues:e})=>({setValue:{maxNPanelsPerRow:me$3.math.max(e.sideBySideChildren.map((e=>e.stateValues.nPanels)))},checkForActualChange:{maxNPanelsPerRow:!0}})},e.specifiedWidths={additionalStateVariablesDefined:[{variableName:"widthsAbsoluteArray",isArray:!0}],isArray:!0,entryPrefixes:["specifiedWidth"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:[`componentSize${e}`]}}}return{globalDependencies:{widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]},widthsAttr:{dependencyType:"attributeComponent",attributeName:"widths",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o={},l=!1;null!==e.widthsAttr?a=e.widthsAttr.stateValues.nComponents:null!==e.widthAttr?(a=r[0],l=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(u.useEssentialOrDefaultValue={specifiedWidths:s}),u},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r,arraySize:a}){let i,s=!1;null!==n.widthsAttr?i=n.widthsAttr.stateValues.nComponents:null!==n.widthAttr?(i=a[0],s=!0):i=0;let o=[];for(let n in e.specifiedWidths){Number(n)({widthsAbsoluteArray:{dependencyType:"stateVariable",variableName:"widthsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.widthsAbsoluteArray){let r=e.widthsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{widthsAbsolute:t}}}},e.specifiedMargins={additionalStateVariablesDefined:[{variableName:"marginsAbsoluteArray",isArray:!0,entryPrefixes:["marginAbsolute"]}],isArray:!0,entryPrefixes:["specifiedMargin"],hasEssential:!0,defaultValueByArrayKey:()=>null,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:({arrayKeys:e})=>({globalDependencies:{marginsAttr:{dependencyType:"attributeComponent",attributeName:"margins",variableNames:["componentSize1","componentSize2","nComponents"]}}}),arrayDefinitionByKey({dependencyValuesByKey:e,globalDependencyValues:t,arrayKeys:n}){let r={},a={},i={};if(null===t.marginsAttr||0===t.marginsAttr.stateValues.nComponents)for(let e of n)a[e]=!0,i[e]=null;else if(1===t.marginsAttr.stateValues.nComponents){let e=null,a=null;t.marginsAttr.stateValues.componentSize1&&(e=t.marginsAttr.stateValues.componentSize1.size,Number.isFinite(e)||(e=null),a=Boolean(t.marginsAttr.stateValues.componentSize1.isAbsolute));for(let t of n)r[t]=e,i[t]=a}else for(let e of n)if(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`]){let n=t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].size;Number.isFinite(n)||(n=null);let a=Boolean(t.marginsAttr.stateValues[`componentSize${Number(e)+1}`].isAbsolute);r[e]=n,i[e]=a}let s={setValue:{marginsAbsoluteArray:i,specifiedMargins:r}};return Object.keys(a).length>0&&(s.useEssentialOrDefaultValue={specifiedMargins:a}),s},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,stateValues:r}){let a=[];if(null===n.marginsAttr)a.push({setEssentialValue:"specifiedMargins",value:e.specifiedMargins});else if(n.marginsAttr.stateValues.componentSize1&&Number.isFinite(n.marginsAttr.stateValues.componentSize1.size)){let t=1===n.marginsAttr.stateValues.nComponents;for(let n in e.specifiedMargins)t?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[n],isAbsolute:await r.marginsAbsolute},variableIndex:n})}else"0"in e.specifiedMargins?a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[0],isAbsolute:await r.marginsAbsolute},variableIndex:0}):a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:0}),"1"in e.specifiedMargins&&n.marginsAttr.stateValues.nComponents>1&&a.push({setDependency:"marginsAttr",desiredValue:{size:e.specifiedMargins[1],isAbsolute:await r.marginsAbsolute},variableIndex:1});return{success:!0,instructions:a}}},e.marginsAbsolute={returnDependencies:()=>({marginsAbsoluteArray:{dependencyType:"stateVariable",variableName:"marginsAbsoluteArray"}}),definition({dependencyValues:e}){let t=null;for(let n in e.marginsAbsoluteArray){let r=e.marginsAbsoluteArray[n];if(null!==r)if(r=Boolean(r),null===t)t=r;else if(t!==r)throw Error("SbsGroup is not implemented for absolute measurements")}return{setValue:{marginsAbsolute:t}}}},e.absoluteMeasurements={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({widthsAbsolute:{dependencyType:"stateVariable",variableName:"widthsAbsolute"},marginsAbsolute:{dependencyType:"stateVariable",variableName:"marginsAbsolute"}}),definition({dependencyValues:e}){let t;if(null===e.widthsAbsolute)t=null!==e.marginsAbsolute&&e.marginsAbsolute;else if(null===e.marginsAbsolute)t=e.widthsAbsolute;else{if(e.widthsAbsolute!==e.marginsAbsolute)throw Error("SbsGroup is not implemented for absolute measurements");t=e.widthsAbsolute}if(!0===t)throw Error("SbsGroup is not implemented for absolute measurements");return{setValue:{absoluteMeasurements:t}}}},e.allWidths={additionalStateVariablesDefined:["allMargins",{variableName:"gapWidth",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"},specifiedWidths:{dependencyType:"stateVariable",variableName:"specifiedWidths"},specifiedMargins:{dependencyType:"stateVariable",variableName:"specifiedMargins"},absoluteMeasurements:{dependencyType:"stateVariable",variableName:"absoluteMeasurements"}}),definition({dependencyValues:e}){let t=0,n=[...e.specifiedWidths],r=[...e.specifiedMargins],a=0,i=0;for(let t=0;t=100){let t=100/(a+s);for(let r=0;r0){let t=(100-(a+s))/i;for(let r=0;r0){let t=(100-(a+s))/(o*e.maxNPanelsPerRow);for(let e=0;e<2;e++)null===r[e]&&(r[e]=t)}else e.maxNPanelsPerRow>1?t=(100-(a+s))/(e.maxNPanelsPerRow-1):1===e.maxNPanelsPerRow?r[1]=100-(r[0]+n[0]):console.warn("Invalid sideBySide, as it must have at least one block child");return{setValue:{allWidths:n,allMargins:r,gapWidth:t}}}},e.widths={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["width"],returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={allWidths:{dependencyType:"stateVariable",variableName:"allWidths"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedWidth:{dependencyType:"stateVariable",variableName:`specifiedWidth${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allWidths[r];return{setValue:{widths:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.widths)n.push({setDependency:t[r].specifiedWidth,desiredValue:e.widths[r],variableIndex:0});return{success:!0,instructions:n}}},e.margins={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"number"},entryPrefixes:["margin"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={allMargins:{dependencyType:"stateVariable",variableName:"allMargins"}},n={};for(let t of e){let e=Number(t)+1;n[t]={specifiedMargin:{dependencyType:"stateVariable",variableName:`specifiedMargin${e}`}}}return{globalDependencies:t,dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e.allMargins[r];return{setValue:{margins:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.margins)n.push({setDependency:t[r].specifiedMargin,desiredValue:e.margins[r],variableIndex:0});return{success:!0,instructions:n}}},e.valigns={public:!0,isArray:!0,shadowingInstructions:{createComponentOfType:"text"},entryPrefixes:["valign"],hasEssential:!0,defaultValueByArrayKey:()=>"top",returnArraySizeDependencies:()=>({maxNPanelsPerRow:{dependencyType:"stateVariable",variableName:"maxNPanelsPerRow"}}),returnArraySize:({dependencyValues:e})=>[e.maxNPanelsPerRow],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:[`text${e}`]}}}return{globalDependencies:{valignAttr:{dependencyType:"attributeComponent",attributeName:"valign",variableNames:["value"]},valignsAttr:{dependencyType:"attributeComponent",attributeName:"valigns",variableNames:["nComponents"]}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,arraySize:r}){let a,i={},s={},o=!1;null!==e.valignsAttr?a=e.valignsAttr.stateValues.nComponents:null!==e.valignAttr?(a=r[0],o=!0):a=0;for(let r of n){let n=Number(r);if(n0&&(l.setValue={valigns:i}),Object.keys(s).length>0&&(l.useEssentialOrDefaultValue={valigns:s}),l},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,globalDependencyValues:n,arraySize:r}){let a,i=!1;null!==n.valignsAttr?a=n.valignsAttr.stateValues.nComponents:null!==n.valignAttr?(a=r[0],i=!0):a=0;let s=[];for(let n in e.valigns){let r=e.valigns[n].toLowerCase();["top","middle","bottom"].includes(r)&&(Number(n)({stringTextChildren:{dependencyType:"child",childGroups:["stringsTexts"],variableNames:["value"]},hChildren:{dependencyType:"child",childGroups:["hs"],variableNames:["value"]}}),definition({dependencyValues:e}){let t;if(e.hChildren.length>0)t=e.hChildren.map((e=>e.stateValues.value));else{let n="";for(let t of e.stringTextChildren)n+="string"==typeof t?t:t.stateValues.value;t=[n]}return{setValue:{terms:t}}}},e}}var Indexing=Object.freeze({__proto__:null,H:H$2,Idx:Idx});class Div extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="div";static rendererType="containerBlock";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Span extends InlineComponent{static componentType="span";static rendererType="containerInline";static renderChildren=!0;static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}}var Divisions=Object.freeze({__proto__:null,Div:Div,Span:Span});class Pre extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="pre";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class DisplayDoenetML extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="displayDoenetML";static rendererType="text";static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"allChildren",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={returnDependencies:()=>({childrenDoenetML:{dependencyType:"doenetML",displayOnlyChildren:!0}}),definition:({dependencyValues:e})=>({setValue:{value:e.childrenDoenetML}})},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:({dependencyValues:e})=>({setValue:{text:e.value}})},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}var Verbatim=Object.freeze({__proto__:null,Pre:Pre,DisplayDoenetML:DisplayDoenetML});class Paginator extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{setPage:this.setPage.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="paginator";static rendererType="containerBlock";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.initialPage={createComponentOfType:"integer",createStateVariable:"initialPage",defaultValue:1},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPages={public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:({dependencyValues:e})=>({setValue:{nPages:e.children.length}})},e.currentPage={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,returnDependencies:()=>({initialPage:{dependencyType:"stateVariable",variableName:"initialPage"},nPages:{dependencyType:"stateVariable",variableName:"nPages"}}),definition:({dependencyValues:e})=>({useEssentialOrDefaultValue:{currentPage:{get defaultValue(){let t=e.initialPage;return Number.isInteger(t)?Math.max(1,Math.min(e.nPages,t)):1}}}}),async inverseDefinition({desiredStateVariableValues:e,stateValues:t,sourceInformation:n={}}){if(!n.fromSetPage)return{success:!1};let r=Number(e.currentPage);return Number.isInteger(r)?(r=Math.max(1,Math.min(await t.nPages,r)),{success:!0,instructions:[{setEssentialValue:"currentPage",value:r}]}):{success:!1}}},e.childIndicesToRender={returnDependencies:()=>({currentPage:{dependencyType:"stateVariable",variableName:"currentPage"}}),definition:({dependencyValues:e})=>({setValue:{childIndicesToRender:[e.currentPage-1]}}),markStale:()=>({updateRenderedChildren:!0})},e}async setPage({number:e,actionId:t}){if(!Number.isInteger(e))return void this.coreFunctions.resolveAction({actionId:t});let n=Math.max(1,Math.min(await this.stateValues.nPages,e)),r=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"currentPage",value:n,sourceInformation:{fromSetPage:!0}}];await this.coreFunctions.performUpdate({updateInstructions:r,actionId:t,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:n,responseText:n.toString()}}})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class PaginatorControls extends BlockComponent{constructor(e){super(e),this.externalActions={},Object.defineProperty(this.externalActions,"setPage",{enumerable:!0,get:async function(){let e=await this.stateValues.paginatorComponentName;return e?{componentName:e,actionName:"setPage"}:void 0}.bind(this)})}static componentType="paginatorControls";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.previousLabel={createComponentOfType:"text",createStateVariable:"previousLabel",defaultValue:"Previous",forRenderer:!0,public:!0},e.nextLabel={createComponentOfType:"text",createStateVariable:"nextLabel",defaultValue:"Next",forRenderer:!0,public:!0},e.pageLabel={createComponentOfType:"text",createStateVariable:"pageLabel",defaultValue:"Page",forRenderer:!0,public:!0},e.paginator={createTargetComponentNames:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.paginatorComponentName={returnDependencies:()=>({paginator:{dependencyType:"attributeTargetComponentNames",attributeName:"paginator"}}),definition({dependencyValues:e}){let t;return t=1===e.paginator?.length?e.paginator[0].absoluteName:null,{setValue:{paginatorComponentName:t}}}},e.currentPage={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorPage:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"currentPage"}}:{},definition:({dependencyValues:e})=>"paginatorPage"in e?{setValue:{currentPage:e.paginatorPage}}:{setValue:{currentPage:1}}},e.nPages={forRenderer:!0,stateVariablesDeterminingDependencies:["paginatorComponentName"],returnDependencies:({stateValues:e})=>e.paginatorComponentName?{paginatorNPages:{dependencyType:"stateVariable",componentName:e.paginatorComponentName,variableName:"nPages"}}:{},definition:({dependencyValues:e})=>"paginatorNPages"in e?{setValue:{nPages:e.paginatorNPages}}:{setValue:{nPages:1}}},e}}var Paginator$1=Object.freeze({__proto__:null,Paginator:Paginator,PaginatorControls:PaginatorControls});class Input extends InlineComponent{static componentType="_input";static createAttributesObject(){let e=super.createAttributesObject();return e.collaborateGroups={createComponentOfType:"collaborateGroups",createStateVariable:"collaborateGroups",defaultValue:null,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nValues={returnDependencies:()=>({}),definition:()=>({setValue:{nValues:1}})},e.answerAncestor={returnDependencies:()=>({answerAncestor:{dependencyType:"ancestor",componentType:"answer",variableNames:["delegateCheckWorkToInput","justSubmitted","creditAchieved","showCorrectness","numberOfAttemptsLeft"]}}),definition:function({dependencyValues:e}){return{setValue:{answerAncestor:e.answerAncestor}}}},e.includeCheckWork={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&(t=e.answerAncestor.stateValues.delegateCheckWorkToInput),{setValue:{includeCheckWork:t}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=0;return e.answerAncestor&&(t=e.answerAncestor.stateValues.creditAchieved),{setValue:{creditAchieved:t}}}},e.valueHasBeenValidated={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition:function({dependencyValues:e}){let t=!1;return e.answerAncestor&&e.answerAncestor.stateValues.justSubmitted&&(t=!0),{setValue:{valueHasBeenValidated:t}}}},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.showCorrectness:!1!==e.showCorrectnessFlag,{setValue:{showCorrectness:t}}}},e.numberOfAttemptsLeft={forRenderer:!0,returnDependencies:()=>({answerAncestor:{dependencyType:"stateVariable",variableName:"answerAncestor"}}),definition({dependencyValues:e}){let t;return t=e.answerAncestor?e.answerAncestor.stateValues.numberOfAttemptsLeft:1/0,{setValue:{numberOfAttemptsLeft:t}}}},e}}class MatrixInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateNumRows:this.updateNumRows.bind(this),updateNumColumns:this.updateNumColumns.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="matrixInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.numRows={createComponentOfType:"integer",createStateVariable:"numRowsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.numColumns={createComponentOfType:"integer",createStateVariable:"numColumnsPreliminary",defaultValue:1,transformNonFiniteTo:0},e.showSizeControls={createComponentOfType:"boolean",createStateVariable:"showSizeControls",defaultValue:!0,public:!0,forRenderer:!0},e.defaultEntry={createComponentOfType:"math",createStateVariable:"defaultEntry",defaultValue:me$3.fromAst("_")},e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentAttributes:t}){if(e.length>0)return{success:!1};return{success:!0,newChildren:[{componentType:"matrixInputGrid"}]}}}),e}static returnChildGroups(){return[{group:"matrixComponentInputs",componentTypes:["matrixComponentInput"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.valueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{valueOriginal:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{valueOriginal:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.valueOriginal,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"valueOriginal",value:e.valueOriginal}]}}},e.immediateValueOriginal={hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.valueOriginal&&!n?{setValue:{immediateValueOriginal:e.valueOriginal},setEssentialValue:{immediateValueOriginal:e.valueOriginal}}:{useEssentialOrDefaultValue:{immediateValueOriginal:{defaultValue:e.valueOriginal}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValueOriginal",value:e.immediateValueOriginal}];return t||n||r.push({setDependency:"valueOriginal",desiredValue:e.immediateValueOriginal}),{success:!0,instructions:r}}},e.haveBoundValue={returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo"}}),definition:({dependencyValues:e})=>({setValue:{haveBoundValue:null!==e.bindValueTo}})},e.numRows={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({numRowsPreliminary:{dependencyType:"stateVariable",variableName:"numRowsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numRowsPreliminary;if(t.numRowsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][1]:vectorOperators.includes(e)&&(n=t.length-1)}}return{setValue:{numRows:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numRows;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numRowsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=t.valueOriginal.tree,i=(await n.defaultEntry).tree;if(1===await n.numColumns&&Array.isArray(e)&&vectorOperators.includes(e[0])){let t=e.length-1;if(rt){let s=deepClone(e),o=await n.accumulatedComponents;for(let e=t;e({numColumnsPreliminary:{dependencyType:"stateVariable",variableName:"numColumnsPreliminary"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},haveBoundValue:{dependencyType:"stateVariable",variableName:"haveBoundValue"}}),definition({dependencyValues:e,usedDefault:t}){let n=e.numColumnsPreliminary;if(t.numColumnsPreliminary||e.haveBoundValue){let t=e.valueOriginal.tree;if(n=1,Array.isArray(t)){let e=t[0];"matrix"===e?n=t[1][2]:Array.isArray(t[1])&&vectorOperators.includes(t[1][0])&&("^"===e&&"T"===t[2]||"prime"===e)&&(n=t[1].length-1)}}return{setValue:{numColumns:n}}},async inverseDefinition({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){let r=e.numColumns;if(!Number.isInteger(r))return{success:!1};r=Math.max(0,r);let a=[{setDependency:"numColumnsPreliminary",desiredValue:r}];if(t.haveBoundValue){let e=(await n.defaultEntry).tree,i=t.valueOriginal.tree,s=i[0];if(Array.isArray(i[1])&&vectorOperators.includes(i[1][0])&&("^"===s&&"T"===i[2]||"prime"===s)){let t=i[1].length-1;if(rt){let s=deepClone(i),o=(await n.accumulatedComponents)[0];o||(o=[]);for(let n=t;n({valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e,previousValues:t}){let n=[];t.accumulatedComponents&&(n=deepClone(t.accumulatedComponents));let r=e.valueOriginal.tree;if(Array.isArray(r)){let e=r[0];if("matrix"===e){let e=r[2];for(let[t,r]of e.slice(1).entries()){let e=n[t];e||(e=n[t]=[]);for(let[t,n]of r.slice(1).entries())e[t]=n}return{setValue:{accumulatedComponents:n}}}if(vectorOperators.includes(e)){for(let[e,t]of r.slice(1).entries()){let r=n[e];r||(r=n[e]=[]),r[0]=t}return{setValue:{accumulatedComponents:n}}}if(Array.isArray(r[1])&&vectorOperators.includes(r[1][0])&&("^"===e&&"T"===r[2]||"prime"===e)){let e=n[0];e||(e=n[0]=[]);for(let[t,n]of r[1].slice(1).entries())e[t]=n;return{setValue:{accumulatedComponents:n}}}}let a=n[0];return a||(a=n[0]=[]),a[0]=r,{setValue:{accumulatedComponents:n}}}},e.componentValues={isArray:!0,entryPrefixes:["componentValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.valueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.valueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.valueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentImmediateValues={isArray:!0,entryPrefixes:["componentImmediateValue"],nDimensions:2,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey:()=>({globalDependencies:{immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},accumulatedComponents:{dependencyType:"stateVariable",variableName:"accumulatedComponents"},defaultEntry:{dependencyType:"stateVariable",variableName:"defaultEntry"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n=e.immediateValueOriginal.tree,r=e.accumulatedComponents,a=e.numRows,i=e.numColumns;if(Array.isArray(n)){let t=n[0];if("matrix"===t){if(n[1][1]===a&&n[1][2]===i){let e={},t=n[2];for(let n=0;ns)for(let t=0;tt)for(let n=t;n[...e]));else{let e=t.immediateValueOriginal.tree;if(o){if(a=e.slice(1,1+i).map((e=>[e])),a.length1)for(let e=0;e1)for(let e=1;ee.slice(1,s+1))),a[0].length1&&a[0].push(...Array(s-1).fill("_")),i>1)for(let e=1;ee[0]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r,treatAsInitialChange:n}]}}if(1===i&&l){let e=t.immediateValueOriginal.tree,r=e[0],i=[e[1][0],...a[0]];return i="^"===r?me$3.fromAst(["^",i,"T"]):me$3.fromAst(["prime",i]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:i,treatAsInitialChange:n}]}}{let e=["matrix",["tuple",t.numRows,t.numColumns],["tuple",...a.map((e=>["tuple",...e]))]];return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:me$3.fromAst(e),treatAsInitialChange:n}]}}}},e.componentValuesForDisplay={isArray:!0,entryPrefixes:["componentValueForDisplay"],nDimensions:2,forRenderer:!0,returnArraySizeDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),returnArraySize:({dependencyValues:e})=>[e.numRows,e.numColumns],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={componentValue:{dependencyType:"stateVariable",variableName:`componentValue${a}`}}}return{globalDependencies:{displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n,usedDefault:r}){let a={};for(let i of n){let n=roundForDisplay({value:t[i].componentValue,dependencyValues:e,usedDefault:r});a[i]=n}return{setValue:{componentValuesForDisplay:a}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentValues:{dependencyType:"stateVariable",variableName:"componentValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},valueOriginal:{dependencyType:"stateVariable",variableName:"valueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.valueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"valueOriginal",desiredValue:e.value}]}}return{success:!1}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},returnDependencies:()=>({componentImmediateValues:{dependencyType:"stateVariable",variableName:"componentImmediateValues"},numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"},immediateValueOriginal:{dependencyType:"stateVariable",variableName:"immediateValueOriginal"}}),definition({dependencyValues:e}){let t=e.numRows,n=e.numColumns,r=["matrix",["tuple",t,n]],a=r[2]=["tuple"];for(let r=0;re[1]))]);return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e}]}}}}else if(1===t.numRows){let e=t.immediateValueOriginal.tree;if(Array.isArray(e)){let t=e[0];if(Array.isArray(e[1])&&vectorOperators.includes(e[1][0])&&("^"===t&&"T"===e[2]||"prime"===t)){let r=[e[1][0],...n[2][1].slice(1)];return r="^"===t?me$3.fromAst(["^",r,"T"]):me$3.fromAst(["prime",r]),{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:r}]}}}}return{success:!0,instructions:[{setDependency:"immediateValueOriginal",desiredValue:e.immediateValue}]}}return{success:!1}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"matrix"}})},e}async updateRawValues({rawRendererValues:e,transient:t=!1,actionId:n}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValues",value:e}],transient:t,actionId:n});this.coreFunctions.resolveAction({actionId:n})}async updateNumRows({numRows:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numRows",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateNumColumns({numColumns:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"numColumns",value:e}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}class MatrixInputGrid extends CompositeComponent{static componentType="matrixInputGrid";static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.numRows={returnDependencies:()=>({parentNumRows:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numRows"}}),definition:({dependencyValues:e})=>({setValue:{numRows:e.parentNumRows}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numRows:{dependencyType:"stateVariable",variableName:"numRows"},numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numRows;r.previousNumRows=i;for(let e=0;eo&&(u=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=u){i=e.replacementsToWithhold-u,o+=u,u=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else u-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(u>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.numColumns={returnDependencies:()=>({parentNumColumns:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"numColumns"}}),definition:({dependencyValues:e})=>({setValue:{numColumns:e.parentNumColumns}})},e.readyToExpandWhenResolved={returnDependencies:()=>({numColumns:{dependencyType:"stateVariable",variableName:"numColumns"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e}j;static async createSerializedReplacements({component:e,componentInfoObjects:t,flags:n,workspace:r}){let a=[],i=await e.stateValues.numColumns,s=await e.stateValues.rowInd;r.previousNumColumns=i;for(let e=0;eo&&(c=l-o,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=c){i=e.replacementsToWithhold-c,o+=c,c=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:i};s.push(t)}else c-=e.replacementsToWithhold,o+=e.replacementsToWithhold,i=0;if(c>0){let e=[];for(let t=o;t({}),definition:()=>({useEssentialOrDefaultValue:{rowInd:!0}})},e.colInd={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{colInd:!0}})},e.format={returnDependencies:()=>({parentFormat:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"format"}}),definition:({dependencyValues:e})=>({setValue:{format:e.parentFormat}})},e.functionSymbols={returnDependencies:()=>({parentFunctionSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"functionSymbols"}}),definition:({dependencyValues:e})=>({setValue:{functionSymbols:e.parentFunctionSymbols}})},e.splitSymbols={returnDependencies:()=>({parentSplitSymbols:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"splitSymbols"}}),definition:({dependencyValues:e})=>({setValue:{splitSymbols:e.parentSplitSymbols}})},e.parseScientificNotation={returnDependencies:()=>({parentParseScientificNotation:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"parseScientificNotation"}}),definition:({dependencyValues:e})=>({setValue:{parseScientificNotation:e.parentParseScientificNotation}})},e.displayDigits={returnDependencies:()=>({parentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDigits"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDigits:e.parentDisplayDigits}};return t.parentDisplayDigits&&(n.markAsUsedDefault={displayDigits:!0}),n}},e.displayDecimals={returnDependencies:()=>({parentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={setValue:{displayDecimals:e.parentDisplayDecimals}};return t.parentDisplayDecimals&&(n.markAsUsedDefault={displayDecimals:!0}),n}},e.displaySmallAsZero={returnDependencies:()=>({parentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"displaySmallAsZero"}}),definition:({dependencyValues:e})=>({setValue:{displaySmallAsZero:e.parentDisplaySmallAsZero}})},e.unionFromU={returnDependencies:()=>({parentUnionFromU:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:"unionFromU"}}),definition:({dependencyValues:e})=>({setValue:{unionFromU:e.parentUnionFromU}})},e.value={stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentValue${t}`}}},definition:function({dependencyValues:e}){return e.parentComponentValue?{setValue:{value:e.parentComponentValue}}:{setValue:{value:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"parentComponentValue",desiredValue:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},stateVariablesDeterminingDependencies:["rowInd","colInd"],returnDependencies:({stateValues:e})=>{let t="";return null!==e.rowInd&&null!==e.colInd&&(t=`${e.rowInd+1}_${e.colInd+1}`),{parentComponentImmediateValue:{dependencyType:"parentStateVariable",parentComponentType:"matrixInput",variableName:`componentImmediateValue${t}`}}},definition:function({dependencyValues:e}){return{setValue:{immediateValue:e.parentComponentImmediateValue}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return{success:!0,instructions:[{setDependency:"parentComponentImmediateValue",desiredValue:e.immediateValue,treatAsInitialChange:t}]}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition({dependencyValues:e,essentialValues:t}){if(void 0!==t.rawRendererValue&&deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t=stripLatex(e.valueForDisplay.toLatex());return"_"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n}){const r=async e=>{let n;e=(e=normalizeLatexString(e,{unionFromU:await t.unionFromU})).replace(/\^(\w)/g,"^{$1}");let r=getFromLatex({functionSymbols:await t.functionSymbols,splitSymbols:await t.splitSymbols,parseScientificNotation:await t.parseScientificNotation});try{n=r(e)}catch(e){n=me$3.fromAst("_")}return n};let a=[];if("string"==typeof e.rawRendererValue){let t=n.rawRendererValue,i=e.rawRendererValue;t!==i&&a.push({setEssentialValue:"rawRendererValue",value:i});let s=await r(t),o=await r(i);deepCompare(o.tree,s.tree)||a.push({setDependency:"immediateValue",desiredValue:o,treatAsInitialChange:!0})}else{a.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let t=await r(n.rawRendererValue);if(!deepCompare(e.rawRendererValue.tree,t.tree)){let t=stripLatex(e.rawRendererValue.toLatex());"_"===t&&(t=""),a.push({setEssentialValue:"rawRendererValue",value:t})}}return{success:!0,instructions:a}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree&&n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"rawRendererValue"}],actionId:e})}}}var MatrixInput$1=Object.freeze({__proto__:null,MatrixInput:MatrixInput,MatrixInputGrid:MatrixInputGrid,MatrixInputRow:MatrixInputRow,default:MatrixComponentInput});class Document extends BaseComponent{constructor(e){super(e),Object.assign(this.actions,{submitAllAnswers:this.submitAllAnswers.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="document";static rendererType="section";static renderChildren=!0;static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return delete e.hide,delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.documentWideCheckWork={createComponentOfType:"boolean",createStateVariable:"documentWideCheckWork",defaultValue:!1,public:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0},e.displayDigitsForCreditAchieved={createComponentOfType:"integer",createStateVariable:"displayDigitsForCreditAchieved",defaultValue:3,public:!0},e.xmlns={createPrimitiveOfType:"string"},e.type={createPrimitiveOfType:"string"},e}static returnChildGroups(){return[{group:"variantControl",componentTypes:["variantControl"]},{group:"title",componentTypes:["title"]},{group:"description",componentTypes:["description"]},{group:"setups",componentTypes:["setup"]},{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStyleDefinitionStateVariables();Object.assign(e,t);let n=returnFeedbackDefinitionStateVariables();return Object.assign(e,n),e.titleChildName={forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"]}}),definition({dependencyValues:e}){let t=null;return e.titleChild.length>0&&(t=e.titleChild[0].componentName),{setValue:{titleChildName:t}}}},e.title={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({titleChild:{dependencyType:"child",childGroups:["title"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.titleChild.length?{setValue:{title:""}}:{setValue:{title:e.titleChild[0].stateValues.text}}},e.description={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({descriptionChild:{dependencyType:"child",childGroups:["description"],variableNames:["text"]}}),definition:({dependencyValues:e})=>0===e.descriptionChild.length?{setValue:{description:""}}:{setValue:{description:e.descriptionChild[0].stateValues.text}}},e.level={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{level:0}})},e.viewedSolution={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{viewedSolution:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"viewedSolution",value:e.viewedSolution}]})},e.scoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"descendant",componentTypes:["_sectioningComponent","answer","setup"],variableNames:["scoredDescendants","aggregateScores","weight"],recurseToMatchedChildren:!1,variablesOptional:!0}}),definition({dependencyValues:e}){let t=[];for(let n of e.scoredDescendants)"setup"!==n.componentType&&(n.stateValues.aggregateScores||void 0===n.stateValues.scoredDescendants?t.push(n):t.push(...n.stateValues.scoredDescendants));return{setValue:{scoredDescendants:t}}}},e.nScoredDescendants={returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}}),definition:({dependencyValues:e})=>({setValue:{nScoredDescendants:e.scoredDescendants.length}})},e.itemCreditAchieved={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={creditAchieved:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"creditAchieved"}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].creditAchieved;return{setValue:{itemCreditAchieved:n}}}},e.itemNumberByAnswerName={stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let n in e.scoredDescendants){let r=e.scoredDescendants[n];t[`descendantsOf${n}`]={dependencyType:"descendant",ancestorName:r.componentName,componentTypes:["answer"],recurseToMatchedChildren:!1}}return t},definition({dependencyValues:e,componentInfoObjects:t}){let n={};for(let[r,a]of e.scoredDescendants.entries()){let i=r+1;for(let t of e[`descendantsOf${r}`])n[t.componentName]=i;t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"answer"})&&(n[a.componentName]=i)}return{setValue:{itemNumberByAnswerName:n}}}},e.itemVariantInfo={isArray:!0,returnArraySizeDependencies:()=>({nScoredDescendants:{dependencyType:"stateVariable",variableName:"nScoredDescendants"}}),returnArraySize:({dependencyValues:e})=>[e.nScoredDescendants],stateVariablesDeterminingDependencies:["scoredDescendants"],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.scoredDescendants[r];e&&(n[r]={generatedVariantInfo:{dependencyType:"stateVariable",componentName:e.componentName,variableName:"generatedVariantInfo",variablesOptional:!0}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].generatedVariantInfo;return{setValue:{itemVariantInfo:n}}}},e.answerDescendants={returnDependencies:()=>({answerDescendants:{dependencyType:"descendant",componentTypes:["answer"],variableNames:["justSubmitted"],recurseToMatchedChildren:!1}}),definition:({dependencyValues:e})=>({setValue:{answerDescendants:e.answerDescendants}})},e.justSubmitted={forRenderer:!0,returnDependencies:()=>({answerDescendants:{dependencyType:"stateVariable",variableName:"answerDescendants"}}),definition:({dependencyValues:e})=>({setValue:{justSubmitted:e.answerDescendants.every((e=>e.stateValues.justSubmitted))}})},e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"}}),definition:({dependencyValues:e})=>({setValue:{showCorrectness:!1!==e.showCorrectnessFlag}})},e.creditAchieved={public:!0,forRenderer:!0,defaultValue:0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}},additionalStateVariablesDefined:[{variableName:"percentCreditAchieved",public:!0,shadowingInstructions:{createComponentOfType:"number",addAttributeComponentsShadowingStateVariables:{displayDigits:{stateVariableToShadow:"displayDigitsForCreditAchieved"}}}}],returnDependencies:()=>({scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"},itemCreditAchieved:{dependencyType:"stateVariable",variableName:"itemCreditAchieved"}}),definition({dependencyValues:e}){let t,n=0,r=0;for(let[t,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;n+=e.itemCreditAchieved[t]*i,r+=i}return t=r>0?n/r:1,{setValue:{creditAchieved:t,percentCreditAchieved:100*t}}}},e.creditAchievedIfSubmit={defaultValue:0,stateVariablesDeterminingDependencies:["scoredDescendants"],returnDependencies({stateValues:e}){let t={scoredDescendants:{dependencyType:"stateVariable",variableName:"scoredDescendants"}};for(let[n,r]of e.scoredDescendants.entries())t["creditAchievedIfSubmit"+n]={dependencyType:"stateVariable",componentName:r.componentName,variableName:"creditAchievedIfSubmit"};return t},definition({dependencyValues:e}){let t=0,n=0;for(let[r,a]of e.scoredDescendants.entries()){let i=a.stateValues.weight;t+=e["creditAchievedIfSubmit"+r]*i,n+=i}return{setValue:{creditAchievedIfSubmit:t/n}}}},e.generatedVariantInfo={providePreviousValuesInDefinition:!0,returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantIndex:{dependencyType:"value",value:e.variantIndex},variantName:{dependencyType:"value",value:e.variantName},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t,previousValues:n}){let r={index:e.variantIndex,name:e.variantName,meta:{createdBy:t}},a=r.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?a.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&a.push(...t.stateValues.generatedVariantInfo.subvariants);for(let[e,t]of a.entries())if(!t.subvariants&&n.generatedVariantInfo){let t=n.generatedVariantInfo.subvariants;t[e]?.subvariants&&(a[e]=Object.assign({},a[e]),a[e].subvariants=t[e].subvariants)}return{setValue:{generatedVariantInfo:r}}}},e.createSubmitAllButton={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"suppressAnswerSubmitButtons",forRenderer:!0}],returnDependencies:()=>({documentWideCheckWork:{dependencyType:"stateVariable",variableName:"documentWideCheckWork"}}),definition({dependencyValues:e,componentName:t}){let n=!1,r=!1;return e.documentWideCheckWork&&(n=!0,r=!0),{setValue:{createSubmitAllButton:n,suppressAnswerSubmitButtons:r}}}},e.suppressCheckwork={forRenderer:!0,returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e}async submitAllAnswers({actionId:e}){this.coreFunctions.requestRecordEvent({verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType}});for(let e of await this.stateValues.answerDescendants)await e.stateValues.justSubmitted||await this.coreFunctions.performAction({componentName:e.componentName,actionName:"submitAnswer"});this.coreFunctions.resolveAction({actionId:e})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){let r,a=e.variants.numberOfVariants,i=e.variants.desiredVariant;if(void 0!==i&&void 0!==i.index){let e=Number(i.index);if(Number.isFinite(e)){Number.isInteger(e)||(console.warn("Variant index "+i.index+" must be an integer"),e=Math.round(e));let t=(e-1)%a;t<0&&(t+=a),r=t+1}else console.warn("Variant index "+i.index+" must be a number"),r=1}if(void 0===r&&(r=1),t.allPossibleVariants=e.variants.allPossibleVariants,t.allVariantNames=e.variants.allVariantNames,t.variantSeed=e.variants.allPossibleVariantSeeds[r-1],t.variantIndex=r,t.variantName=e.variants.allPossibleVariants[r-1],t.uniqueIndex=e.variants.allPossibleVariantUniqueIndices[r-1],t.variantRng=new t.rngClass(t.variantSeed),t.subpartVariantRng=new t.rngClass(t.variantSeed+"s"),i?.subvariants&&n)for(let e in i.subvariants){let t=i.subvariants[e],r=n[e];if(void 0===r)break;r.variants.desiredVariant=t}}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){return determineVariantsForSection({serializedComponent:e,componentInfoObjects:t,isDocument:!0})}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants.allPossibleVariantUniqueIndices[t-1];if(void 0===r)return{success:!1};let a=getVariantsForDescendantsForUniqueVariants({variantIndex:r,serializedComponent:e,componentInfoObjects:n});return a.success?{success:!0,desiredVariant:{index:t,subvariants:a.desiredVariants}}:(console.log("Failed to get unique variant for document."),{success:!1})}static includeBlankStringChildren=!0}class TextList$1 extends InlineComponent{static componentType="textList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="texts";static primaryStateVariableForDefinition="textsShadow";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"text"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"text"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"texts",componentTypes:["text"]},{group:"textLists",componentTypes:["textList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.textsShadow={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{textsShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[];if(e.textAndTextListChildren.length>0){let a=0;for(let[i,s]of e.textAndTextListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"textList"})){let t=e.textListChildren[a];a++;for(let e=0;ea&&(n=a,r=r.slice(0,a)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["value","text"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},textsShadow:{dependencyType:"stateVariable",variableName:"textsShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].textAndTextListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["text"+t]}else null!==e.textsShadow&&(r[a]=e.textsShadow[a])}return{setValue:{texts:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.texts){if(!n[t])continue;let a=n[t].textAndTextListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].textAndTextListChildren,desiredValue:e.texts[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"texts"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.componentNamesInList={returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.textAndTextListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"textList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},textListChildren:{dependencyType:"child",childGroups:["textLists"],variableNames:["nComponents"]},textAndTextListChildren:{dependencyType:"child",childGroups:["texts","textLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"textList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.textAndTextListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"textList"})){let t=e.textListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=["text"]}class TextList extends InlineComponent{static componentType="randomizedTextList";static stateVariableForAttributeValue="texts";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={default:!1},e.maximumNumber={default:null},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"atLeastZeroTexts",componentType:"text",comparison:"atLeast",number:0}),r=t.newLeaf({name:"atLeastZeroTextLists",componentType:"textList",comparison:"atLeast",number:0}),a=t.newLeaf({name:"exactlyOneString",componentType:"string",number:1,isSugar:!0,returnSugarDependencies:()=>({stringChildren:{dependencyType:"child",childLogicName:"exactlyOneString",variableNames:["value"]}}),logicToWaitOnSugar:["atLeastZeroTexts"],replacementFunction:function({dependencyValues:e}){let t=e.stringChildren[0],n=t.stateValues.value.split(",").map((e=>({componentType:"text",state:{value:e.trim()}})));return{success:!0,newChildren:n,toDelete:[t.componentName]}}}),i=t.newOperator({name:"textAndTextLists",operator:"and",propositions:[n,r]});return t.newOperator({name:"TextsXorSugar",operator:"xor",propositions:[a,i],setAsBase:!0}),t}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.texts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["text"],returnDependencies:()=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["value","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},childrenToRender:{dependencyType:"stateVariable",variableName:"childrenToRender"}}),definition:function({dependencyValues:e}){let t=[],n=e.textAndTextListChildren.map((e=>e.componentName));for(let r of e.childrenToRender){let a=n.indexOf(r),i=e.textAndTextListChildren[a];i.stateValues.texts?t.push(...i.stateValues.texts):t.push(i.stateValues.value)}return{setValue:{texts:t}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:({dependencyValues:e})=>({setValue:{text:e.texts.join(", ")}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({texts:{dependencyType:"stateVariable",variableName:"texts"}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.texts.length}}}},e.childrenToRender={returnDependencies:({sharedParameters:e})=>({textAndTextListChildren:{dependencyType:"child",childLogicName:"textAndTextLists",variableNames:["childrenToRender"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},selectRng:{dependencyType:"value",value:e.selectRng,doNotProxy:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.textAndTextListChildren)n.stateValues.childrenToRender?t.push(...n.stateValues.childrenToRender):t.push(n.componentName);let n=e.maximumNumber;null!==n&&t.length>n&&(n=Math.max(0,Math.floor(n)),t=t.slice(0,n)),console.log("randomizing children");for(let n=t.length-1;n>0;n--){const r=e.selectRng(),a=Math.floor(r*(n+1));[t[n],t[a]]=[t[a],t[n]]}let r=Math.ceil(e.selectRng()*t.length);return console.log(`numChildren: ${r}`),t=t.slice(0,r),{setValue:{childrenToRender:t}}}},e}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.aslist({key:this.componentName}))}}class TupleList extends MathList{static componentType="tupleList";static rendererType="mathList";static includeBlankStringChildren=!1;static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"math",children:e}:e[0]}))}}}),e}}class NumberList extends InlineComponent{static componentType="numberList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="numbers";static primaryStateVariableForDefinition="numbersShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"number"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"number"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"numbers",componentTypes:["number"]},{group:"numberLists",componentTypes:["numberList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({}),definition:()=>({useEssentialOrDefaultValue:{numbersShadow:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;if(e.numberAndNumberListChildren.length>0)for(let[i,s]of e.numberAndNumberListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},isArray:!0,entryPrefixes:["number"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["value","number"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].numberAndNumberListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["number"+t]}else null!==e.numbersShadow&&(r[a]=e.numbersShadow[a])}return{setValue:{numbers:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.numbers){if(!n[t])continue;let a=n[t].numberAndNumberListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].numberAndNumberListChildren,desiredValue:e.numbers[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition({dependencyValues:e}){let t;return t=0===e.numbers.length?me$3.fromAst("_"):1===e.numbers.length?me$3.fromAst(e.numbers[0]):me$3.fromAst(["list",...e.numbers]),{setValue:{math:t}}}},e.text={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["valueForDisplay","text","texts"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},numbersShadow:{dependencyType:"stateVariable",variableName:"numbersShadow"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n=[],r={};if(e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(r.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(r.padToDigits=e.displayDigits)),e.numberAndNumberListChildren.length>0)for(let t of e.numberAndNumberListChildren)void 0!==t.stateValues.valueForDisplay?n.push(t.stateValues.text):n.push(...t.stateValues.texts);else null!==e.numbersShadow&&(n=e.numbersShadow.map((n=>roundForDisplay({value:me$3.fromAst(n),dependencyValues:e,usedDefault:t}).toString(r))));let a=e.maximumNumber;return null!==a&&n.length>a&&(a=Math.max(0,Math.floor(a)),n=n.slice(0,a)),{setValue:{text:n.join(", "),texts:n}}}},e.componentNamesInList={returnDependencies:()=>({numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.numberAndNumberListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"numberList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},numberListChildren:{dependencyType:"child",childGroups:["numberLists"],variableNames:["nComponents"]},numberAndNumberListChildren:{dependencyType:"child",childGroups:["numbers","numberLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.numberAndNumberListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"numberList"})){let t=e.numberListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class NumberListFromString extends InlineComponent{static componentType="numberListFromString";static rendererType="asList";static renderChildren=!0;static stateVariableForAttributeValue="numbers";static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({stringChildren:{dependencyType:"child",childGroups:["strings"]}}),definition:function({dependencyValues:e}){return{setValue:{nComponents:e.stringChildren.length}}}},e.numbers={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["number"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey:()=>({globalDependencies:{stringChildren:{dependencyType:"child",childGroups:["strings"]}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={};for(let[t,r]of e.stringChildren.entries())n[t]=Number(r);return{setValue:{numbers:n}}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"numbers"},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:["texts"],returnDependencies:()=>({numbers:{dependencyType:"stateVariable",variableName:"numbers"}}),definition:function({dependencyValues:e}){let t=e.numbers.map((e=>e.toString()));return{setValue:{text:t.join(", "),texts:t}}}},e}}class P$2 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="p";static renderChildren=!0;static includeBlankStringChildren=!0;static returnChildGroups(){return[{group:"inlines",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inlines"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text?t+=n.stateValues.text:t+=" ";return{setValue:{text:t}}}},e}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class BooleanList extends InlineComponent{static componentType="booleanList";static rendererType="asList";static renderChildren=!0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static stateVariableForAttributeValue="booleans";static descendantCompositesMustHaveAReplacement=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.unordered={createComponentOfType:"boolean",createStateVariable:"unordered",defaultValue:!1,public:!0},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions(),t=returnGroupIntoComponentTypeSeparatedBySpaces({componentType:"boolean"}),n=returnBreakStringsIntoComponentTypeBySpaces({componentType:"boolean"});return e.push({replacementFunction:function({matchedChildren:e,isAttributeComponent:r=!1,createdFromMacro:a=!1}){return r&&!a?t({matchedChildren:e}):n({matchedChildren:e})}}),e}static returnChildGroups(){return[{group:"booleans",componentTypes:["boolean"]},{group:"booleanLists",componentTypes:["booleanList"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.overrideChildHide={returnDependencies:()=>({}),definition:()=>({setValue:{overrideChildHide:!0}})},e.nComponents={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:["childIndexByArrayKey"],returnDependencies:()=>({maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=0,r=[],a=0;for(let[i,s]of e.booleanAndBooleanListChildren.entries())if(t.isInheritedComponentType({inheritedComponentType:s.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[a];a++;for(let e=0;ei&&(n=i,r=r.slice(0,i)),{setValue:{nComponents:n,childIndexByArrayKey:r},checkForActualChange:{nComponents:!0}}}},e.booleans={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},isArray:!0,entryPrefixes:["boolean"],stateVariablesDeterminingDependencies:["childIndexByArrayKey"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=[],a="1";t.childIndexByArrayKey[r]&&(e=[t.childIndexByArrayKey[r][0]],a=t.childIndexByArrayKey[r][1]+1),n[r]={booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["value","boolean"+a],variablesOptional:!0,childIndices:e}}}return{globalDependencies:{childIndexByArrayKey:{dependencyType:"stateVariable",variableName:"childIndexByArrayKey"}},dependenciesByKey:n}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=t[a].booleanAndBooleanListChildren[0];if(n)if(void 0!==n.stateValues.value)r[a]=n.stateValues.value;else{let t=e.childIndexByArrayKey[a][1]+1;r[a]=n.stateValues["boolean"+t]}}return{setValue:{booleans:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t in e.booleans){if(!n[t])continue;let a=n[t].booleanAndBooleanListChildren[0];a&&(void 0!==a.stateValues.value?i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:0}):i.push({setDependency:r[t].booleanAndBooleanListChildren,desiredValue:e.booleans[t],childIndex:0,variableIndex:1}))}return{success:!0,instructions:i}}},e.nValues={isAlias:!0,targetVariableName:"nComponents"},e.values={isAlias:!0,targetVariableName:"booleans"},e.componentNamesInList={returnDependencies:()=>({booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],variableNames:["componentNamesInList"],variablesOptional:!0},maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];for(let r of e.booleanAndBooleanListChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"booleanList"})?n.push(...r.stateValues.componentNamesInList):n.push(r.componentName);let r=e.maximumNumber;return null!==r&&n.length>r&&(r=Math.max(0,Math.floor(r)),n=n.slice(0,r)),{setValue:{componentNamesInList:n}}}},e.nComponentsToDisplayByChild={additionalStateVariablesDefined:["nChildrenToRender"],returnDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"},booleanListChildren:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["nComponents"]},booleanAndBooleanListChildren:{dependencyType:"child",childGroups:["booleans","booleanLists"],skipComponentNames:!0},parentNComponentsToDisplayByChild:{dependencyType:"parentStateVariable",parentComponentType:"booleanList",variableName:"nComponentsToDisplayByChild"}}),definition:function({dependencyValues:e,componentInfoObjects:t,componentName:n}){let r=e.nComponents;null!==e.parentNComponentsToDisplayByChild&&(r=e.parentNComponentsToDisplayByChild[n]);let a={},i=0,s=0,o=0;for(let n of e.booleanAndBooleanListChildren){let l=Math.max(0,r-i);if(l>0&&s++,t.isInheritedComponentType({inheritedComponentType:n.componentType,baseComponentType:"booleanList"})){let t=e.booleanListChildren[o];o++;let n=Math.min(l,t.stateValues.nComponents);a[t.componentName]=n,i+=n}else i+=1}return{setValue:{nComponentsToDisplayByChild:a,nChildrenToRender:s}}},markStale:()=>({updateRenderedChildren:!0})},e}}class Copy extends CompositeComponent{static componentType="copy";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static includeBlankStringChildren=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNewNamespaces={createPrimitiveOfType:"boolean"},e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.obtainPropFromComposite={createPrimitiveOfType:"boolean",createStateVariable:"obtainPropFromComposite",defaultValue:!1,public:!0},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.sourceSubnames={createPrimitiveOfType:"stringArray",createStateVariable:"targetSubnames",defaultValue:null,public:!0},e.sourceSubnamesComponentIndex={createComponentOfType:"numberList",createStateVariable:"targetSubnamesComponentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:["hide"],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.link={createPrimitiveOfType:"boolean"},e.removeEmptyArrayEntries={createPrimitiveOfType:"boolean",createStateVariable:"removeEmptyArrayEntries",defaultValue:!1},e}static keepChildrenSerialized({serializedComponent:e}){return void 0===e.children?[]:Object.keys(e.children)}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.target={returnDependencies:()=>({target:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:({dependencyValues:e})=>({setValue:{target:e.target}})},e.targetSourcesName={additionalStateVariablesDefined:[{variableName:"sourcesChildNumber",hasEssential:!0,shadowVariable:!0}],stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceNameMappings;if(!n)return{};let r=n[e.target];return r?{targetSourcesName:{dependencyType:"value",value:r.name},sourcesChildNumber:{dependencyType:"value",value:r.childNumber}}:{}},definition:function({dependencyValues:e}){let t=e.targetSourcesName,n=e.sourcesChildNumber;return t||(t=null,n=null),{setValue:{targetSourcesName:t,sourcesChildNumber:n},setEssentialValue:{targetSourcesName:t,sourcesChildNumber:n}}}},e.targetSources={stateVariablesDeterminingDependencies:["targetSourcesName"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>e.targetSourcesName?{targetSourcesComponent:{dependencyType:"componentIdentity",componentName:e.targetSourcesName}}:{},definition:function({dependencyValues:e}){let t=e.targetSourcesComponent;return t||(t=null),{setValue:{targetSources:t}}}},e.sourceIndex={stateVariablesDeterminingDependencies:["target"],determineDependenciesImmediately:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:function({stateValues:e,sharedParameters:t}){let n=t.sourceIndexMappings;if(!n)return{};let r=n[e.target];return void 0===r?{}:{sourceIndex:{dependencyType:"value",value:r}}},definition:function({dependencyValues:e}){let t=e.sourceIndex;return void 0===t&&(t=null),{setValue:{sourceIndex:t},setEssentialValue:{sourceIndex:t}}}},e.targetComponent={shadowVariable:!0,stateVariablesDeterminingDependencies:["targetSources","sourceIndex"],determineDependenciesImmediately:!0,returnDependencies:({stateValues:e})=>null!==e.sourceIndex?{}:null!==e.targetSources?{targetSourcesChildren:{dependencyType:"stateVariable",componentName:e.targetSources.componentName,variableName:"childIdentities"},sourcesChildNumber:{dependencyType:"stateVariable",variableName:"sourcesChildNumber"}}:{targetComponent:{dependencyType:"targetComponent"}},definition:function({dependencyValues:e}){let t=null;return e.targetSourcesChildren?(t=e.targetSourcesChildren[e.sourcesChildNumber],t||(t=null)):e.targetComponent&&(t=e.targetComponent),{setValue:{targetComponent:t}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.cid={additionalStateVariablesDefined:["doenetId"],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null}};let t=null,n=null,r=e.uri.match(/[:&]cid=([^&]+)/i);return r&&(t=r[1]),r=e.uri.match(/[:&]doenetid=([^&]+)/i),r&&(n=r[1]),{setValue:{cid:t,doenetId:n}}}},e.serializedComponentsForCid={returnDependencies:()=>({cid:{dependencyType:"stateVariable",variableName:"cid"},serializedChildren:{dependencyType:"serializedChildren",doNotProxy:!0}}),definition:function({dependencyValues:e}){return e.cid&&e.serializedChildren?.length>0?{setValue:{serializedComponentsForCid:e.serializedChildren}}:{setValue:{serializedComponentsForCid:null}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.isPlainMacro={returnDependencies:()=>({isPlainMacro:{dependencyType:"doenetAttribute",attributeName:"isPlainMacro"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainMacro&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainMacro];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainMacro:n}}}},e.isPlainCopy={returnDependencies:()=>({isPlainCopy:{dependencyType:"doenetAttribute",attributeName:"isPlainCopy"},targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"},targetSubnames:{dependencyType:"stateVariable",variableName:"targetSubnames"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=e.isPlainCopy&&(!t.isCompositeComponent({componentType:e.targetComponent?.componentType})||e.targetSubnames);if(n&&e.typeAttr){n=!1;let r=t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()],a=t.allComponentClasses[e.targetComponent?.componentType];if(a){let e=t.publicStateVariableInfo[a.componentType].stateVariableDescriptions[a.variableForPlainCopy];r===a.componentType||!e||void 0!==e.createComponentOfType&&e.createComponentOfType!==r||(n=!0)}}return{setValue:{isPlainCopy:n}}}},e.linkAttrForDetermineDeps={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"}}),definition({dependencyValues:e}){let t;return t=null===e.linkAttr||e.linkAttr,{setValue:{linkAttrForDetermineDeps:t}}}},e.replacementSourceIdentities={stateVariablesDeterminingDependencies:["targetComponent","componentIndex","propName","targetSubnames","targetSubnamesComponentIndex","obtainPropFromComposite","linkAttrForDetermineDeps"],additionalStateVariablesDefined:["addLevelToAssignNames"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={},r=!1,a=!1;if(null!==e.targetComponent){if(t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})&&(!e.propName||!e.obtainPropFromComposite))if(e.linkAttrForDetermineDeps){a=!0;let t=e.targetSubnamesComponentIndex;t&&(t=[...t]),n.targets={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,componentIndex:e.componentIndex,targetSubnames:e.targetSubnames,targetSubnamesComponentIndex:t}}else r=!0;a||null!==e.componentIndex&&1!==e.componentIndex||(n.targets={dependencyType:"stateVariable",variableName:"targetComponent"})}return n.addLevelToAssignNames={dependencyType:"value",value:r},n},definition({dependencyValues:e}){let t=null;return e.targets&&(t=e.targets,Array.isArray(t)||(t=[t])),{setValue:{replacementSourceIdentities:t,addLevelToAssignNames:e.addLevelToAssignNames}}}},e.replacementSources={stateVariablesDeterminingDependencies:["replacementSourceIdentities","propName","propIndex","isPlainMacro","isPlainCopy"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){let n={replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(!e.propName&&null!==e.propIndex)throw Error("You cannot specify a propIndex without specifying a prop.");if(null!==e.replacementSourceIdentities)for(let[r,a]of e.replacementSourceIdentities.entries()){let i,s=e.propName;if(e.isPlainMacro?s=t.allComponentClasses[a.componentType].variableForPlainMacro:e.isPlainCopy&&(s=t.allComponentClasses[a.componentType].variableForPlainCopy),s){n["propName"+r]={dependencyType:"value",value:s};let t=e.propIndex;t&&(t=[...t]),i={dependencyType:"stateVariable",componentName:a.componentName,variableName:s,returnAsComponentObject:!0,variablesOptional:!0,propIndex:t,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0}}else i={dependencyType:"componentIdentity",componentName:a.componentName};n["target"+r]=i}return n},definition({dependencyValues:e}){let t=null,n=null;if(null!==e.replacementSourceIdentities){t=[],n=[];for(let r in e.replacementSourceIdentities){let a=e["target"+r];if(a){let i;t.push(a),a.stateValues&&(i=Object.keys(a.stateValues)[0]),!i&&e["propName"+r]&&(i="__prop_name_not_found"),n.push(i)}}}return{setValue:{replacementSources:t,effectivePropNameBySource:n}}}},e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({linkAttr:{dependencyType:"attributePrimitive",attributeName:"link"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;return n=null===e.linkAttr?!(e.serializedComponentsForCid||e.replacementSourceIdentities&&e.replacementSourceIdentities.some((e=>t.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"module"})))):!1!==e.linkAttr,{setValue:{link:n}}}},e.readyToExpandWhenResolved={stateVariablesDeterminingDependencies:["targetComponent","propName","obtainPropFromComposite","link"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"},serializedComponentsForCid:{dependencyType:"stateVariable",variableName:"serializedComponentsForCid"},link:{dependencyType:"stateVariable",variableName:"link"}};return!e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.targetReadyToExpandWhenResolved={dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"readyToExpandWhenResolved"}),e.link||(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={stateVariablesDeterminingDependencies:["targetComponent","replacementSourceIdentities","effectivePropNameBySource","propName","obtainPropFromComposite","link","removeEmptyArrayEntries"],returnDependencies:function({stateValues:e,componentInfoObjects:t}){if(!e.link)return{};let n={targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},replacementSourceIdentities:{dependencyType:"stateVariable",variableName:"replacementSourceIdentities"},propIndex:{dependencyType:"stateVariable",variableName:"propIndex"}};if(null!==e.effectivePropNameBySource)for(let[t,r]of e.effectivePropNameBySource.entries())if(r){let a=e.replacementSourceIdentities[t];n["sourceArraySize"+t]={dependencyType:"stateVariableArraySize",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0},n["sourceComponentType"+t]={dependencyType:"stateVariableComponentType",componentName:a.componentName,variableName:r,variablesOptional:!0,caseInsensitiveVariableMatch:!0}}return null===e.targetComponent||!t.isCompositeComponent({componentType:e.targetComponent.componentType,includeNonStandard:!1})||e.propName&&e.obtainPropFromComposite||(n.allReplacementIdentities={dependencyType:"replacement",compositeName:e.targetComponent.componentName,recursive:!0,variableNames:["isInactiveCompositeReplacement"]}),e.removeEmptyArrayEntries&&(n.replacementSources={dependencyType:"stateVariable",variableName:"replacementSources"}),n},markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e.effectiveAssignNames={returnDependencies:()=>({assignNames:{dependencyType:"doenetAttribute",attributeName:"assignNames"},addLevelToAssignNames:{dependencyType:"stateVariable",variableName:"addLevelToAssignNames"}}),definition({dependencyValues:e}){let t=e.assignNames;return t&&e.addLevelToAssignNames&&(t=[t]),{setValue:{effectiveAssignNames:t}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,resolveItem:i,publicCaseInsensitiveAliasSubstitutions:s}){await e.stateValues.nComponentsSpecified,n.numReplacementsBySource=[],n.numNonStringReplacementsBySource=[],n.propVariablesCopiedBySource=[],n.sourceNames=[],n.uniqueIdentifiersUsedBySource={};let o=e.attributes.newNamespace?.primitive,l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.serializedComponentsForCid;if(c){let t=deepClone([c[0]]),i=deepClone(c.slice(1));if(t[0].children){let n;if(n=t[0].componentName?t[0].componentName+"/":t[0].originalName+"/",e.doenetAttributes.keptNewNamespaceOfLastChild){n=n.slice(0,n.length-1);let e=n.lastIndexOf("/");n=n.slice(0,e+1)}restrictTNamesToNamespace({components:t[0].children,namespace:n,invalidateReferencesToBaseNamespace:e.doenetAttributes.keptNewNamespaceOfLastChild})}if("externalContent"===t[0].componentType)for(let n of t[0].children){if("object"!=typeof n)continue;n.attributes||(n.attributes={});let t=convertAttributesForComponentType({attributes:e.attributes,componentType:n.componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in t){let n=t[e];n.component?setTNamesToAbsolute([n.component]):n.childrenForComponent&&setTNamesToAbsolute(n.childrenForComponent)}Object.assign(n.attributes,t)}else{t[0].attributes||(t[0].attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});for(let e in n){let t=n[e];t.component?setTNamesToAbsolute([t.component]):t.childrenForComponent&&setTNamesToAbsolute(t.childrenForComponent)}Object.assign(t[0].attributes,n)}return t=processAssignNames({assignNames:u,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r}).serializedComponents,e.doenetAttributes.fromCopyFromURI&&i.length>0&&this.addChildrenFromComposite({replacements:t,children:i,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:r}),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let p=await e.stateValues.sourceIndex;if(null!==p){let t=processAssignNames({assignNames:u,serializedComponents:[{componentType:"number",attributes:convertAttributesForComponentType({attributes:e.attributes,componentType:"number",componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a}),state:{value:p,fixed:!0}}],parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:r});return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t.serializedComponents,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}let d=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!d){let t=[];if(e.doenetAttributes.fromCopyTarget){let i=r.componentTypeLowerCaseMapping[e.attributes.createComponentOfType.primitive.toLowerCase()],s=r.allComponentClasses[i],c=convertAttributesForComponentType({attributes:e.attributes,componentType:i,componentInfoObjects:r,compositeAttributesObj:l,compositeCreatesNewNamespace:o,flags:a});n.uniqueIdentifiersUsedBySource[0]=[];let p=getUniqueIdentifierFromBase(i+"|empty",n.uniqueIdentifiersUsedBySource[0]),d=deepClone(e.serializedChildren);s.includeBlankStringChildren||(d=d.filter((e=>"string"!=typeof e||""!==e.trim())));let m=c;e.attributes.assignNewNamespaces?.primitive&&(m.newNamespace={primitive:!0}),t=[{componentType:i,attributes:m,children:d,uniqueIdentifier:p}],t=processAssignNames({assignNames:u,serializedComponents:t,parentName:e.componentName,componentInfoObjects:r,originalNamesAreConsistent:!0}).serializedComponents,n.numReplacementsBySource.push(t.length),n.numNonStringReplacementsBySource.push(t.filter((e=>"string"!=typeof e)).length)}return{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:t,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l})).replacements}}let m=await i({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!m.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let h=await e.stateValues.effectivePropNameBySource;for(let t in d){if(h[t]&&(m=await i({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!m.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let f=[],y=[],g=[],b=0,v=0;for(let i in d){let o,u=n.uniqueIdentifiersUsedBySource[i]=[];if(e.attributes.createComponentOfType?.primitive){let t=await e.stateValues.nComponentsSpecified,n=d.length;o=Math.floor(t/n),i"string"!=typeof e)).length,b+=y[i],v+=g[i],f.push(...p)}return n.numReplacementsBySource=y,n.numNonStringReplacementsBySource=g,n.sourceNames=d.map((e=>e.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:f,assignNames:u,workspace:n,componentInfoObjects:r,compositeAttributesObj:l,flags:a})).replacements}}static async createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c,fromCopyTarget:p}){let d=(await e.stateValues.replacementSourceIdentities)[t];if("object"!=typeof d)return{serializedReplacements:[d]};let m=n[d.componentName],h=await e.stateValues.link;h&&!await e.stateValues.removeEmptyArrayEntries||(d=(await e.stateValues.replacementSources)[t]);let f=e.attributes.newNamespace?.primitive,y=await e.stateValues.effectiveAssignNames,g=(await e.stateValues.effectivePropNameBySource)[t];if(g){let t=await replacementFromProp({component:e,components:n,replacementSource:d,propName:g,numReplacementsSoFar:r,numNonStringReplacementsSoFar:a,uniqueIdentifiersUsed:i,compositeAttributesObj:s,componentInfoObjects:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c});return{serializedReplacements:processAssignNames({assignNames:y,serializedComponents:t.serializedReplacements,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o}).serializedComponents,propVariablesCopiedByReplacement:t.propVariablesCopiedByReplacement}}let b=await e.stateValues.sourceAttributesToIgnore,v=await e.stateValues.sourceAttributesToIgnoreRecursively,N=[await m.serialize({copyAll:!h,copyVariants:!h,sourceAttributesToIgnore:b,sourceAttributesToIgnoreRecursively:v})];h||void 0===N[0].state?.fixed||delete N[0].state.fixed,N=postProcessCopy({serializedComponents:N,componentName:e.componentName,uniqueIdentifiersUsed:i,addShadowDependencies:h,unlinkExternalCopies:!h}),N.length>0&&delete N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:o,compositeAttributesObj:s,compositeCreatesNewNamespace:f,flags:c});Object.assign(t.attributes,n)}return N[0].attributes.newNamespace?.primitive&&!e.attributes.assignNewNamespaces?.primitive&&(N[0].doenetAttributes.haveNewNamespaceOnlyFromShadow=!0),N=processAssignNames({assignNames:y,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,serializedComponents:N,parentName:e.componentName,parentCreatesNewNamespace:f,indOffset:a,componentInfoObjects:o,originalNamesAreConsistent:f&&!y}).serializedComponents,p&&1===N.length&&e.serializedChildren.length>0&&this.addChildrenFromComposite({replacements:N,children:e.serializedChildren,assignNewNamespaces:e.attributes.assignNewNamespaces?.primitive,componentInfoObjects:o}),{serializedReplacements:N}}static addChildrenFromComposite({replacements:e,children:t,assignNewNamespaces:n,componentInfoObjects:r}){let a=e[0];a.children||(a.children=[]);let i=deepClone(t);if(r.allComponentClasses[a.componentType].includeBlankStringChildren||(i=i.filter((e=>"string"!=typeof e||""!==e.trim()))),e[0].attributes.newNamespace?.primitive&&n){renameAutonameBasedOnNewCounts(i,countRegularComponentTypesInNamespace(a.children))}let s=processAssignNames({serializedComponents:i,parentName:e[0].componentName,parentCreatesNewNamespace:n,componentInfoObjects:r,originalNamesAreConsistent:!0});if(e[0].attributes.newNamespace?.primitive&&!n)for(let e of s.serializedComponents)"object"==typeof e&&(e.doenetAttributes.ignoreParentNewNamespace=!0);a.children.push(...s.serializedComponents)}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,flags:i,resolveItem:s,publicCaseInsensitiveAliasSubstitutions:o}){if(await e.stateValues.serializedComponentsForCid)return[];if(null!==await e.stateValues.sourceIndex)return[];let l=this.createAttributesObject(),u=await e.stateValues.effectiveAssignNames,c=await e.stateValues.replacementSourceIdentities;if(!await e.stateValues.targetComponent||!c){if(await e.stateValues.targetSources)return[];{let t=[];if(e.replacements.length>0){let n={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length};t.push(n)}let n=0===r.sourceNames.length;r.sourceNames=[],r.numReplacementsBySource=[],r.numNonStringReplacementsBySource=[],r.propVariablesCopiedBySource=[];let s=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return n?[]:s.replacementChanges}}if(await e.stateValues.targetInactive){let t=[],n=e.replacements.length;if(n>0){if(e.replacementsToWithhold!==n){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:n};t.push(e)}t=(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:t,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i})).replacementChanges}return t}let p=await s({componentName:e.componentName,type:"determineDependencies",stateVariable:"replacementSources",dependency:"__determine_dependencies",expandComposites:!1});if(!p.success)throw Error(`Couldn't resolve determineDependencies of replacementSources of ${e.componentName}`);let d=await e.stateValues.effectivePropNameBySource;for(let t in c){if(d[t]&&(p=await s({componentName:e.componentName,type:"recalculateDownstreamComponents",stateVariable:"replacementSources",dependency:"target"+t,expandComposites:!1}),!p.success))throw Error(`Couldn't resolve recalculateDownstreamComponents for target${t} of replacementSources of ${e.componentName}`)}let m=[];if(e.replacementsToWithhold>0){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};m.push(e)}let h=0,f=0,y=[],g=[],b=[],v=Math.max(c.length,r.numReplacementsBySource.length),N=!1;for(let t=0;t0){if(!N){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToDelete:e};m.push(t)}N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}r.uniqueIdentifiersUsedBySource[t]=[]}y[t]=0,g[t]=0,b.push([]);continue}let p=r.sourceNames[t],v=void 0===p||u.componentName!==p||N;if(!v)for(let n=0;ne+t),0);v.numberReplacementsToReplace=e,N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}m.push(v);continue}if(!d[t]&&r.numReplacementsBySource[t]>0){h+=r.numReplacementsBySource[t],f+=r.numNonStringReplacementsBySource[t],y[t]=r.numReplacementsBySource[t],g[t]=r.numNonStringReplacementsBySource[t];continue}let T=r.uniqueIdentifiersUsedBySource[t]=[],C=await this.createReplacementForSource({component:e,sourceNum:t,components:n,numReplacementsSoFar:h,numNonStringReplacementsSoFar:f,uniqueIdentifiersUsed:T,compositeAttributesObj:l,componentInfoObjects:a,nComponentsForSource:s,publicCaseInsensitiveAliasSubstitutions:o,flags:i}),A=C.propVariablesCopiedByReplacement,V=C.serializedReplacements,x=V.length;if(x!==r.numReplacementsBySource[t]){let e=r.numReplacementsBySource.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h,numberReplacementsToReplace:e,serializedReplacements:V,assignNamesOffset:f};m.push(n),N=!0,r.numReplacementsBySource.slice(t).forEach(((e,t)=>r.numReplacementsBySource[t]=0)),r.numNonStringReplacementsBySource.slice(t).forEach(((e,t)=>r.numNonStringReplacementsBySource[t]=0))}else{let n=0;for(let a=0;ae!==A[a][t]))?(s=!1,i=!0):e.replacements[h+a].componentType!==V[a].componentType&&(i=!0)),0==a&&i&&s){1===await e.stateValues.nComponentsSpecified&&1===x&&!(e.replacementsToWithhold>0)&&1===r.sourceNames.length&&(i=!1)}if(i){let e={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:h+a,numberReplacementsToReplace:1,serializedReplacements:[V[a]],assignNamesOffset:f+n};m.push(e)}"string"!=typeof V[a]&&n++}}let S=V.filter((e=>"string"!=typeof e)).length;h+=x,f+=S,y[t]=x,g[t]=S,b[t]=A}let T=0===r.sourceNames.length;r.numReplacementsBySource=y,r.numNonStringReplacementsBySource=g,r.sourceNames=c.map((e=>e.componentName)),r.propVariablesCopiedBySource=b;let C=await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:m,assignNames:u,workspace:r,componentInfoObjects:a,compositeAttributesObj:l,flags:i});return T&&0===r.sourceNames.length?[]:C.replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,numReplacementsToDelete:a,uniqueIdentifiersUsed:i,components:s,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}){let d=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,numNonStringReplacementsSoFar:r,components:s,uniqueIdentifiersUsed:i,compositeAttributesObj:o,componentInfoObjects:l,nComponentsForSource:u,publicCaseInsensitiveAliasSubstitutions:c,flags:p}),m=d.propVariablesCopiedByReplacement,h=d.serializedReplacements,f={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:a,serializedReplacements:h,assignNamesOffset:r};return{numReplacements:h.length,numNonStringReplacements:h.filter((e=>"string"!=typeof e)).length,propVariablesCopiedByReplacement:m,replacementInstruction:f}}}async function replacementFromProp({component:e,components:t,replacementSource:n,propName:r,uniqueIdentifiersUsed:a,compositeAttributesObj:i,componentInfoObjects:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=[],p=[],d=e.attributes.newNamespace?.primitive,m=-1,h=t[n.componentName],f=l({stateVariables:[r],componentClass:h.constructor})[0];if(void 0===f||"__not_public"===f.slice(0,12))return"__prop_name_not_found"!==r&&console.warn(`Could not find prop ${r} on a component of type ${n.componentType}`),{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let y=h.state[f],g=await y.value,b=await e.stateValues.link;if(y.isArray||y.isArrayEntry){let t,r,l,g;if(y.isArray?(t=y,l=await y.arraySize,r=y.getAllArrayKeys(l,!1)):(t=h.state[y.arrayStateVariable],r=await y.unflattenedArrayKeys,g=await y.arrayKeys),t.shadowingInstructions?.hasVariableComponentType&&(await e.stateValues.replacementSources,!t.shadowingInstructions.createComponentOfType))return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};let v=y.wrappingComponents,N=v.length,T=o;if(y.isArray)T=l.slice(0,l.length-N).reduce(((e,t)=>e*t),1);else if(0===g.length)T=0;else if(0===N)T=g.length;else if(N>=y.nDimensions)T=1;else if(N===y.nDimensions-1)T=r.length;else{T=flattenLevels(r,y.nDimensions-N-1).length}if(0===N){let o=flattenDeep(r);for(let r=0;r1)for(let e of r){let t=await o(e,i-1);l.push(...t.pieces),c.push(...t.propVariablesCopiedByPiece)}else for(let i of r){let r,o,p=t.arrayVarNameFromArrayKey(i),d=[p],m=getUniqueIdentifierFromBase(n.componentName+"|shadow|"+p,a),f=t.shadowingInstructions.createComponentOfType;if(Array.isArray(f)&&(f=f[t.keyToIndex(i)]),t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){r={};for(let e in t.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let n=t.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,a=h.state[n];a.isArray&&(n=a.arrayVarNameFromArrayKey(i)),r[e]={stateVariableToShadow:n}}}if(t.shadowingInstructions.addStateVariablesShadowingStateVariables){o={};for(let e in t.shadowingInstructions.addStateVariablesShadowingStateVariables){let n=t.shadowingInstructions.addStateVariablesShadowingStateVariables[e].stateVariableToShadow,r=h.state[n];r.isArray&&(n=r.arrayVarNameFromArrayKey(i)),o[e]={stateVariableToShadow:n}}}if(b){let t={};if(r){let n=s.allComponentClasses[f].createAttributesObject();for(let a in r){let i=r[a].stateVariableToShadow,s={componentType:n[a].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:i}]}};t[a]={component:s}}}l.push({componentType:f,attributes:t,downstreamDependencies:{[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:p,additionalStateVariableShadowing:o}]},uniqueIdentifier:m})}else{let e={};if(r){let t={};for(let e in r){let n=r[e].stateVariableToShadow,a=h.state[n],s=await a.value;a.isArray&&(s=s[a.keyToIndex[i]]),h.state[n].usedDefault||(t[e]=s)}let n=convertAttributesForComponentType({attributes:t,componentType:f,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}let n="value",a=s.allComponentClasses[f];a.primaryEssentialStateVariable?n=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(n=a.primaryStateVariableForDefinition);let o=t.keyToIndex(i);Array.isArray(o)||(o=[o]);let c=await t.value;for(let e of o)c=c[e];let p={componentType:f,attributes:e,state:{[n]:c},uniqueIdentifier:m};l.push(p)}c.push(d)}let p=v[i-1];if(l.length>0&&p&&p.length>0){for(let e=p.length-1;e>=0;e--){let t="object"==typeof p[e]?p[e].componentType:p[e],n=getUniqueIdentifierFromBase(t+"|wrapper",a),r=[],i={};for(let e of l)if(e.isAttribute){let t=e.isAttribute;delete e.isAttribute,i[t]={component:e}}else r.push(e);l=[{componentType:t,children:r,attributes:i,uniqueIdentifier:n,skipSugar:!0}],"object"==typeof p[e]&&(p[e].doenetAttributes&&(l[0].doenetAttributes=Object.assign({},p[e].doenetAttributes)),p[e].isAttribute&&(l[0].isAttribute=p[e].isAttribute))}c=[flattenDeep(c)]}return{pieces:l,propVariablesCopiedByPiece:c}},l=await o(r,y.nDimensions),N=l.pieces;p=l.propVariablesCopiedByPiece;for(let t of N){if("object"!=typeof t)continue;t.attributes||(t.attributes={});let r=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});Object.assign(t.attributes,r),b&&(t.downstreamDependencies={[n.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,ignorePrimaryStateVariable:!0}]})}if(m+=N.length,c.push(...N),N.length0?"object"==typeof i[0]?(n=i[0].componentType,r=Object.assign({},i[0].doenetAttributes)):n=i[0]:(n=t.shadowingInstructions.createComponentOfType,Array.isArray(n)&&(n=y.isArrayEntry?n[t.keyToIndex(g[e])]:n[e]));let s={componentType:n,uniqueIdentifier:getUniqueIdentifierFromBase(n+"|empty",a)};r&&(s.doenetAttributes=r),c.push(s)}else if(N>T)throw Error(`Something went wrong when creating replacements for ${e.componentName} as we ended up with too many replacements`)}}else{if(y.shadowingInstructions?.hasVariableComponentType&&await y.value,!y.shadowingInstructions?.createComponentOfType)return{serializedReplacements:[],propVariablesCopiedByReplacement:[]};m++,(p[m]=[]).push(f);let t=getUniqueIdentifierFromBase(h.componentName+"|shadow|"+f,a);if("string"===y.shadowingInstructions.createComponentOfType)c.push(await y.value);else{let n=convertAttributesForComponentType({attributes:e.attributes,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,compositeAttributesObj:i,compositeCreatesNewNamespace:d,flags:u});if(b){let r={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t=s.allComponentClasses[y.shadowingInstructions.createComponentOfType].createAttributesObject();for(let n in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let a=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[n].stateVariableToShadow,i={componentType:t[n].createComponentOfType,downstreamDependencies:{[h.componentName]:[{compositeName:e.componentName,dependencyType:"referenceShadow",propVariable:a}]}};r[n]={component:i}}}Object.assign(r,n),c.push({componentType:y.shadowingInstructions.createComponentOfType,attributes:r,downstreamDependencies:{[h.componentName]:[{dependencyType:"referenceShadow",compositeName:e.componentName,propVariable:f,additionalStateVariableShadowing:y.shadowingInstructions.addStateVariablesShadowingStateVariables}]},uniqueIdentifier:t})}else{let e={};if(y.shadowingInstructions.addAttributeComponentsShadowingStateVariables){let t={};for(let e in y.shadowingInstructions.addAttributeComponentsShadowingStateVariables)if("fixed"!==e){let n=y.shadowingInstructions.addAttributeComponentsShadowingStateVariables[e].stateVariableToShadow,r=await h.state[n].value;h.state[n].usedDefault||(t[e]=r)}let n=convertAttributesForComponentType({attributes:t,componentType:y.shadowingInstructions.createComponentOfType,componentInfoObjects:s,flags:u});if(y.shadowingInstructions.attributesToShadow)for(let e of y.shadowingInstructions.attributesToShadow)h.attributes[e]?.component?n[e]={component:await(h.attributes[e]?.component.serialize({copyAll:!0,copyVariants:!0}))}:void 0!==h.attributes[e]?.primitive&&(n[e]={primitive:JSON.parse(JSON.stringify(h.attributes[e].primitive))});Object.assign(e,n)}Object.assign(e,n);let r="value",a=s.allComponentClasses[y.shadowingInstructions.createComponentOfType];a.primaryEssentialStateVariable?r=a.primaryEssentialStateVariable:a.primaryStateVariableForDefinition&&(r=a.primaryStateVariableForDefinition);let i={componentType:y.shadowingInstructions.createComponentOfType,attributes:e,state:{[r]:g},uniqueIdentifier:t};c.push(i)}}}return{serializedReplacements:c,propVariablesCopiedByReplacement:p}}class Extract extends CompositeComponent{static componentType="extract";static assignNamesToReplacements=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.createComponentOfType={createPrimitiveOfType:"string"},e.nComponents={createPrimitiveOfType:"number"},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nComponentsSpecified={returnDependencies:()=>({nComponentsAttr:{dependencyType:"attributePrimitive",attributeName:"nComponents"},typeAttr:{dependencyType:"attributePrimitive",attributeName:"createComponentOfType"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n;if(e.typeAttr){if(!(t.componentTypeLowerCaseMapping[e.typeAttr.toLowerCase()]in t.allComponentClasses))throw Error(`Invalid componentType ${e.typeAttr} of copy.`);n=null!==e.nComponentsAttr?e.nComponentsAttr:1}else{if(null!==e.nComponentsAttr)throw Error("You must specify createComponentOfType when specifying nComponents for a copy.");n=null}return{setValue:{nComponentsSpecified:n}}}},e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.sourceComponents={stateVariablesDeterminingDependencies:["propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameBySource"],returnDependencies:function({stateValues:e}){let t,n;null!==e.componentIndex&&(n=Number(e.componentIndex),t=Number.isInteger(n)?[n-1]:[]);let r=e.propIndex;return r&&(r=[...r]),{children:{dependencyType:"child",childGroups:["anything"],variableNames:[e.propName],variablesOptional:!0,childIndices:t,propIndex:r,caseInsensitiveVariableMatch:!0,publicStateVariablesOnly:!0,useMappedVariableNames:!0},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.children,n=[];for(let e of t){let t;e.stateValues&&(t=Object.keys(e.stateValues)[0]),t||(t="__prop_name_not_found"),n.push(t)}return{setValue:{sourceComponents:t,effectivePropNameBySource:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({replacementClasses:{dependencyType:"stateVariable",variableName:"sourceComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({sourceComponents:{dependencyType:"stateVariable",variableName:"sourceComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=[],l=0;n.propVariablesCopiedBySource=[],n.uniqueIdentifiersUsedBySource={};let u=this.createAttributesObject(),c=await e.stateValues.sourceComponents;for(let a=0;ae.componentName)),{replacements:(await verifyReplacementsMatchSpecifiedType({component:e,replacements:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:u,flags:a})).replacements}}static async createReplacementForSource({component:e,components:t,sourceNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,publicCaseInsensitiveAliasSubstitutions:o}){let l=(await e.stateValues.effectivePropNameBySource)[n],u=await replacementFromProp({component:e,components:t,replacementSource:(await e.stateValues.sourceComponents)[n],propName:l,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,publicCaseInsensitiveAliasSubstitutions:o}),c=u.serializedReplacements,p=u.propVariablesCopiedByReplacement,d=e.attributes.newNamespace?.primitive;return c=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:c,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:d,componentInfoObjects:i}).serializedComponents,{serializedReplacements:c,propVariablesCopiedByReplacement:p}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a,publicCaseInsensitiveAliasSubstitutions:i}){let s=[],o=0,l=[],u=[],c=this.createAttributesObject(),p=await e.stateValues.sourceComponents,d=Math.max(p.length,n.numReplacementsBySource.length),m=!1;for(let a=0;a0){if(!m){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToDelete:e};s.push(t)}m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}n.uniqueIdentifiersUsedBySource[a]=[]}l[a]=0,u.push([]);continue}let h=n.sourceNames[a],f=void 0===h||d.componentName!==h||m;if(!f)for(let t=0;te+t),0);g.numberReplacementsToReplace=e,m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}s.push(g);continue}let y=n.uniqueIdentifiersUsedBySource[a]=[],g=await this.createReplacementForSource({component:e,sourceNum:a,components:t,numReplacementsSoFar:o,uniqueIdentifiersUsed:y,componentInfoObjects:r,compositeAttributesObj:c,publicCaseInsensitiveAliasSubstitutions:i}),b=g.propVariablesCopiedByReplacement,v=g.serializedReplacements,N=v.length;if(N!==n.numReplacementsBySource[a]){let e=n.numReplacementsBySource.slice(a).reduce(((e,t)=>e+t),0),t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o,numberReplacementsToReplace:e,serializedReplacements:v,assignNamesOffset:o};s.push(t),m=!0,n.numReplacementsBySource.slice(a).forEach(((e,t)=>n.numReplacementsBySource[t]=0))}else for(let e=0;et!==b[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:o+e,numberReplacementsToReplace:1,serializedReplacements:[v[e]],assignNamesOffset:o+e};s.push(t)}o+=N,l[a]=N,u[a]=b}return n.numReplacementsBySource=l,n.numNonStringReplacementsBySource=[...l],n.sourceNames=p.map((e=>e.componentName)),n.propVariablesCopiedBySource=u,(await verifyReplacementsMatchSpecifiedType({component:e,replacementChanges:s,assignNames:e.doenetAttributes.assignNames,workspace:n,componentInfoObjects:r,compositeAttributesObj:c,flags:a})).replacementChanges}static async recreateReplacements({component:e,sourceNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}){let u=await this.createReplacementForSource({component:e,sourceNum:t,numReplacementsSoFar:n,components:i,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,publicCaseInsensitiveAliasSubstitutions:l}),c=u.propVariablesCopiedByReplacement,p=u.serializedReplacements,d={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:p,assignNamesOffset:n};return{numReplacements:p.length,propVariablesCopiedByReplacement:c,replacementInstruction:d}}}class Collect extends CompositeComponent{static componentType="collect";static assignNamesToReplacements=!0;static acceptTarget=!0;static acceptAnyAttribute=!0;static stateVariableToEvaluateAfterReplacements="needsReplacementsUpdatedWhenStale";static createAttributesObject(){let e=super.createAttributesObject();return delete e.disabled,delete e.modifyIndirectly,delete e.fixed,delete e.styleNumber,delete e.isResponse,e.assignNamesSkip={createPrimitiveOfType:"number"},e.prop={createPrimitiveOfType:"string"},e.maximumNumber={createComponentOfType:"number",createStateVariable:"maximumNumber",defaultValue:null,public:!0},e.componentIndex={createComponentOfType:"integer",createStateVariable:"componentIndex",defaultValue:null,public:!0},e.propIndex={createComponentOfType:"numberList",createStateVariable:"propIndex",defaultValue:null,public:!0},e.sourceAttributesToIgnore={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnore",defaultValue:[],public:!0},e.sourceAttributesToIgnoreRecursively={createPrimitiveOfType:"stringArray",createStateVariable:"sourceAttributesToIgnoreRecursively",defaultValue:["isResponse"],public:!0},e.componentTypes={createComponentOfType:"textList"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.link={returnDependencies:()=>({}),definition:()=>({setValue:{link:!0}})},e.targetComponent={shadowVariable:!0,returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"}}),definition:function({dependencyValues:e}){return null===e.targetComponent?(console.warn("No copy target"),{setValue:{targetName:""}}):{setValue:{targetName:e.targetComponent.componentName}}}},e.propName={shadowVariable:!0,returnDependencies:()=>({propName:{dependencyType:"attributePrimitive",attributeName:"prop"}}),definition:function({dependencyValues:e}){return{setValue:{propName:e.propName}}}},e.componentTypesToCollect={shadowVariable:!0,additionalStateVariablesDefined:[{variableName:"componentClassesToCollect",shadowVariable:!0}],returnDependencies:()=>({componentTypesAttr:{dependencyType:"attributeComponent",attributeName:"componentTypes",variableNames:["texts"]}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[],r=[];if(null!==e.componentTypesAttr)for(let a of e.componentTypesAttr.stateValues.texts){let e=t.componentTypeLowerCaseMapping[a.toLowerCase()],i=t.allComponentClasses[e];if(i)n.push(e),r.push(i);else{let e="Cannot collect component type "+a+". Component type not found.";console.warn(e)}}return{setValue:{componentTypesToCollect:n,componentClassesToCollect:r}}}},e.collectedComponents={stateVariablesDeterminingDependencies:["componentTypesToCollect","targetName","propName","componentIndex","propIndex"],additionalStateVariablesDefined:["effectivePropNameByComponent"],returnDependencies:function({stateValues:e}){if(!e.targetName)return{};let t={dependencyType:"descendant",ancestorName:e.targetName,componentTypes:e.componentTypesToCollect,useReplacementsForComposites:!0,includeNonActiveChildren:!0,recurseToMatchedChildren:!1,componentIndex:e.componentIndex};if(e.propName){let n=e.propIndex;n&&(n=[...n]),t.variableNames=[e.propName],t.variablesOptional=!0,t.propIndex=n,t.caseInsensitiveVariableMatch=!0,t.publicStateVariablesOnly=!0,t.useMappedVariableNames=!0}return{descendants:t,maximumNumber:{dependencyType:"stateVariable",variableName:"maximumNumber"},propName:{dependencyType:"stateVariable",variableName:"propName"}}},definition:function({dependencyValues:e}){let t=e.descendants;if(t||(t=[]),null!==e.maximumNumber&&t.length>e.maximumNumber){let n=Math.max(0,Math.floor(e.maximumNumber));t=t.slice(0,n)}let n=[];for(let r of t){let t;r.stateValues&&(t=Object.keys(r.stateValues)[0]),!t&&e.propName&&(t="__prop_name_not_found"),n.push(t)}return{setValue:{collectedComponents:t,effectivePropNameByComponent:n}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"},needsReplacementsUpdatedWhenStale:{dependencyType:"stateVariable",variableName:"needsReplacementsUpdatedWhenStale"}}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.needsReplacementsUpdatedWhenStale={returnDependencies:()=>({collectedComponents:{dependencyType:"stateVariable",variableName:"collectedComponents"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{needsReplacementsUpdatedWhenStale:!0}})},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r,nComponentsForSource:a,publicCaseInsensitiveAliasSubstitutions:i,flags:s}){if(!await e.stateValues.targetComponent)return{replacements:[]};let o=[],l=[],u=0,c=[];n.propVariablesCopiedByCollected=[],n.uniqueIdentifiersUsedByCollected={};let p=this.createAttributesObject(),d=await e.stateValues.collectedComponents;for(let m=0;me.componentName))}else l[m]=0,c[m]=[],n.propVariablesCopiedByCollected[m]=[];return n.numReplacementsByCollected=l,n.collectedNames=d.map((e=>e.componentName)),n.replacementNamesByCollected=c,{replacements:o}}static async createReplacementForCollected({component:e,components:t,collectedNum:n,numReplacementsSoFar:r,uniqueIdentifiersUsed:a,componentInfoObjects:i,compositeAttributesObj:s,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l,flags:u}){let c=(await e.stateValues.collectedComponents)[n],p=t[c.componentName],d=[],m=[];if(!p)return{serializedReplacements:d,propVariablesCopiedByReplacement:m};let h=e.attributes.newNamespace?.primitive,f=(await e.stateValues.effectivePropNameByComponent)[n];if(f){let n=await replacementFromProp({component:e,components:t,replacementSource:c,propName:f,uniqueIdentifiersUsed:a,compositeAttributesObj:s,componentInfoObjects:i,nComponentsForSource:o,publicCaseInsensitiveAliasSubstitutions:l});d=n.serializedReplacements,m=n.propVariablesCopiedByReplacement}else{let t=await e.stateValues.sourceAttributesToIgnore,r=await e.stateValues.sourceAttributesToIgnoreRecursively;d=postProcessCopy({serializedComponents:[await p.serialize({sourceAttributesToIgnore:t,sourceAttributesToIgnoreRecursively:r})],componentName:e.componentName,uniqueIdentifiersUsed:a,identifierPrefix:n+"|"});for(let t of d){t.attributes||(t.attributes={});let n=convertAttributesForComponentType({attributes:e.attributes,componentType:t.componentType,componentInfoObjects:i,compositeAttributesObj:s,compositeCreatesNewNamespace:h,flags:u});Object.assign(t.attributes,n)}}return d=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,indOffset:r,parentCreatesNewNamespace:h,componentInfoObjects:i}).serializedComponents,{serializedReplacements:d,propVariablesCopiedByReplacement:m}}static async calculateReplacementChanges({component:e,componentChanges:t,components:n,workspace:r,componentInfoObjects:a,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}){let l=0;for(let t=0;t0){if(!y){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);if(e>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToDelete:e};u.push(t)}y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}r.uniqueIdentifiersUsedByCollected[t]=[]}p[t]=0,d.push([]),m.push([]);continue}let f=r.collectedNames[t];if(void 0===f||l.componentName!==f||y){let l=0;void 0!==f&&(l=r.numReplacementsByCollected[t]);let h=l;y&&(h=0);let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:c,numReplacementsToDelete:h,components:n,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o});c+=v.numReplacements,p[t]=v.numReplacements,d[t]=v.propVariablesCopiedByReplacement;let N=v.replacementInstruction;if(m[t]=N.serializedReplacements.map((e=>e.componentName)),!y&&v.numReplacements!==l){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0);N.numberReplacementsToReplace=e,y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}u.push(N);continue}if(!await e.stateValues.propName){c+=r.numReplacementsByCollected[t],p[t]=r.numReplacementsByCollected[t],m[t]=r.replacementNamesByCollected[t],d[t]=[];continue}let b=r.uniqueIdentifiersUsedByCollected[t]=[],v=await this.createReplacementForCollected({component:e,collectedNum:t,components:n,numReplacementsSoFar:c,uniqueIdentifiersUsed:b,componentInfoObjects:a,compositeAttributesObj:g,nComponentsForSource:i,publicCaseInsensitiveAliasSubstitutions:s,flags:o}),N=v.propVariablesCopiedByReplacement,T=v.serializedReplacements,C=T.length;if(C!==r.numReplacementsByCollected[t]){let e=r.numReplacementsByCollected.slice(t).reduce(((e,t)=>e+t),0),n={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c,numberReplacementsToReplace:e,serializedReplacements:T,assignNamesOffset:c};u.push(n),y=!0,r.numReplacementsByCollected.slice(t).forEach(((e,t)=>r.numReplacementsByCollected[t]=0))}else for(let e=0;et!==N[e][n]))){let t={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:c+e,numberReplacementsToReplace:1,serializedReplacements:[T[e]],assignNamesOffset:c+e};u.push(t)}c+=C,p[t]=C,d[t]=N,m[t]=T.map((e=>e.componentName))}return r.numReplacementsByCollected=p,r.collectedNames=h.map((e=>e.componentName)),r.propVariablesCopiedByCollected=d,r.replacementNamesByCollected=m,u}static async recreateReplacements({component:e,collectedNum:t,numReplacementsSoFar:n,numReplacementsToDelete:r,uniqueIdentifiersUsed:a,components:i,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}){let p=await this.createReplacementForCollected({component:e,collectedNum:t,components:i,numReplacementsSoFar:n,uniqueIdentifiersUsed:a,componentInfoObjects:s,compositeAttributesObj:o,nComponentsForSource:l,publicCaseInsensitiveAliasSubstitutions:u,flags:c}),d=p.propVariablesCopiedByReplacement,m=p.serializedReplacements,h={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:n,numberReplacementsToReplace:r,serializedReplacements:m,assignNamesOffset:n};return{numReplacements:m.length,propVariablesCopiedByReplacement:d,replacementInstruction:h}}}class Ref extends InlineComponent{constructor(e){super(e),Object.assign(this.actions,{navigateToTarget:this.navigateToTarget.bind(this)})}static componentType="ref";static renderChildren=!0;static acceptTarget=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.textType={createComponentOfType:"text",createStateVariable:"textType",defaultValue:"type-global",public:!0},e.uri={createPrimitiveOfType:"string",createStateVariable:"uri",defaultValue:null,public:!0,forRenderer:!0},e.page={createPrimitiveOfType:"integer",createStateVariable:"page",defaultValue:null,public:!0,forRenderer:!0},e.createButton={createComponentOfType:"boolean",createStateVariable:"createButton",defaultValue:!1,forRenderer:!0},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.targetComponent={returnDependencies:()=>({targetComponent:{dependencyType:"targetComponent"}}),definition:function({dependencyValues:e}){return{setValue:{targetComponent:e.targetComponent}}}},e.targetInactive={stateVariablesDeterminingDependencies:["targetComponent"],returnDependencies:({stateValues:e})=>e.targetComponent?{targetIsInactiveCompositeReplacement:{dependencyType:"stateVariable",componentName:e.targetComponent.componentName,variableName:"isInactiveCompositeReplacement"}}:{},definition:function({dependencyValues:e}){return{setValue:{targetInactive:Boolean(e.targetIsInactiveCompositeReplacement)}}}},e.targetName={forRenderer:!0,returnDependencies:()=>({targetComponent:{dependencyType:"stateVariable",variableName:"targetComponent"},uri:{dependencyType:"stateVariable",variableName:"uri"},page:{dependencyType:"stateVariable",variableName:"page"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"},targetAttribute:{dependencyType:"doenetAttribute",attributeName:"target"}}),definition:function({dependencyValues:e}){if(e.uri||e.page){if(e.targetAttribute){let t=e.targetAttribute;return"/"!==t[0]&&(t="/"+t),{setValue:{targetName:t}}}return{setValue:{targetName:""}}}return null===e.targetComponent||e.targetInactive?{setValue:{targetName:""}}:{setValue:{targetName:e.targetComponent.componentName}}}},e.cid={forRenderer:!0,additionalStateVariablesDefined:[{variableName:"doenetId",forRenderer:!0},{variableName:"variantIndex",forRenderer:!0},{variableName:"edit",forRenderer:!0},{variableName:"draft",forRenderer:!0},{variableName:"hash",forRenderer:!0}],returnDependencies:()=>({uri:{dependencyType:"stateVariable",variableName:"uri"}}),definition:function({dependencyValues:e}){if(!e.uri||"doenet:"!==e.uri.substring(0,7).toLowerCase())return{setValue:{cid:null,doenetId:null,variantIndex:null,edit:null,draft:null,hash:null}};let t=null,n=null,r=null,a=null,i=null,s=null,o=e.uri.match(/[:&]cid=([^&^#]+)/i);return o&&(t=o[1]),o=e.uri.match(/[:&]doenetid=([^&^#]+)/i),o&&(n=o[1]),o=e.uri.match(/[:&]variant=([^&^#]+)/i),o&&(r=Number(o[1]),!Number.isInteger(r)&&r>=1&&(r=1)),o=e.uri.match(/[:&]edit=([^&^#]+)/i),o&&(i="true"===o[1].toLowerCase()),o=e.uri.match(/[:&]draft=([^&^#]+)/i),o&&(a="true"===o[1].toLowerCase()),o=e.uri.match(/(#.+)/i),o&&(s=o[1]),{setValue:{cid:t,doenetId:n,variantIndex:r,edit:i,draft:a,hash:s}}}},e.linkText={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,stateVariablesDeterminingDependencies:["targetName"],returnDependencies({stateValues:e}){let t={allChildren:{dependencyType:"child",childGroups:["anything"],variableNames:["text"],variablesOptional:!0},uri:{dependencyType:"stateVariable",variableName:"uri"},targetInactive:{dependencyType:"stateVariable",variableName:"targetInactive"}};return e.targetName&&(t.equationTag={dependencyType:"stateVariable",componentName:e.targetName,variableName:"equationTag",variablesOptional:!0},t.title={dependencyType:"stateVariable",componentName:e.targetName,variableName:"title",variablesOptional:!0}),t},definition:function({dependencyValues:e}){let t="";if(0===e.allChildren.length)null!==e.uri?t=e.uri:e.targetInactive||(null!==e.title?t=e.title:null!==e.equationTag&&(t="("+e.equationTag+")"));else for(let n of e.allChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return t||(t="???"),{setValue:{linkText:t}}}},e}async navigateToTarget({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.cid,n=await this.stateValues.doenetId,r=await this.stateValues.variantIndex,a=await this.stateValues.edit,i=await this.stateValues.hash,s=await this.stateValues.page,o=await this.stateValues.uri,l=await this.stateValues.targetName,u=this.componentOrAdaptedName;this.coreFunctions.navigateToTarget({cid:t,doenetId:n,variantIndex:r,edit:a,hash:i,page:s,uri:o,targetName:l,actionId:e,componentName:this.componentName,effectiveName:u})}}}class Coords extends MathComponent{static componentType="coords";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createVectors,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createVectors={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createVectors:!0}})},e}}class LineSegment extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveLineSegment:this.moveLineSegment.bind(this),lineSegmentClicked:this.lineSegmentClicked.bind(this),mouseDownOnLineSegment:this.mouseDownOnLineSegment.bind(this)})}static componentType="lineSegment";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpointsDraggable={createComponentOfType:"boolean"},e.endpoints={createComponentOfType:"_pointListComponent"},e.showCoordsWhenDragging={createComponentOfType:"boolean",createStateVariable:"showCoordsWhenDragging",defaultValue:!0,public:!0,forRenderer:!0},e.labelPosition={createComponentOfType:"text",createStateVariable:"labelPosition",defaultValue:"upperright",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["upperright","upperleft","lowerright","lowerleft"]},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" line segment"}}}},e.endpointsDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({endpointsDraggableAttr:{dependencyType:"attributeComponent",attributeName:"endpointsDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.endpointsDraggableAttr?{setValue:{endpointsDraggable:e.endpointsDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{endpointsDraggable:{defaultValue:e.draggable}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["nDimensions"]}}),definition:function({dependencyValues:e}){if(null!==e.endpointsAttr){return{setValue:{nDimensions:e.endpointsAttr.stateValues.nDimensions},checkForActualChange:{nDimensions:!0}}}return{setValue:{nDimensions:2}}}},e.endpoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["endpointX","endpoint"],hasEssential:!0,set:convertValueToMathExpression,defaultValueByArrayKey:e=>me$3.fromAst("0,0"===e?1:0),getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("endpointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("endpoints"===t)return 1===e.length?"endpoint"+e[0]:`endpointX${e[0]}_${e[1]}`;if("endpoint"===t.slice(0,8)){let n=Number(t.slice(8));if(Number.isInteger(n)&&n>0)return`endpointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={endpointsAttr:{dependencyType:"attributeComponent",attributeName:"endpoints",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,arraySize:n}){let r={},a={};for(let n of t){let[t,i]=n.split(","),s=Number(t)+1+"_"+(Number(i)+1);null!==e[n].endpointsAttr&&e[n].endpointsAttr.stateValues["pointX"+s]?r[n]=e[n].endpointsAttr.stateValues["pointX"+s]:a[n]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoints:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoints:a}),i},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){let i=[];for(let r in e.endpoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].endpointsAttr&&t[r].endpointsAttr.stateValues["pointX"+o]?i.push({setDependency:n[r].endpointsAttr,desiredValue:e.endpoints[r],childIndex:0,variableIndex:0}):i.push({setEssentialValue:"endpoints",value:{[r]:e.endpoints[r]}})}return{success:!0,instructions:i}}},e.length={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoints:{dependencyType:"stateVariable",variableName:"endpoints"}}),definition({dependencyValues:e}){let t=0,n=e.endpoints[0],r=e.endpoints[1],a=!0;for(let i=0;ie+t*t),0));r=r.map((e=>e/o));let l=e.length.evaluate_to_constant();if(!Number.isFinite(l)||l<0)return{success:!1};let u=[],c=[],p=l/2;for(let e=0;e({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>Number.isNaN(e.nDimensions)?[0]:[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={endpoint:{dependencyType:"stateVariable",variableName:"endpoint"+(Number(n)+1)}};return{globalDependencies:{nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}},dependenciesByKey:t}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(Number.isNaN(e.nDimensions))return{};let r={};for(let a of n){let n=t[a].endpoint,i=[];for(let t=0;t({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0][0],n=e.numericalEndpoints[0][1],r=e.numericalEndpoints[1][0],a=e.numericalEndpoints[1][1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e.slope={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition({dependencyValues:e}){if(2!==e.nDimensions)return{setValue:{slope:NaN}};let t=e.numericalEndpoints;return{setValue:{slope:(t[1][1]-t[0][1])/(t[1][0]-t[0][0])}}}},e}async moveLineSegment({point1coords:e,point2coords:t,transient:n,actionId:r}){if(void 0===e||void 0===t){if(!await this.stateValues.endpointsDraggable)return await this.coreFunctions.resolveAction({actionId:r})}else if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:r});let a={};return void 0!==e&&(a["0,0"]=me$3.fromAst(e[0]),a["0,1"]=me$3.fromAst(e[1])),void 0!==t&&(a["1,0"]=me$3.fromAst(t[0]),a["1,1"]=me$3.fromAst(t[1])),n?await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],transient:!0,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:[{componentName:this.componentName,updateType:"updateValue",stateVariable:"endpoints",value:a}],actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{point1:e,point2:t}}})}async lineSegmentClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnLineSegment({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Ray extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveRay:this.moveRay.bind(this),rayClicked:this.rayClicked.bind(this),mouseDownOnRay:this.mouseDownOnRay.bind(this)})}static componentType="ray";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.endpoint={createComponentOfType:"point"},e.through={createComponentOfType:"point"},e.direction={createComponentOfType:"vector"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" ray"}}}},e.directionShadow={defaultValue:null,hasEssential:!0,essentialVarName:"direction",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{directionShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"directionShadow",value:convertValueToMathExpression(e.directionShadow)}]}}},e.throughShadow={defaultValue:null,hasEssential:!0,essentialVarName:"through",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{throughShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"throughShadow",value:convertValueToMathExpression(e.throughShadow)}]}}},e.endpointShadow={defaultValue:null,hasEssential:!0,essentialVarName:"endpoint",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{endpointShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"endpointShadow",value:convertValueToMathExpression(e.endpointShadow)}]}}},e.basedOnThrough={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr&&null!==e.directionAttr?(null!==e.throughAttr&&console.warn("Ray is prescribed by through, endpoint, and direction. Ignoring specified through."),{setValue:{basedOnThrough:!1},checkForActualChange:{basedOnThrough:!0}}):null!==e.throughAttr?{setValue:{basedOnThrough:!0},checkForActualChange:{basedOnThrough:!0}}:{setValue:{basedOnThrough:null!==e.throughShadow},checkForActualChange:{basedOnThrough:!0}}}},e.basedOnEndpoint={returnDependencies:()=>({endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}}),definition:function({dependencyValues:e}){return null!==e.endpointAttr?{setValue:{basedOnEndpoint:!0},checkForActualChange:{basedOnEndpoint:!0}}:{setValue:{basedOnEndpoint:null!==e.endpointShadow},checkForActualChange:{basedOnEndpoint:!0}}}},e.basedOnDirection={returnDependencies:()=>({directionAttr:{dependencyType:"attributeComponent",attributeName:"direction"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}}),definition:function({dependencyValues:e}){return null!==e.directionAttr?{setValue:{basedOnDirection:!0},checkForActualChange:{basedOnDirection:!0}}:{setValue:{basedOnDirection:null!==e.directionShadow},checkForActualChange:{basedOnDirection:!0}}}},e.nDimDirection={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"},directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["nDimensions"]}};return e.basedOnDirection||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(null!==e.directionAttr)t=e.directionAttr.stateValues.nDimensions;else if(e.directionShadow){let n=e.directionShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnThrough?e.basedOnEndpoint?e.nDimThrough===e.nDimEndpoint?e.nDimThrough:NaN:e.nDimThrough:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimDirection:t},checkForActualChange:{nDimDirection:!0}}}},e.nDimThrough={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nDimensions"]}};return e.basedOnThrough||(e.basedOnEndpoint&&(t.nDimEndpoint={dependencyType:"stateVariable",variableName:"nDimEndpoint"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnThrough){if(null!==e.throughAttr)t=e.throughAttr.stateValues.nDimensions;else if(e.throughShadow){let n=e.throughShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnEndpoint?e.nDimDirection===e.nDimEndpoint?e.nDimDirection:NaN:e.nDimDirection:e.basedOnEndpoint?e.nDimEndpoint:2;return{setValue:{nDimThrough:t},checkForActualChange:{nDimThrough:!0}}}},e.nDimEndpoint={stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough","basedOnEndpoint"],returnDependencies({stateValues:e}){let t={basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"},endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["nDimensions"]}};return e.basedOnEndpoint||(e.basedOnThrough&&(t.nDimThrough={dependencyType:"stateVariable",variableName:"nDimThrough"}),e.basedOnDirection&&(t.nDimDirection={dependencyType:"stateVariable",variableName:"nDimDirection"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnEndpoint){if(null!==e.endpointAttr)t=e.endpointAttr.stateValues.nDimensions;else if(e.endpointShadow){let n=e.endpointShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDirection?e.basedOnThrough?e.nDimDirection===e.nDimThrough?e.nDimDirection:NaN:e.nDimDirection:e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimEndpoint:t},checkForActualChange:{nDimEndpoint:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"},nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"},nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDirection){if(e.basedOnEndpoint){if(e.nDimDirection!==e.nDimEndpoint)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnThrough&&e.nDimDirection!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDirection}else if(e.basedOnEndpoint){if(e.basedOnThrough&&e.nDimEndpoint!==e.nDimThrough)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimEndpoint}else t=e.basedOnThrough?e.nDimThrough:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.direction={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"directionX"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["directionX"],hasEssential:!0,essentialVarName:"direction2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDirection","basedOnThrough"],returnArraySizeDependencies:()=>({nDimDirection:{dependencyType:"stateVariable",variableName:"nDimDirection"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDirection],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={directionAttr:{dependencyType:"attributeComponent",attributeName:"direction",variableNames:["x"+e]}},!t.basedOnDirection&&t.basedOnThrough&&(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e})}return{globalDependencies:{basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},directionShadow:{dependencyType:"stateVariable",variableName:"directionShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;e.basedOnDirection?null!==t[i].directionAttr?r[i]=t[i].directionAttr.stateValues["x"+n]:null!==e.directionShadow&&(r[i]=e.directionShadow.get_component(Number(i))):e.basedOnThrough?r[i]=t[i].throughX.subtract(t[i].endpointX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={direction:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={direction:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.direction)t.basedOnDirection?null!==n[a].directionAttr?i.push({setDependency:r[a].directionAttr,desiredValue:e.direction[a],variableIndex:0}):s=!0:t.basedOnThrough?i.push({setDependency:r[a].throughX,desiredValue:n[a].endpointX.add(e.direction[a]).simplify()}):i.push({setEssentialValue:"direction",value:{[a]:convertValueToMathExpression(e.direction[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.direction)t[Number(n)+1]=e.direction[n].tree;t.length=a[0]+1,i.push({setDependency:"directionShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.direction&&i.push({setDependency:"directionShadow",desiredValue:e.direction[0]});return{success:!0,instructions:i}}},e.through={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["throughX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnThrough"],returnArraySizeDependencies:()=>({nDimThrough:{dependencyType:"stateVariable",variableName:"nDimThrough"}}),returnArraySize:({dependencyValues:e})=>[e.nDimThrough],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["x"+e]}},t.basedOnThrough||(n[r].endpointX={dependencyType:"stateVariable",variableName:"endpointX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnEndpoint:{dependencyType:"stateVariable",variableName:"basedOnEndpoint"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},throughShadow:{dependencyType:"stateVariable",variableName:"throughShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnThrough?null!==t[a].throughAttr?r[a]=t[a].throughAttr.stateValues["x"+n]:null!==e.throughShadow&&(r[a]=e.throughShadow.get_component(Number(a))):r[a]=t[a].endpointX.add(t[a].directionX).simplify()}return{setValue:{through:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.through)t.basedOnThrough?n[a].throughAttr&&null!==n[a].throughAttr?i.push({setDependency:r[a].throughAttr,desiredValue:e.through[a],variableIndex:0}):null!==t.throughShadow&&(s=!0):i.push({setDependency:r[a].directionX,desiredValue:e.through[a].subtract(n[a].endpointX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.through)t[Number(n)+1]=e.through[n].tree;t.length=a[0]+1,i.push({setDependency:"throughShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.through&&i.push({setDependency:"throughShadow",desiredValue:e.through[0]});return{success:!0,instructions:i}}},e.endpoint={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"endpointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["endpointX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"endpoint2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnEndpoint","basedOnThrough","basedOnDirection"],returnArraySizeDependencies:()=>({nDimEndpoint:{dependencyType:"stateVariable",variableName:"nDimEndpoint"}}),returnArraySize:({dependencyValues:e})=>[e.nDimEndpoint],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={endpointAttr:{dependencyType:"attributeComponent",attributeName:"endpoint",variableNames:["x"+e]}},t.basedOnEndpoint||t.basedOnThrough&&t.basedOnDirection&&(n[r].throughX={dependencyType:"stateVariable",variableName:"throughX"+e},n[r].directionX={dependencyType:"stateVariable",variableName:"directionX"+e})}return{globalDependencies:{basedOnDirection:{dependencyType:"stateVariable",variableName:"basedOnDirection"},basedOnThrough:{dependencyType:"stateVariable",variableName:"basedOnThrough"},endpointShadow:{dependencyType:"stateVariable",variableName:"endpointShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].endpointAttr?r[i]=t[i].endpointAttr.stateValues["x"+n]:null!==e.endpointShadow?r[i]=e.endpointShadow.get_component(Number(i)):e.basedOnThrough&&e.basedOnDirection?r[i]=t[i].throughX.subtract(t[i].directionX).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={endpoint:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={endpoint:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.endpoint)n[a].endpointAttr&&null!==n[a].endpointAttr?i.push({setDependency:r[a].endpointAttr,desiredValue:e.endpoint[a],variableIndex:0}):null!==t.endpointShadow?s=!0:t.basedOnThrough&&t.basedOnDirection?i.push({setDependency:r[a].directionX,desiredValue:n[a].throughX.subtract(e.endpoint[a]).simplify()}):i.push({setEssentialValue:"endpoint",value:{[a]:convertValueToMathExpression(e.endpoint[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.endpoint)t[Number(n)+1]=e.endpoint[n].tree;t.length=a[0]+1,i.push({setDependency:"endpointShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.endpoint&&i.push({setDependency:"endpointShadow",desiredValue:e.endpoint[0]});return{success:!0,instructions:i}}},e.numericalEndpoint={forRenderer:!0,returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},endpoint:{dependencyType:"stateVariable",variableName:"endpoint"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.endpoint,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},through:{dependencyType:"stateVariable",variableName:"through"}}),definition({dependencyValues:e}){if(Number.isNaN(e.nDimensions))return null;let t=e.through,n=[];for(let r=0;r({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoint:{dependencyType:"stateVariable",variableName:"numericalEndpoint"},numericalThroughpoint:{dependencyType:"stateVariable",variableName:"numericalThroughpoint"}}),definition({dependencyValues:e}){let t=e.numericalEndpoint[0],n=e.numericalEndpoint[1],r=e.numericalThroughpoint[0],a=e.numericalThroughpoint[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}async moveRay({endpointcoords:e,throughcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){let s=[];if(void 0!==e){if(await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let n;if(void 0===t){let t=await this.stateValues.numericalThroughpoint;n=e.map(((e,n)=>t[n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"endpoint",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnThrough){let t=await this.stateValues.numericalThroughpoint,n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnThrough)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"through",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=await this.stateValues.numericalEndpoint);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnThrough&&await this.stateValues.basedOnDirection){let e=await this.stateValues.numericalEndpoint,n=t.map(((t,n)=>t-e[n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"direction",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{through:t,endpoint:e}}})}async rayClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnRay({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Polygon extends Polyline{constructor(e){super(e),Object.assign(this.actions,{movePolygon:this.movePolygon.bind(this),polygonClicked:this.polygonClicked.bind(this),mouseDownOnPolygon:this.mouseDownOnPolygon.bind(this)})}static componentType="polygon";static representsClosedPath=!0;get movePolygon(){return this.movePolyline}get polygonClicked(){return this.polylineClicked}get mouseDownOnPolygon(){return this.mouseDownOnPolyline}static createAttributesObject(){let e=super.createAttributesObject();return e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" polygon",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" polygon with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" polygon",{setValue:{styleDescriptionWithNoun:t}}}},e.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},e.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalVertices:{dependencyType:"stateVariable",variableName:"numericalVertices"},nVertices:{dependencyType:"stateVariable",variableName:"nVertices"}}),definition({dependencyValues:e}){let t,n,r=e.nDimensions,a=e.nVertices,i=e.numericalVertices,s=[],o=i[a-1]?.[0],l=i[a-1]?.[1];for(let e=0;e=1?{x1:h,x2:f}:{x1:l+g*a*n,x2:u+g*y*o};let b=Math.pow((d-r.x1)/n,2)+Math.pow((m-r.x2)/o,2);b0&&(p.x3=0),p}}}}},e}}class Triangle extends Polygon{static componentType="triangle";static rendererType="polygon";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","triangle"),{setValue:{styleDescriptionWithNoun:n}}},e.vertices.hasEssential=!0,e.vertices.defaultValueByArrayKey=function(e){return["0,1","1,0"].includes(e)?me$3.fromAst(1):me$3.fromAst(0)},e.vertices.returnArraySizeDependencies=()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),e.vertices.returnArraySize=function({dependencyValues:e}){return[3,e.nDimensions]},e.vertices.arrayDefinitionByKey=function({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let[t,i]=a.split(","),s=Number(t)+1+"_"+(Number(i)+1),o=e[a].vertices;null!==o&&o.stateValues["pointX"+s]?n[a]=o.stateValues["pointX"+s]:r[a]=!0}return{setValue:{vertices:n},useEssentialOrDefaultValue:{vertices:r}}},e.vertices.inverseArrayDefinitionByKey=async function({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.vertices){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);null!==t[r].vertices&&t[r].vertices.stateValues["pointX"+o]?i.push({setDependency:n[r].vertices,desiredValue:e.vertices[r],variableIndex:0}):i.push({setEssentialValue:"vertices",value:{[r]:e.vertices[r].simplify()}})}return{success:!0,instructions:i}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:3}})},e}}class Rectangle extends Polygon{static componentType="rectangle";static rendererType="polygon";static createAttributesObject(){let e=super.createAttributesObject();return e.center={createComponentOfType:"point"},e.width={createComponentOfType:"number"},e.height={createComponentOfType:"number"},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=e.styleDescriptionWithNoun.definition;return e.styleDescriptionWithNoun.definition=function({dependencyValues:e}){let n=t({dependencyValues:e}).setValue.styleDescriptionWithNoun;return n=n.replaceAll("polygon","rectangle"),{setValue:{styleDescriptionWithNoun:n}}},e.nVerticesSpecified={returnDependencies:()=>({verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.verticesAttr?{setValue:{nVerticesSpecified:e.verticesAttr.stateValues.nPoints}}:{setValue:{nVerticesSpecified:0}}}},e.essentialVertex={isArray:!0,entryPrefixes:["essentialVertexX"],defaultValueByArrayKey:()=>me$3.fromAst(0),hasEssential:!0,returnArraySizeDependencies:()=>({nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}}),returnArraySize:({dependencyValues:e})=>[0===e.nVerticesSpecified?2:0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialVertex:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[];for(let n in e.essentialVertex)t.push({setEssentialValue:"essentialVertex",value:{[n]:e.essentialVertex[n]}});return{success:!0,instructions:t}}},e.haveSpecifiedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{haveSpecifiedCenter:null!==e.centerAttr}})},e.specifiedCenter={isArray:!0,entryPrefixes:["specifiedCenterX"],returnArraySizeDependencies:()=>({haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.haveSpecifiedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=Number(r)+1;null!==e[r].centerAttr&&(n[r]=e[r].centerAttr.stateValues["x"+t])}return{setValue:{specifiedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.specifiedCenter)t[a].centerAttr&&null!==t[a].centerAttr&&r.push({setDependency:n[a].centerAttr,desiredValue:e.specifiedCenter[a],variableIndex:0});return{success:!0,instructions:r}}},e.specifiedWidth={defaultValue:1,hasEssential:!0,essentialVarName:"width",returnDependencies:()=>({widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.widthAttr?{setValue:{specifiedWidth:e.widthAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedWidth:!0}}:{setValue:{specifiedWidth:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.widthAttr?{success:!0,instructions:[{setDependency:"widthAttr",desiredValue:e.specifiedWidth,childIndex:0,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedWidth",value:e.specifiedWidth}]}},e.specifiedHeight={defaultValue:1,hasEssential:!0,essentialVarName:"height",returnDependencies:()=>({heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["value"]},nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"},haveSpecifiedCenter:{dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"}}),definition:({dependencyValues:e})=>null!==e.heightAttr?{setValue:{specifiedHeight:e.heightAttr.stateValues.value}}:(e.haveSpecifiedCenter?1:0)+e.nVerticesSpecified<=1?{useEssentialOrDefaultValue:{specifiedHeight:!0}}:{setValue:{specifiedHeight:null}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>null!==t.heightAttr?{success:!0,instructions:[{setDependency:"heightAttr",desiredValue:e.specifiedHeight,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"specifiedHeight",value:e.specifiedHeight}]}},e.center={public:!0,isArray:!0,entryPrefixes:["centerX"],shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_"+e},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].vertex0,a=e[r].vertex2;n[r]=t.add(a).divide(2).simplify()}return{setValue:{center:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,stateValues:r}){let a=[],i=await r.center;for(let r in e.center){let s=Number(r),o=t[r].vertex0,l=t[r].vertex2,u=e.center[s].subtract(i[s]),c=o.add(u).simplify(),p=l.add(u).simplify();a.push({setDependency:n[r].vertex0,desiredValue:c},{setDependency:n[r].vertex2,desiredValue:p})}return{success:!0,instructions:a}}},e.width={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_1"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_1"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{width:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.width)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.height={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:({})=>({vertex0:{dependencyType:"stateVariable",variableName:"vertexX1_2"},vertex2:{dependencyType:"stateVariable",variableName:"vertexX3_2"}}),definition({dependencyValues:e}){let t=e.vertex0.evaluate_to_constant(),n=e.vertex2.evaluate_to_constant();return{setValue:{height:Math.abs(t-n)}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=t.vertex0.evaluate_to_constant(),r=t.vertex2.evaluate_to_constant(),a=(r+n)/2,i=(r-n<0?-1:1)*Math.max(0,e.height)/2;return{success:!0,instructions:[{setDependency:"vertex0",desiredValue:me$3.fromAst(a-i)},{setDependency:"vertex2",desiredValue:me$3.fromAst(a+i)}]}}},e.vertices={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["vertexX","vertex"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vertexX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vertices"===t)return 1===e.length?"vertex"+e[0]:`vertexX${e[0]}_${e[1]}`;if("vertex"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vertexX${n}_${e[0]}`}return null},stateVariablesDeterminingDependencies:["nVerticesSpecified","haveSpecifiedCenter"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[4,2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={nVerticesSpecified:{dependencyType:"stateVariable",variableName:"nVerticesSpecified"}};if(0===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(",");n[t]={specifiedCenter:{dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)}},"0"===r?n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}:n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"}}else for(let t of e){let[e,r]=t.split(",");n[t]={essentialVertex:{dependencyType:"stateVariable",variableName:"essentialVertexX"+(Number(r)+1)}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else if(1===t.nVerticesSpecified)if(r.haveSpecifiedCenter={dependencyType:"stateVariable",variableName:"haveSpecifiedCenter"},t.haveSpecifiedCenter)for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},("0"===r&&"1"===e||"2"===e||"1"===r&&"2"===e||"3"===e)&&(n[t].specifiedCenter={dependencyType:"stateVariable",variableName:"specifiedCenterX"+(Number(r)+1)})}else for(let t of e){let[e,r]=t.split(","),a="1_"+(Number(r)+1);n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+a]}},"0"===r?"1"!==e&&"2"!==e||(n[t].specifiedWidth={dependencyType:"stateVariable",variableName:"specifiedWidth"}):"2"!==e&&"3"!==e||(n[t].specifiedHeight={dependencyType:"stateVariable",variableName:"specifiedHeight"})}else for(let t of e){let e,[r,a]=t.split(","),i="1_"+(Number(a)+1),s="2_"+(Number(a)+1);e="0"===r?i:"2"===r?s:"1"===r?"0"===a?s:i:"0"===a?i:s,n[t]={verticesAttr:{dependencyType:"attributeComponent",attributeName:"vertices",variableNames:["pointX"+e]}}}return{dependenciesByKey:n,globalDependencies:r}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,globalDependencyValues:n}){let r={};if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let[t,a]=n.split(","),i=e[n].specifiedCenter;if("0"===a){let a=e[n].specifiedWidth;r[n]="0"===t||"3"===t?i.subtract(a/2):i.add(a/2)}else{let a=e[n].specifiedHeight;r[n]="0"===t||"1"===t?i.subtract(a/2):i.add(a/2)}}else for(let n of t){let[t,a]=n.split(","),i=e[n].essentialVertex;if("0"===a)if("0"===t||"3"===t)r[n]=i;else{let t=e[n].specifiedWidth;r[n]=i.add(t)}else if("0"===t||"1"===t)r[n]=i;else{let t=e[n].specifiedHeight;r[n]=i.add(t)}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter)for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i&&("0"===a||"3"===a)||"1"===i&&("0"===a||"1"===a))r[n]=t;else{let a=e[n].specifiedCenter;r[n]=t.add(a.subtract(t).multiply(2))}}else for(let n of t){let t,[a,i]=n.split(","),s=e[n].verticesAttr;if(t=null!==s&&1===Object.keys(s.stateValues).length?Object.values(s.stateValues)[0]:me$3.fromAst("_"),"0"===i)if("0"===a||"3"===a)r[n]=t;else{let a=e[n].specifiedWidth;r[n]=t.add(a)}else if("0"===a||"1"===a)r[n]=t;else{let a=e[n].specifiedHeight;r[n]=t.add(a)}}else for(let n of t){let t=e[n].verticesAttr;null!==t&&1===Object.keys(t.stateValues).length?r[n]=Object.values(t.stateValues)[0]:r[n]=me$3.fromAst("_")}return{setValue:{vertices:r}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,globalDependencyValues:n,stateValues:r,workspace:a,initialChange:i,dependencyNamesByKey:s}){if(i&&!await r.draggable)return{success:!1};if(!a.v0){let e=await r.vertices;a.v0=[...e[0]],a.v2=[...e[2]]}let o,l,u,c,p,d;for(let t in e.vertices){let[n,r]=t.split(","),i=e.vertices[t];"0"===n?a.v0[Number(r)]=i:"2"===n?a.v2[Number(r)]=i:"1"===n?"0"===r?a.v2[Number(r)]=i:a.v0[Number(r)]=i:"0"===r?a.v0[Number(r)]=i:a.v2[Number(r)]=i,"0"===r?(o=t,"0"===n||"3"===n?u=t:p=t):(l=t,"0"===n||"1"===n?c=t:d=t)}let m=[];if(0===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==o){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant(),t=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[o].specifiedWidth,desiredValue:e},{setDependency:s[o].specifiedCenter,desiredValue:t})}if(void 0!==l){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant(),t=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[l].specifiedHeight,desiredValue:e},{setDependency:s[l].specifiedCenter,desiredValue:t})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].essentialVertex,desiredValue:e})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].essentialVertex,desiredValue:e})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else if(1===n.nVerticesSpecified)if(n.haveSpecifiedCenter){if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].add(a.v0[0]).divide(2).simplify();m.push({setDependency:s[p].specifiedCenter,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].add(a.v0[1]).divide(2).simplify();m.push({setDependency:s[d].specifiedCenter,desiredValue:e})}}else{if(void 0!==u){let e=a.v0[0].simplify();m.push({setDependency:s[u].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==p){let e=a.v2[0].subtract(a.v0[0]).evaluate_to_constant();m.push({setDependency:s[p].specifiedWidth,desiredValue:e})}if(void 0!==c){let e=a.v0[1].simplify();m.push({setDependency:s[c].verticesAttr,desiredValue:e,variableIndex:0})}if(void 0!==d){let e=a.v2[1].subtract(a.v0[1]).evaluate_to_constant();m.push({setDependency:s[d].specifiedHeight,desiredValue:e})}}else void 0!==u&&m.push({setDependency:s[u].verticesAttr,desiredValue:a.v0[0],variableIndex:0}),void 0!==p&&m.push({setDependency:s[p].verticesAttr,desiredValue:a.v2[0],variableIndex:0}),void 0!==c&&m.push({setDependency:s[c].verticesAttr,desiredValue:a.v0[1],variableIndex:0}),void 0!==d&&m.push({setDependency:s[d].verticesAttr,desiredValue:a.v2[1],variableIndex:0});return{success:!0,instructions:m}}},e.nVertices={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{nVertices:4}})},e}async movePolygon({pointCoords:e,transient:t,sourceInformation:n,actionId:r}){let a=[],i={};for(let t in e)i[t+",0"]=me$3.fromAst(e[t][0]),i[t+",1"]=me$3.fromAst(e[t][1]);if(a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"vertices",value:i,sourceInformation:n}),1===Object.keys(e).length){let t=Number(Object.keys(e)[0]),n=me$3.fromAst(e[t][0]),r=me$3.fromAst(e[t][1]),i=(t+2)%4,s=await this.stateValues.vertices,o=s[i][0],l=s[i][1];if(await this.stateValues.nVerticesSpecified<2)if(await this.stateValues.haveSpecifiedCenter){let e,i;0===t?(e=n.add(o).divide(2),i=r.add(l).divide(2)):1===t?i=r.add(l).divide(2):3===t&&(e=n.add(o).divide(2)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{0:e.simplify()}}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedCenter",value:{1:i.simplify()}})}else{let e,i;0===t?(e=o.subtract(n),i=l.subtract(r)):1===t?i=l.subtract(r):3===t&&(e=o.subtract(n)),void 0!==e&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedWidth",value:e.simplify()}),void 0!==i&&a.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"specifiedHeight",value:i.simplify()})}}return t?await this.coreFunctions.performUpdate({updateInstructions:a,transient:t,actionId:r}):await this.coreFunctions.performUpdate({updateInstructions:a,actionId:r,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{pointCoordinates:e}}})}}class Circle extends Curve{constructor(e){super(e),Object.assign(this.actions,{moveCircle:this.moveCircle.bind(this),circleClicked:this.circleClicked.bind(this),mouseDownOnCircle:this.mouseDownOnCircle.bind(this)})}static componentType="circle";static rendererType="circle";static representsClosedPath=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.through={createComponentOfType:"_pointListComponent"},e.center={createComponentOfType:"point"},e.radius={createComponentOfType:"math"},e.filled={createComponentOfType:"boolean",createStateVariable:"filled",defaultValue:!1,public:!0,forRenderer:!0},delete e.parMin,delete e.parMax,delete e.variable,e}static returnChildGroups(){return GraphicalComponent.returnChildGroups()}static returnStateVariableDefinitions(e){let t=GraphicalComponent.returnStateVariableDefinitions(e);return t.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord,n&&(t+=" with "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" with "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},t.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t,n=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(n&&(n+=" "),n+=e.selectedStyle.lineStyleWord),n&&(n+=" "),e.filled?e.selectedStyle.fillColorWord===e.selectedStyle.lineColorWord?(t="filled "+e.selectedStyle.fillColorWord+" circle",n&&(t+=" with a "+n+"border")):t="filled "+e.selectedStyle.fillColorWord+" circle with a "+n+e.selectedStyle.lineColorWord+" border":t=n+e.selectedStyle.lineColorWord+" circle",{setValue:{styleDescriptionWithNoun:t}}}},t.borderStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{borderStyleDescription:t}}}},t.fillStyleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"},filled:{dependencyType:"stateVariable",variableName:"filled"}}),definition:function({dependencyValues:e}){let t;return t=e.filled?e.selectedStyle.fillColorWord:"unfilled",{setValue:{fillStyleDescription:t}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"circle"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:NaN}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:NaN}})},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[0],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:()=>({setValue:{fs:{}}})},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null!==e.throughAttr?{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}:{setValue:{nThroughPoints:0}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;null!==s&&s.stateValues["pointX"+i]?n[r]=s.stateValues["pointX"+i]:n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],variableIndex:0})}return{success:!0,instructions:i}}},t.havePrescribedCenter={returnDependencies:()=>({centerAttr:{dependencyType:"attributeComponent",attributeName:"center"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedCenter:null!==e.centerAttr},checkForActualChange:{havePrescribedCenter:!0}})},t.prescribedCenter={isArray:!0,entryPrefixes:["prescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={centerAttr:{dependencyType:"attributeComponent",attributeName:"center",variableNames:["x"+e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let e of n){let n=Number(e)+1;null!==t[e].centerAttr&&(r[e]=t[e].centerAttr.stateValues["x"+n],r[e]||(r[e]=me$3.fromAst("_")))}return{setValue:{prescribedCenter:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[];for(let t of Object.keys(e.prescribedCenter).reverse())null!==n[t].centerAttr&&i.push({setDependency:r[t].centerAttr,desiredValue:e.prescribedCenter[t],variableIndex:0});return{success:!0,instructions:i}}},t.prescribedRadius={defaultValue:null,returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius",variableNames:["value"]}}),definition:function({dependencyValues:e}){return null!==e.radiusAttr?{setValue:{prescribedRadius:e.radiusAttr.stateValues.value}}:{setValue:{prescribedRadius:null}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return null!==t.radiusAttr?{success:!0,instructions:[{setDependency:"radiusAttr",desiredValue:e.prescribedRadius,childIndex:0,variableIndex:0}]}:{success:!1}}},t.havePrescribedRadius={returnDependencies:()=>({radiusAttr:{dependencyType:"attributeComponent",attributeName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{havePrescribedRadius:null!==e.radiusAttr},checkForActualChange:{havePrescribedRadius:!0}})},t.numericalPrescribedRadius={returnDependencies:()=>({prescribedRadius:{dependencyType:"stateVariable",variableName:"prescribedRadius"}}),additionalStateVariablesDefined:["haveNonNumericalPrescribedRadius"],definition:function({dependencyValues:e}){let t,n=!1;return null===e.prescribedRadius?t=null:(t=e.prescribedRadius.evaluate_to_constant(),Number.isFinite(t)||(t=NaN,n=!0)),{setValue:{haveNonNumericalPrescribedRadius:n,numericalPrescribedRadius:t},checkForActualChange:{haveNonNumericalEntriesNumericalRadius:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){return await n.haveNonNumericalPrescribedRadius?{success:!1}:void 0!==e.numericalPrescribedRadius?null===t.prescribedRadius?{success:!1}:{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:me$3.fromAst(e.numericalPrescribedRadius)}]}:{success:!1}}},t.numericalPrescribedCenter={isArray:!0,entryPrefixes:["numericalPrescribedCenterX"],returnArraySizeDependencies:()=>({havePrescribedCenter:{dependencyType:"stateVariable",variableName:"havePrescribedCenter"}}),returnArraySize:({dependencyValues:e})=>[e.havePrescribedCenter?2:0],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let e=Number(n)+1;t[n]={prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}return{dependenciesByKey:t}},arrayDefinitionByKey:function({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].prescribedCenterX;t?(n[r]=t.evaluate_to_constant(),Number.isFinite(n[r])||(n[r]=NaN)):n[r]=NaN}return{setValue:{numericalPrescribedCenter:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.numericalPrescribedCenter)n.push({setDependency:t[r].prescribedCenterX,desiredValue:me$3.fromAst(e.numericalPrescribedCenter[r])});return{success:!0,instructions:n}}},t.haveNonNumericalPrescribedCenter={returnDependencies:()=>({numericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"}}),definition({dependencyValues:e}){let t=e.numericalPrescribedCenter.some((e=>!Number.isFinite(e)));return{setValue:{haveNonNumericalPrescribedCenter:t},checkForActualChange:{haveNonNumericalPrescribedCenter:!0}}}},t.numericalThroughPoints={returnDependencies:()=>({throughPoints:{dependencyType:"stateVariable",variableName:"throughPoints"}}),additionalStateVariablesDefined:["haveNonNumericalThroughPoints"],definition:function({dependencyValues:e}){let t=!1,n=[];for(let r of e.throughPoints){let e=[];for(let n=0;n<2;n++){let a;try{a=r[n].evaluate_to_constant()}catch(n){console.warn("Invalid point of circle"),t=!0,e=[];break}if(!Number.isFinite(a)){t=!0,e=[];break}e.push(a)}if(!(e.length>0)){n=[];break}n.push(e)}return{setValue:{haveNonNumericalThroughPoints:t,numericalThroughPoints:n},checkForActualChange:{haveNonNumericalThroughPoints:!0}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(await n.haveNonNumericalThroughPoints)return{success:!1};if(void 0!==e.numericalThroughPoints){let t={};for(let[n,r]of e.numericalThroughPoints.entries())t[n+",0"]=me$3.fromAst(r[0]),t[n+",1"]=me$3.fromAst(r[1]);return{success:!0,instructions:[{setDependency:"throughPoints",desiredValue:t}]}}return{success:!1}}},t.haveNumericalEntries={returnDependencies:()=>({haveNonNumericalPrescribedCenter:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},haveNonNumericalThroughPoints:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:({dependencyValues:e})=>({setValue:{haveNumericalEntries:!(e.haveNonNumericalPrescribedCenter||e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)}})},t.numericalRadiusCalculatedWithCenter={additionalStateVariablesDefined:["numericalCenterCalculatedWithRadius"],returnDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"}}),definition:function({dependencyValues:e}){if(e.haveNonNumericalThroughPoints){let t="Haven't implemented circle through "+e.nThroughPoints+" points";return t+=" in case where don't have numerical values.",console.warn(t),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}if(2===e.nThroughPoints){let{numericalCenter:t,numericalRadius:n}=circleFromTwoNumericalPoints({point1:e.numericalThroughPoints[0],point2:e.numericalThroughPoints[1]});return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}if(3===e.nThroughPoints){let t,n,r=e.numericalThroughPoints[0][0],a=e.numericalThroughPoints[1][0],i=e.numericalThroughPoints[2][0],s=e.numericalThroughPoints[0][1],o=e.numericalThroughPoints[1][1],l=e.numericalThroughPoints[2][1];if(r===a&&s===o)if(r===i&&s===l)t=[r,s],n=0;else{let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[i,l]});t=e.numericalCenter,n=e.numericalRadius}else if(r===i&&s===l||a===i&&o===l){let e=circleFromTwoNumericalPoints({point1:[r,s],point2:[a,o]});t=e.numericalCenter,n=e.numericalRadius}else{let e=r*r+s*s,u=a*a+o*o,c=i*i+l*l,p=r*(o-l)-s*(a-i)+a*l-i*o,d=e*(l-o)+u*(s-l)+c*(o-s),m=e*(a-i)+u*(i-r)+c*(r-a),h=e*(i*o-a*l)+u*(r*l-i*s)+c*(a*s-r*o);0!==p?(t=[-d/(2*p),-m/(2*p)],n=Math.sqrt((d*d+m*m-4*p*h)/(4*p*p))):(t=[NaN,NaN],n=NaN)}return{setValue:{numericalCenterCalculatedWithRadius:t,numericalRadiusCalculatedWithCenter:n}}}return e.nThroughPoints>3?(console.warn("Can't calculate circle through more than 3 points"),{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}):{setValue:{numericalRadiusCalculatedWithCenter:null,numericalCenterCalculatedWithRadius:null}}}},t.essentialRadius={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{essentialRadius:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"essentialRadius",value:e.essentialRadius}]}}},t.numericalRadius={forRenderer:!0,stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={haveNonNumericalPrescribedRadius:{dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.numericalPrescribedRadius={dependencyType:"stateVariable",variableName:"numericalPrescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter?1===e.nThroughPoints&&(t.haveNonNumericalPrescribedCenter={dependencyType:"stateVariable",variableName:"haveNonNumericalPrescribedCenter"},t.numericalPrescribedCenter={dependencyType:"stateVariable",variableName:"numericalPrescribedCenter"},t.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}):e.nThroughPoints>1&&(t.numericalRadiusCalculatedWithCenter={dependencyType:"stateVariable",variableName:"numericalRadiusCalculatedWithCenter"},t.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"}),t},definition:function({dependencyValues:e}){if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalPrescribedCenter||e.haveNonNumericalThroughPoints)return{setValue:{numericalRadius:NaN}};if(void 0!==e.numericalPrescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalRadius:NaN}}):{setValue:{numericalRadius:Math.max(0,e.numericalPrescribedRadius)}};if(void 0!==e.numericalPrescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}if(1===e.nThroughPoints){let t=e.numericalThroughPoints[0];return void 0===t?{setValue:{numericalRadius:NaN}}:{setValue:{numericalRadius:Math.sqrt(Math.pow(t[0]-e.numericalPrescribedCenter[0],2)+Math.pow(t[1]-e.numericalPrescribedCenter[1],2))}}}return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{numericalRadius:NaN}}}if(e.nThroughPoints<2){let t=e.essentialRadius;if(t instanceof me$3.class){try{t=t.evaluate_to_constant()}catch(e){}Number.isFinite(t)||(t=NaN)}return{setValue:{numericalRadius:t}}}return{setValue:{numericalRadius:e.numericalRadiusCalculatedWithCenter}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n}){if(void 0!==t.numericalPrescribedRadius)return{success:!0,instructions:[{setDependency:"numericalPrescribedRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(void 0!==t.numericalPrescribedCenter){if(0===t.nThroughPoints)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};if(1===t.nThroughPoints){let t=Math.max(0,e.numericalRadius),r=(await n.throughAngles)[0];if(!Number.isFinite(r))return{success:!1};let a=await n.numericalCenter;return{success:!0,instructions:[{setDependency:"numericalThroughPoints",desiredValue:[[a[0]+t*Math.cos(r),a[1]+t*Math.sin(r)]]}]}}return{success:!1}}if(t.nThroughPoints<2)return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:Math.max(0,e.numericalRadius)}]};{let r=[],a=Math.max(0,e.numericalRadius);for(let e=0;e0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey:function({arrayKeys:e}){let t={};for(let n of e)t[n]=!0;return{useEssentialOrDefaultValue:{essentialCenter:t}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,stateValues:t,workspace:n}){let r=[];for(let t in e.essentialCenter)r.push({setEssentialValue:"essentialCenter",value:{[t]:e.essentialCenter[t]}});return{success:!0,instructions:r}}},t.numericalCenter={forRenderer:!0,isArray:!0,entryPrefixes:["numericalCenterX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){for(let t of e){let e=Number(t)+1;r[t]={numericalPrescribedCenterX:{dependencyType:"stateVariable",variableName:"numericalPrescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.numericalThroughPoints={dependencyType:"stateVariable",variableName:"numericalThroughPoints"},n.haveNonNumericalThroughPoints={dependencyType:"stateVariable",variableName:"haveNonNumericalThroughPoints"},t.havePrescribedRadius||1==t.nThroughPoints?n.numericalRadius={dependencyType:"stateVariable",variableName:"numericalRadius"}:t.nThroughPoints>1&&(n.numericalCenterCalculatedWithRadius={dependencyType:"stateVariable",variableName:"numericalCenterCalculatedWithRadius"})}return{globalDependencies:n,dependenciesByKey:r}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n)if(void 0!==t[a].numericalPrescribedCenterX){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{numericalCenter:[NaN,NaN]}};r[a]=t[a].numericalPrescribedCenterX}if(Object.keys(r).length>0)return{setValue:{numericalCenter:r}};if(e.haveNonNumericalPrescribedRadius||e.haveNonNumericalThroughPoints)return{setValue:{numericalCenter:[NaN,NaN]}};if(void 0!==e.numericalRadius){if(0===e.nThroughPoints){for(let e of n){let n=t[e].essentialCenterX;if(n instanceof me$3.class){try{n=n.evaluate_to_constant()}catch(e){}Number.isFinite(n)||(n=NaN)}r[e]=n}return{setValue:{numericalCenter:r}}}if(1===e.nThroughPoints){if(e.numericalThroughPoints.length<1)return{setValue:{numericalCenter:[NaN,NaN]}};return{setValue:{numericalCenter:[e.numericalThroughPoints[0][0],e.numericalThroughPoints[0][1]-e.numericalRadius]}}}if(2===e.nThroughPoints){if(e.numericalThroughPoints.length<2)return{setValue:{numericalCenter:[NaN,NaN]}};let t=e.numericalRadius,n=e.numericalThroughPoints[0][0],r=e.numericalThroughPoints[1][0],a=e.numericalThroughPoints[0][1],i=e.numericalThroughPoints[1][1],s=Math.pow(n-r,2)+Math.pow(a-i,2),o=t*t;return t<0||4*o0)return{success:!0,instructions:s};if(0===t.nThroughPoints){for(let t in e.numericalCenter)s.push({setDependency:r[t].essentialCenterX,desiredValue:e.numericalCenter[t]});return{success:!0,instructions:s}}{i.desiredCenter||(i.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.numericalCenter[t]?i.desiredCenter[t]=e.numericalCenter[t]:void 0===i.desiredCenter[t]&&(i.desiredCenter[t]=a.numericalCenter[t]);let n=[],r=await a.throughAngles,s=await a.numericalRadius;for(let e=0;e({haveNumericalEntries:{dependencyType:"stateVariable",variableName:"haveNumericalEntries"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"}}),definition:function({dependencyValues:e}){if(!(e.haveNumericalEntries&&e.nThroughPoints>0&&e.numericalRadius>0&&e.numericalCenter.every((e=>Number.isFinite(e)))))return{useEssentialOrDefaultValue:{throughAngles:!0}};let t=[];for(let n of e.numericalThroughPoints)t.push(Math.atan2(n[1]-e.numericalCenter[1],n[0]-e.numericalCenter[0]));return{setValue:{throughAngles:t},setEssentialValue:{throughAngles:t}}}},t.radius={public:!0,shadowingInstructions:{createComponentOfType:"math"},stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnDependencies:function({stateValues:e}){let t={numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"},nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"},essentialRadius:{dependencyType:"stateVariable",variableName:"essentialRadius"}};return e.havePrescribedRadius?(t.prescribedRadius={dependencyType:"stateVariable",variableName:"prescribedRadius"},e.havePrescribedCenter&&e.nThroughPoints>0&&(t.haveCenterRadiusPoints={dependencyType:"value",value:!0})):e.havePrescribedCenter&&1===e.nThroughPoints&&(t.prescribedCenter={dependencyType:"stateVariable",variableName:"prescribedCenter"},t.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"}),t},definition:function({dependencyValues:e}){if(Number.isFinite(e.numericalRadius))return{setValue:{radius:me$3.fromAst(e.numericalRadius)}};if(void 0!==e.prescribedRadius)return e.haveCenterRadiusPoints?(console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{radius:me$3.fromAst("_")}}):{setValue:{radius:e.prescribedRadius}};if(void 0!==e.prescribedCenter){if(0===e.nThroughPoints){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}if(1!==e.nThroughPoints)return console.warn("Can't calculate circle with specified center through more than 1 point"),{setValue:{radius:me$3.fromAst("_")}};try{let t=e.throughPoints[0],n=t[0],r=t[1],a=e.prescribedCenter[0],i=e.prescribedCenter[1];return{setValue:{radius:n.subtract(a).pow(2).add(r.subtract(i).pow(2)).pow(.5).simplify()}}}catch(e){return console.warn("Invalid center or through points of circle"),{setValue:{radius:me$3.fromAst("_")}}}}if(e.nThroughPoints<2){let t=e.essentialRadius;return t instanceof me$3.class||(t=Number.isFinite(t)?me$3.fromAst(t):me$3.fromAst("_")),{setValue:{radius:t}}}return console.warn(`Have not implemented circle through ${e.nThroughPoints} points when non-numerical values`),{setValue:{radius:me$3.fromAst("_")}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){let n=e.radius.evaluate_to_constant();if(Number.isFinite(n)&&Number.isFinite(t.numericalRadius))return{success:!0,instructions:[{setDependency:"numericalRadius",desiredValue:n}]};if(void 0!==t.prescribedRadius)return{success:!0,instructions:[{setDependency:"prescribedRadius",desiredValue:e.radius}]};if(0===t.nThroughPoints){return{success:!0,instructions:[{setDependency:"essentialRadius",desiredValue:e.radius}]}}return console.warn("Can't change radius of circle with non-numerical values through points"),{success:!1}}},t.diameter={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition:({dependencyValues:e})=>({setValue:{diameter:e.radius.multiply(2).simplify()}}),inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return{success:!0,instructions:[{setDependency:"radius",desiredValue:e.diameter.divide(2).simplify()}]}}},t.center={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"centerX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["centerX"],stateVariablesDeterminingDependencies:["nThroughPoints","havePrescribedCenter","havePrescribedRadius"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={},r={};if(t.havePrescribedCenter){n.havePrescribedCenter={dependencyType:"value",value:!0};for(let t of e){let e=Number(t)+1;r[t]={numericalCenterX:{dependencyType:"stateVariable",variableName:"numericalCenterX"+e},prescribedCenterX:{dependencyType:"stateVariable",variableName:"prescribedCenterX"+e}}}t.havePrescribedRadius&&t.nThroughPoints>0&&(n.haveCenterRadiusPoints={dependencyType:"value",value:!0})}else{for(let t of e){let e=Number(t)+1;r[t]={essentialCenterX:{dependencyType:"stateVariable",variableName:"essentialCenterX"+e}}}n.numericalCenter={dependencyType:"stateVariable",variableName:"numericalCenter"},n.nThroughPoints={dependencyType:"stateVariable",variableName:"nThroughPoints"},n.throughPoints={dependencyType:"stateVariable",variableName:"throughPoints"},t.havePrescribedRadius?n.radius={dependencyType:"stateVariable",variableName:"prescribedRadius"}:1==t.nThroughPoints&&(n.radius={dependencyType:"stateVariable",variableName:"radius"})}return{dependenciesByKey:r,globalDependencies:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.havePrescribedCenter){if(e.haveCenterRadiusPoints)return console.warn("Can't calculate circle with specified radius and center and through points"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}};let r={};for(let e of n)Number.isFinite(t[e].numericalCenterX)?r[e]=me$3.fromAst(t[e].numericalCenterX):r[e]=t[e].prescribedCenterX;return{setValue:{center:r}}}if(e.numericalCenter.every((e=>Number.isFinite(e))))return{setValue:{center:e.numericalCenter.map((e=>me$3.fromAst(e)))}};if(void 0!==e.radius){if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}if(1===e.nThroughPoints){let t;try{t=[e.throughPoints[0][0],e.throughPoints[0][1].subtract(e.radius).simplify()]}catch(e){t=[me$3.fromAst("_"),me$3.fromAst("_")]}return{setValue:{center:t}}}return console.warn("Can't create circle through more than one point with given radius when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}}if(0===e.nThroughPoints){let e={};for(let r of n){let n=t[r].essentialCenterX;n instanceof me$3.class||(n=Number.isFinite(n)?me$3.fromAst(n):me$3.fromAst("_")),e[r]=n}return{setValue:{center:e}}}return console.warn("Can't create circle through more than one point when don't have numerical values"),{setValue:{center:[me$3.fromAst("_"),me$3.fromAst("_")]}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,stateValues:n,dependencyNamesByKey:r,workspace:a}){if(t.havePrescribedCenter){let t=[];for(let n in e.center)t.push({setDependency:r[n].prescribedCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}a.desiredCenter||(a.desiredCenter={});for(let t=0;t<2;t++)void 0!==e.center[t]?a.desiredCenter[t]=e.center[t]:void 0===a.desiredCenter[t]&&(a.desiredCenter[t]=(await n.center)[t]);let i=[],s=!0;for(let e=0;e<2;e++){let t=a.desiredCenter[e].evaluate_to_constant();if(!Number.isFinite(t)){s=!1;break}i.push(t)}if(s&&t.numericalCenter.every((e=>Number.isFinite(e))))return{success:!0,instructions:[{setDependency:"numericalCenter",desiredValue:i}]};if(0===t.nThroughPoints){let t=[];for(let n in e.center)t.push({setDependency:r[n].essentialCenterX,desiredValue:e.center[n],arrayKey:n});return{success:!0,instructions:t}}return console.warn("Haven't implemented changing center of circle through points with non numerical values"),{success:!1}}},t.nearestPoint={returnDependencies:()=>({numericalCenter:{dependencyType:"stateVariable",variableName:"numericalCenter"},numericalRadius:{dependencyType:"stateVariable",variableName:"numericalRadius"}}),definition({dependencyValues:e}){let t=e.numericalRadius,n=e.numericalCenter[0],r=e.numericalCenter[1];return{setValue:{nearestPoint:function({variables:e,scales:a}){let i=e.x1?.evaluate_to_constant(),s=e.x2?.evaluate_to_constant();if(!Number.isFinite(i)||!Number.isFinite(s))return{};if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(t)))return{};let o=Math.atan2(s-r,i-n),l={x1:n+t*Math.cos(o),x2:r+t*Math.sin(o)};return void 0!==e.x3&&(l.x3=0),l}}}}},t}async moveCircle({center:e,radius:t,throughAngles:n,transient:r,actionId:a}){let i=[],s=await this.stateValues.nThroughPoints,o=await this.stateValues.numericalPrescribedCenter;if((s<=1||null!==o)&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"numericalCenter",value:e}),s>=1){let r=[];void 0===n&&(n=await this.stateValues.throughAngles),void 0===t&&(t=await this.stateValues.numericalRadius);for(let a=0;a({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" parabola"}}}},t.curveType={forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{curveType:"function"}})},t.parMax={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMax:1/0}})},t.parMin={public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,returnDependencies:()=>({}),definition:()=>({setValue:{parMin:-1/0}})},t.aShadow={defaultValue:1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{aShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"aShadow",value:e.aShadow}]}}},t.nThroughPoints={returnDependencies:()=>({throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:function({dependencyValues:e}){return null===e.throughAttr?{setValue:{nThroughPoints:0}}:{setValue:{nThroughPoints:e.throughAttr.stateValues.nPoints}}}},t.throughPoints={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"throughPointX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,nDimensions:2,entryPrefixes:["throughPointX","throughPoint"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("throughPointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("throughPoints"===t)return 1===e.length?"throughPoint"+e[0]:`throughPointX${e[0]}_${e[1]}`;if("throughPoint"===t.slice(0,12)){let n=Number(t.slice(12));if(Number.isInteger(n)&&n>0)return`throughPointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints,2],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(","),a=Number(e)+1+"_"+(Number(r)+1);t[n]={throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["pointX"+a]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let[t,a]=r.split(","),i=Number(t)+1+"_"+(Number(a)+1),s=e[r].throughAttr;if(null!==s&&s.stateValues["pointX"+i]){let e=s.stateValues["pointX"+i].evaluate_to_constant();Number.isFinite(e)?n[r]=me$3.fromAst(e):n[r]=me$3.fromAst("_")}else n[r]=me$3.fromAst("_")}return{setValue:{throughPoints:n}}},async inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n,initialChange:r,stateValues:a}){if(r&&!await a.draggable)return{success:!1};let i=[];for(let r in e.throughPoints){let[a,s]=r.split(","),o=Number(a)+1+"_"+(Number(s)+1);if(null===t[r].throughAttr||!t[r].throughAttr.stateValues["pointX"+o])return{success:!1};i.push({setDependency:n[r].throughAttr,desiredValue:e.throughPoints[r],childIndex:0,variableIndex:0})}return{success:!0,instructions:i}}},t.numericalThroughPoints={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({nThroughPoints:{dependencyType:"stateVariable",variableName:"nThroughPoints"}}),returnArraySize:({dependencyValues:e})=>[e.nThroughPoints],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={throughPoint:{dependencyType:"stateVariable",variableName:"throughPoint"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].throughPoint.map((e=>e.tree));t.every((e=>Number.isFinite(e)))||(t=Array(t.length).fill(NaN)),n[r]=t}return{setValue:{numericalThroughPoints:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyValuesByKey:t,dependencyNamesByKey:n}){let r=[];for(let a in e.numericalThroughPoints){if(!t[a].throughPoint)return{success:!1};r.push({setDependency:n[a].throughPoint,desiredValue:e.numericalThroughPoints[a].map((e=>me$3.fromAst(e)))})}return{success:!0,instructions:r}}},t.numericalPrescribedVertex={returnDependencies:()=>({prescribedVertex:{dependencyType:"stateVariable",variableName:"prescribedVertex"}}),definition({dependencyValues:e}){if(null===e.prescribedVertex)return{setValue:{numericalPrescribedVertex:null}};let t,n;try{t=e.prescribedVertex.get_component(0).evaluate_to_constant(),n=e.prescribedVertex.get_component(1).evaluate_to_constant(),Number.isFinite(t)&&Number.isFinite(n)||(t=NaN,n=NaN)}catch(e){t=NaN,n=NaN}return{setValue:{numericalPrescribedVertex:[t,n]}}}},t.pointsAreNumerical={returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"}}),definition:({dependencyValues:e})=>({setValue:{pointsAreNumerical:e.numericalThroughPoints.every((e=>Number.isFinite(e[0])))&&(!e.numericalPrescribedVertex||Number.isFinite(e.numericalPrescribedVertex[0]))},checkForActualChange:{pointsAreNumerical:!0}})},t.a={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"b",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},{variableName:"c",public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0},"realValued"],returnDependencies:()=>({numericalThroughPoints:{dependencyType:"stateVariable",variableName:"numericalThroughPoints"},numericalPrescribedVertex:{dependencyType:"stateVariable",variableName:"numericalPrescribedVertex"},pointsAreNumerical:{dependencyType:"stateVariable",variableName:"pointsAreNumerical"},aShadow:{dependencyType:"stateVariable",variableName:"aShadow"}}),definition:function({dependencyValues:e,componentName:t}){if(!e.pointsAreNumerical)return{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}};let n,r,a,i=!0;if(e.numericalPrescribedVertex){if(0===e.numericalThroughPoints.length){let t=e.numericalPrescribedVertex,i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}{let t=e.numericalPrescribedVertex,i=t[0],s=t[1],o=e.numericalThroughPoints[0],l=o[0];return n=(o[1]-s)/(l-i)**2,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}}if(0===e.numericalThroughPoints.length)return{setValue:{a:e.aShadow,realValued:!0},useEssentialOrDefaultValue:{b:!0,c:!0}};if(1===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],i=t[0],s=t[1];return n=e.aShadow,r=-2*n*i,a=n*i*i+s,{setValue:{a:n,b:r,c:a,realValued:!0}}}if(2===e.numericalThroughPoints.length){n=e.aShadow;let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c;return s===c?o==p?(r=-2*n*s,a=n*l+o):(i=!1,n=NaN,r=NaN,a=NaN):(r=(o-p-n*(l-d))/(s-c),a=o-n*l-r*s),{setValue:{a:n,b:r,c:a,realValued:i}}}if(3===e.numericalThroughPoints.length){let t=e.numericalThroughPoints[0],s=t[0],o=t[1],l=s*s,u=e.numericalThroughPoints[1],c=u[0],p=u[1],d=c*c,m=e.numericalThroughPoints[2],h=m[0],f=m[1],y=h*h,g=l-y,b=d-y,v=s-h,N=c-h,T=o-f,C=p-f,A=g*N-b*v;if(0===A){let t,u,d,m=!1;s===c?o===p?s===h?o==f?t=1:m=!0:(t=2,u=h,d=f):m=!0:s===h?o===f?(t=2,u=c,d=p):m=!0:c===h&&p===f?(t=2,u=c,d=p):m=!0,m?(i=!1,n=NaN,r=NaN,a=NaN):1===t?(n=e.aShadow,r=-2*n*s,a=n*s*s+o):(n=e.aShadow,r=(o-d-n*(l-u*u))/(s-u),a=o-n*l-r*s)}else n=(T*N-C*v)/A,r=(C*g-T*b)/A,a=o-r*s-n*l;return{setValue:{a:n,b:r,c:a,realValued:i}}}return console.warn("Haven't implemented parabola through more than 3 points"),{setValue:{a:NaN,b:NaN,c:NaN,realValued:!1}}},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,workspace:r}){if(!t.pointsAreNumerical)return{success:!1};let a={},i=function(e){if(Number.isFinite(e))return{success:!0,value:e};if(e instanceof me$3.class){let t=e.evaluate_to_constant();if(Number.isFinite(t))return{success:!0,value:t}}return{success:!1}};if(void 0!==e.a){let t=i(e.a);if(!t.success)return{success:!1};a.a=t.value}if(void 0!==e.b){let t=i(e.b);if(!t.success)return{success:!1};a.b=t.value}if(void 0!==e.c){let t=i(e.c);if(!t.success)return{success:!1};a.c=t.value}Object.assign(r,a);let s=async function(e){return void 0!==r[e]?r[e]:await n[e]};if(0===t.numericalThroughPoints.length){let e=[];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),void 0!==a.b&&e.push({setEssentialValue:"b",value:a.b}),void 0!==a.c&&e.push({setEssentialValue:"c",value:a.c}),{success:!0,instructions:e}}if(1===t.numericalThroughPoints.length){let e=await s("a"),t=await s("b"),n=await s("c"),r=[{setDependency:"numericalThroughPoints",desiredValue:[[-t/(2*e),n-t*t/(4*e)]]}];return void 0!==a.a&&r.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:r}}if(2===t.numericalThroughPoints.length){let e=await s("a"),n=await s("b"),r=await s("c"),i=t.numericalThroughPoints[0][0],o=t.numericalThroughPoints[1][0];if(i===o){i=-n/(2*e);let t=r-n*n/(4*e),s=[{setDependency:"numericalThroughPoints",desiredValue:[[i,t],[i,t]]}];return void 0!==a.a&&s.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:s}}{let t=[{setDependency:"numericalThroughPoints",desiredValue:[[i,e*i*i+n*i+r],[o,e*o*o+n*o+r]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}if(3===t.numericalThroughPoints.length){let e,n=await s("a"),r=await s("b"),i=await s("c"),o=t.numericalThroughPoints[0][0],l=t.numericalThroughPoints[1][0],u=t.numericalThroughPoints[2][0],c=3;if(o===l?o===u?c=1:(c=2,e=3):o===u?(c=2,e=2):l===u&&(c=2,e=1),3===c){let e=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,n*l*l+r*l+i],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&e.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:e}}if(2===c){if(1===e){let e=n*l*l+r*l+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,n*o*o+r*o+i],[l,e],[l,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}if(2===e){let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[l,n*l*l+r*l+i],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}{let e=n*o*o+r*o+i,t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[u,n*u*u+r*u+i]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}{o=-r/(2*n);let e=i-r*r/(4*n),t=[{setDependency:"numericalThroughPoints",desiredValue:[[o,e],[o,e],[o,e]]}];return void 0!==a.a&&t.push({setDependency:"aShadow",desiredValue:a.a}),{success:!0,instructions:t}}}return{success:!1}}},t.vertex={public:!0,shadowingInstructions:{createComponentOfType:"math",returnWrappingComponents:e=>"vertexX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["vertexX"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[2],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"},realValued:{dependencyType:"stateVariable",variableName:"realValued"}}}),arrayDefinitionByKey:function({globalDependencyValues:e}){let t={};return e.realValued&&0!==e.a?(t[0]=me$3.fromAst(-e.b/(2*e.a)),t[1]=me$3.fromAst(e.c-e.b**2/(4*e.a))):(t[0]=me$3.fromAst("_"),t[1]=me$3.fromAst("_")),{setValue:{vertex:t}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,workspace:n,stateValues:r}){let a,i;if(a="0"in e.vertex?e.vertex[0].evaluate_to_constant():void 0!==n.x?n.x:(await r.vertex)[0].tree,!Number.isFinite(a))return{success:!1};if(n.x=a,i="1"in e.vertex?e.vertex[1].evaluate_to_constant():void 0!==n.y?n.y:(await r.vertex)[1].tree,!Number.isFinite(i))return{success:!1};n.y=i;let s=t.a;return{success:!0,instructions:[{setDependency:"b",desiredValue:-2*s*a,additionalDependencyValues:{c:i+s*a*a}}]}}},t.equation={public:!0,shadowingInstructions:{createComponentOfType:"math"},additionalProperties:{simplify:"numberspreserveorder",displaysmallaszero:!0},returnDependencies:()=>({a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition:function({dependencyValues:e}){let t=["=","y",["+",["*",e.a,["^","x",2]],["*",e.b,"x"],e.c]];return{setValue:{equation:me$3.fromAst(t).evaluate_numbers({skip_ordering:!0})}}}},t.fs={forRenderer:!0,isArray:!0,entryPrefixes:["f"],additionalStateVariablesDefined:[{variableName:"fDefinitions",isArray:!0,forRenderer:!0}],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[1],returnArrayDependenciesByKey:()=>({globalDependencies:{a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}}),arrayDefinitionByKey:({globalDependencyValues:e})=>({setValue:{fs:[function(t){return e.a*t*t+e.b*t+e.c}],fDefinitions:[{functionType:"formula",formula:["+",["*",e.a,"x","x"],["*",e.b,"x"],e.c],variables:["x"],nInputs:1,nOutputs:1,domain:null}]}})},t.f={isAlias:!0,targetVariableName:"f1"},t.nearestPoint={returnDependencies:()=>({f:{dependencyType:"stateVariable",variableName:"f"},a:{dependencyType:"stateVariable",variableName:"a"},b:{dependencyType:"stateVariable",variableName:"b"},c:{dependencyType:"stateVariable",variableName:"c"}}),definition({dependencyValues:e,componentName:t}){let n=!(Number.isFinite(e.a)&&Number.isFinite(e.b)&&Number.isFinite(e.c));return{setValue:{nearestPoint:function({variables:t,scales:r}){if(n)return{};let a=r[0],i=r[1],s=t.x1?.evaluate_to_constant(),o=t.x2?.evaluate_to_constant();if(!Number.isFinite(s)||!Number.isFinite(o))return{};s/=a,o/=i;let l=e.a*a*a/i,u=e.b*a/i,c=e.c/i;if(0===l){let e=u*u+1,n={};return n.x1=(s+u*o-u*c)/e*a,n.x2=(u*(s+u*o)+c)/e*i,void 0!==t.x3&&(n.x3=0),n}let p=c-o,d=2*l**2,m=cardano(3*l*u/d,(2*l*p+u**2+1)/d,(u*p-s)/d,1e-14),h=m[0],f=e.f(h*a)/i,y=(s-h)**2+(o-f)**2;for(let t of m.slice(1)){let n=t,r=e.f(n*a)/i,l=(s-n)**2+(o-r)**2;l0){const t=Math.sqrt(s/108),n=2*Math.sqrt(Math.cbrt(i*i/4+s/108)),r=Math.atan2(t,-i/2);return[Math.cos(r/3),Math.cos(r/3+2*Math.PI/3),Math.cos(r/3-2*Math.PI/3)].sort(((e,t)=>e-t)).map((t=>n*t-e/3))}const o=Math.sqrt(-s/108);return[Math.cbrt(-i/2+o)+Math.cbrt(-i/2-o)-e/3]}class BezierControls extends InlineComponent{static componentType="bezierControls";static rendererType="containerInline";static createAttributesObject(){let e=super.createAttributesObject();return e.alwaysVisible={createComponentOfType:"boolean",createStateVariable:"alwaysVisible",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"controlVectors",children:[{componentType:"vector",children:e}]}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"controlVectors",componentTypes:["controlVectors"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nControls={returnDependencies:()=>({nParentPoints:{dependencyType:"parentStateVariable",variableName:"nThroughPoints",skipComponentNames:!0}}),definition({dependencyValues:e}){let t=e.nParentPoints;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nControls:t}}}},e.pointIndMap={returnDependencies:()=>({controlChildren:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["pointNumber"]}}),definition:function({dependencyValues:e}){let t=[],n=-1;for(let[r,a]of e.controlChildren.entries()){let e=a.stateValues.pointNumber;Number.isFinite(e)?n=Math.round(e)-1:n+=1,t[n]=r}return{setValue:{pointIndMap:t}}}},e.directions={isArray:!0,entryPrefixes:["direction"],hasEssential:!0,defaultValueByArrayKey:()=>"none",stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["direction"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.direction:r[a]=!0}return{setValue:{directions:n},useEssentialOrDefaultValue:{directions:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.directions){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.directions[i],childIndex:0,variableIndex:0}):a[i]=e.directions[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"directions",value:a}),{success:!0,instructions:r}}},e.hiddenControls={isArray:!0,entryPrefixes:["hiddenControl"],hasEssential:!0,defaultValueByArrayKey:()=>!1,stateVariablesDeterminingDependencies:["pointIndMap"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"}}),returnArraySize:({dependencyValues:e})=>[e.nControls],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=t.pointIndMap[r];void 0!==e&&(n[r]={controlChild:{dependencyType:"child",childGroups:["controlVectors"],variableNames:["hide"],childIndices:[e]}})}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={},r={};for(let a of t){let t=e[a].controlChild;t&&1===t.length?n[a]=t[0].stateValues.hide:r[a]=!0}return{setValue:{hiddenControls:n},useEssentialOrDefaultValue:{hiddenControls:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.hiddenControls){let s=n[i].controlChild;s&&1===s.length?r.push({setDependency:t[i].controlChild,desiredValue:e.hiddenControls[i],childIndex:0,variableIndex:0}):a[i]=e.hiddenControls[i]}return Object.keys(a).length>0&&r.push({setEssentialValue:"hiddenControls",value:a}),{success:!0,instructions:r}}},e.nDimensions={returnDependencies:()=>({nParentDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t=e.nParentDimensions;return Number.isInteger(t)&&t>=0||(t=0),{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.essentialSymmetricControls={isArray:!0,entryPrefixes:["essentialSymmetricControl"],nDimensions:2,hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,e.nDimensions],returnArrayDependenciesByKey:()=>({}),arrayDefinitionByKey({arrayKeys:e}){let t={};for(let n of e)n.split(",").map((e=>Number(e))),t[n]=!0;return{useEssentialOrDefaultValue:{essentialSymmetricControls:t}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e}){let t=[],n={};for(let t in e.essentialSymmetricControls)n[t]=e.essentialSymmetricControls[t];return Object.keys(n).length>0&&t.push({setEssentialValue:"essentialSymmetricControls",value:n}),{success:!0,instructions:t}}},e.controls={isArray:!0,entryPrefixes:["control"],nDimensions:3,hasEssential:!0,shadowVariable:!0,defaultValueByArrayKey:()=>me$3.fromAst(1),stateVariablesDeterminingDependencies:["pointIndMap","directions"],returnArraySizeDependencies:()=>({nControls:{dependencyType:"stateVariable",variableName:"nControls"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nControls,2,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=r.split(",").map((e=>Number(e))),a=e.map((e=>e+1));n[r]={direction:{dependencyType:"stateVariable",variableName:"direction"+a[0]}};let i=t.directions[e[0]];if("none"!==i&&(0===e[1]||1===e[1])){let s=t.pointIndMap[e[0]];void 0!==s&&("symmetric"===i||"previous"===i&&0===e[1]||"next"===i&&1===e[1]?n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX1_"+a[2]],childIndices:[s]}:"both"===i&&(n[r].controlChild={dependencyType:"child",childGroups:["controlVectors"],variableNames:["vectorX"+a[1]+"_"+a[2]],childIndices:[s]})),"symmetric"===i&&(n[r].essentialSymmetricControl={dependencyType:"stateVariable",variableName:"essentialSymmetricControl"+a[0]+"_"+a[2]})}}return{dependenciesByKey:n}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t,componentName:n}){let r={},a={};for(let n of t){let t=n.split(",").map((e=>Number(e))),i=t.map((e=>e+1)),s=e[n].direction;if(0===t[1])if("none"===s||"next"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length){let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}o&&("symmetric"===s?r[n]=e[n].essentialSymmetricControl:a[n]=!0)}else if(1===t[1])if("none"===s||"previous"===s)r[n]=null;else{let t=e[n].controlChild,o=!0;if(t&&1===t.length)if("both"===s){let e=t[0].stateValues["vectorX2_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]=me$3.fromAst(e))}else{let e=t[0].stateValues["vectorX1_"+i[2]];e&&(o=!1,e=e.evaluate_to_constant(),Number.isFinite(e)||(e=NaN),r[n]="symmetric"===s?me$3.fromAst(-e):me$3.fromAst(e))}o&&("symmetric"===s?e[n].essentialSymmetricControl&&(r[n]=me$3.fromAst(-e[n].essentialSymmetricControl.tree)):a[n]=!0)}}return{setValue:{controls:r},useEssentialOrDefaultValue:{controls:a}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t,dependencyValuesByKey:n}){let r=[],a={};for(let i in e.controls){let s=i.split(",").map((e=>Number(e))),o=s.map((e=>e+1)),l=n[i].direction;if(l)if(0===s[1]){if("none"!==l&&"next"!==l){let s=n[i].controlChild,u=!0;if(s&&1===s.length){s[0].stateValues["vectorX1_"+o[2]]&&(u=!1,r.push({setDependency:t[i].controlChild,desiredValue:e.controls[i],childIndex:0,variableIndex:0}))}if(u){let n=e.controls[i].evaluate_to_constant();Number.isFinite(n)||(n=NaN),n=me$3.fromAst(n),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:n}):a[i]=n}}}else if(1===s[1]&&"none"!==l&&"previous"!==l){let s,u=n[i].controlChild,c=!0;if(u&&1===u.length)if("both"===l){u[0].stateValues["vectorX2_"+o[2]]&&(c=!1)}else{u[0].stateValues["vectorX1_"+o[2]]&&(c=!1)}s="symmetric"===l?me$3.fromAst(["-",e.controls[i].tree]):e.controls[i],c?(s=s.evaluate_to_constant(),Number.isFinite(s)||(s=NaN),s=me$3.fromAst(s),"symmetric"===l?r.push({setDependency:t[i].essentialSymmetricControl,desiredValue:s}):a[i]=s):r.push({setDependency:t[i].controlChild,desiredValue:s,childIndex:0,variableIndex:0})}}return Object.keys(a).length>0&&r.push({setEssentialValue:"controls",value:a}),{success:!0,instructions:r}}},e}}class VectorListComponent extends BaseComponent{static componentType="_vectorListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"vector",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"vectors",componentTypes:["vector"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nVectors={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],skipComponentNames:!0}}),definition:({dependencyValues:e})=>({setValue:{nVectors:e.vectorChildren.length},checkForActualChange:{nVectors:!0}})},e.nDimensions={returnDependencies:()=>({vectorChildren:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.vectorChildren.length)t=2;else{t=1;for(let n of e.vectorChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.vectors={isArray:!0,nDimensions:2,entryPrefixes:["vectorX","vector"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("vectorX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("vectors"===t)return 1===e.length?"vector"+e[0]:`vectorX${e[0]}_${e[1]}`;if("vector"===t.slice(0,6)){let n=Number(t.slice(6));if(Number.isInteger(n)&&n>0)return`vectorX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nVectors:{dependencyType:"stateVariable",variableName:"nVectors"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nVectors,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].vectorChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{vectors:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.vectors)n.push({setDependency:t[r].vectorChild,desiredValue:e.vectors[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class ControlVectors extends VectorListComponent{static componentType="controlVectors";static createAttributesObject(){let e=super.createAttributesObject();return e.direction={createComponentOfType:"text",createStateVariable:"direction",defaultValue:"symmetric",public:!0,toLowerCase:!0,validValues:["symmetric","previous","next","both","none"]},e.pointNumber={createComponentOfType:"number",createStateVariable:"pointNumber",defaultValue:null,public:!0},e}}class PointListComponent extends BaseComponent{static componentType="_pointListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoParensPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"point",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"points",componentTypes:["point"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nPoints={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nPoints:e.pointChildren.length},checkForActualChange:{nPoints:!0}}}},e.nDimensions={returnDependencies:()=>({pointChildren:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"],skipPlaceholders:!0}}),definition:function({dependencyValues:e}){let t;if(0===e.pointChildren.length)t=2;else{t=1;for(let n of e.pointChildren)Number.isFinite(n.stateValues.nDimensions)&&(t=Math.max(t,n.stateValues.nDimensions))}return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},arrayVarNameFromPropIndex(e,t){if("points"===t)return 1===e.length?"point"+e[0]:`pointX${e[0]}_${e[1]}`;if("point"===t.slice(0,5)){let n=Number(t.slice(5));if(Number.isInteger(n)&&n>0)return`pointX${n}_${e[0]}`}return null},returnArraySizeDependencies:()=>({nPoints:{dependencyType:"stateVariable",variableName:"nPoints"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nPoints,e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e){let[e,r]=n.split(",");t[n]={pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+(Number(r)+1)],childIndices:[e]}}}return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=r.split(",")[1],a=e[r].pointChild[0];a&&(n[r]=a.stateValues["x"+(Number(t)+1)])}return{setValue:{points:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.points)n.push({setDependency:t[r].pointChild,desiredValue:e.points[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}class IntervalListComponent extends BaseComponent{static componentType="_intervalListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=breakEmbeddedStringsIntoIntervalPieces({componentList:e});return!0!==t.success?{success:!1}:{success:!0,newChildren:t.pieces.map((function(e){return e.length>1||"string"==typeof e[0]?{componentType:"interval",children:e}:e[0]}))}}}),e}static returnChildGroups(){return[{group:"intervals",componentTypes:["interval"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nIntervals={returnDependencies:()=>({intervalChildren:{dependencyType:"child",childGroups:["intervals"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nIntervals:e.intervalChildren.length},checkForActualChange:{nIntervals:!0}}}},e.intervals={isArray:!0,nDimensions:1,entryPrefixes:["interval"],returnArraySizeDependencies:()=>({nIntervals:{dependencyType:"stateVariable",variableName:"nIntervals"}}),returnArraySize:({dependencyValues:e})=>[e.nIntervals],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={intervalChild:{dependencyType:"child",childGroups:["intervals"],variableNames:["value"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].intervalChild[0];t&&(n[r]=t.stateValues.value)}return{setValue:{intervals:n}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,dependencyNamesByKey:t}){let n=[];for(let r in e.intervals)n.push({setDependency:t[r].intervalChild,desiredValue:e.intervals[r],childIndex:0,variableIndex:0});return{success:!0,instructions:n}}},e}}function breakEmbeddedStringsIntoIntervalPieces({componentList:e}){let t=0,n=[],r=[];for(let a of e){if("string"!=typeof a){if(0===t)return{success:!1};r.push(a);continue}let e=a.trim(),i=0;for(let a=0;ai){let t=a+1,n=e.substring(i,t).trim();n.length>0&&r.push(n)}n.push(r),r=[],i=a+1}t--}else if(0===t&&!s.match(/\s/))return{success:!1}}if(e.length>i){let t=e.substring(i,e.length).trim();r.push(t)}}return 0!==t||r.length>0?{success:!1}:{success:!0,pieces:n}}class LineListComponent extends BaseComponent{static componentType="_lineListComponent";static rendererType="containerInline";static renderChildren=!0;static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e}){let t=e.reduce((function(e,t){return"string"==typeof t?[...e,...t.split(/\s+/).filter((e=>e)).map((e=>({componentType:"line",children:[e]})))]:[...e,t]}),[]);return{success:!0,newChildren:t}}}),e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nLines={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],skipComponentNames:!0}}),definition:function({dependencyValues:e}){return{setValue:{nLines:e.lineChildren.length},checkForActualChange:{nLines:!0}}}},e.lineNames={isArray:!0,entryPrefixes:["lineName"],returnArraySizeDependencies:()=>({nLines:{dependencyType:"stateVariable",variableName:"nLines"}}),returnArraySize:({dependencyValues:e})=>[e.nLines],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={lineChild:{dependencyType:"child",childGroups:["lines"],childIndices:[n]}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].lineChild[0];t&&(n[r]=t.componentName)}return{setValue:{lineNames:n}}}},e}}class AngleListComponent extends BaseComponent{static componentType="_angleListComponent";static createAttributesObject(){let e=super.createAttributesObject();return e.hide={default:!0},e}static returnChildLogic(e){let t=super.returnChildLogic(e),n=t.newLeaf({name:"AtLeastZeroAngles",componentType:"angle",comparison:"atLeast",number:0}),r=breakStringsAndOthersIntoComponentsByStringCommas(),a=t.newLeaf({name:"AtLeastOneString",componentType:"string",comparison:"atLeast",number:1}),i=t.newLeaf({name:"AtLeastOneMath",componentType:"math",comparison:"atLeast",number:1}),s=t.newOperator({name:"StringsAndMaths",operator:"or",propositions:[a,i],requireConsecutive:!0,isSugar:!0,replacementFunction:r});return t.newOperator({name:"AnglesXorSugar",operator:"xor",propositions:[n,s],setAsBase:!0}),t}updateState(e={}){if(e.init&&(this._state.angles={trackChanges:!0}),super.updateState(e),!this.childLogicSatisfied)return this.unresolvedState.angles=!0,void(this.unresolvedState.nAngles=!0);if(this.currentTracker.trackChanges.childrenChanged(this.componentName)){delete this.unresolvedState.angles,delete this.unresolvedState.nAngles;let e=this.childLogic.returnMatches("AtLeastZeroAngles");this.state.nAngles=e.length,this.state.angles=e.map((e=>this.activeChildren[e]))}}initializeRenderer(){void 0===this.renderer&&(this.renderer=new this.availableRenderers.container({key:this.componentName}))}updateChildrenWhoRender(){this.childrenWhoRender=this.state.angles.map((e=>e.componentName))}}class Vector extends GraphicalComponent{constructor(e){super(e),Object.assign(this.actions,{moveVector:this.moveVector.bind(this),vectorClicked:this.vectorClicked.bind(this),mouseDownOnVector:this.mouseDownOnVector.bind(this)})}static componentType="vector";static primaryStateVariableForDefinition="displacementShadow";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.headDraggable={createComponentOfType:"boolean"},e.tailDraggable={createComponentOfType:"boolean"},e.x={createComponentOfType:"math"},e.y={createComponentOfType:"math"},e.z={createComponentOfType:"math"},e.xs={createComponentOfType:"mathList"},e.displacement={createComponentOfType:"vector"},e.head={createComponentOfType:"point"},e.tail={createComponentOfType:"point"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.displayWithAngleBrackets={createComponentOfType:"boolean",createStateVariable:"displayWithAngleBrackets",defaultValue:!1,public:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=returnBreakStringsSugarFunction({childrenToComponentFunction:e=>({componentType:"math",children:e}),mustStripOffOuterParentheses:!0}),r=e.map((e=>typeof e)),a=r.indexOf("string"),i=r.lastIndexOf("string");if(-1===a){let n=t.componentIsSpecifiedType,r=e.filter((e=>!(n(e,"point")||n(e,"vector")||n(e,"label"))));if(1===r.length){let t=r[0],n=e.indexOf(t);return{success:!0,newAttributes:{displacement:{component:{componentType:"math",children:r}}},newChildren:[...e.slice(0,n),...e.slice(n+1)]}}return{success:!1}}let s=[...e.slice(0,a),...e.slice(i+1)],o=n({matchedChildren:e=e.slice(a,i+1)});return o.success||1!==e.length?o.success?{success:!0,newAttributes:{xs:{component:{componentType:"mathList",children:o.newChildren,skipSugar:!0}}},newChildren:s}:{success:!1}:{success:!0,newAttributes:{x:{component:{componentType:"math",children:e}}},newChildren:s}}}),e}static returnChildGroups(){let e=super.returnChildGroups();return e.push({group:"points",componentTypes:["point"]},{group:"vectors",componentTypes:["vector"]}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.styleDescription={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({selectedStyle:{dependencyType:"stateVariable",variableName:"selectedStyle"}}),definition:function({dependencyValues:e}){let t=e.selectedStyle.lineWidthWord;return e.selectedStyle.lineStyleWord&&(t&&(t+=" "),t+=e.selectedStyle.lineStyleWord),t&&(t+=" "),t+=e.selectedStyle.lineColorWord,{setValue:{styleDescription:t}}}},e.styleDescriptionWithNoun={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({styleDescription:{dependencyType:"stateVariable",variableName:"styleDescription"}}),definition:function({dependencyValues:e}){return{setValue:{styleDescriptionWithNoun:e.styleDescription+" vector"}}}},e.tailDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({tailDraggableAttr:{dependencyType:"attributeComponent",attributeName:"tailDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.tailDraggableAttr?{setValue:{tailDraggable:e.tailDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{tailDraggable:{defaultValue:e.draggable}}}},e.headDraggable={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,forRenderer:!0,returnDependencies:()=>({headDraggableAttr:{dependencyType:"attributeComponent",attributeName:"headDraggable",variableNames:["value"]},draggable:{dependencyType:"stateVariable",variableName:"draggable"}}),definition:({dependencyValues:e})=>e.headDraggableAttr?{setValue:{headDraggable:e.headDraggableAttr.stateValues.value}}:{useEssentialOrDefaultValue:{headDraggable:{defaultValue:e.draggable}}}},e.displacementShadow={defaultValue:null,hasEssential:!0,essentialVarName:"displacement",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{displacementShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"displacementShadow",value:convertValueToMathExpression(e.displacementShadow)}]}}},e.headShadow={defaultValue:null,hasEssential:!0,essentialVarName:"head",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{headShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"headShadow",value:convertValueToMathExpression(e.headShadow)}]}}},e.tailShadow={defaultValue:null,hasEssential:!0,essentialVarName:"tail",set:convertValueToMathExpression,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{tailShadow:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"tailShadow",value:convertValueToMathExpression(e.tailShadow)}]}}},e.sourceOfDisplacement={returnDependencies:()=>({xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement"},pointChild:{dependencyType:"child",childGroups:["points"]},vectorChild:{dependencyType:"child",childGroups:["vectors"]}}),definition({dependencyValues:e}){let t=null;return e.vectorChild.length>0?t="vectorChild":e.pointChild.length>0?t="pointChild":null!==e.displacementAttr?t="displacementAttr":null!==e.xsAttr?t="xsAttr":null===e.xAttr&&null===e.yAttr&&null===e.zAttr||(t="componentAttrs"),{setValue:{sourceOfDisplacement:t}}}},e.basedOnHead={returnDependencies:()=>({headAttr:{dependencyType:"attributeComponent",attributeName:"head"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr&&null!==e.sourceOfDisplacement?(null!==e.headAttr&&console.warn("Vector is prescribed by head, tail, and displacement. Ignoring specified head."),{setValue:{basedOnHead:!1},checkForActualChange:{basedOnHead:!0}}):null!==e.headAttr?{setValue:{basedOnHead:!0},checkForActualChange:{basedOnHead:!0}}:{setValue:{basedOnHead:null!==e.headShadow},checkForActualChange:{basedOnHead:!0}}}},e.basedOnTail={returnDependencies:()=>({tailAttr:{dependencyType:"attributeComponent",attributeName:"tail"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}}),definition:function({dependencyValues:e}){return null!==e.tailAttr?{setValue:{basedOnTail:!0},checkForActualChange:{basedOnTail:!0}}:{setValue:{basedOnTail:null!==e.tailShadow},checkForActualChange:{basedOnTail:!0}}}},e.basedOnDisplacement={returnDependencies:()=>({sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"}}),definition:function({dependencyValues:e}){return null!==e.sourceOfDisplacement?{setValue:{basedOnDisplacement:!0},checkForActualChange:{basedOnDisplacement:!0}}:{setValue:{basedOnDisplacement:null!==e.displacementShadow},checkForActualChange:{basedOnDisplacement:!0}}}},e.nDimDisplacement={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["nDimensions"]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["nDimensions"]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["nDimensions"]},xAttr:{dependencyType:"attributeComponent",attributeName:"x"},yAttr:{dependencyType:"attributeComponent",attributeName:"y"},zAttr:{dependencyType:"attributeComponent",attributeName:"z"},xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["nComponents"]}};return e.basedOnDisplacement||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":t=e.vectorChild[0].stateValues.nDimensions;break;case"pointChild":t=e.pointChild[0].stateValues.nDimensions;break;case"displacementAttr":t=e.displacementAttr.stateValues.nDimensions;break;case"xsAttr":t=e.xsAttr.stateValues.nComponents;break;case"componentAttrs":t=null!==e.zAttr?3:null!==e.yAttr?2:1;break;default:let n=e.displacementShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:1}else t=e.basedOnHead?e.basedOnTail?e.nDimHead===e.nDimTail?e.nDimHead:NaN:e.nDimHead:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimDisplacement:t},checkForActualChange:{nDimDisplacement:!0}}}},e.nDimHead={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"},headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["nDimensions"]}};return e.basedOnHead||(e.basedOnTail&&(t.nDimTail={dependencyType:"stateVariable",variableName:"nDimTail"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnHead){if(null!==e.headAttr)t=e.headAttr.stateValues.nDimensions;else if(e.headShadow){let n=e.headShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnTail?e.nDimDisplacement===e.nDimTail?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnTail?e.nDimTail:2;return{setValue:{nDimHead:t},checkForActualChange:{nDimHead:!0}}}},e.nDimTail={stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","basedOnTail"],returnDependencies({stateValues:e}){let t={basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"},tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["nDimensions"]}};return e.basedOnTail||(e.basedOnHead&&(t.nDimHead={dependencyType:"stateVariable",variableName:"nDimHead"}),e.basedOnDisplacement&&(t.nDimDisplacement={dependencyType:"stateVariable",variableName:"nDimDisplacement"})),t},definition:function({dependencyValues:e}){let t;if(e.basedOnTail){if(null!==e.tailAttr)t=e.tailAttr.stateValues.nDimensions;else if(e.tailShadow){let n=e.tailShadow.tree;t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.length-1:2}}else t=e.basedOnDisplacement?e.basedOnHead?e.nDimDisplacement===e.nDimHead?e.nDimDisplacement:NaN:e.nDimDisplacement:e.basedOnHead?e.nDimHead:2;return{setValue:{nDimTail:t},checkForActualChange:{nDimTail:!0}}}},e.nDimensions={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"},nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"},nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),definition:function({dependencyValues:e}){let t;if(e.basedOnDisplacement){if(e.basedOnTail){if(e.nDimDisplacement!==e.nDimTail)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}}}else if(e.basedOnHead&&e.nDimDisplacement!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimDisplacement}else if(e.basedOnTail){if(e.basedOnHead&&e.nDimTail!==e.nDimHead)return console.warn("nDimensions mismatch in vector"),{setValue:{nDimensions:NaN}};t=e.nDimTail}else t=e.basedOnHead?e.nDimHead:2;return{setValue:{nDimensions:t},checkForActualChange:{nDimensions:!0}}}},e.displacement={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros","displayWithAngleBrackets"],returnWrappingComponents:e=>"x"===e?[]:[["vector",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["x"],hasEssential:!0,essentialVarName:"displacement2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnDisplacement","basedOnHead","sourceOfDisplacement"],returnArraySizeDependencies:()=>({nDimDisplacement:{dependencyType:"stateVariable",variableName:"nDimDisplacement"}}),returnArraySize:({dependencyValues:e})=>[e.nDimDisplacement],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={xsAttr:{dependencyType:"attributeComponent",attributeName:"xs",variableNames:["math"+e]},displacementAttr:{dependencyType:"attributeComponent",attributeName:"displacement",variableNames:["x"+e]},pointChild:{dependencyType:"child",childGroups:["points"],variableNames:["x"+e]},vectorChild:{dependencyType:"child",childGroups:["vectors"],variableNames:["x"+e]}},"0"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"x",variableNames:["value"]}:"1"===r?n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"y",variableNames:["value"]}:"2"===r&&(n[r].componentAttr={dependencyType:"attributeComponent",attributeName:"z",variableNames:["value"]}),!t.basedOnDisplacement&&t.basedOnHead&&(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e})}return{globalDependencies:{basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},displacementShadow:{dependencyType:"stateVariable",variableName:"displacementShadow"},sourceOfDisplacement:{dependencyType:"stateVariable",variableName:"sourceOfDisplacement"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;if(e.basedOnDisplacement)switch(e.sourceOfDisplacement){case"vectorChild":r[i]=t[i].vectorChild[0].stateValues["x"+n];break;case"pointChild":r[i]=t[i].pointChild[0].stateValues["x"+n];break;case"displacementAttr":r[i]=t[i].displacementAttr.stateValues["x"+n];break;case"xsAttr":r[i]=t[i].xsAttr.stateValues["math"+n].simplify();break;case"componentAttrs":let s=t[i].componentAttr;null===s?a[i]={defaultValue:me$3.fromAst(0)}:r[i]=s.stateValues.value.simplify();break;default:let o=e.displacementShadow.tree;Array.isArray(o)&&vectorOperators.includes(o[0])?r[i]=e.displacementShadow.get_component(Number(i)):r[i]=e.displacementShadow}else e.basedOnHead?r[i]=t[i].headX.subtract(t[i].tailX).simplify():a[i]={defaultValue:me$3.fromAst("0"===i?1:0)}}let i={};return Object.keys(r).length>0&&(i.setValue={displacement:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={displacement:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.displacement)if(t.basedOnDisplacement)switch(t.sourceOfDisplacement){case"vectorChild":i.push({setDependency:r[a].vectorChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"pointChild":i.push({setDependency:r[a].pointChild,desiredValue:e.displacement[a],childIndex:0,variableIndex:0});break;case"displacementAttr":i.push({setDependency:r[a].displacementAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"xsAttr":i.push({setDependency:r[a].xsAttr,desiredValue:e.displacement[a],variableIndex:0});break;case"componentAttrs":null===n[a].componentAttr?i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}}):i.push({setDependency:r[a].componentAttr,desiredValue:e.displacement[a],variableIndex:0});break;default:s=!0}else t.basedOnHead?i.push({setDependency:r[a].headX,desiredValue:n[a].tailX.add(e.displacement[a]).simplify()}):i.push({setEssentialValue:"displacement",value:{[a]:convertValueToMathExpression(e.displacement[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.displacement)t[Number(n)+1]=e.displacement[n].tree;t.length=a[0]+1,i.push({setDependency:"displacementShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.displacement&&i.push({setDependency:"displacementShadow",desiredValue:e.displacement[0]});return{success:!0,instructions:i}}},e.x={isAlias:!0,targetVariableName:"x1"},e.y={isAlias:!0,targetVariableName:"x2"},e.z={isAlias:!0,targetVariableName:"x3"},e.head={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"headX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["headX"],set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnHead"],returnArraySizeDependencies:()=>({nDimHead:{dependencyType:"stateVariable",variableName:"nDimHead"}}),returnArraySize:({dependencyValues:e})=>[e.nDimHead],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={headAttr:{dependencyType:"attributeComponent",attributeName:"head",variableNames:["x"+e]}},t.basedOnHead||(n[r].tailX={dependencyType:"stateVariable",variableName:"tailX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnTail:{dependencyType:"stateVariable",variableName:"basedOnTail"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},headShadow:{dependencyType:"stateVariable",variableName:"headShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={};for(let a of n){let n=Number(a)+1;e.basedOnHead?null!==t[a].headAttr?r[a]=t[a].headAttr.stateValues["x"+n]:null!==e.headShadow&&(r[a]=e.headShadow.get_component(Number(a))):r[a]=t[a].tailX.add(t[a].x).simplify()}return{setValue:{head:r}}},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.head)t.basedOnHead?n[a].headAttr&&null!==n[a].headAttr?i.push({setDependency:r[a].headAttr,desiredValue:e.head[a],variableIndex:0}):null!==t.headShadow&&(s=!0):i.push({setDependency:r[a].x,desiredValue:e.head[a].subtract(n[a].tailX).simplify()});if(s)if(a[0]>1){let t=["vector"];for(let n in e.head)t[Number(n)+1]=e.head[n].tree;t.length=a[0]+1,i.push({setDependency:"headShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.head&&i.push({setDependency:"headShadow",desiredValue:e.head[0]});return{success:!0,instructions:i}}},e.tail={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],returnWrappingComponents:e=>"tailX"===e?[]:[["point",{componentType:"mathList",isAttribute:"xs"}]]},isArray:!0,entryPrefixes:["tailX"],hasEssential:!0,defaultValueByArrayKey:()=>me$3.fromAst(0),essentialVarName:"tail2",set:convertValueToMathExpression,stateVariablesDeterminingDependencies:["basedOnTail","basedOnHead","basedOnDisplacement"],returnArraySizeDependencies:()=>({nDimTail:{dependencyType:"stateVariable",variableName:"nDimTail"}}),returnArraySize:({dependencyValues:e})=>[e.nDimTail],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={};for(let r of e){let e=Number(r)+1;n[r]={tailAttr:{dependencyType:"attributeComponent",attributeName:"tail",variableNames:["x"+e]}},t.basedOnTail||t.basedOnHead&&t.basedOnDisplacement&&(n[r].headX={dependencyType:"stateVariable",variableName:"headX"+e},n[r].x={dependencyType:"stateVariable",variableName:"x"+e})}return{globalDependencies:{basedOnDisplacement:{dependencyType:"stateVariable",variableName:"basedOnDisplacement"},basedOnHead:{dependencyType:"stateVariable",variableName:"basedOnHead"},tailShadow:{dependencyType:"stateVariable",variableName:"tailShadow"}},dependenciesByKey:n}},arrayDefinitionByKey:function({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){let r={},a={};for(let i of n){let n=Number(i)+1;null!==t[i].tailAttr?r[i]=t[i].tailAttr.stateValues["x"+n]:null!==e.tailShadow?r[i]=e.tailShadow.get_component(Number(i)):e.basedOnHead&&e.basedOnDisplacement?r[i]=t[i].headX.subtract(t[i].x).simplify():a[i]=!0}let i={};return Object.keys(r).length>0&&(i.setValue={tail:r}),Object.keys(a).length>0&&(i.useEssentialOrDefaultValue={tail:a}),i},inverseArrayDefinitionByKey({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,arraySize:a}){let i=[],s=!1;for(let a in e.tail)n[a].tailAttr&&null!==n[a].tailAttr?i.push({setDependency:r[a].tailAttr,desiredValue:e.tail[a],variableIndex:0}):null!==t.tailShadow?s=!0:t.basedOnHead&&t.basedOnDisplacement?i.push({setDependency:r[a].x,desiredValue:n[a].headX.subtract(e.tail[a]).simplify()}):i.push({setEssentialValue:"tail",value:{[a]:convertValueToMathExpression(e.tail[a])}});if(s)if(a[0]>1){let t=["vector"];for(let n in e.tail)t[Number(n)+1]=e.tail[n].tree;t.length=a[0]+1,i.push({setDependency:"tailShadow",desiredValue:me$3.fromAst(t)})}else 1===a[0]&&"0"in e.tail&&i.push({setDependency:"tailShadow",desiredValue:e.tail[0]});return{success:!0,instructions:i}}},e.magnitude={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},displacement:{dependencyType:"stateVariable",variableName:"displacement"}}),definition({dependencyValues:e}){let t=0,n=!0;for(let r=0;re/i));let s=e.magnitude.evaluate_to_constant();if(!Number.isFinite(s)||s<0)return{success:!1};let o=[];for(let e=0;e({head:{dependencyType:"stateVariable",variableName:"head"},tail:{dependencyType:"stateVariable",variableName:"tail"},nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),definition:function({dependencyValues:e}){let t,n;if(1===e.nDimensions)e.head[0].evaluate_to_constant(),n=e.tail[0].evaluate_to_constant(),Number.isFinite(n)||(n=NaN);else{t=[],n=[];for(let r=0;r({displacement:{dependencyType:"stateVariable",variableName:"displacement"},displayWithAngleBrackets:{dependencyType:"stateVariable",variableName:"displayWithAngleBrackets"}}),definition({dependencyValues:e}){let t=[];for(let n of e.displacement)n?t.push(n.tree):t.push("_");if(t.length>1){t=[e.displayWithAngleBrackets?"altvector":"vector",...t]}else t=1===t.length?t[0]:"_";return{setValue:{displacementCoords:me$3.fromAst(t)}}},inverseDefinition({desiredStateVariableValues:e}){let t,n=e.displacementCoords.tree;return t=Array.isArray(n)&&vectorOperators.includes(n[0])?n.slice(1).map((e=>me$3.fromAst(e))):[e.displacementCoords],{success:!0,instructions:[{setDependency:"displacement",desiredValue:t}]}}},e.latex={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({displacementCoords:{dependencyType:"stateVariable",variableName:"displacementCoords"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:roundForDisplay({value:e.displacementCoords,dependencyValues:e,usedDefault:t}).toLatex(n)}}}},e.nearestPoint={returnDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"},numericalEndpoints:{dependencyType:"stateVariable",variableName:"numericalEndpoints"}}),definition({dependencyValues:e}){let t=e.numericalEndpoints[0]?.[0],n=e.numericalEndpoints[0]?.[1],r=e.numericalEndpoints[1]?.[0],a=e.numericalEndpoints[1]?.[1],i=Number.isFinite(t)&&Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a),s=2!==e.nDimensions||!i||r===t&&a===n;return{setValue:{nearestPoint:function({variables:e,scales:i}){if(s)return{};let o=i[0],l=i[1],u=(r-t)/o,c=(a-n)/l,p=u*u+c*c,d=((e.x1-t)/o*u+(e.x2-n)/l*c)/p,m={};return m=d<=0?{x1:t,x2:n}:d>=1?{x1:r,x2:a}:{x1:t+d*u*o,x2:n+d*c*l},void 0!==e.x3&&(m.x3=0),m}}}}},e}static adapters=[{stateVariable:"displacementCoords",componentType:"coords",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]}];async moveVector({tailcoords:e,headcoords:t,transient:n,skippable:r,sourceInformation:a,actionId:i}){if(void 0!==e){if(void 0!==t){if(!await this.stateValues.draggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.tailDraggable)return await this.coreFunctions.resolveAction({actionId:i})}else if(!await this.stateValues.headDraggable)return await this.coreFunctions.resolveAction({actionId:i});let s=[];if(void 0!==e){if(await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let n;if(void 0===t){let t=await this.stateValues.numericalEndpoints;n=e.map(((e,n)=>t[1][n]-e))}else n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}else s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"tail",value:e.map((e=>me$3.fromAst(e))),sourceInformation:a});if(void 0===t&&!await this.stateValues.basedOnHead){let t=await this.stateValues.numericalEndpoints,n=e.map(((e,n)=>t[1][n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}if(void 0!==t){if(await this.stateValues.basedOnHead)s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"head",value:t.map((e=>me$3.fromAst(e))),sourceInformation:a});else{null==e&&(e=(await this.stateValues.numericalEndpoints)[0]);let n=e.map(((e,n)=>t[n]-e));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}if(void 0===e&&await this.stateValues.basedOnHead&&await this.stateValues.basedOnDisplacement){let e=await this.stateValues.numericalEndpoints,n=t.map(((t,n)=>t-e[0][n]));s.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"displacement",value:n.map((e=>me$3.fromAst(e))),sourceInformation:a})}}return n?await this.coreFunctions.performUpdate({updateInstructions:s,transient:n,skippable:r,actionId:i}):await this.coreFunctions.performUpdate({updateInstructions:s,actionId:i,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{head:t,tail:e}}})}async vectorClicked({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"click",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}async mouseDownOnVector({actionId:e}){await this.coreFunctions.triggerChainedActions({triggeringAction:"down",componentName:this.componentName}),this.coreFunctions.resolveAction({actionId:e})}}class Angle extends GraphicalComponent{static componentType="angle";static createAttributesObject(){let e=super.createAttributesObject();return e.draggable={createComponentOfType:"boolean",createStateVariable:"draggable",defaultValue:!0,public:!0,forRenderer:!0},e.radius={createComponentOfType:"math",createStateVariable:"radius",defaultValue:me$3.fromAst(1),public:!0},e.chooseReflexAngle={createComponentOfType:"text",createStateVariable:"chooseReflexAngle",defaultValue:"never",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["never","allowed","always"]},e.inDegrees={createComponentOfType:"boolean",createStateVariable:"inDegrees",defaultValue:!1,public:!0,forRenderer:!0},e.radians={createComponentOfType:"math"},e.degrees={createComponentOfType:"math"},e.through={createComponentOfType:"_pointListComponent"},e.betweenLines={createComponentOfType:"_lineListComponent"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.emphasizeRightAngle={createComponentOfType:"boolean",createStateVariable:"emphasizeRightAngle",defaultValue:!0,public:!0,forRenderer:!0},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,componentInfoObjects:t}){let n=e.map((e=>t.componentIsSpecifiedType(e,"label"))),r=[],a=[];if(0===n.filter((e=>e)).length)r=e;else{if(n[0]){let t=n.indexOf(!1);-1!==t&&(a.push(...e.slice(0,t)),e=e.slice(t),n=n.slice(t))}let t=n.indexOf(!0);-1===t?r=e:(r=e.slice(0,t),a.push(...e.slice(t)))}return 0===r.length?{success:!1}:{success:!0,newAttributes:{radians:{component:{componentType:"math",children:r}}},newChildren:a}}}),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({betweenLines:{dependencyType:"attributeComponent",attributeName:"betweenLines"}}),definition({dependencyValues:e}){let t=null;return null!==e.betweenLines&&(t=e.betweenLines.componentName),{setValue:{betweenLinesName:t}}}},e.nPointsSpecified={returnDependencies:()=>({through:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["nPoints"]}}),definition:({dependencyValues:e})=>null!==e.through?{setValue:{nPointsSpecified:e.through.stateValues.nPoints}}:{setValue:{nPointsSpecified:0}}},e.points={isArray:!0,nDimensions:2,entryPrefixes:["pointX","point"],stateVariablesDeterminingDependencies:["betweenLinesName"],returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3,2],getArrayKeysFromVarName({arrayEntryPrefix:e,varEnding:t,arraySize:n}){if("pointX"===e){let e=t.split("_").map((e=>Number(e)-1));return 2===e.length&&e.every(((e,t)=>Number.isInteger(e)&&e>=0))?n?e.every(((e,t)=>e=0?n?ee+","+n)):[]:[e+",0"]:[]}},returnArrayDependenciesByKey({stateValues:e}){let t={nPointsSpecified:{dependencyType:"stateVariable",variableName:"nPointsSpecified"},throughAttr:{dependencyType:"attributeComponent",attributeName:"through",variableNames:["points"]},radiansAttr:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degreesAttr:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]}};return null!==e.betweenLinesName&&(t.lineChildren={dependencyType:"child",parentName:e.betweenLinesName,childGroups:["lines"],variableNames:["points","nDimensions","coeff0","coeffvar1","coeffvar2","nearestPoint"]}),{globalDependencies:t}},arrayDefinitionByKey({globalDependencyValues:e}){if(e.lineChildren){if(e.lineChildren.length>2){console.warn(`Cannot define an angle between ${e.lineChildren.length} line(s)`);let t={};for(let e=0;e<3;e++)for(let n=0;n<2;n++)t[e+","+n]=me$3.fromAst("_");return{setValue:{points:t}}}if(1===e.lineChildren.length){let t=e.lineChildren[0];if(2!==t.stateValues.nDimensions){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let n=t.stateValues.nearestPoint({variables:{x1:me$3.fromAst(0),x2:me$3.fromAst(0)}}),r=t.stateValues.points[0][0].evaluate_to_constant(),a=t.stateValues.points[0][1].evaluate_to_constant(),i=t.stateValues.points[1][0].evaluate_to_constant(),s=t.stateValues.points[1][1].evaluate_to_constant(),o=Math.atan2(s-a,i-r),l={"0,0":me$3.fromAst(n.x1+Math.cos(o)),"0,1":me$3.fromAst(n.x2+Math.sin(o)),"1,0":me$3.fromAst(n.x1),"1,1":me$3.fromAst(n.x2)},u=null;if(e.radiansAttr){if(u=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(u)){let e={};return e["2,0"]=me$3.fromAst("_"),e["2,1"]=me$3.fromAst("_"),{setValue:{points:e}}}}else if(e.degreesAttr){let t=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(t))return l["2,0"]=me$3.fromAst("_"),l["2,1"]=me$3.fromAst("_"),{setValue:{points:l}};u=t/180*Math.PI}else u=Math.PI/2;let c=o+u;return l["2,0"]=me$3.fromAst(n.x1+Math.cos(c)),l["2,1"]=me$3.fromAst(n.x2+Math.sin(c)),{setValue:{points:l}}}{let t=e.lineChildren[0],n=e.lineChildren[1],r=calculateLineIntersection(t,n);if(void 0===r){let e={};for(let t=0;t<3;t++)for(let n=0;n<2;n++)e[t+","+n]=me$3.fromAst("_");return{setValue:{points:e}}}let a=r,i=t.stateValues.points[0][0].evaluate_to_constant(),s=t.stateValues.points[0][1].evaluate_to_constant(),o=t.stateValues.points[1][0].evaluate_to_constant(),l=t.stateValues.points[1][1].evaluate_to_constant(),u=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];i=n.stateValues.points[0][0].evaluate_to_constant(),s=n.stateValues.points[0][1].evaluate_to_constant(),o=n.stateValues.points[1][0].evaluate_to_constant(),l=n.stateValues.points[1][1].evaluate_to_constant();let c=[me$3.fromAst(a[0].tree+o-i),me$3.fromAst(a[1].tree+l-s)];return{setValue:{points:{"0,0":u[0],"0,1":u[1],"1,0":a[0],"1,1":a[1],"2,0":c[0],"2,1":c[1]}}}}}let t,n=e.nPointsSpecified;t=e.throughAttr?e.throughAttr.stateValues.points:[];let r={};for(let[e,n]of t.entries())r[e+",0"]=n[0],r[e+",1"]=n[1];if(0===n&&(r["0,0"]=me$3.fromAst(1),r["0,1"]=me$3.fromAst(0)),n<2&&(r["1,0"]=me$3.fromAst(0),r["1,1"]=me$3.fromAst(0)),n<3){let t=null;if(e.radiansAttr){if(t=e.radiansAttr.stateValues.value.evaluate_to_constant(),!Number.isFinite(t))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}}}else if(e.degreesAttr){let n=e.degreesAttr.stateValues.value.evaluate_to_constant();if(!Number.isFinite(n))return r["2,0"]=me$3.fromAst("_"),r["2,1"]=me$3.fromAst("_"),{setValue:{points:r}};t=n/180*Math.PI}else t=Math.PI/2;let n=r["0,0"].evaluate_to_constant(),a=r["0,1"].evaluate_to_constant(),i=r["1,0"].evaluate_to_constant(),s=r["1,1"].evaluate_to_constant(),o=Math.atan2(a-s,n-i)+t;r["2,0"]=me$3.fromAst(i+Math.cos(o)),r["2,1"]=me$3.fromAst(s+Math.sin(o))}return{setValue:{points:r}}}},e.radians={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},additionalStateVariablesDefined:[{variableName:"swapPointOrder",forRenderer:!0}],returnDependencies:()=>({radians:{dependencyType:"attributeComponent",attributeName:"radians",variableNames:["value"]},degrees:{dependencyType:"attributeComponent",attributeName:"degrees",variableNames:["value"]},points:{dependencyType:"stateVariable",variableName:"points"},chooseReflexAngle:{dependencyType:"stateVariable",variableName:"chooseReflexAngle"}}),definition({dependencyValues:e}){let t=!1;if(null!==e.radians)return{setValue:{radians:e.radians.stateValues.value.simplify(),swapPointOrder:t}};if(null!==e.degrees)return{setValue:{radians:e.degrees.stateValues.value.divide(me$3.fromAst(180)).simplify().multiply(me$3.fromAst("pi")).simplify(),swapPointOrder:t}};let n,r=[],a=!1;for(let t=0;t<3;t++)r.push([e.points[t][0].evaluate_to_constant(),e.points[t][1].evaluate_to_constant()]),null!==r[t][0]&&null!==r[t][1]||(a=!0);return a?{setValue:{radians:me$3.fromAst("_"),swapPointOrder:t}}:(n=Math.atan2(r[2][1]-r[1][1],r[2][0]-r[1][0])-Math.atan2(r[0][1]-r[1][1],r[0][0]-r[1][0]),n<0&&(n+=2*Math.PI),n>Math.PI?"never"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0):"always"===e.chooseReflexAngle&&(n=2*Math.PI-n,t=!0),{setValue:{radians:me$3.fromAst(n),swapPointOrder:t}})}},e.value={isAlias:!0,targetVariableName:"radians"},e.angle={isAlias:!0,targetVariableName:"radians"},e.degrees={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},returnDependencies:()=>({radians:{dependencyType:"stateVariable",variableName:"radians"}}),definition({dependencyValues:e}){let t;if("_"===e.radians.tree||Number.isNaN(e.radians.tree))t=e.radians;else{let n=e.radians.evaluate_to_constant();t=Number.isFinite(n)?me$3.fromAst(180*n/Math.PI):e.radians.multiply(me$3.fromAst(["/",180,"pi"])).simplify()}return{setValue:{degrees:t}}}},e.latexForRenderer={forRenderer:!0,returnDependencies:()=>({inDegrees:{dependencyType:"stateVariable",variableName:"inDegrees"},radians:{dependencyType:"stateVariable",variableName:"radians"},degrees:{dependencyType:"stateVariable",variableName:"degrees"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits));let r=roundForDisplay({value:e.inDegrees?e.degrees:e.radians,dependencyValues:e,usedDefault:t}).toLatex(n);return e.inDegrees&&(r+="^\\circ"),{setValue:{latexForRenderer:r}}}},e.numericalPoints={isArray:!0,entryPrefixes:["numericalPoint"],forRenderer:!0,returnArraySizeDependencies:()=>({}),returnArraySize:()=>[3],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={point:{dependencyType:"stateVariable",variableName:"point"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t){let t=e[r].point,a=[];for(let e=0;e<2;e++){let n=t[e].evaluate_to_constant();Number.isFinite(n)||(n=NaN),a.push(n)}n[r]=a}return{setValue:{numericalPoints:n}}}},e.numericalRadius={forRenderer:!0,returnDependencies:()=>({radius:{dependencyType:"stateVariable",variableName:"radius"}}),definition({dependencyValues:e}){let t=e.radius.evaluate_to_constant();return Number.isFinite(t)||(t=NaN),{setValue:{numericalRadius:t}}}},e}static adapters=["radians"]}function calculateLineIntersection(e,t){if(2!==e.stateValues.nDimensions||2!==t.stateValues.nDimensions)return void console.log("Calculating angle between two lines implemented only in 2D");let n=e.stateValues.coeffvar1.evaluate_to_constant(),r=e.stateValues.coeffvar2.evaluate_to_constant(),a=e.stateValues.coeff0.evaluate_to_constant(),i=t.stateValues.coeffvar1.evaluate_to_constant(),s=t.stateValues.coeffvar2.evaluate_to_constant(),o=t.stateValues.coeff0.evaluate_to_constant();if(!(Number.isFinite(n)&&Number.isFinite(r)&&Number.isFinite(a)&&Number.isFinite(i)&&Number.isFinite(s)&&Number.isFinite(o)))return void console.log("Calculating angle between two lines implemented only for constant coefficients");let l=n*s-i*r;if(Math.abs(l)<1e-14)return Math.abs(o*n-a*i)>1e-14?void console.log("Cannot calculate angle between two parallel lines"):0===n&&0===r&&0===a||0===i&&0===s&&0===o?void 0:0!==r?[me$3.fromAst(0),me$3.fromAst(-a/r)]:[me$3.fromAst(-a/n),me$3.fromAst(0)];let u=(o*r-a*s)/l,c=(a*i-o*n)/l;return[me$3.fromAst(u),me$3.fromAst(c)]}var defaults$5={space:"",cycles:!1,replacer:(e,t)=>t,stringify:JSON.stringify},util$1={isArray:Array.isArray,assign:Object.assign,isObject:e=>"object"==typeof e,isFunction:e=>"function"==typeof e,isBoolean:e=>"boolean"==typeof e,isRegex:e=>e instanceof RegExp,keys:Object.keys};const DEFAULTS=defaults$5,isFunction$2=util$1.isFunction,isBoolean$1=util$1.isBoolean,isObject$2=util$1.isObject,isArray$3=util$1.isArray,isRegex=util$1.isRegex,assign$1=util$1.assign,keys$1=util$1.keys;function serialize(e){return null==e?e:isRegex(e)?e.toString():e.toJSON?e.toJSON():e}function stringifyDeterministic(e,t){t=t||assign$1({},DEFAULTS),isFunction$2(t)&&(t={compare:t});const n=t.space||DEFAULTS.space,r=isBoolean$1(t.cycles)?t.cycles:DEFAULTS.cycles,a=t.replacer||DEFAULTS.replacer,i=t.stringify||DEFAULTS.stringify,s=t.compare&&function(e){return function(t){return function(n,r){const a={key:n,value:t[n]},i={key:r,value:t[r]};return e(a,i)}}}(t.compare);r||i(e);const o=[];return function e(t,l,u,c){const p=n?"\n"+new Array(c+1).join(n):"",d=n?": ":":";if(u=serialize(u),void 0!==(u=a.call(t,l,u))){if(!isObject$2(u)||null===u)return i(u);if(isArray$3(u)){const t=[];for(let r=0;r0)for(let e of t.children)"object"!=typeof e?e.trim()&&(p=!0):i(e,"when")||(i(e,"math")||i(e,"number")||i(e,"mathList")||i(e,"numberList")?(s=!0,p=!0):i(e,"text")||i(e,"textList")?(o=!0,p=!0):i(e,"boolean")?(l=!0,p=!0):i(e,"booleanList")?l=!0:n.isInheritedComponentType({inheritedComponentType:e.componentType,baseComponentType:"_composite"})&&!e.attributes?.createComponentOfType?.primitive?p=!0:i(e,"orbitalDiagram")||(p=!0));else p=!0;else i(t,"mathInput")?(h.push(!1),s=!0,c=!0):i(t,"textInput")?(h.push(!1),o=!0,c=!0):i(t,"_input")||i(t,"considerAsResponses")?(h.push(!1),c=!0):(n.isInheritedComponentType({inheritedComponentType:t.componentType,baseComponentType:"_composite"})&&t.attributes?.createComponentOfType?.primitive,h.push(!0),p=!0);if(c&&(d=!0),u>0){if(e=e.filter((e=>"string"!=typeof e||""!==e.trim())),e.length!==u)return{success:!1};{let n={componentType:"choiceInput",children:e};return t.shuffleOrder&&(n.attributes={shuffleOrder:{primitive:!0}}),{success:!0,newChildren:[n]}}}if(t.handGraded&&!m&&(p=!0),!p&&!d){for(let t of e)if(i(t,"award")&&t.children?.length>0&&r(t.children)){d=!0;break}if(!d)for(let t of e)i(t,"award")&&t.children?.length>0&&a(t.children)}let f=[],y=[],g=[];if(0===h.filter((e=>!e)).length)f=e;else{if(!h[0]){let t=h.indexOf(!0);-1!==t&&(y=e.slice(0,t),e=e.slice(t),h=h.slice(t))}let t=h.indexOf(!1);-1===t?f=e:(f=e.slice(0,t),g=e.slice(t))}for(;"string"==typeof f[0]&&""===f[0].trim();)f=f.slice(1);let b,v,N=f.length;for(;"string"==typeof f[N-1]&&""===f[N-1].trim();)f=f.slice(0,N-1),N=f.length;if(t.type?(v=t.type,["math","text","boolean"].includes(v)||(console.warn(`Invalid type ${v}`),v="math")):v=s?"math":o?"text":l?"boolean":"math",0===f.length)b=[...y,...g];else{let e;e=f.length>1||n.isInheritedComponentType({inheritedComponentType:f[0].componentType,baseComponentType:"_composite"})&&!f[0].props?.componentType?[{componentType:v,children:f}]:f,b=[...y,{componentType:"award",children:e},...g]}if(p&&!c){b=[{componentType:v+"Input"},...b]}return{success:!0,newChildren:b}}}),e}static returnChildGroups(){return[{group:"awards",componentTypes:["award"]},{group:"inputs",componentTypes:["_input"]},{group:"responses",componentTypes:["considerAsResponses"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"disabled",newName:"disabledOriginal"}),e.showCorrectness={forRenderer:!0,returnDependencies:()=>({showCorrectnessPreliminary:{dependencyType:"stateVariable",variableName:"showCorrectnessPreliminary"},showCorrectnessFlag:{dependencyType:"flag",flagName:"showCorrectness"},handGraded:{dependencyType:"stateVariable",variableName:"handGraded"}}),definition({dependencyValues:e,usedDefault:t}){let n;return n=t.showCorrectnessPreliminary?!1!==e.showCorrectnessFlag&&!e.handGraded:e.showCorrectnessPreliminary,{setValue:{showCorrectness:n}}}},e.haveAwardThatRequiresInput={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["requireInputInAnswer"]}}),definition:({dependencyValues:e})=>({setValue:{haveAwardThatRequiresInput:e.awardChildren.some((e=>e.stateValues.requireInputInAnswer))}})},e.allInputChildrenIncludingSugared={returnDependencies:()=>({allInputChildrenIncludingSugared:{dependencyType:"child",childGroups:["inputs"]}}),definition:({dependencyValues:e})=>({setValue:{allInputChildrenIncludingSugared:e.allInputChildrenIncludingSugared}})},e.inputChildren={stateVariablesDeterminingDependencies:["allInputChildrenIncludingSugared"],additionalStateVariablesDefined:["inputChildIndices","skippedFirstInput"],forRenderer:!0,returnDependencies({stateValues:e}){let t={allInputChildrenIncludingSugared:{dependencyType:"stateVariable",variableName:"allInputChildrenIncludingSugared"},haveAwardThatRequiresInput:{dependencyType:"stateVariable",variableName:"haveAwardThatRequiresInput"},handGraded:{dependencyType:"stateVariable",variableName:"handGraded"}};return e.allInputChildrenIncludingSugared.length>0&&(t.firstInputFromSugar={dependencyType:"doenetAttribute",componentName:e.allInputChildrenIncludingSugared[0].componentName,attributeName:"createdFromSugar"}),t},definition({dependencyValues:e}){let t=[...e.allInputChildrenIncludingSugared],n=[...e.allInputChildrenIncludingSugared.keys()],r=!1;return"choiceInput"!==t[0]?.componentType&&(!(e.haveAwardThatRequiresInput||e.handGraded)||e.allInputChildrenIncludingSugared.length>1)&&e.firstInputFromSugar&&(r=!0,t=t.slice(1),n=n.slice(1)),{setValue:{inputChildren:t,inputChildIndices:n,skippedFirstInput:r}}}},e.inputChildrenWithValues={stateVariablesDeterminingDependencies:["inputChildIndices"],forRenderer:!0,returnDependencies:({stateValues:e})=>({inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["valueToRecordOnSubmit","valueRecordedAtSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0}}),definition:function({dependencyValues:e}){return{setValue:{inputChildrenWithValues:e.inputChildren}}}},e.inputChildWithValues={returnDependencies:()=>({inputChildrenWithValues:{dependencyType:"stateVariable",variableName:"inputChildrenWithValues"}}),definition({dependencyValues:e}){let t=null;return 1===e.inputChildrenWithValues.length&&(t=e.inputChildrenWithValues[0]),{setValue:{inputChildWithValues:t}}}},e.awardInputResponseChildren={returnDependencies:()=>({awardInputResponseChildren:{dependencyType:"child",childGroups:["awards","inputs","responses"]},skippedFirstInput:{dependencyType:"stateVariable",variableName:"skippedFirstInput"}}),definition({dependencyValues:e}){let t=[...e.awardInputResponseChildren];return e.skippedFirstInput&&(t=t.slice(1)),{setValue:{awardInputResponseChildren:t}}}},e.nResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnDependencies({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","nValues"],variablesOptional:!0,recurseToMatchedChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?n["childNValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"nValues",variablesOptional:!0}:n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenWithNValues"};return n},definition({dependencyValues:e,componentInfoObjects:t}){let n=0;for(let[r,a]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"award"}))for(let a of e["child"+r])a.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_composite"})&&(void 0===a.stateValues.nValues?n+=1:n+=a.stateValues.nValues);else if(t.isInheritedComponentType({inheritedComponentType:a,baseComponentType:"_input"})){let t=e["childNValues"+r];n+=void 0===t?1:t}else for(let t of e["child"+r])void 0===t.stateValues.nValues?n+=1:n+=t.stateValues.nValues;return{setValue:{nResponses:n}}}},e.currentResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["currentResponse"],stateVariablesDeterminingDependencies:["awardInputResponseChildren"],returnArraySizeDependencies:()=>({nResponses:{dependencyType:"stateVariable",variableName:"nResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nResponses],returnArrayDependenciesByKey({stateValues:e,componentInfoObjects:t}){let n={childTypes:{dependencyType:"value",value:e.awardInputResponseChildren.map((e=>e.componentType))}};for(let[r,a]of e.awardInputResponseChildren.entries())t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"award"})?n["child"+r]={dependencyType:"descendant",ancestorName:a.componentName,componentTypes:["_base"],variableNames:["isResponse","value","values","formula","componentType"],variablesOptional:!0,recurseToMatchedChildren:!0,includeAttributeChildren:!0,includeNonActiveChildren:!0,skipOverAdapters:!0}:t.isInheritedComponentType({inheritedComponentType:a.componentType,baseComponentType:"_input"})?(n["childValue"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"value",variablesOptional:!0},n["childValues"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"values",variablesOptional:!0},n["childComponentType"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"componentType",variablesOptional:!0}):n["child"+r]={dependencyType:"stateVariable",componentName:a.componentName,variableName:"childrenAsResponses"};return{globalDependencies:n}},arrayDefinitionByKey({globalDependencyValues:e,componentInfoObjects:t}){let n=[],r=[],a=[];for(let[n,r]of e.childTypes.entries())if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"award"}))for(let r of e["child"+n])r.stateValues.isResponse&&!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})&&a.push(r);else if(t.isInheritedComponentType({inheritedComponentType:r,baseComponentType:"_input"})){let t={componentType:r,stateValues:{value:e["childValue"+n],values:e["childValues"+n],componentType:e["childComponentType"+n]}};a.push(t)}else a.push(...e["child"+n]);for(let e of a){let t=e.stateValues.componentType;t||(t=e.componentType),"mathList"===t?t="math":"numberList"===t?t="number":"textList"===t?t="text":"booleanList"===t&&(t="boolean"),Array.isArray(e.stateValues.values)?(n.push(...e.stateValues.values),r.push(...Array(e.stateValues.values.length).fill(t))):void 0!==e.stateValues.value?(n.push(e.stateValues.value),r.push(t)):e.stateValues.formula instanceof me$3.class?(n.push(e.stateValues.formula),r.push("math")):(n.push(""),r.push("text"))}return{setValue:{currentResponses:n},setCreateComponentOfType:{currentResponses:r}}}},e.currentResponse={isAlias:!0,targetVariableName:"currentResponse1"},e.nSubmittedResponses={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nSubmittedResponses:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmittedResponses",value:e.nSubmittedResponses}]})},e.submittedResponsesComponentType={hasEssential:!0,defaultValue:null,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{submittedResponsesComponentType:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return e.submittedResponsesComponentType?{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[...e.submittedResponsesComponentType]}]}:{success:!0,instructions:[{setEssentialValue:"submittedResponsesComponentType",value:[]}]}}},e.submittedResponses={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["submittedResponse"],defaultValueByArrayKey:()=>"_",hasEssential:!0,inverseShadowToSetEntireArray:!0,doNotCombineInverseArrayInstructions:!0,returnArraySizeDependencies:()=>({nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}),returnArraySize:({dependencyValues:e})=>[e.nSubmittedResponses],returnArrayDependenciesByKey:()=>({globalDependencies:{submittedResponsesComponentType:{dependencyType:"stateVariable",variableName:"submittedResponsesComponentType"},nSubmittedResponses:{dependencyType:"stateVariable",variableName:"nSubmittedResponses"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=[];e.submittedResponsesComponentType&&t.push(...e.submittedResponsesComponentType.slice(0,e.nSubmittedResponses));let n={};for(let r=0;r({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{suppressCheckwork:e.autoSubmit}})},e.delegateCheckWork={additionalStateVariablesDefined:["delegateCheckWorkToInput","delegateCheckWorkToAncestor"],forRenderer:!0,returnDependencies:()=>({inputChildren:{dependencyType:"stateVariable",variableName:"inputChildren"},forceFullCheckworkButton:{dependencyType:"stateVariable",variableName:"forceFullCheckworkButton"},sectionAncestor:{dependencyType:"ancestor",componentType:"_sectioningComponent",variableNames:["suppressAnswerSubmitButtons"]},documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["suppressAnswerSubmitButtons"]}}),definition:function({dependencyValues:e}){let t=!1,n=!1,r=!1;return e.documentAncestor.stateValues.suppressAnswerSubmitButtons||e.sectionAncestor?.stateValues.suppressAnswerSubmitButtons?t=r=!0:1!==e.inputChildren.length||e.forceFullCheckworkButton||(n=r=!0),{setValue:{delegateCheckWork:r,delegateCheckWorkToAncestor:t,delegateCheckWorkToInput:n}}}},e.creditAchievedIfSubmit={additionalStateVariablesDefined:["awardsUsedIfSubmit","awardChildren","inputUsedIfSubmit"],stateVariablesDeterminingDependencies:["inputChildIndices"],returnDependencies:({stateValues:e})=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["credit","creditAchievedIfSubmit","fractionSatisfiedIfSubmit"]},inputChildren:{dependencyType:"child",childGroups:["inputs"],variableNames:["creditAchievedIfSubmit","value"],childIndices:e.inputChildIndices,variablesOptional:!0},nAwardsCredited:{dependencyType:"stateVariable",variableName:"nAwardsCredited"}}),definition:function({dependencyValues:e}){let t=0,n=e.nAwardsCredited,r=Array(n).fill(null),a=null;if(0===e.awardChildren.length){if(1===e.inputChildren.length){let n=e.inputChildren[0].stateValues.creditAchievedIfSubmit;n>=0&&(t=n,a=e.inputChildren[0].componentName)}}else{let a=Array(n).fill(null),i=0;for(let t of e.awardChildren){let e=t.stateValues.creditAchievedIfSubmit;if((e>i||null===r[n-1])&&t.stateValues.fractionSatisfiedIfSubmit>0)if(null===r[0])r[0]=t.componentName,a[0]=e,i=Math.min(...a);else for(let[s,o]of a.entries())if(e>o||null===o){r.splice(s,0,t.componentName),r=r.slice(0,n),a.splice(s,0,e),a=a.slice(0,n),i=Math.min(...a);break}}t=Math.min(1,a.reduce(((e,t)=>e+t),0))}return{setValue:{creditAchievedIfSubmit:t,awardsUsedIfSubmit:r,awardChildren:e.awardChildren,inputUsedIfSubmit:a}}}},e.creditAchieved={defaultValue:0,public:!0,shadowingInstructions:{createComponentOfType:"number"},forRenderer:!0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}}},e.responseHasBeenSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{responseHasBeenSubmitted:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"responseHasBeenSubmitted",value:e.responseHasBeenSubmitted}]}}},e.autoSubmit={returnDependencies:()=>({autoSubmit:{dependencyType:"flag",flagName:"autoSubmit"}}),definition:({dependencyValues:e})=>({setValue:{autoSubmit:Boolean(e.autoSubmit)}})},e.creditAchievedDependencies={shadowVariable:!0,stateVariablesDeterminingDependencies:["autoSubmit"],returnDependencies:({stateValues:e})=>({currentCreditAchievedDependencies:{dependencyType:"recursiveDependencyValues",variableNames:["creditAchievedIfSubmit"],includeImmediateValueWithValue:!e.autoSubmit,includeRawValueWithImmediateValue:!e.autoSubmit,includeOnlyEssentialValues:!0}}),definition({dependencyValues:e}){let t=lib(e.currentCreditAchievedDependencies,{replacer:serializedComponentsReplacer});return{setValue:{creditAchievedDependencies:Base64.stringify(sha1(t))}}},markStale:()=>({answerCreditPotentiallyChanged:!0})},e.creditAchievedDependenciesAtSubmit={defaultValue:null,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchievedDependenciesAtSubmit:!0}}),inverseDefinition:function({desiredStateVariableValues:e}){return{success:!0,instructions:[{setEssentialValue:"creditAchievedDependenciesAtSubmit",value:e.creditAchievedDependenciesAtSubmit}]}}},e.justSubmitted={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({currentCreditAchievedDependencies:{dependencyType:"stateVariable",variableName:"creditAchievedDependencies"},creditAchievedDependenciesAtSubmit:{dependencyType:"stateVariable",variableName:"creditAchievedDependenciesAtSubmit"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"},hasBeenCorrect:{dependencyType:"stateVariable",variableName:"hasBeenCorrect"}}),definition:function({dependencyValues:e,justUpdatedForNewComponent:t,componentName:n}){if(e.disableAfterCorrect&&e.hasBeenCorrect)return{setValue:{justSubmitted:!0}};return e.creditAchievedDependenciesAtSubmit!==e.currentCreditAchievedDependencies&&!t?{setValue:{justSubmitted:!1},setEssentialValue:{justSubmitted:!1}}:{useEssentialOrDefaultValue:{justSubmitted:!0}}},inverseDefinition:({desiredStateVariableValues:e,componentName:t})=>({success:!0,instructions:[{setEssentialValue:"justSubmitted",value:e.justSubmitted}]})},e.allFeedbacks={returnDependencies:()=>({awardChildren:{dependencyType:"child",childGroups:["awards"],variableNames:["feedbacks"]},feedbackComponents:{dependencyType:"descendant",componentTypes:["_input"],variableNames:["feedbacks"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.awardChildren)t.push(...n.stateValues.feedbacks);for(let n of e.feedbackComponents)Array.isArray(n.stateValues.feedbacks)&&t.push(...n.stateValues.feedbacks);return{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n({}),definition:()=>({useEssentialOrDefaultValue:{nSubmissions:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nSubmissions",value:e.nSubmissions}]})},e.numberOfAttemptsLeft={public:!0,shadowingInstructions:{createComponentOfType:"integer"},forRenderer:!0,returnDependencies:()=>({nSubmissions:{dependencyType:"stateVariable",variableName:"nSubmissions"},maximumNumberOfAttempts:{dependencyType:"stateVariable",variableName:"maximumNumberOfAttempts"}}),definition:({dependencyValues:e})=>({setValue:{numberOfAttemptsLeft:e.maximumNumberOfAttempts-e.nSubmissions}})},e.hasBeenCorrect={defaultValue:!1,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({creditAchieved:{dependencyType:"stateVariable",variableName:"creditAchieved"}}),definition:({dependencyValues:e})=>1===e.creditAchieved?{setValue:{hasBeenCorrect:!0},setEssentialValue:{hasBeenCorrect:!0}}:{useEssentialOrDefaultValue:{hasBeenCorrect:!0}}},e.disabled={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,stateVariablesDeterminingDependencies:["disableAfterCorrect"],returnDependencies({stateValues:e}){let t={disabledOriginal:{dependencyType:"stateVariable",variableName:"disabledOriginal"},numberOfAttemptsLeft:{dependencyType:"stateVariable",variableName:"numberOfAttemptsLeft"},disableAfterCorrect:{dependencyType:"stateVariable",variableName:"disableAfterCorrect"}};return e.disableAfterCorrect&&(t.hasBeenCorrect={dependencyType:"stateVariable",variableName:"hasBeenCorrect"}),t},definition:({dependencyValues:e})=>({setValue:{disabled:e.disabledOriginal||e.numberOfAttemptsLeft<1||e.disableAfterCorrect&&e.hasBeenCorrect}})},e.inItemNumber={returnDependencies:()=>({documentAncestor:{dependencyType:"ancestor",componentType:"document",variableNames:["itemNumberByAnswerName"]}}),definition:({dependencyValues:e,componentName:t})=>({setValue:{inItemNumber:e.documentAncestor.stateValues.itemNumberByAnswerName[t]}})},e}async submitAnswer({actionId:e}){let t=await this.stateValues.numberOfAttemptsLeft;if(t<1)return void console.warn(`Cannot submit answer for ${this.componentName} as number of attempts left is ${t}`);let n=await this.stateValues.creditAchievedIfSubmit;await this.stateValues.handGraded&&(n=0);let r=await this.stateValues.awardsUsedIfSubmit,a=await this.stateValues.inputUsedIfSubmit,i=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchieved",value:n},{updateType:"updateValue",componentName:this.componentName,stateVariable:"responseHasBeenSubmitted",value:!0}],s=await this.stateValues.inputChildrenWithValues;if(1===s.length){let e=s[0];a===e.componentName&&"valueToRecordOnSubmit"in e.stateValues&&"valueRecordedAtSubmit"in e.stateValues&&i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"valueRecordedAtSubmit",value:e.stateValues.valueToRecordOnSubmit})}let o=await this.stateValues.currentResponses;i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponses",value:o}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"submittedResponsesComponentType",value:this.state.currentResponses.shadowingInstructions.createComponentOfType}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"justSubmitted",value:!0}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"creditAchievedDependenciesAtSubmit",value:await this.stateValues.creditAchievedDependencies}),i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"nSubmissions",value:await this.stateValues.nSubmissions+1});for(let e of await this.stateValues.awardChildren){let t=r.includes(e.componentName);i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"awarded",value:t}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"creditAchieved",value:e.stateValues.creditAchievedIfSubmit}),i.push({updateType:"updateValue",componentName:e.componentName,stateVariable:"fractionSatisfied",value:e.stateValues.fractionSatisfiedIfSubmit})}let l=[];for(let e of o)if(e.toString)try{l.push(e.toString())}catch(e){l.push("_")}else l.push(e);return i.push({updateType:"recordItemSubmission",itemNumber:await this.stateValues.inItemNumber,submittedComponent:this.componentName,response:o,responseText:l,creditAchieved:n}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:e,event:{verb:"submitted",object:{componentName:this.componentName,componentType:this.componentType},result:{response:o,responseText:l,creditAchieved:n}},suppressToast:await this.stateValues.suppressToast}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}class Award extends BaseComponent{static componentType="award";static rendererType=void 0;static includeBlankStringChildren=!0;static removeBlankStringChildrenPostSugar=!0;static variableForPlainMacro="awarded";static variableForPlainCopy="awarded";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:1,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.symbolicEquality={createComponentOfType:"boolean",createStateVariable:"symbolicEquality",defaultValue:!1,public:!0,fallBackToParentStateVariable:"symbolicEquality"},e.expandOnCompare={createComponentOfType:"boolean",createStateVariable:"expandOnCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"expandOnCompare"},e.simplifyOnCompare={createComponentOfType:"text",createStateVariable:"simplifyOnCompare",defaultValue:"none",toLowerCase:!0,valueTransformations:{"":"full",true:"full"},validValues:["none","full","numbers","numberspreserveorder"],public:!0,fallBackToParentStateVariable:"simplifyOnCompare"},e.unorderedCompare={createComponentOfType:"boolean",createStateVariable:"unorderedCompare",defaultValue:!1,public:!0,fallBackToParentStateVariable:"unorderedCompare"},e.matchByExactPositions={createComponentOfType:"boolean",createStateVariable:"matchByExactPositions",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchByExactPositions"},e.allowedErrorInNumbers={createComponentOfType:"number",createStateVariable:"allowedErrorInNumbers",defaultValue:0,public:!0,fallBackToParentStateVariable:"allowedErrorInNumbers"},e.includeErrorInNumberExponents={createComponentOfType:"boolean",createStateVariable:"includeErrorInNumberExponents",defaultValue:!1,public:!0,fallBackToParentStateVariable:"includeErrorInNumberExponents"},e.allowedErrorIsAbsolute={createComponentOfType:"boolean",createStateVariable:"allowedErrorIsAbsolute",defaultValue:!1,public:!0,fallBackToParentStateVariable:"allowedErrorIsAbsolute"},e.nSignErrorsMatched={createComponentOfType:"number",createStateVariable:"nSignErrorsMatched",defaultValue:0,public:!0,fallBackToParentStateVariable:"nSignErrorsMatched"},e.nPeriodicSetMatchesRequired={createComponentOfType:"integer",createStateVariable:"nPeriodicSetMatchesRequired",defaultValue:3,public:!0,fallBackToParentStateVariable:"nPeriodicSetMatchesRequired"},e.caseInsensitiveMatch={createComponentOfType:"boolean",createStateVariable:"caseInsensitiveMatch",defaultValue:!1,public:!0,fallBackToParentStateVariable:"caseInsensitiveMatch"},e.matchBlanks={createComponentOfType:"boolean",createStateVariable:"matchBlanks",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchBlanks"},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.sourcesAreResponses={createPrimitiveOfType:"string"},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e}static preprocessSerializedChildren({serializedChildren:e,attributes:t,componentName:n}){if(t.sourcesAreResponses){let r,a=t.sourcesAreResponses.primitive.split(/\s+/).filter((e=>e));r=t.newNamespace?.primitive?n+"/":getNamespaceFromName(n);for(let t of a){let n;if("/"===t[0])n=t;else if("../"===t.slice(0,3)){let e=getNamespaceFromName(r.slice(0,r.length-1)),a=t.slice(3);for(;"../"===a.slice(0,3);){if("/"===e){n=null;break}e=getNamespaceFromName(e.slice(0,e.length-1)),a=a.slice(3)}null!==n&&(n=e+a)}else n=r+t;addResponsesToDescendantsWithTarget(e,t,n)}}}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({replacementFunction:function({matchedChildren:e,parentAttributes:t,componentInfoObjects:n}){for(;"string"==typeof e[0]&&""===e[0].trim();)e=e.slice(1);let r=e.length;for(;"string"==typeof e[r-1]&&""===e[r-1].trim();)r=(e=e.slice(0,r-1)).length;if(1===e.length&&"object"==typeof e[0])return{success:!1};let a,i=n.componentIsSpecifiedType,s=!1,o=!1,l=!1;for(let t of e)"object"==typeof t&&(i(t,"math")||i(t,"number")||i(t,"mathList")||i(t,"numberList")?s=!0:i(t,"text")||i(t,"textList")?o=!0:(i(t,"boolean")||i(t,"booleanList"))&&(l=!0));return t.type?(a=t.type,["math","text","boolean"].includes(a)||(console.warn(`Invalid type ${a}`),a="math")):a=s?"math":o?"text":l?"boolean":"math",{success:!0,newChildren:[{componentType:a,children:e}]}}}),e}static returnChildGroups(){return[{group:"whens",componentTypes:["when"]},{group:"maths",componentTypes:["math"]},{group:"numbers",componentTypes:["number"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]},{group:"mathLists",componentTypes:["mathList"]},{group:"numberLists",componentTypes:["numberList"]},{group:"textLists",componentTypes:["textList"]},{group:"booleanLists",componentTypes:["booleanList"]},{group:"otherComparableTypes",componentTypes:["orbitalDiagram"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.parsedExpression={additionalStateVariablesDefined:["requireInputInAnswer"],returnDependencies:()=>({whenChild:{dependencyType:"child",childGroups:["whens"]},typeChildren:{dependencyType:"child",childGroups:["maths","numbers","texts","booleans","mathLists","numberLists","textLists","booleanLists","otherComparableTypes"]}}),definition:function({dependencyValues:e}){let t=null,n=!1;return 0==e.whenChild.length&&e.typeChildren.length>0&&(n=!0,t=me$3.fromAst(["=","comp1","comp2"])),{setValue:{parsedExpression:t,requireInputInAnswer:n}}}},e.creditAchievedIfSubmit={public:!0,shadowingInstructions:{createComponentOfType:"number"},additionalStateVariablesDefined:[{variableName:"fractionSatisfiedIfSubmit",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({credit:{dependencyType:"stateVariable",variableName:"credit"},whenChild:{dependencyType:"child",childGroups:["whens"],variableNames:["fractionSatisfied"]},mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value","unordered"]},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},textChild:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},booleanChild:{dependencyType:"child",childGroups:["booleans"],variableNames:["value"]},mathListChild:{dependencyType:"child",childGroups:["mathLists"],variableNames:["maths","unordered"]},numberListChild:{dependencyType:"child",childGroups:["numberLists"],variableNames:["numbers","unordered"]},textListChild:{dependencyType:"child",childGroups:["textLists"],variableNames:["texts","unordered"]},booleanListChild:{dependencyType:"child",childGroups:["booleanLists"],variableNames:["booleans","unordered"]},otherComparableChild:{dependencyType:"child",childGroups:["otherComparableTypes"],variableNames:["value"]},answerInput:{dependencyType:"parentStateVariable",variableName:"inputChildWithValues"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"}}),definition:function({dependencyValues:e,usedDefault:t}){let n;if(e.whenChild.length>0)n=e.whenChild[0].stateValues.fractionSatisfied;else{if(!e.answerInput||!e.parsedExpression)return{setValue:{creditAchievedIfSubmit:0,fractionSatisfiedIfSubmit:0}};n=evaluateLogicDirectlyFromChildren({dependencyValues:e,usedDefault:t})}n=Math.max(0,Math.min(1,n));let r=0;return Number.isFinite(e.credit)&&(r=Math.max(0,Math.min(1,e.credit))*n),{setValue:{fractionSatisfiedIfSubmit:n,creditAchievedIfSubmit:r}}}},e.fractionSatisfied={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{fractionSatisfied:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"fractionSatisfied",value:e.fractionSatisfied}]}:{success:!1}}},e.creditAchieved={public:!0,shadowingInstructions:{createComponentOfType:"number"},defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{creditAchieved:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"creditAchieved",value:e.creditAchieved}]}:{success:!1}}},e.awarded={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},defaultValue:!1,hasEssential:!0,doNotShadowEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{awarded:!0}}),inverseDefinition:function({desiredStateVariableValues:e,initialChange:t}){return t?{success:!0,instructions:[{setEssentialValue:"awarded",value:e.awarded}]}:{success:!1}}},e.allFeedbacks={returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},awarded:{dependencyType:"stateVariable",variableName:"awarded"}}),definition:function({dependencyValues:e}){if(!e.awarded)return{setValue:{allFeedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{allFeedbacks:t}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;n0?n.textChildrenByCode.comp2=e.textChild[0]:e.mathChild.length>0?n.mathChildrenByCode.comp2=e.mathChild[0]:e.numberChild.length>0?n.numberChildrenByCode.comp2=e.numberChild[0]:e.booleanChild.length>0?n.booleanChildrenByCode.comp2=e.booleanChild[0]:e.textListChild.length>0?n.textListChildrenByCode.comp2=e.textListChild[0]:e.mathListChild.length>0?n.mathListChildrenByCode.comp2=e.mathListChild[0]:e.numberListChild.length>0?n.numberListChildrenByCode.comp2=e.numberListChild[0]:e.booleanListChild.length>0?n.booleanListChildrenByCode.comp2=e.booleanListChild[0]:e.otherComparableChild.length>0&&(n.otherChildrenByCode.comp2=e.otherComparableChild[0]);let a=e.answerInput.stateValues.immediateValue;void 0===a&&(a=e.answerInput.stateValues.value);let i={stateValues:{value:a}};return"textInput"===e.answerInput.componentType?n.textChildrenByCode.comp1=i:"booleanInput"===e.answerInput.componentType?n.booleanChildrenByCode.comp1=i:n.mathChildrenByCode.comp1=i,evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:r,dependencyValues:n})}function addResponsesToDescendantsWithTarget(e,t,n){for(let r of e){let e=r.props;if(e&&0!==Object.keys(e).length||(e=r.doenetAttributes),e)for(let a in e)if("target"===a.toLowerCase()&&e[a]===t||"targetcomponentname"===a.toLowerCase()&&e[a]===n){r.attributes||(r.attributes={});let e=Object.keys(r.attributes).map((e=>e.toLowerCase())).includes("isresponse");e||(r.attributes.isResponse=!0)}r.children&&addResponsesToDescendantsWithTarget(r.children,t,n)}}class When extends BooleanComponent{static componentType="when";static rendererType=void 0;static stateVariableForAttributeValue="conditionSatisfied";static createAttributesObject(){let e=super.createAttributesObject();e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"};for(let t of["symbolicEquality","expandOnCompare","simplifyOnCompare","unorderedCompare","matchByExactPositions","allowedErrorInNumbers","includeErrorInNumberExponents","allowedErrorIsAbsolute","nSignErrorsMatched","nPeriodicSetMatchesRequired","caseInsensitiveMatch","matchBlanks"])e[t].fallBackToParentStateVariable=t;return e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},additionalStateVariablesDefined:[{variableName:"fractionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"number"}},{variableName:"conditionSatisfied",public:!0,shadowingInstructions:{createComponentOfType:"boolean"}}],returnDependencies:()=>({matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"},symbolicEquality:{dependencyType:"stateVariable",variableName:"symbolicEquality"},expandOnCompare:{dependencyType:"stateVariable",variableName:"expandOnCompare"},simplifyOnCompare:{dependencyType:"stateVariable",variableName:"simplifyOnCompare"},unorderedCompare:{dependencyType:"stateVariable",variableName:"unorderedCompare"},matchByExactPositions:{dependencyType:"stateVariable",variableName:"matchByExactPositions"},allowedErrorInNumbers:{dependencyType:"stateVariable",variableName:"allowedErrorInNumbers"},includeErrorInNumberExponents:{dependencyType:"stateVariable",variableName:"includeErrorInNumberExponents"},allowedErrorIsAbsolute:{dependencyType:"stateVariable",variableName:"allowedErrorIsAbsolute"},nSignErrorsMatched:{dependencyType:"stateVariable",variableName:"nSignErrorsMatched"},nPeriodicSetMatchesRequired:{dependencyType:"stateVariable",variableName:"nPeriodicSetMatchesRequired"},caseInsensitiveMatch:{dependencyType:"stateVariable",variableName:"caseInsensitiveMatch"},matchBlanks:{dependencyType:"stateVariable",variableName:"matchBlanks"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},booleanListChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanListChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},textListChildrenByCode:{dependencyType:"stateVariable",variableName:"textListChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},mathListChildrenByCode:{dependencyType:"stateVariable",variableName:"mathListChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},numberListChildrenByCode:{dependencyType:"stateVariable",variableName:"numberListChildrenByCode"},otherChildrenByCode:{dependencyType:"stateVariable",variableName:"otherChildrenByCode"}}),definition({dependencyValues:e,usedDefault:t}){if(null===e.parsedExpression)return{setValue:{conditionSatisfied:!1,value:!1,fractionSatisfied:0}};let n=t.unorderedCompare,r=evaluateLogic({logicTree:e.parsedExpression.tree,canOverrideUnorderedCompare:n,dependencyValues:e}),a=1===r;return{setValue:{fractionSatisfied:r,conditionSatisfied:a,value:a}}}},e}}class MathInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateRawValue:this.updateRawValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="mathInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"math",createStateVariable:"prefill",defaultValue:me$3.fromAst("_"),public:!0,copyComponentAttributesForCreatedComponent:["format","functionSymbols","splitSymbols","parseScientificNotation"]},e.prefillLatex={createComponentOfType:"latex",createStateVariable:"prefillLatex",defaultValue:"",public:!0},e.format={createComponentOfType:"text",createStateVariable:"format",defaultValue:"text",public:!0},e.functionSymbols={createComponentOfType:"textList",createStateVariable:"functionSymbols",defaultValue:["f","g"],public:!0},e.splitSymbols={createComponentOfType:"boolean",createStateVariable:"splitSymbols",defaultValue:!0,public:!0,fallBackToParentStateVariable:"splitSymbols"},e.parseScientificNotation={createComponentOfType:"boolean",createStateVariable:"parseScientificNotation",defaultValue:!1,public:!0,fallBackToParentStateVariable:"parseScientificNotation"},e.displayDigits={createComponentOfType:"integer",createStateVariable:"displayDigits",defaultValue:10,public:!0},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"math"},e.unionFromU={createComponentOfType:"boolean",createStateVariable:"unionFromU",defaultValue:!1,public:!0},e.hideNaN={createComponentOfType:"boolean",createStateVariable:"hideNaN",defaultValue:!0,public:!0},e.removeStrings={createComponentOfType:"textList",createStateVariable:"removeStrings",defaultValue:null},e}static returnSugarInstructions(){let e=[];return e.push({replacementFunction:function({matchedChildren:e}){return 0===e.length?{success:!1}:{success:!0,newChildren:[{componentType:"math",children:e}]}}}),e}static returnChildGroups(){return[{group:"maths",componentTypes:["math"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({mathChild:{dependencyType:"child",childGroups:["maths"],variableNames:["value"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"},unionFromU:{dependencyType:"stateVariable",variableName:"unionFromU"},functionSymbols:{dependencyType:"stateVariable",variableName:"functionSymbols"},splitSymbols:{dependencyType:"stateVariable",variableName:"splitSymbols"},parseScientificNotation:{dependencyType:"stateVariable",variableName:"parseScientificNotation"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return e.mathChild.length>0?{setValue:{value:e.mathChild[0].stateValues.value}}:e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{get defaultValue(){return!t.prefill||t.prefillLatex?e.prefill:calculateMathExpressionFromLatex({latex:e.prefillLatex,unionFromU:e.unionFromU,functionSymbols:e.functionSymbols,splitSymbols:e.splitSymbols,parseScientificNotation:e.parseScientificNotation})}}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.mathChild.length>0?{success:!0,instructions:[{setDependency:"mathChild",desiredValue:e.value,variableIndex:0,childIndex:0}]}:t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"math",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n,usedDefault:r}){return!t.value||n||r.value?{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}:{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),set:convertValueToMathExpression,definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t})}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.valueForDisplay.toString()}}}},e.dontUpdateRawValueInDefinition={defaultValue:!1,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{dontUpdateRawValueInDefinition:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"dontUpdateRawValueInDefinition",value:e.dontUpdateRawValueInDefinition}]})},e.rawRendererValue={forRenderer:!0,hasEssential:!0,shadowVariable:!0,defaultValue:"",provideEssentialValuesInDefinition:!0,public:!0,shadowingInstructions:{createComponentOfType:"text"},additionalStateVariablesDefined:[{variableName:"lastValueForDisplay",hasEssential:!0,shadowVariable:!0,defaultValue:null,set:convertValueToMathExpression}],returnDependencies:()=>({immediateValue:{dependencyType:"stateVariable",variableName:"immediateValue"},valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},hideNaN:{dependencyType:"stateVariable",variableName:"hideNaN"},dontUpdateRawValueInDefinition:{dependencyType:"stateVariable",variableName:"dontUpdateRawValueInDefinition"},prefill:{dependencyType:"stateVariable",variableName:"prefill"},prefillLatex:{dependencyType:"stateVariable",variableName:"prefillLatex"}}),definition({dependencyValues:e,essentialValues:t,justUpdatedForNewComponent:n,usedDefault:r}){if(void 0!==t.rawRendererValue&&(n||deepCompare(t.lastValueForDisplay.tree,e.valueForDisplay.tree)||e.dontUpdateRawValueInDefinition))return{useEssentialOrDefaultValue:{rawRendererValue:!0,lastValueForDisplay:!0}};{let t;return t=r.immediateValue&&r.prefill&&!r.prefillLatex?stripLatex(e.prefillLatex):stripLatex(e.valueForDisplay.toLatex({showBlanks:!1})),e.hideNaN&&"NaN"===t&&(t=""),{setValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay},setEssentialValue:{rawRendererValue:t,lastValueForDisplay:e.valueForDisplay}}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t,essentialValues:n,dependencyValues:r,componentName:a}){let i=[];if("string"==typeof e.rawRendererValue){let r=n.rawRendererValue,a=e.rawRendererValue;r!==a&&i.push({setEssentialValue:"rawRendererValue",value:a});let s=await t.unionFromU,o=await t.functionSymbols,l=await t.splitSymbols,u=await t.parseScientificNotation,c=await t.removeStrings,p=calculateMathExpressionFromLatex({latex:r,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c}),d=calculateMathExpressionFromLatex({latex:a,unionFromU:s,functionSymbols:o,splitSymbols:l,parseScientificNotation:u,removeStrings:c});deepCompare(d.tree,p.tree)||i.push({setDependency:"immediateValue",desiredValue:d,treatAsInitialChange:!0})}else if(e.rawRendererValue instanceof me$3.class){i.push({setEssentialValue:"lastValueForDisplay",value:e.rawRendererValue});let a=await t.unionFromU,s=await t.functionSymbols,o=await t.splitSymbols,l=await t.parseScientificNotation,u=await t.removeStrings,c=calculateMathExpressionFromLatex({latex:n.rawRendererValue,unionFromU:a,functionSymbols:s,splitSymbols:o,parseScientificNotation:l,removeStrings:u});if(!deepCompare(e.rawRendererValue.tree,c.tree)){let t=stripLatex(e.rawRendererValue.toLatex({showBlanks:!1}));r.hideNaN&&"NaN"===t&&(t=""),i.push({setEssentialValue:"rawRendererValue",value:t})}}else e.lastValueForDisplay instanceof me$3.class&&i.push({setEssentialValue:"lastValueForDisplay",value:e.lastValueForDisplay});return{success:!0,instructions:i}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"math"}})},e}async updateRawValue({rawRendererValue:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(await this.stateValues.disabled)this.coreFunctions.resolveAction({actionId:e});else{let t=await this.stateValues.immediateValue;if(!deepCompare((await this.stateValues.value).tree,t.tree)){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!0},{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"dontUpdateRawValueInDefinition",value:!1},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}];"_"!==t.tree?n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"rawRendererValue",valueOfStateVariable:"valueForDisplay"}):n.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"lastValueForDisplay",valueOfStateVariable:"valueForDisplay"});let r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:e})}}static adapters=[{stateVariable:"value",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero"]}]}function calculateMathExpressionFromLatex({latex:e,unionFromU:t,functionSymbols:n,splitSymbols:r,parseScientificNotation:a,removeStrings:i}){let s;if(i)for(let t of i)["$","%"].includes(t)&&(t="\\"+t),e=e.replaceAll(t,"");e=normalizeLatexString(e,{unionFromU:t});let o=getFromLatex({functionSymbols:n,splitSymbols:r,parseScientificNotation:a});try{s=o(e)}catch(e){s=me$3.fromAst("_")}return s}class Textinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateImmediateValue:this.updateImmediateValue.bind(this),updateValue:this.updateValue.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="textInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static processWhenJustUpdatedForNewComponent=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"text",createStateVariable:"prefill",defaultValue:"",public:!0},e.size={createComponentOfType:"number",createStateVariable:"size",defaultValue:10,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"text"},e.expanded={createComponentOfType:"boolean",createStateVariable:"expanded",defaultValue:!1,forRenderer:!0,public:!0,fallBackToParentStateVariable:"expanded"},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:600,isAbsolute:!0},forRenderer:!0,public:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:120,isAbsolute:!0},forRenderer:!0,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.value={public:!0,shadowingInstructions:{createComponentOfType:"text"},hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.immediateValue={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,changes:t,justUpdatedForNewComponent:n}){return t.value&&!n?{setValue:{immediateValue:e.value},setEssentialValue:{immediateValue:e.value}}:{useEssentialOrDefaultValue:{immediateValue:{defaultValue:e.value}}}},inverseDefinition:function({desiredStateVariableValues:e,initialChange:t,shadowedVariable:n}){let r=[{setEssentialValue:"immediateValue",value:e.immediateValue}];return t||n||r.push({setDependency:"value",desiredValue:e.immediateValue}),{success:!0,instructions:r}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"text"}})},e}async updateImmediateValue({text:e,actionId:t}){if(!await this.stateValues.disabled)return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",value:e},{updateType:"setComponentNeedingUpdateValue",componentName:this.componentName}],transient:!0,actionId:t});this.coreFunctions.resolveAction({actionId:t})}async updateValue({actionId:e}){if(!await this.stateValues.disabled){let t=await this.stateValues.immediateValue;if(await this.stateValues.value!==t){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:t},{updateType:"executeUpdate"},{updateType:"updateValue",componentName:this.componentName,stateVariable:"immediateValue",valueOfStateVariable:"value"},{updateType:"unsetComponentNeedingUpdateValue"}],r={verb:"answered",object:{componentName:this.componentName,componentType:this.componentType},result:{response:t,responseText:t}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:e,event:r}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}}this.coreFunctions.resolveAction({actionId:e})}}class BooleanInput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateBoolean:this.updateBoolean.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="booleanInput";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.prefill={createComponentOfType:"boolean",createStateVariable:"prefill",defaultValue:!1,public:!0},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.asToggleButton={createComponentOfType:"boolean",createStateVariable:"asToggleButton",defaultValue:!1,forRenderer:!0,public:!0},e.bindValueTo={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.value={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,hasEssential:!0,shadowVariable:!0,returnDependencies:()=>({bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},prefill:{dependencyType:"stateVariable",variableName:"prefill"}}),definition:function({dependencyValues:e}){return e.bindValueTo?{setValue:{value:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{value:{defaultValue:e.prefill}}}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.value,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"value",value:e.value}]}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){return{setValue:{text:e.value?"true":"false"}}}},e.componentType={returnDependencies:()=>({}),definition:()=>({setValue:{componentType:"boolean"}})},e}static adapters=["value"];async updateBoolean({boolean:e,actionId:t}){if(!await this.stateValues.disabled){let n=[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],r={verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}},a=await this.stateValues.answerAncestor;return a&&(r.context={answerAncestor:a.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,event:r,actionId:t}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}}class Choiceinput extends Input{constructor(e){super(e),Object.assign(this.actions,{updateSelectedIndices:this.updateSelectedIndices.bind(this)}),this.externalActions={},Object.defineProperty(this.externalActions,"submitAnswer",{enumerable:!0,get:async function(){let e=await this.stateValues.answerAncestor;return null!==e?{componentName:e.componentName,actionName:"submitAnswer"}:void 0}.bind(this)})}static componentType="choiceInput";static renderChildren=!0;static variableForPlainMacro="values";static variableForPlainCopy="values";static createsVariants=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.selectMultiple={createComponentOfType:"boolean",createStateVariable:"selectMultiple",defaultValue:!1,public:!0,forRenderer:!0,fallBackToParentStateVariable:"selectMultiple"},e.matchPartial={createComponentOfType:"boolean",createStateVariable:"matchPartial",defaultValue:!1,public:!0,fallBackToParentStateVariable:"matchPartial"},e.inline={createComponentOfType:"boolean"},e.shuffleOrder={createPrimitiveOfType:"boolean",createStateVariable:"shuffleOrder",defaultValue:!1,public:!0},e.preselectChoice={createComponentOfType:"number",createStateVariable:"preselectChoice",defaultValue:null},e.bindValueTo={createComponentOfType:"text"},e.placeHolder={createComponentOfType:"text",createStateVariable:"placeHolder",defaultValue:"",forRenderer:!0},e.submitLabel={createComponentOfType:"text",createStateVariable:"submitLabel",defaultValue:"Check Work",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabel"},e.submitLabelNoCorrectness={createComponentOfType:"text",createStateVariable:"submitLabelNoCorrectness",defaultValue:"Submit Response",public:!0,forRenderer:!0,fallBackToParentStateVariable:"submitLabelNoCorrectness"},e}static returnChildGroups(){return[{group:"choices",componentTypes:["choice"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.inline={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},forRenderer:!0,defaultValue:!1,hasEssential:!0,returnDependencies:()=>({inlineAttr:{dependencyType:"attributeComponent",attributeName:"inline",variableNames:["value"]},parentInline:{dependencyType:"parentStateVariable",variableName:"inline"}}),definition:({dependencyValues:e})=>e.inlineAttr?{setValue:{inline:e.inlineAttr.stateValues.value}}:null!==e.parentInline?{setValue:{inline:e.parentInline}}:{useEssentialOrDefaultValue:{inline:{}}}},e.numberChoices={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:({dependencyValues:e})=>({setValue:{numberChoices:e.choiceChildren.length}})},e.choiceOrder={forRenderer:!0,shadowVariable:!0,returnDependencies:({sharedParameters:e})=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantSeed:{dependencyType:"value",value:e.variantSeed},rngClass:{dependencyType:"value",value:e.rngClass,doNotProxy:!0},variants:{dependencyType:"variants"}}),definition:function({dependencyValues:e}){let t,n=e.choiceChildren.length;if(e.shuffleOrder){let r=e.variants?.desiredVariant?.indices;if(void 0!==r)if(r.length!==n)console.warn("Ignoring indices specified for choiceInput as number of indices doesn't match number of choice children.");else{if(r=r.map(Number),!r.every(Number.isInteger))throw Error("All indices specified for choiceInput must be integers");if(r.every((e=>e>=1&&e<=n)))return{setValue:{choiceOrder:r}};console.warn("Ignoring indices specified for choiceInput as some indices out of range.")}let a=e.rngClass(e.variantSeed+"co");t=[...Array(n).keys()].map((e=>e+1));for(let e=n-1;e>0;e--){const n=a(),r=Math.floor(n*(e+1));[t[e],t[r]]=[t[r],t[e]]}}else t=[...Array(n).keys()].map((e=>e+1));return{setValue:{choiceOrder:t}}}},e.generatedVariantInfo={additionalStateVariablesDefined:["isVariantComponent"],returnDependencies:({componentInfoObjects:e,sharedParameters:t})=>({variantSeed:{dependencyType:"value",value:t.variantSeed},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},shuffleOrder:{dependencyType:"stateVariable",variableName:"shuffleOrder"},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(e.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}};e.shuffleOrder&&(n.indices=e.choiceOrder);let r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n,isVariantComponent:!0}}}},e.choiceChildrenOrdered={additionalStateVariablesDefined:[{variableName:"numberChoices",public:!0,shadowingInstructions:{createComponentOfType:"number"}}],returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"]}}),definition:function({dependencyValues:e}){let t=e.choiceChildren.length,n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceChildrenOrdered:n,numberChoices:t}}}},e.choiceTexts={public:!0,shadowingInstructions:{createComponentOfType:"text"},isArray:!0,entryPrefixes:["choiceText"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceTexts:t.map((e=>e.stateValues.text))}}}},e.choiceMaths={public:!0,shadowingInstructions:{createComponentOfType:"math"},isArray:!0,entryPrefixes:["choiceMath"],forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choiceMaths:t.map((e=>e.stateValues.math))}}}},e.choicePreselects={isArray:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["preSelect"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicePreselects:t.map((e=>e.stateValues.preSelect))}}}},e.choicesDisabled={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["disabled"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesDisabled:t.map((e=>e.stateValues.disabled))}}}},e.choicesHidden={isArray:!0,forRenderer:!0,returnArraySizeDependencies:()=>({numberChoices:{dependencyType:"stateVariable",variableName:"numberChoices"}}),returnArraySize:({dependencyValues:e})=>[e.numberChoices],returnArrayDependenciesByKey:()=>({globalDependencies:{choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["hidden"]}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));return{setValue:{choicesHidden:t.map((e=>e.stateValues.hidden))}}}},e.componentType={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["math"]}}),definition({dependencyValues:e}){let t="text";return e.choiceChildren.length>0&&e.choiceChildren.every((e=>e.stateValues.math))&&(t="math"),{setValue:{componentType:t}}}},e.indicesMatchedByBoundValue={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1]));if(null!==e.bindValueTo){let n=t.map((e=>e.stateValues.text.toLowerCase().trim()));if(e.bindValueTo.stateValues.value){if(e.selectMultiple){let t=e.bindValueTo.stateValues.value.toLowerCase().split(",").map((e=>e.trim())),r=[];for(let e of t){let t=n.indexOf(e);-1===t||r.includes(t+1)||r.push(t+1)}return r.sort(((e,t)=>e-t)),{setValue:{indicesMatchedByBoundValue:r}}}{let t=n.indexOf(e.bindValueTo.stateValues.value.toLowerCase().trim());if(-1!==t)return{setValue:{indicesMatchedByBoundValue:[t+1]}}}}}return{setValue:{indicesMatchedByBoundValue:[]}}}},e.allSelectedIndices={hasEssential:!0,returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["text"]},indicesMatchedByBoundValue:{dependencyType:"stateVariable",variableName:"indicesMatchedByBoundValue"},preselectChoice:{dependencyType:"stateVariable",variableName:"preselectChoice"},choicePreselects:{dependencyType:"stateVariable",variableName:"choicePreselects"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>null!==e.bindValueTo?{setValue:{allSelectedIndices:e.indicesMatchedByBoundValue}}:{useEssentialOrDefaultValue:{allSelectedIndices:{get defaultValue(){let t=e.choicePreselects.indexOf(!0);return-1!==t?[t+1]:null!==e.preselectChoice?[e.preselectChoice]:[]}}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(null===t.bindValueTo)return{success:!0,instructions:[{setEssentialValue:"allSelectedIndices",value:e.allSelectedIndices}]};{let n="";if(e.allSelectedIndices.length>0){let r=t.choiceOrder.map((e=>t.choiceChildren[e-1])),a=[];for(let t of e.allSelectedIndices){let e=r[t-1];e&&a.push(e.stateValues.text)}n=a.join(", ")}return{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:n,variableIndex:0}]}}}},e.nSelectedIndices={returnDependencies:()=>({allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}),definition:({dependencyValues:e})=>({setValue:{nSelectedIndices:e.allSelectedIndices.length}})},e.selectedIndices={public:!0,shadowingInstructions:{createComponentOfType:"number"},isArray:!0,entryPrefixes:["selectedIndex"],forRenderer:!0,returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{allSelectedIndices:{dependencyType:"stateVariable",variableName:"allSelectedIndices"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n in e.allSelectedIndices)t[n]=e.allSelectedIndices[n];return{setValue:{selectedIndices:t}}}},e.selectedIndex={isAlias:!0,targetVariableName:"selectedIndex1"},e.selectedValues={public:!0,shadowingInstructions:{hasVariableComponentType:!0},isArray:!0,entryPrefixes:["selectedValue"],returnArraySizeDependencies:()=>({nSelectedIndices:{dependencyType:"stateVariable",variableName:"nSelectedIndices"}}),returnArraySize:({dependencyValues:e})=>[e.nSelectedIndices],returnArrayDependenciesByKey:()=>({globalDependencies:{selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceTexts:{dependencyType:"stateVariable",variableName:"choiceTexts"},choiceMaths:{dependencyType:"stateVariable",variableName:"choiceMaths"},componentType:{dependencyType:"stateVariable",variableName:"componentType"}}}),arrayDefinitionByKey({globalDependencyValues:e,arrayKeys:t}){let n={},r=e.componentType;for(let a of t)n[a]="math"===r?e.choiceMaths[e.selectedIndices[a]-1]:e.choiceTexts[e.selectedIndices[a]-1];return{setValue:{selectedValues:n},setCreateComponentOfType:{selectedValues:r}}}},e.selectedValue={isAlias:!0,targetVariableName:"selectedValue1"},e.values={isAlias:!0,targetVariableName:"selectedValues"},e.nValues={isAlias:!0,targetVariableName:"nSelectedIndices"},e.childIndicesSelected={returnDependencies:()=>({selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"},choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"}}),definition({dependencyValues:e}){let t=e.selectedIndices.map((t=>e.choiceOrder[t-1]));return{setValue:{childIndicesSelected:t}}}},e.creditAchievedIfSubmit={returnDependencies:()=>({choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["selected","credit"]},selectMultiple:{dependencyType:"stateVariable",variableName:"selectMultiple"},matchPartial:{dependencyType:"stateVariable",variableName:"matchPartial"}}),definition:function({dependencyValues:e}){let t=0;if(e.selectMultiple){let n=0,r=0,a=0;for(let t of e.choiceChildren)t.stateValues.selected?1===t.stateValues.credit?n++:r++:1===t.stateValues.credit&&a++;if(e.matchPartial){let e=n+r+a;t=0===e?1:n/e}else r+a===0&&(t=1)}else for(let n of e.choiceChildren)if(n.stateValues.selected){t=n.stateValues.credit;break}return{setValue:{creditAchievedIfSubmit:t}}}},e.valueToRecordOnSubmit={isAlias:!0,targetVariableName:"selectedIndices"},e.submittedIndices={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["submitted"]}}),definition({dependencyValues:e}){let t=[],n=e.choiceOrder.map((t=>e.choiceChildren[t-1]));for(let[e,r]of n.entries())r.stateValues.submitted&&t.push(e+1);return{setValue:{submittedIndices:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){let n=[];for(let[r,a]of t.choiceOrder.entries())n.push({setDependency:"choiceChildren",desiredValue:e.submittedIndices.includes(r+1),variableIndex:0,childIndex:a-1});return{success:!0,instructions:n}}},e.valueRecordedAtSubmit={isAlias:!0,targetVariableName:"submittedIndices"},e.allFeedbacks={returnDependencies:()=>({choiceOrder:{dependencyType:"stateVariable",variableName:"choiceOrder"},choiceChildren:{dependencyType:"child",childGroups:["choices"],variableNames:["feedbacks"]}}),definition({dependencyValues:e}){let t=e.choiceOrder.map((t=>e.choiceChildren[t-1])),n=[];for(let e of t)n.push(...e.stateValues.feedbacks);return{setValue:{allFeedbacks:n}}}},e.numberFeedbacks={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}),definition:({dependencyValues:e})=>({setValue:{numberFeedbacks:e.allFeedbacks.length},checkForActualChange:{numberFeedbacks:!0}})},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedback"},isArray:!0,entryPrefixes:["feedback"],returnArraySizeDependencies:()=>({numberFeedbacks:{dependencyType:"stateVariable",variableName:"numberFeedbacks"}}),returnArraySize:({dependencyValues:e})=>[e.numberFeedbacks],returnArrayDependenciesByKey:()=>({globalDependencies:{allFeedbacks:{dependencyType:"stateVariable",variableName:"allFeedbacks"}}}),arrayDefinitionByKey({globalDependencyValues:e}){let t={};for(let n=0;nr[e-1]))}},i=await this.stateValues.answerAncestor;return i&&(a.context={answerAncestor:i.componentName}),await this.coreFunctions.performUpdate({updateInstructions:n,actionId:t,event:a}),await this.coreFunctions.triggerChainedActions({componentName:this.componentName})}this.coreFunctions.resolveAction({actionId:t})}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n})}static determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t}){if(!e.attributes?.shuffleOrder?.primitive)return super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});let n=0;for(let r of e.children)if("choice"===r.componentType)n++;else{if(!t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"_composite"})||"choice"!==r.attributes.createComponentOfType?.primitive)return{success:!1};if(void 0!==r.attributes.nComponents?.primitive){let e=Number(r.attributes.nComponents?.primitive);if(!(Number.isInteger(e)&&e>=0))return{success:!1};n+=e}else n++}let r=1;for(let e=2;e<=n;e++)r*=e;let a=super.determineNumberOfUniqueVariants({serializedComponent:e,componentInfoObjects:t});if(!a.success)return{success:!1};let i=a.numberOfVariants*r;return e.variants.numberOfVariants=i,e.variants.uniqueVariantData={numberOfVariantsByDescendant:e.variants.uniqueVariantData.numberOfVariantsByDescendant,numberOfPermutations:r,numberOfChoices:n},{success:!0,numberOfVariants:i}}static getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n}){let r=e.variants?.numberOfVariants;if(void 0===r)return{success:!1};if(!Number.isInteger(t)||t<1||t>r)return{success:!1};if(!e.attributes.shuffleOrder?.primitive)return super.getUniqueVariant({serializedComponent:e,variantIndex:t,componentInfoObjects:n});let a=e.variants.uniqueVariantData.numberOfVariantsByDescendant,i=e.variants.descendantVariantComponents,s=e.variants.uniqueVariantData.numberOfPermutations,o=e.variants.uniqueVariantData.numberOfChoices,l=[...a];l.push(s);let u=enumerateCombinations({numberOfOptionsByIndex:l,maxNumber:t})[t-1].map((e=>e+1)),c=u.pop(),p=u,d=[...Array(o).keys()].map((e=>e+1)),m=enumeratePermutations({values:d,maxNumber:c})[c-1],h=!1,f=[];for(let e=0;e1){let t=i[e],r=n.allComponentClasses[t.componentType].getUniqueVariant({serializedComponent:t,variantIndex:p[e],componentInfoObjects:n});if(!r.success)return{success:!1};f.push(r.desiredVariant),h=!0}else f.push({});let y={indices:m};return h&&(y.subvariants=f),{success:!0,desiredVariant:y}}}class Choice extends InlineComponent{static componentType="choice";static rendererType="containerInline";static renderChildren=!0;static variableForPlainMacro="submitted";static variableForPlainCopy="submitted";static createAttributesObject(){let e=super.createAttributesObject();return e.credit={createComponentOfType:"number",createStateVariable:"credit",defaultValue:0,public:!0,attributesForCreatedComponent:{convertBoolean:!0}},e.feedbackCodes={createComponentOfType:"textList",createStateVariable:"feedbackCodes",defaultValue:[],public:!0},e.feedbackText={createComponentOfType:"text",createStateVariable:"feedbackText",defaultValue:null,public:!0},e.preSelect={createComponentOfType:"boolean",createStateVariable:"preSelect",defaultValue:!1},e}static returnChildGroups(){return[{group:"children",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t="";for(let n of e.inlineChildren)"object"!=typeof n?t+=n.toString():"string"==typeof n.stateValues.text&&(t+=n.stateValues.text);return{setValue:{text:t}}}},e.math={public:!0,shadowingInstructions:{createComponentOfType:"math"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["children"],variableNames:["value","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=null;if(1===e.inlineChildren.length){let n=e.inlineChildren[0];if("object"==typeof n){let e=n.stateValues.value;if(e instanceof me$3.class)t=e;else if("number"==typeof e)t=me$3.fromAst(e);else if("string"==typeof n.stateValues.latex)try{t=me$3.fromLatex(n.stateValues.latex)}catch(e){}}}return{setValue:{math:t}}}},e.selected={defaultValue:!1,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({countAmongSiblings:{dependencyType:"countAmongSiblingsOfSameType"},childIndicesSelected:{dependencyType:"parentStateVariable",parentComponentType:"choiceInput",variableName:"childIndicesSelected"},primaryShadow:{dependencyType:"primaryShadow",variableNames:["selected"]}}),definition({dependencyValues:e,componentName:t}){let n;return n=e.childIndicesSelected?e.childIndicesSelected.includes(e.countAmongSiblings):!!e.primaryShadow&&e.primaryShadow.stateValues.selected,{setValue:{selected:n}}}},e.submitted={defaultValue:!1,hasEssential:!0,public:!0,shadowingInstructions:{createComponentOfType:"boolean"},doNotShadowEssential:!0,returnDependencies:()=>({primaryShadow:{dependencyType:"primaryShadow",variableNames:["submitted"]}}),definition:({dependencyValues:e})=>e.primaryShadow?{setValue:{submitted:e.primaryShadow.stateValues.submitted}}:{useEssentialOrDefaultValue:{submitted:!0}},inverseDefinition:function({desiredStateVariableValues:e,dependencyValues:t}){return t.primaryShadow?{success:!1}:{success:!0,instructions:[{setEssentialValue:"submitted",value:e.submitted}]}}},e.feedbacks={public:!0,shadowingInstructions:{createComponentOfType:"feedbacktext"},returnDependencies:()=>({feedbackText:{dependencyType:"stateVariable",variableName:"feedbackText"},feedbackCodes:{dependencyType:"stateVariable",variableName:"feedbackCodes"},feedbackDefinitionAncestor:{dependencyType:"ancestor",variableNames:["feedbackDefinitions"]},submitted:{dependencyType:"stateVariable",variableName:"submitted"}}),definition({dependencyValues:e}){if(!e.submitted)return{setValue:{feedbacks:[]}};let t=[],n=e.feedbackDefinitionAncestor.stateValues.feedbackDefinitions;for(let r of e.feedbackCodes){let e=n[r.toLowerCase()];e&&t.push(e)}return null!==e.feedbackText&&t.push(e.feedbackText),{setValue:{feedbacks:t}}}},e}static includeBlankStringChildren=!0;static adapters=["text","math"]}class NumberComponent extends InlineComponent{static componentType="number";static variableForPlainMacro="value";static createAttributesObject(){let e=super.createAttributesObject();return e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer"},e.displaySmallAsZero={createComponentOfType:"number",valueForTrue:1e-14,valueForFalse:0},e.padZeros={createComponentOfType:"boolean"},e.renderAsMath={createComponentOfType:"boolean",createStateVariable:"renderAsMath",defaultValue:!1,public:!0,forRenderer:!0},e.convertBoolean={createPrimitiveOfType:"boolean",createStateVariable:"convertBoolean",defaultValue:!1},e.valueOnNaN={createPrimitiveOfType:"number",createStateVariable:"valueOnNaN",defaultValue:NaN},e}static returnSugarInstructions(){let e=super.returnSugarInstructions();return e.push({childrenRegex:/..+/,replacementFunction:({matchedChildren:e,componentAttributes:t})=>({success:!t.convertBoolean,newChildren:[{componentType:"math",children:e}]})}),e}static returnChildGroups(){return[{group:"strings",componentTypes:["string"]},{group:"numbers",componentTypes:["number"]},{group:"maths",componentTypes:["math"]},{group:"texts",componentTypes:["text"]},{group:"booleans",componentTypes:["boolean"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({numberListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDigits"},mathListParentDisplayDigits:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDigits"},numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDigits"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDigits){if(!t.numberListParentDisplayDigits)return{setValue:{displayDigits:e.numberListParentDisplayDigits}};r=!0,n=e.numberListParentDisplayDigits}if(null!==e.mathListParentDisplayDigits){if(!t.mathListParentDisplayDigits)return{setValue:{displayDigits:e.mathListParentDisplayDigits}};r=!0,n=e.mathListParentDisplayDigits}let a=null!==e.numberListParentDisplayDecimals&&!t.numberListParentDisplayDecimals||null!==e.mathListParentDisplayDecimals&&!t.mathListParentDisplayDecimals,i=null===e.displayDigitsAttr||t.displayDigitsAttr,s=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!i&&!s){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displayDecimals"},mathListParentDisplayDecimals:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displayDecimals"},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displayDecimals"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplayDecimals){if(!t.numberListParentDisplayDecimals)return{setValue:{displayDecimals:e.numberListParentDisplayDecimals}};r=!0,n=e.numberListParentDisplayDecimals}if(null!==e.mathListParentDisplayDecimals){if(!t.mathListParentDisplayDecimals)return{setValue:{displayDecimals:e.mathListParentDisplayDecimals}};r=!0,n=e.mathListParentDisplayDecimals}if(null!==e.displayDecimalsAttr){if(!t.displayDecimalsAttr)return{setValue:{displayDecimals:e.displayDecimalsAttr.stateValues.value}};r=!0,n=e.displayDecimalsAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displayDecimals)return{setValue:{displayDecimals:e.numberMathChildren[0].stateValues.displayDecimals}};r=!0,n=e.numberMathChildren[0].stateValues.displayDecimals}return r?{useEssentialOrDefaultValue:{displayDecimals:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displayDecimals:!0}}}},e.displaySmallAsZero={public:!0,shadowingInstructions:{createComponentOfType:"number"},hasEssential:!0,defaultValue:0,returnDependencies:()=>({numberListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"displaySmallAsZero"},mathListParentDisplaySmallAsZero:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"displaySmallAsZero"},displaySmallAsZeroAttr:{dependencyType:"attributeComponent",attributeName:"displaySmallAsZero",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["displaySmallAsZero"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentDisplaySmallAsZero){if(!t.numberListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberListParentDisplaySmallAsZero}};r=!0,n=e.numberListParentDisplaySmallAsZero}if(null!==e.mathListParentDisplaySmallAsZero){if(!t.mathListParentDisplaySmallAsZero)return{setValue:{displaySmallAsZero:e.mathListParentDisplaySmallAsZero}};r=!0,n=e.mathListParentDisplaySmallAsZero}if(null!==e.displaySmallAsZeroAttr){if(!t.displaySmallAsZeroAttr)return{setValue:{displaySmallAsZero:e.displaySmallAsZeroAttr.stateValues.value}};r=!0,n=e.displaySmallAsZeroAttr.stateValues.value}if(1===e.numberMathChildren.length&&0===e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].displaySmallAsZero)return{setValue:{displaySmallAsZero:e.numberMathChildren[0].stateValues.displaySmallAsZero}};r=!0,n=e.numberMathChildren[0].stateValues.displaySmallAsZero}return r?{useEssentialOrDefaultValue:{displaySmallAsZero:{defaultValue:n}}}:{useEssentialOrDefaultValue:{displaySmallAsZero:!0}}}},e.padZeros={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},hasEssential:!0,defaultValue:!1,returnDependencies:()=>({numberListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"numberList",variableName:"padZeros"},mathListParentPadZeros:{dependencyType:"parentStateVariable",parentComponentType:"mathList",variableName:"padZeros"},padZerosAttr:{dependencyType:"attributeComponent",attributeName:"padZeros",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]},numberMathChildren:{dependencyType:"child",childGroups:["numbers","maths"],variableNames:["padZeros"]},otherChildren:{dependencyType:"child",childGroups:["strings","texts","booleans"]}}),definition({dependencyValues:e,usedDefault:t}){let n,r=!1;if(null!==e.numberListParentPadZeros){if(!t.numberListParentPadZeros)return{setValue:{padZeros:e.numberListParentPadZeros}};r=!0,n=e.numberListParentPadZeros}if(null!==e.mathListParentPadZeros){if(!t.mathListParentPadZeros)return{setValue:{padZeros:e.mathListParentPadZeros}};r=!0,n=e.mathListParentPadZeros}if(null!==e.padZerosAttr){if(!t.padZerosAttr)return{setValue:{padZeros:e.padZerosAttr.stateValues.value}};r=!0,n=e.padZerosAttr.stateValues.value}if(1===e.numberMathChildren.length&&0==e.otherChildren.length){if(!t.numberMathChildren[0]||!t.numberMathChildren[0].padZeros)return{setValue:{padZeros:e.numberMathChildren[0].stateValues.padZeros}};r=!0,n=e.numberMathChildren[0].stateValues.padZeros}return r?{useEssentialOrDefaultValue:{padZeros:{defaultValue:n}}}:{useEssentialOrDefaultValue:{padZeros:!0}}}},e.singleNumberOrStringChild={additionalStateVariablesDefined:["singleMathChild"],returnDependencies:()=>({numberChildren:{dependencyType:"child",childGroups:["numbers"]},stringChildren:{dependencyType:"child",childGroups:["strings"]},mathChildren:{dependencyType:"child",childGroups:["maths"]},booleanChildren:{dependencyType:"child",childGroups:["booleans"]},textChildren:{dependencyType:"child",childGroups:["texts"]}}),definition({dependencyValues:e}){let t=e.numberChildren.length+e.stringChildren.length,n=e.mathChildren.length,r=e.booleanChildren.length+e.textChildren.length;return{setValue:{singleNumberOrStringChild:t<=1&&n+r===0,singleMathChild:1===n&&t+r===0}}}},e.parsedExpression={additionalStateVariablesDefined:["codePre"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"]},stringChildren:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]}}),definition:buildParsedExpression},e.mathChildrenByCode={additionalStateVariablesDefined:["textChildrenByCode","numberChildrenByCode","booleanChildrenByCode"],returnDependencies:()=>({allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","booleans"],variablesOptional:!0},codePre:{dependencyType:"stateVariable",variableName:"codePre"}}),definition({dependencyValues:e,componentInfoObjects:t}){let n={},r={},a={},i={},s=0,o=e.codePre;for(let l of e.allChildren)if("string"!=typeof l){let e=o+s;t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"math"})?n[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"number"})?r[e]=l:t.isInheritedComponentType({inheritedComponentType:l.componentType,baseComponentType:"text"})?a[e]=l:i[e]=l,s+=1}return{setValue:{mathChildrenByCode:n,numberChildrenByCode:r,textChildrenByCode:a,booleanChildrenByCode:i}}}},e.value={public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],addAttributeComponentsShadowingStateVariables:{fixed:{stateVariableToShadow:"fixed"}}},hasEssential:!0,stateVariablesDeterminingDependencies:["singleNumberOrStringChild"],returnDependencies:({stateValues:e})=>e.singleNumberOrStringChild?{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},numberChild:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]},stringChild:{dependencyType:"child",childGroups:["strings"],variableNames:["value"]},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}}:{singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"},convertBoolean:{dependencyType:"stateVariable",variableName:"convertBoolean"},parsedExpression:{dependencyType:"stateVariable",variableName:"parsedExpression"},allChildren:{dependencyType:"child",childGroups:["strings","numbers","maths","texts","booleans"],variableNames:["value","texts","maths","unordered"],variablesOptional:!0},booleanChildrenByCode:{dependencyType:"stateVariable",variableName:"booleanChildrenByCode"},textChildrenByCode:{dependencyType:"stateVariable",variableName:"textChildrenByCode"},mathChildrenByCode:{dependencyType:"stateVariable",variableName:"mathChildrenByCode"},numberChildrenByCode:{dependencyType:"stateVariable",variableName:"numberChildrenByCode"},valueOnNaN:{dependencyType:"stateVariable",variableName:"valueOnNaN"}},definition({dependencyValues:e,componentInfoObjects:t}){if(e.singleNumberOrStringChild){if(0===e.numberChild.length){if(0===e.stringChild.length)return{useEssentialOrDefaultValue:{value:{defaultValue:e.valueOnNaN}}};let n=Number(e.stringChild[0]);if(Number.isNaN(n))try{if(n=me$3.fromAst(textToAst$1.convert(e.stringChild[0])).evaluate_to_constant(),"boolean"==typeof n)n=e.convertBoolean?n?1:0:e.valueOnNaN;else if(null===n||Number.isNaN(n))if(e.convertBoolean){n=evaluateLogic({logicTree:buildParsedExpression({dependencyValues:{stringChildren:e.stringChild,allChildren:e.stringChild},componentInfoObjects:t}).setValue.parsedExpression.tree,dependencyValues:{booleanChildrenByCode:{},booleanListChildrenByCode:{},textChildrenByCode:{},textListChildrenByCode:{},mathChildrenByCode:{},mathListChildrenByCode:{},numberChildrenByCode:{},numberListChildrenByCode:{},otherChildrenByCode:{}},valueOnInvalid:e.valueOnNaN})}else n=e.valueOnNaN;else n?.re===1/0||n?.re===-1/0||n?.im===1/0||n?.im===-1/0?n=numberToMathExpression(n).evaluate_to_constant():0===n?.im&&(n=n.re)}catch(t){n=e.valueOnNaN}return{setValue:{value:n}}}{let t=e.numberChild[0].stateValues.value;return Number.isNaN(t)&&(t=e.valueOnNaN),{setValue:{value:t}}}}if(null===e.parsedExpression)return{setValue:{value:e.valueOnNaN}};if(0===Object.keys(e.textChildrenByCode).length&&0===Object.keys(e.booleanChildrenByCode).length){let t,n=function(t){if("string"==typeof t){let n=e.mathChildrenByCode[t];return void 0!==n?n.stateValues.value.tree:(n=e.numberChildrenByCode[t],void 0!==n?numberToMathExpression(n.stateValues.value).tree:t)}return Array.isArray(t)?[t[0],...t.slice(1).map(n)]:t};try{t=me$3.fromAst(n(e.parsedExpression.tree)).evaluate_to_constant()}catch(n){t=e.valueOnNaN}if(!Number.isNaN(t)&&("number"==typeof t||"number"==typeof t?.re&&"number"==typeof t?.im))return t.re===1/0||t.re===-1/0||t.im===1/0||t.im===-1/0?t=numberToMathExpression(t).evaluate_to_constant():0===t.im&&(t=t.re),{setValue:{value:t}}}if(!e.convertBoolean)return{setValue:{value:e.valueOnNaN}};return(e=Object.assign({},e)).mathListChildrenByCode={},e.numberListChildrenByCode={},e.textListChildrenByCode={},e.booleanListChildrenByCode={},e.otherChildrenByCode={},{setValue:{value:evaluateLogic({logicTree:e.parsedExpression.tree,dependencyValues:e,valueOnInvalid:e.valueOnNaN})}}},set:function(e){if(null===e)return NaN;if("number"==typeof e||"number"==typeof e?.re&&"number"==typeof e?.im)return e;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst$1.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return t},inverseDefinition:async function({desiredStateVariableValues:e,dependencyValues:t,stateValues:n,overrideFixed:r}){if(!await n.canBeModified&&!r)return{success:!1};let a,i=e.value;return i instanceof me$3.class?(i=i.evaluate_to_constant(),(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=t.valueOnNaN)):(Number.isNaN(i)||"number"!=typeof i&&("number"!=typeof i?.re||"number"!=typeof i?.im))&&(i=Number(i),Number.isNaN(i)&&(i=t.valueOnNaN)),t.singleNumberOrStringChild?(a=0===t.numberChild.length?0===t.stringChild.length?[{setEssentialValue:"value",value:numberToMathExpression(i).evaluate_to_constant()}]:[{setDependency:"stringChild",desiredValue:numberToMathExpression(i).toString(),childIndex:0,variableIndex:0}]:[{setDependency:"numberChild",desiredValue:i,childIndex:0,variableIndex:0}],{success:!0,instructions:a}):t.singleMathChild?{success:!0,instructions:[{setDependency:"allChildren",desiredValue:numberToMathExpression(i),childIndex:0,variableIndex:0}]}:{success:!1}}},e.valueForDisplay={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:numberToMathExpression(e.value),dependencyValues:e,usedDefault:t}).evaluate_to_constant()}}}},e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},forRenderer:!0,returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{text:numberToMathExpression(e.valueForDisplay).toString(n)}}},async inverseDefinition({desiredStateVariableValues:e,stateValues:t}){let n=Number(e.text);if(Number.isFinite(n))return{success:!0,instructions:[{setDependency:"value",desiredValue:n}]};{let t,r=getFromText({parseScientificNotation:!1});try{t=r(e.text)}catch(e){return{success:!1}}return n=t.evaluate_to_constant(),Number.isFinite(n)?{success:!0,instructions:[{setDependency:"value",desiredValue:n}]}:{success:!1}}}},e.math=mathStateVariableFromNumberStateVariable({numberVariableName:"value",mathVariableName:"math",isPublic:!0}),e.math.shadowingInstructions.attributesToShadow=["displayDigits","displayDecimals","displaySmallAsZero","padZeros"],e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({valueForDisplay:{dependencyType:"stateVariable",variableName:"valueForDisplay"},padZeros:{dependencyType:"stateVariable",variableName:"padZeros"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"}}),definition({dependencyValues:e,usedDefault:t}){let n={};return e.padZeros&&(t.displayDigits&&!t.displayDecimals?Number.isFinite(e.displayDecimals)&&(n.padToDecimals=e.displayDecimals):e.displayDigits>=1&&(n.padToDigits=e.displayDigits)),{setValue:{latex:numberToMathExpression(e.valueForDisplay).toLatex(n)}}}},e.canBeModified={returnDependencies:()=>({numberChildModifiable:{dependencyType:"child",childGroups:["numbers"],variableNames:["canBeModified"]},modifyIndirectly:{dependencyType:"stateVariable",variableName:"modifyIndirectly"},fixed:{dependencyType:"stateVariable",variableName:"fixed"},singleNumberOrStringChild:{dependencyType:"stateVariable",variableName:"singleNumberOrStringChild"},singleMathChild:{dependencyType:"stateVariable",variableName:"singleMathChild"}}),definition:function({dependencyValues:e}){return!e.modifyIndirectly||e.fixed||!e.singleNumberOrStringChild&&!e.singleMathChild?{setValue:{canBeModified:!1}}:1!==e.numberChildModifiable.length||e.numberChildModifiable[0].stateValues.canBeModified?{setValue:{canBeModified:!0}}:{setValue:{canBeModified:!1}}}},e}static adapters=[{stateVariable:"math",stateVariablesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},"text"]}class Integer extends NumberComponent{static componentType="integer";static rendererType="number";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return renameStateVariable({stateVariableDefinitions:e,oldName:"value",newName:"valuePreRound"}),e.value={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({valuePreRound:{dependencyType:"stateVariable",variableName:"valuePreRound"}}),set:function(e){if(null===e)return NaN;let t=Number(e);if(Number.isNaN(t))try{t=me$3.fromAst(textToAst.convert(e)).evaluate_to_constant(),null===t&&(t=NaN)}catch(e){t=NaN}return Math.round(t)},definition:({dependencyValues:e})=>({setValue:{value:Math.round(e.valuePreRound)}}),inverseDefinition({desiredStateVariableValues:e}){let t=e.value;return t instanceof me$3.class?(t=t.evaluate_to_constant(),Number.isFinite(t)||(t=NaN)):t=Number(t),t=Math.round(t),{success:!0,instructions:[{setDependency:"valuePreRound",desiredValue:t}]}}},e}}const maxWidth=850,sizePossibilities=["tiny","small","medium","large","full"],widthFractions=[1/12,.3,.5,.7,1],fractionMidpoints=widthFractions.map(((e,t)=>(e+(widthFractions[t+1]||1/0))/2)),orderedWidthMidpoints=fractionMidpoints.map((e=>maxWidth*e)),orderedPercentWidthMidpoints=fractionMidpoints.map((e=>100*e)),widthsBySize={};sizePossibilities.forEach(((e,t)=>widthsBySize[e]=Math.floor(widthFractions[t]*maxWidth)));const percentWidthsBySize={};sizePossibilities.forEach(((e,t)=>percentWidthsBySize[e]=Math.round(100*widthFractions[t])));class Graph$1 extends BlockComponent{constructor(e){super(e),Object.assign(this.actions,{changeAxisLimits:this.changeAxisLimits.bind(this),addChildren:this.addChildren.bind(this),deleteChildren:this.deleteChildren.bind(this),recordVisibilityChange:this.recordVisibilityChange.bind(this)})}static componentType="graph";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.xmin={createComponentOfType:"number",createStateVariable:"xminPrelim",defaultValue:-10},e.xmax={createComponentOfType:"number",createStateVariable:"xmaxPrelim",defaultValue:10},e.ymin={createComponentOfType:"number",createStateVariable:"yminPrelim",defaultValue:-10},e.ymax={createComponentOfType:"number",createStateVariable:"ymaxPrelim",defaultValue:10},e.width={createComponentOfType:"_componentSize"},e.size={createComponentOfType:"text"},e.aspectRatio={createComponentOfType:"number"},e.height={createComponentOfType:"_componentSize"},e.displayMode={createComponentOfType:"text",createStateVariable:"displayMode",validValues:["block","inline"],defaultValue:"block",forRenderer:!0,public:!0},e.horizontalAlign={createComponentOfType:"text",createStateVariable:"horizontalAlign",validValues:["center","left","right"],defaultValue:"center",forRenderer:!0,public:!0},e.identicalAxisScales={createPrimitiveOfType:"boolean",createStateVariable:"identicalAxisScales",defaultValue:!1,public:!0},e.displayXAxis={createComponentOfType:"boolean",createStateVariable:"displayXAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxis={createComponentOfType:"boolean",createStateVariable:"displayYAxis",defaultValue:!0,public:!0,forRenderer:!0},e.displayXAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayXAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.displayYAxisTickLabels={createComponentOfType:"boolean",createStateVariable:"displayYAxisTickLabels",defaultValue:!0,public:!0,forRenderer:!0},e.xlabel={createComponentOfType:"label"},e.xlabelPosition={createComponentOfType:"text",createStateVariable:"xlabelPosition",defaultValue:"right",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["right","left"]},e.xTickScaleFactor={createComponentOfType:"math",createStateVariable:"xTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.ylabel={createComponentOfType:"label"},e.ylabelPosition={createComponentOfType:"text",createStateVariable:"ylabelPosition",defaultValue:"top",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["top","bottom"]},e.ylabelAlignment={createComponentOfType:"text",createStateVariable:"ylabelAlignment",defaultValue:"left",public:!0,forRenderer:!0,toLowerCase:!0,validValues:["left","right"]},e.yTickScaleFactor={createComponentOfType:"math",createStateVariable:"yTickScaleFactor",defaultValue:null,public:!0,forRenderer:!0},e.showNavigation={createComponentOfType:"boolean",createStateVariable:"showNavigation",defaultValue:!0,public:!0,forRenderer:!0},e.fixAxes={createComponentOfType:"boolean",createStateVariable:"fixAxes",defaultValue:!1,public:!0,forRenderer:!0},e.grid={createComponentOfType:"text"},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.padZeros={createComponentOfType:"boolean",createStateVariable:"padZeros",defaultValue:!1,public:!0},e.showBorder={createComponentOfType:"boolean",createStateVariable:"showBorder",defaultValue:!0,public:!0,forRenderer:!0},e}static returnChildGroups(){return[{group:"xlabels",componentTypes:["xlabel"]},{group:"ylabels",componentTypes:["ylabel"]},{group:"graphical",componentTypes:["_graphical","text","image","math","m","md","label"]},{group:"childrenThatShouldNotBeHere",componentTypes:["_base"],matchAfterAdapters:!0}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({xlabelAttr:{dependencyType:"attributeComponent",attributeName:"xlabel",variableNames:["value","hasLatex"]},xlabelChild:{dependencyType:"child",childGroups:["xlabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.xlabelChild.length>0){let t=e.xlabelChild[e.xlabelChild.length-1];return{setValue:{xlabel:t.stateValues.value,xlabelHasLatex:t.stateValues.hasLatex}}}return e.xlabelAttr?{setValue:{xlabel:e.xlabelAttr.stateValues.value,xlabelHasLatex:e.xlabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{xlabel:!0},setValue:{xlabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.xlabel)return{success:!1};if(t.xlabelChild.length>0){let n=t.xlabelChild.length-1;return{success:!0,instructions:[{setDependency:"xlabelChild",desiredValue:e.xlabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"xlabel",value:e.xlabel}]}}},e.ylabel={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"label",addStateVariablesShadowingStateVariables:{hasLatex:{stateVariableToShadow:"ylabelHasLatex"}}},hasEssential:!0,defaultValue:"",additionalStateVariablesDefined:[{variableName:"ylabelHasLatex",forRenderer:!0}],returnDependencies:()=>({ylabelAttr:{dependencyType:"attributeComponent",attributeName:"ylabel",variableNames:["value","hasLatex"]},ylabelChild:{dependencyType:"child",childGroups:["ylabels"],variableNames:["value","hasLatex"]}}),definition({dependencyValues:e}){if(e.ylabelChild.length>0){let t=e.ylabelChild[e.ylabelChild.length-1];return{setValue:{ylabel:t.stateValues.value,ylabelHasLatex:t.stateValues.hasLatex}}}return e.ylabelAttr?{setValue:{ylabel:e.ylabelAttr.stateValues.value,ylabelHasLatex:e.ylabelAttr.stateValues.hasLatex}}:{useEssentialOrDefaultValue:{ylabel:!0},setValue:{ylabelHasLatex:!1}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if("string"!=typeof e.ylabel)return{success:!1};if(t.ylabelChild.length>0){let n=t.ylabelChild.length-1;return{success:!0,instructions:[{setDependency:"ylabelChild",desiredValue:e.ylabel,childIndex:n,variableIndex:0}]}}return{success:!0,instructions:[{setEssentialValue:"ylabel",value:e.ylabel}]}}},e.graphicalDescendants={forRenderer:!0,returnDependencies:()=>({graphicalDescendants:{dependencyType:"descendant",componentTypes:["_graphical"]}}),definition:function({dependencyValues:e}){return{setValue:{graphicalDescendants:e.graphicalDescendants}}}},e.childIndicesToRender={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"]},allChildren:{dependencyType:"child",childGroups:["graphical","xlabels","ylabels","childrenThatShouldNotBeHere"]}}),definition({dependencyValues:e}){let t=[],n=e.graphicalChildren.map((e=>e.componentName));for(let[r,a]of e.allChildren.entries())n.includes(a.componentName)&&t.push(r);return{setValue:{childIndicesToRender:t}}}},e.nChildrenAdded={defaultValue:0,hasEssential:!0,returnDependencies:()=>({}),definition:()=>({useEssentialOrDefaultValue:{nChildrenAdded:!0}}),inverseDefinition:({desiredStateVariableValues:e})=>({success:!0,instructions:[{setEssentialValue:"nChildrenAdded",value:e.nChildrenAdded}]})},e.size={public:!0,defaultValue:"medium",hasEssential:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({sizeAttr:{dependencyType:"attributeComponent",attributeName:"size",variableNames:["value"]},widthAttr:{dependencyType:"attributeComponent",attributeName:"width",variableNames:["componentSize"]}}),definition({dependencyValues:e}){const t="medium";if(e.sizeAttr){let n=e.sizeAttr.stateValues.value.toLowerCase();return sizePossibilities.includes(n)||(n=t),{setValue:{size:n}}}if(e.widthAttr){let n=e.widthAttr.stateValues.componentSize;if(null===n)return{setValue:{size:t}};let r,{isAbsolute:a,size:i}=n;if(a){for(let[e,t]of orderedWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}else{for(let[e,t]of orderedPercentWidthMidpoints.entries())if(i<=t){r=sizePossibilities[e];break}r||(r=t)}return{setValue:{size:r}}}return{useEssentialOrDefaultValue:{size:!0}}}},e.width={public:!0,forRenderer:!0,shadowingInstructions:{createComponentOfType:"_componentSize"},returnDependencies:()=>({size:{dependencyType:"stateVariable",variableName:"size"}}),definition:({dependencyValues:e})=>({setValue:{width:{isAbsolute:!0,size:widthsBySize[e.size]}}})},e.aspectRatioFromAxisScales={returnDependencies:()=>({aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},heightAttr:{dependencyType:"attributeComponent",attributeName:"height",variableNames:["componentSize"]}}),definition:({dependencyValues:e})=>(null!==e.heightAttr&&console.warn("Height attribute of graph is deprecated and is being ignored. Use aspectRatio attribute instead."),{setValue:{aspectRatioFromAxisScales:e.identicalAxisScales&&null===e.aspectRatioAttr},checkForActualChange:{aspectRatioFromAxisScales:!0}})},e.aspectRatio={public:!0,forRenderer:!0,defaultValue:1,hasEssential:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["aspectRatioFromAxisScales"],returnDependencies:({stateValues:e})=>e.aspectRatioFromAxisScales?{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xscale:{dependencyType:"stateVariable",variableName:"xscale"},yscale:{dependencyType:"stateVariable",variableName:"yscale"}}:{aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},aspectRatioAttr:{dependencyType:"attributeComponent",attributeName:"aspectRatio",variableNames:["value"]},width:{dependencyType:"stateVariable",variableName:"width"}},definition({dependencyValues:e}){if(e.aspectRatioFromAxisScales){return{setValue:{aspectRatio:e.xscale/e.yscale}}}if(null!==e.aspectRatioAttr){let t=e.aspectRatioAttr.stateValues.value;return Number.isFinite(t)||(t=1),{setValue:{aspectRatio:t}}}return{useEssentialOrDefaultValue:{aspectRatio:!0}}}},e.xmin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xminPrelim:{dependencyType:"stateVariable",variableName:"xminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmin:e.xminPrelim}};if(!t.xminPrelim)return{setValue:{xmin:e.xminPrelim}};let n=!t.xmaxPrelim,r=!t.yminPrelim,a=!t.ymaxPrelim;if(r&&a){let t=e.aspectRatio,r=(e.ymaxPrelim-e.yminPrelim)*t;return n?{setValue:{xmin:e.xmaxPrelim-r}}:{setValue:{xmin:-r/2}}}return n?{setValue:{xmin:e.xmaxPrelim-20}}:{setValue:{xmin:-10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xminPrelim",desiredValue:e.xmin}]}},e.xmax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},xmaxPrelim:{dependencyType:"stateVariable",variableName:"xmaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{xmax:e.xmaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.xminPrelim;if(s){let t=e.aspectRatio,a=(e.ymaxPrelim-e.yminPrelim)*t;if(o){let t=e.xmaxPrelim-l;return{setValue:{xmax:l+Math.max(t,a)}}}return n?{setValue:{xmax:l+a}}:r?{setValue:{xmax:e.xmaxPrelim}}:{setValue:{xmax:a/2}}}return r?{setValue:{xmax:e.xmaxPrelim}}:n?{setValue:{xmax:l+20}}:{setValue:{xmax:10}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"xmaxPrelim",desiredValue:e.xmax}]}},e.ymin={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},yminPrelim:{dependencyType:"stateVariable",variableName:"yminPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.ymaxPrelim={dependencyType:"stateVariable",variableName:"ymaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymin:e.yminPrelim}};if(!t.yminPrelim)return{setValue:{ymin:e.yminPrelim}};let n=!t.ymaxPrelim,r=!t.xminPrelim,a=!t.xmaxPrelim,i=r&&a,s=e.aspectRatio;if(i){let t=(e.xmaxPrelim-e.xminPrelim)/s;return n?{setValue:{ymin:e.ymaxPrelim-t}}:{setValue:{ymin:-t/2}}}return n?{setValue:{ymin:e.ymaxPrelim-20/s}}:{setValue:{ymin:-10/s}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"yminPrelim",desiredValue:e.ymin}]}},e.ymax={stateVariablesDeterminingDependencies:["identicalAxisScales","aspectRatioFromAxisScales"],public:!0,shadowingInstructions:{createComponentOfType:"number",attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,returnDependencies({stateValues:e}){let t={identicalAxisScales:{dependencyType:"stateVariable",variableName:"identicalAxisScales"},aspectRatioFromAxisScales:{dependencyType:"stateVariable",variableName:"aspectRatioFromAxisScales"},ymaxPrelim:{dependencyType:"stateVariable",variableName:"ymaxPrelim"}};return e.identicalAxisScales&&!e.aspectRatioFromAxisScales&&(t.xminPrelim={dependencyType:"stateVariable",variableName:"xminPrelim"},t.yminPrelim={dependencyType:"stateVariable",variableName:"yminPrelim"},t.xmaxPrelim={dependencyType:"stateVariable",variableName:"xmaxPrelim"},t.aspectRatio={dependencyType:"stateVariable",variableName:"aspectRatio"}),t},definition({dependencyValues:e,usedDefault:t}){if(!e.identicalAxisScales||e.aspectRatioFromAxisScales)return{setValue:{ymax:e.ymaxPrelim}};let n=!t.xminPrelim,r=!t.xmaxPrelim,a=!t.yminPrelim,i=!t.ymaxPrelim,s=a&&i,o=n&&r,l=e.yminPrelim,u=e.aspectRatio;if(o){let t=(e.xmaxPrelim-e.xminPrelim)/u;if(s){let n=e.ymaxPrelim-l;return{setValue:{ymax:l+Math.max(n,t)}}}return a?{setValue:{ymax:l+t}}:i?{setValue:{ymax:e.ymaxPrelim}}:{setValue:{ymax:t/2}}}return i?{setValue:{ymax:e.ymaxPrelim}}:a?{setValue:{ymax:l+20/u}}:{setValue:{ymax:10/u}}},inverseDefinition:async({desiredStateVariableValues:e,stateValues:t})=>await t.fixAxes?{success:!1}:{success:!0,instructions:[{setDependency:"ymaxPrelim",desiredValue:e.ymax}]}},e.xscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({xmin:{dependencyType:"stateVariable",variableName:"xmin"},xmax:{dependencyType:"stateVariable",variableName:"xmax"}}),definition:({dependencyValues:e})=>({setValue:{xscale:e.xmax-e.xmin}})},e.yscale={public:!0,shadowingInstructions:{createComponentOfType:"number"},returnDependencies:()=>({ymin:{dependencyType:"stateVariable",variableName:"ymin"},ymax:{dependencyType:"stateVariable",variableName:"ymax"}}),definition:({dependencyValues:e})=>({setValue:{yscale:e.ymax-e.ymin}})},e.gridAttrCompName={returnDependencies:()=>({gridAttr:{dependencyType:"attributeComponent",attributeName:"grid"}}),definition:({dependencyValues:e})=>e.gridAttr?{setValue:{gridAttrCompName:e.gridAttr.componentName}}:{setValue:{gridAttrCompName:null}}},e.gridAttrCompChildren={stateVariablesDeterminingDependencies:["gridAttrCompName"],returnDependencies:({stateValues:e})=>e.gridAttrCompName?{gridAttrCompChildren:{dependencyType:"child",parentName:e.gridAttrCompName,childGroups:["textLike"],variableNames:["value"]}}:{},definition:({dependencyValues:e})=>e.gridAttrCompChildren?{setValue:{gridAttrCompChildren:e.gridAttrCompChildren}}:{setValue:{gridAttrCompChildren:null}}},e.grid={public:!0,shadowingInstructions:{hasVariableComponentType:!0,attributesToShadow:["displayDigits","displayDecimals","displaySmallAsZero","padZeros"]},forRenderer:!0,stateVariablesDeterminingDependencies:["gridAttrCompChildren"],returnDependencies({stateValues:e}){if(e.gridAttrCompChildren){let t={gridAttrCompChildren:{dependencyType:"stateVariable",variableName:"gridAttrCompChildren"},gridAttr:{dependencyType:"attributeComponent",attributeName:"grid",variableNames:["value"]}};for(let[n,r]of e.gridAttrCompChildren.entries())t["childAdapter"+n]={dependencyType:"adapterSourceStateVariable",componentName:r.componentName,variableName:"value"};return t}return{}},definition({dependencyValues:e}){if(!e.gridAttrCompChildren)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};let t=e.gridAttr.stateValues.value.toLowerCase().trim();if("true"===t?t="medium":"false"===t&&(t="none"),["medium","dense","none"].includes(t))return{setValue:{grid:t},setCreateComponentOfType:{grid:"text"}};let n=[],r=[];for(let t of e.gridAttrCompChildren)if("string"!=typeof t)r.push(t);else{let e=t.split(/\s+/),a=e[0];""===a?r.length>0&&(n.push(r),r=[]):r.push(a);for(let t of e.slice(1))r.length>0&&(n.push(r),r=[]),""!==t&&r.push(t)}if(r.length>0&&n.push(r),n.length<2)return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t=[];for(let r of n)if(1===r.length){let n=r[0];if("string"==typeof n){let e=me$3.fromText(n).evaluate_to_constant();if(!(e>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(e)}else{let r=e.gridAttrCompChildren.indexOf(n),a=e["childAdapter"+r];if(a instanceof me$3.class&&(a=a.evaluate_to_constant()),!(a>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(a)}}else{let n=1;for(let t of r)if("string"==typeof t)n*=me$3.fromText(t).evaluate_to_constant();else{let r=e.gridAttrCompChildren.indexOf(t),a=e["childAdapter"+r];a instanceof me$3.class&&(a=a.evaluate_to_constant()),n*=a}if(!(n>0))return{setValue:{grid:"none"},setCreateComponentOfType:{grid:"text"}};t.push(n)}return{setValue:{grid:t},setCreateComponentOfType:{grid:"numberList"}}}},e}async changeAxisLimits({xmin:e,xmax:t,ymin:n,ymax:r,actionId:a}){let i=[];return void 0!==e&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmin",value:e}),void 0!==t&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"xmax",value:t}),void 0!==n&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymin",value:n}),void 0!==r&&i.push({updateType:"updateValue",componentName:this.componentName,stateVariable:"ymax",value:r}),await this.coreFunctions.performUpdate({updateInstructions:i,actionId:a,event:{verb:"interacted",object:{componentName:this.componentName,componentType:this.componentType},result:{xmin:e,xmax:t,ymin:n,ymax:r}}})}async addChildren({serializedComponents:e,actionId:t}){if(e&&e.length>0){let n=processAssignNames({serializedComponents:e,parentName:this.componentName,parentCreatesNewNamespace:this.attributes.newNamespace?.primitive,componentInfoObjects:this.componentInfoObjects,indOffset:await this.stateValues.nChildrenAdded});return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"addComponents",serializedComponents:n.serializedComponents,parentName:this.componentName,assignNamesOffset:await this.stateValues.nChildrenAdded},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded+n.serializedComponents.length}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}async deleteChildren({number:e,actionId:t}){let n=Math.min(e,await this.stateValues.nChildrenAdded);if(n>0){let e=this.definingChildren.length,r=this.definingChildren.slice(e-n,e).map((e=>e.componentName));return await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"deleteComponents",componentNames:r},{updateType:"updateValue",componentName:this.componentName,stateVariable:"nChildrenAdded",value:await this.stateValues.nChildrenAdded-n}],actionId:t})}this.coreFunctions.resolveAction({actionId:t})}recordVisibilityChange({isVisible:e,actionId:t}){this.coreFunctions.requestRecordEvent({verb:"visibilityChanged",object:{componentName:this.componentName,componentType:this.componentType},result:{isVisible:e}}),this.coreFunctions.resolveAction({actionId:t})}}class Variables extends MathList{static componentType="variables";static stateVariableForAttributeValue="variables";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();e.variables={public:!0,shadowingInstructions:{createComponentOfType:"variable"},isArray:!0,entryPrefixes:["var"],returnArraySizeDependencies:()=>({nComponents:{dependencyType:"stateVariable",variableName:"nComponents"}}),returnArraySize:({dependencyValues:e})=>[e.nComponents],returnArrayDependenciesByKey({arrayKeys:e}){let t={};for(let n of e)t[n]={math:{dependencyType:"stateVariable",variableName:"math"+(Number(n)+1)}};return{dependenciesByKey:t}},arrayDefinitionByKey({dependencyValuesByKey:e,arrayKeys:t}){let n={};for(let r of t)n[r]=e[r].math;return{setValue:{variables:n}}}};let t=this.componentType;return e.validVariables={returnDependencies:()=>({variables:{dependencyType:"stateVariable",variableName:"variables"}}),definition:function({dependencyValues:e}){let n=[];for(let r of e.variables){let e=isValidVariable(r);e||(console.warn("Invalid value for "+t),e=!1),n.push(e)}return{setValue:{validVariables:n}}}},e}}class Variable extends MathComponent{static componentType="variable";static rendererType="math";static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.validVariable={returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"}}),definition:function({dependencyValues:e}){let t=isValidVariable(e.value);return t||console.warn("Invalid value of a "+this.componentType),{setValue:{validVariable:t}}}},e}}class Interval extends MathComponent{static componentType="interval";static rendererType="math";static createAttributesObject(){let e=super.createAttributesObject();return delete e.createIntervals,e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.createIntervals={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({}),definition:()=>({setValue:{createIntervals:!0}})},e}}class Group extends Template{static componentType="group";static renderedDefault=!0}class Option$1 extends Group{static componentType="option";static renderedDefault=!1;static createAttributesObject(){let e=super.createAttributesObject();return e.selectForVariants={createComponentOfType:"textListFromString",createStateVariable:"selectForVariants",defaultValue:[],public:!0},e.selectWeight={createComponentOfType:"number",createStateVariable:"selectWeight",defaultValue:1,public:!0},e}}class Sequence extends CompositeComponent{static componentType="sequence";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();e.fixed={leaveRaw:!0},e.displayDigits={leaveRaw:!0},e.displayDecimals={leaveRaw:!0},e.displaySmallAsZero={leaveRaw:!0},e.padZeros={leaveRaw:!0};let t=returnStandardSequenceAttributes();return Object.assign(e,t),e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnStandardSequenceStateVariableDefinitions();return Object.assign(e,t),e.readyToExpandWhenResolved={returnDependencies:()=>({from:{dependencyType:"stateVariable",variableName:"from"},length:{dependencyType:"stateVariable",variableName:"length"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"},exclude:{dependencyType:"stateVariable",variableName:"exclude"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validSequence)return t.lastReplacementParameters={from:null,length:null,step:null,type:null,exclude:null},{replacements:[]};let a=await e.stateValues.from,i=await e.stateValues.length,s=await e.stateValues.step,o=await e.stateValues.type,l=await e.stateValues.exclude;t.lastReplacementParameters={from:a,length:i,step:s,type:o,exclude:l};let u=e.attributes.newNamespace?.primitive,c=returnSequenceValues({from:a,step:s,length:i,exclude:l,type:o,lowercase:await e.stateValues.lowercase}),p=o;"letters"===o&&(p="text");let d=[],m={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(m[t]=e.attributes[t]);for(let e of c){let t={};Object.keys(m).length>0&&(t=convertAttributesForComponentType({attributes:m,componentType:p,componentInfoObjects:n,compositeCreatesNewNamespace:u,flags:r}));let a={componentType:p,attributes:t,state:{value:e,fixed:!0}};d.push(a)}return{replacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:d,parentName:e.componentName,parentCreatesNewNamespace:u,componentInfoObjects:n}).serializedComponents}}static async calculateReplacementChanges({component:e,workspace:t,componentInfoObjects:n,flags:r}){let a=t.lastReplacementParameters,i=[];if(!await e.stateValues.validSequence){let t=e.replacementsToWithhold;if(t||(t=0),e.replacements.length-t>0){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};i.push(t)}return a.length=0,i}let s=await e.stateValues.from,o=await e.stateValues.length,l=await e.stateValues.step,u=await e.stateValues.type,c=await e.stateValues.exclude,p=await e.stateValues.lowercase;if(a.type!==u||a.exclude.length>0||c.length>0){let a=(await this.createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r})).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:a,replacementsToWithhold:0};i.push(s)}else{let t=!1;"math"===u?s.equals(a.from)&&l.equals(a.step)||(t=!0):s===a.from&&l===a.step||(t=!0);let c,d=a.length,m=0,h=0,f=d;if(od&&(m=o-d,e.replacementsToWithhold>0))if(e.replacementsToWithhold>=m){c=e.replacementsToWithhold-m,h+=m,d+=m,m=0;let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:c};i.push(t)}else m-=e.replacementsToWithhold,h+=e.replacementsToWithhold,d+=e.replacementsToWithhold,c=0;if(!0===t&&(h=d,f=0),h>0)for(let t=f;t0){let t=[],a=e.attributes.newNamespace?.primitive,o={};for(let t of["fixed","displayDigits","displaySmallAsZero","displayDecimals","padZeros"])t in e.attributes&&(o[t]=e.attributes[t]);for(let i=d;i0&&(m=convertAttributesForComponentType({attributes:o,componentType:d,componentInfoObjects:n,compositeCreatesNewNamespace:a,flags:r}));let h={componentType:d,attributes:m,state:{value:c,fixed:!0}};t.push(h)}let c={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:d,serializedReplacements:processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:a,componentInfoObjects:n,indOffset:d}).serializedComponents,replacementsToWithhold:0,assignNamesOffset:d};i.push(c)}}return a.type=u,a.from=s,a.length=o,a.step=l,a.exclude=c,i}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes,t="number";this.attributes.type&&this.attributes.type.primitive&&(t=this.attributes.type.primitive);let n=this.componentInfoObjects.allComponentClasses["letters"===t?"text":t].rendererType;return e.includes(n)||e.push(n),e}}class Map$1 extends CompositeComponent{static componentType="map";static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.behavior={createComponentOfType:"text",createStateVariable:"behavior",defaultValue:"combination",public:!0,trim:!0},e.isResponse={leaveRaw:!0},e}static returnChildGroups(){return[{group:"templates",componentTypes:["template"]},{group:"sources",componentTypes:["sources"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nSources={additionalStateVariablesDefined:["sourcesNames","sourceAliases","sourceIndexAliases"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["alias","indexAlias"]}}),definition:function({dependencyValues:e}){return{setValue:{nSources:e.sourcesChildren.length,sourcesNames:e.sourcesChildren.map((e=>e.componentName)),sourceAliases:e.sourcesChildren.map((e=>e.stateValues.alias)),sourceIndexAliases:e.sourcesChildren.map((e=>e.stateValues.indexAlias))}}}},e.nIterates={additionalStateVariablesDefined:["minNIterates","sourcesChildNames"],returnDependencies:()=>({sourcesChildren:{dependencyType:"child",childGroups:["sources"],variableNames:["numberOfChildren","childComponentNames"]}}),definition:function({dependencyValues:e}){let t=e.sourcesChildren.map((e=>e.stateValues.numberOfChildren)),n=Math.min(...t),r=e.sourcesChildren.map((e=>[...e.stateValues.childComponentNames]));return{setValue:{nIterates:t,minNIterates:n,sourcesChildNames:r}}}},e.template={returnDependencies:()=>({templateChild:{dependencyType:"child",childGroups:["templates"],variableNames:["serializedChildren","newNamespace"]}}),definition:function({dependencyValues:e}){let t=e.templateChild[0];if(!t)return{setValue:{template:null}};let n={componentType:"template",state:{rendered:!0},children:t.stateValues.serializedChildren,originalName:t.componentName};return t.stateValues.newNamespace&&(n.attributes={newNamespace:{primitive:!0}}),{setValue:{template:n}}}},e.validBehavior={returnDependencies:()=>({behavior:{dependencyType:"stateVariable",variableName:"behavior"},nIterates:{dependencyType:"stateVariable",variableName:"nIterates"}}),definition:function({dependencyValues:e}){let t=!0;return"parallel"===e.behavior?e.nIterates.slice(1).some((t=>t!=e.nIterates[0]))&&console.warn("Warning: map with parallel behavior and different numbers of iterates in sources activeChildren. Extra iterates will be ignored."):"combination"!==e.behavior&&(console.warn("Invalid map behavior: "+e.behavior),t=!1),{setValue:{validBehavior:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({validBehavior:{dependencyType:"stateVariable",variableName:"validBehavior"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,workspace:t,componentInfoObjects:n,flags:r}){if(!await e.stateValues.validBehavior)return t.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0},{replacements:[]};t.lastReplacementParameters={sourcesNames:await e.stateValues.sourcesNames,sourcesChildNames:await e.stateValues.sourcesChildNames,behavior:await e.stateValues.behavior,nIterates:await e.stateValues.nIterates,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]};let a=[];if("parallel"===await e.stateValues.behavior)for(let t=0;t=c-1){r++;let t=[deepClone(p)],n={};n=convertAttributesForComponentType({attributes:e.attributes,componentType:t[0].componentType,componentInfoObjects:a,compositeAttributesObj:d,compositeCreatesNewNamespace:l,flags:i}),t[0].attributes||(t[0].attributes={}),Object.assign(t[0].attributes,n),!t[0].attributes.newNamespace?.primitive&&t[0].children&&markToCreateAllUniqueNames(t[0].children);let u=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:t,parentName:e.componentName,parentCreatesNewNamespace:l,componentInfoObjects:a,indOffset:r}).serializedComponents[0];await addSharedParameters(u,e,o),s.push(u)}else{let n=await this.recurseThroughCombinations({component:e,sourcesNumber:t+1,childnumberArray:o,iterateNumber:r,componentInfoObjects:a,flags:i});s.push(...n.replacements),r=n.iterateNumber}return{replacements:s,iterateNumber:r}}static async calculateReplacementChanges({component:e,components:t,workspace:n,componentInfoObjects:r,flags:a}){let i=[];if(!await e.stateValues.validBehavior){if(n.lastReplacementParameters={sourcesNames:[],sourcesChildNames:[],behavior:void 0,nIterates:void 0,minNIterates:void 0,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},e.replacements.length>0){let t={changeType:"delete",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToDelete:e.replacements.length,replacementsToWithhold:0};i.push(t)}return i}let s=n.lastReplacementParameters,o=!1,l=!0,u=await e.stateValues.nSources,c=await e.stateValues.sourcesNames;if(u!==s.sourcesNames.length)l=!1;else for(let e=0;e1&&(o=!0)}else o=!0;if(o){let t=await this.createSerializedReplacements({component:e,workspace:n,componentInfoObjects:r,flags:a}).replacements,s={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:t,replacementsToWithhold:0};return i.push(s),n.lastReplacementParameters={sourcesNames:c,sourcesChildNames:d,behavior:m,nIterates:p,minNIterates:await e.stateValues.minNIterates,replacementsToWithhold:0,withheldSubstitutionChildNames:[]},i}let h=await e.stateValues.minNIterates,f=s.minNIterates,y=0,g=e.replacementsToWithhold;g||(g=0);let b=s.withheldSubstitutionChildNames,v=!1;if(hf){let t=h-f;if(g>0)if(g>=t){y=g-t,t=0;let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:y};i.push(e)}else t-=g,f+=g,y=0;if(t>0){let t=[];for(let n=f;nr?{success:!1}:{success:!0,desiredVariant:{index:t}}}}async function addSharedParameters(e,t,n){let r=e.doenetAttributes.addToSharedParameters=[],a=await t.stateValues.sourcesNames;for(let[e,i]of(await t.stateValues.sourceAliases).entries())if(i){let t=a[e];r.push({parameterName:"sourceNameMappings",key:i,value:{name:t,childNumber:n[e]}})}for(let[e,a]of(await t.stateValues.sourceIndexAliases).entries())a&&r.push({parameterName:"sourceIndexMappings",key:a,value:n[e]+1})}class Sources extends BaseComponent{static componentType="sources";static rendererType="containerInline";static renderChildren=!0;static createAttributesObject(){let e=super.createAttributesObject();return e.alias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Aliases can contain only letters, numbers, hyphens, and underscores");return e}},e.indexAlias={createPrimitiveOfType:"string",validationFunction:function(e){if(!/[a-zA-Z_]/.test(e.substring(0,1)))throw Error("All index aliases must begin with a letter or an underscore");if(!/^[a-zA-Z0-9_\-]+$/.test(e))throw Error("Index aliases can contain only letters, numbers, hyphens, and underscores");return e}},e}static returnChildGroups(){return[{group:"anything",componentTypes:["_base"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.alias={returnDependencies:()=>({alias:{dependencyType:"attributePrimitive",attributeName:"alias"}}),definition:({dependencyValues:e})=>({setValue:{alias:e.alias}})},e.indexAlias={returnDependencies:()=>({indexAlias:{dependencyType:"attributePrimitive",attributeName:"indexAlias"}}),definition:({dependencyValues:e})=>({setValue:{indexAlias:e.indexAlias}})},e.numberOfChildren={additionalStateVariablesDefined:["childComponentNames","childIdentities"],returnDependencies:()=>({children:{dependencyType:"child",childGroups:["anything"]}}),definition:function({dependencyValues:e}){let t=e.children.length,n=e.children.map((e=>e.componentName));return{setValue:{numberOfChildren:t,childComponentNames:n,childIdentities:e.children}}}},e}}class Slider extends BaseComponent{constructor(e){super(e),this.changeValue=this.changeValue.bind(this),Object.assign(this.actions,{changeValue:this.changeValue})}static componentType="slider";static variableForPlainMacro="value";static variableForPlainCopy="value";static createAttributesObject(){let e=super.createAttributesObject();return e.type={createPrimitiveOfType:"string",createStateVariable:"type",defaultValue:"number",toLowerCase:!0,validValues:["number","text"],forRenderer:!0},e.width={createComponentOfType:"_componentSize",createStateVariable:"width",defaultValue:{size:300,isAbsolute:!0},public:!0,forRenderer:!0},e.height={createComponentOfType:"_componentSize",createStateVariable:"height",defaultValue:{size:100,isAbsolute:!0},public:!0,forRenderer:!0},e.initialValue={createComponentOfType:"_componentWithSelectableType",createStateVariable:"initialValue",defaultValue:null},e.labelIsName={createComponentOfType:"boolean",createStateVariable:"labelIsName",defaultValue:!1,public:!0},e.showControls={createComponentOfType:"boolean",createStateVariable:"showControls",defaultValue:!1,public:!0,forRenderer:!0},e.showTicks={createComponentOfType:"boolean",createStateVariable:"showTicks",defaultValue:!0,public:!0,forRenderer:!0},e.showValue={createComponentOfType:"boolean",createStateVariable:"showValue",defaultValue:!0,public:!0,forRenderer:!0},e.from={createComponentOfType:"number",createStateVariable:"from",defaultValue:0,public:!0,forRenderer:!0},e.to={createComponentOfType:"number",createStateVariable:"to",defaultValue:10,public:!0,forRenderer:!0},e.step={createComponentOfType:"number",createStateVariable:"step",defaultValue:1,public:!0,forRenderer:!0},e.displayDigits={createComponentOfType:"integer"},e.displayDecimals={createComponentOfType:"integer",createStateVariable:"displayDecimals",defaultValue:null,public:!0},e.displaySmallAsZero={createComponentOfType:"number",createStateVariable:"displaySmallAsZero",valueForTrue:1e-14,valueForFalse:0,defaultValue:0,public:!0},e.bindValueTo={createComponentOfType:"_componentWithSelectableType"},e}static returnChildGroups(){return[{group:"numbersTexts",componentTypes:["number","text"]},{group:"markers",componentTypes:["markers"]},{group:"labels",componentTypes:["label"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions(),t=returnLabelStateVariableDefinitions();return Object.assign(e,t),e.displayDigits={public:!0,shadowingInstructions:{createComponentOfType:"integer"},hasEssential:!0,defaultValue:10,returnDependencies:()=>({displayDigitsAttr:{dependencyType:"attributeComponent",attributeName:"displayDigits",variableNames:["value"]},displayDecimalsAttr:{dependencyType:"attributeComponent",attributeName:"displayDecimals",variableNames:["value"]}}),definition({dependencyValues:e,usedDefault:t}){if(null!==e.displayDigitsAttr){let n=t.displayDigitsAttr,r=null===e.displayDecimalsAttr||t.displayDecimalsAttr;if(!n&&!r){let t=e.displayDigitsAttr.shadowDepth;e.displayDecimalsAttr.shadowDepth({numberAndTextChildren:{dependencyType:"child",childGroups:["numbersTexts"],variableNames:["value"]},type:{dependencyType:"stateVariable",variableName:"type"}}),definition:function({dependencyValues:e,componentInfoObjects:t}){let n=[];if("text"===e.type)for(let r of e.numberAndTextChildren)t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"text"})?n.push(r.stateValues.value):n.push(r.stateValues.value.toString());else if(e.numberAndTextChildren.length>0){for(let r of e.numberAndTextChildren)if(t.isInheritedComponentType({inheritedComponentType:r.componentType,baseComponentType:"number"}))n.push(r.stateValues.value);else{let e=Number(r.stateValues.value);Number.isFinite(e)&&n.push(e)}n.sort(((e,t)=>e-t))}return{setValue:{items:n},setCreateComponentOfType:{items:e.type}}}},e.nItems={forRenderer:!0,public:!0,shadowingInstructions:{createComponentOfType:"integer"},returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},to:{dependencyType:"stateVariable",variableName:"to"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t=e.items.length;return 0===t&&"number"===e.type&&(t=Math.floor((e.to-e.from)/e.step+1e-10)+1,t>=0&&Number.isFinite(t)||(t=0)),{setValue:{nItems:t}}}},e.firstItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[0]:"number"===e.type?e.from:null,{setValue:{firstItem:t}}}},e.lastItem={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"},from:{dependencyType:"stateVariable",variableName:"from"},nItems:{dependencyType:"stateVariable",variableName:"nItems"},step:{dependencyType:"stateVariable",variableName:"step"},type:{dependencyType:"stateVariable",variableName:"type"}}),definition({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.items.length-1]:"number"===e.type?e.from+(e.nItems-1)*e.step:null,{setValue:{lastItem:t}}}},e.valueToIndex={forRenderer:!0,returnDependencies:()=>({items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t={};for(let[n,r]of e.items.entries())t[r]=n;return{setValue:{valueToIndex:t}}}},e.preliminaryValue={hasEssential:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},initialValue:{dependencyType:"stateVariable",variableName:"initialValue"},bindValueTo:{dependencyType:"attributeComponent",attributeName:"bindValueTo",variableNames:["value"]}}),definition:({dependencyValues:e})=>e.bindValueTo?{setValue:{preliminaryValue:e.bindValueTo.stateValues.value}}:{useEssentialOrDefaultValue:{preliminaryValue:{get defaultValue(){return e.initialValue}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.bindValueTo?{success:!0,instructions:[{setDependency:"bindValueTo",desiredValue:e.preliminaryValue,variableIndex:0}]}:{success:!0,instructions:[{setEssentialValue:"preliminaryValue",value:e.preliminaryValue}]}},e.index={forRenderer:!0,returnDependencies:()=>({type:{dependencyType:"stateVariable",variableName:"type"},valueToIndex:{dependencyType:"stateVariable",variableName:"valueToIndex"},items:{dependencyType:"stateVariable",variableName:"items"},preliminaryValue:{dependencyType:"stateVariable",variableName:"preliminaryValue"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"},nItems:{dependencyType:"stateVariable",variableName:"nItems"}}),definition:function({dependencyValues:e}){let t=findIndexOfClosestValidValue(e);return void 0===t&&(t=0),{setValue:{index:t}}},inverseDefinition({desiredStateVariableValues:e,dependencyValues:t}){if(0===t.items.length){let n=t.from,r=t.step,a=e.index;return Number.isInteger(a)&&(a>=0&&a({type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"},index:{dependencyType:"stateVariable",variableName:"index"},from:{dependencyType:"stateVariable",variableName:"from"},step:{dependencyType:"stateVariable",variableName:"step"}}),definition:function({dependencyValues:e}){let t;return t=e.items.length>0?e.items[e.index]:e.from+e.step*e.index,{setValue:{value:t},setCreateComponentOfType:{value:e.type}}},inverseDefinition:invertSliderValue},e.valueForDisplay={forRenderer:!0,returnDependencies:()=>({value:{dependencyType:"stateVariable",variableName:"value"},displayDigits:{dependencyType:"stateVariable",variableName:"displayDigits"},displayDecimals:{dependencyType:"stateVariable",variableName:"displayDecimals"},displaySmallAsZero:{dependencyType:"stateVariable",variableName:"displaySmallAsZero"}}),definition:function({dependencyValues:e,usedDefault:t}){return{setValue:{valueForDisplay:roundForDisplay({value:e.value,dependencyValues:e,usedDefault:t}).tree}}}},e.markers={forRenderer:!0,returnDependencies:()=>({markersChild:{dependencyType:"child",childGroups:["markers"],variableNames:["markerType","markers"]},type:{dependencyType:"stateVariable",variableName:"type"},items:{dependencyType:"stateVariable",variableName:"items"}}),definition:function({dependencyValues:e}){let t=[];if(e.markersChild.length>0){let n=e.markersChild[0].stateValues.markerType;"empty"===n?t=[...e.items]:n!==e.type?(console.warn("Markers type doesn't match slider type."),t=[]):t=e.markersChild[0].stateValues.markers}return{setValue:{markers:t}}}},e}async changeValue({value:e,transient:t,actionId:n}){if(!await this.stateValues.disabled)return t?await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],transient:t,actionId:n}):await this.coreFunctions.performUpdate({updateInstructions:[{updateType:"updateValue",componentName:this.componentName,stateVariable:"value",value:e}],actionId:n,event:{verb:"selected",object:{componentName:this.componentName,componentType:this.componentType},result:{response:e,responseText:e.toString()}}});this.coreFunctions.resolveAction({actionId:n})}}function findIndexOfClosestValidValue({preliminaryValue:e,valueToIndex:t,type:n,items:r,from:a,step:i,nItems:s}){let o=e;if(0===r.length){if(!Number.isFinite(o))return;let e=Math.round((o-a)/i);return e>=0?er[e]?t:e;let n=Math.round((t+e)/2);return o>r[n]?u(n,t):u(e,n)},c=u();if(0!==c){let e=r[c-1],t=r[c];Math.abs(o-e)({textChildren:{dependencyType:"child",childGroups:["texts"]},numberChildren:{dependencyType:"child",childGroups:["numbers"]}}),definition:function({dependencyValues:e}){let t;return t=e.textChildren.length>0?"text":e.numberChildren.length>0?"number":"empty",{setValue:{markerType:t}}}},e.markers={public:!0,isArray:!0,shadowingInstructions:{hasVariableComponentType:!0},entryPrefixes:["item"],returnDependencies:()=>({markerType:{dependencyType:"stateVariable",variableName:"markerType"},textChildren:{dependencyType:"child",childGroups:["texts"],variableNames:["value"]},numberChildren:{dependencyType:"child",childGroups:["numbers"],variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=[],n=e.markerType;return"text"===e.markerType?t=e.textChildren.map((e=>e.stateValues.value)):"number"===e.markerType?(t=e.numberChildren.map((e=>e.stateValues.value)),t.sort(((e,t)=>e-t))):n="text",{setValue:{markers:t},setCreateComponentOfType:{markers:n}}}},e}}class Pegboard extends GraphicalComponent{static componentType="pegboard";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0,forRenderer:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0,forRenderer:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0,forRenderer:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0,forRenderer:!0},e}}function applyConstraintFromComponentConstraints({variables:e,applyComponentConstraint:t,scales:n}){let r={},a=!1;for(let i in e){let s=t({variables:{[i]:e[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}return a?{constrained:a,variables:r}:{}}class Constraints extends BaseComponent{static componentType="constraints";static rendererType=void 0;static createAttributesObject(){let e=super.createAttributesObject();return e.baseOnGraph={createTargetComponentNames:!0},e}static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["independentComponentConstraints"]}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.constraintChildren.every((e=>e.stateValues.independentComponentConstraints))}})},e.arrayEntryPrefixForConstraints={returnDependencies:()=>({arrayEntryPrefixForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayEntryPrefixForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayEntryPrefixForConstraints:e.arrayEntryPrefixForConstraints}})},e.arrayVariableForConstraints={returnDependencies:()=>({arrayVariableForConstraints:{dependencyType:"parentStateVariable",variableName:"arrayVariableForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{arrayVariableForConstraints:e.arrayVariableForConstraints}})},e.nDimensions={returnDependencies:()=>({nDimensions:{dependencyType:"parentStateVariable",variableName:"nDimensionsForConstraints"}}),definition:({dependencyValues:e})=>({setValue:{nDimensions:e.nDimensions}})},e.graphComponentName={returnDependencies:()=>({graphComponentName:{dependencyType:"attributeTargetComponentNames",attributeName:"baseOnGraph"}}),definition:({dependencyValues:e})=>1===e.graphComponentName?.length?{setValue:{graphComponentName:e.graphComponentName[0].absoluteName}}:{setValue:{graphComponentName:null}}},e.scales={public:!0,shadowingInstructions:{createComponentOfType:"number"},stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xscale","yscale"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(e.graph){let t=e.graph.stateValues,n=[t.xscale,t.yscale,1];if(n.every((e=>Number.isFinite(e)&&e>0)))return{setValue:{scales:n}}}return{setValue:{scales:[1,1,1]}}}},e.graphXmin={additionalStateVariablesDefined:["graphXmax","graphYmin","graphYmax"],stateVariablesDeterminingDependencies:["graphComponentName"],returnDependencies:({stateValues:e})=>e.graphComponentName?{graph:{dependencyType:"multipleStateVariables",componentName:e.graphComponentName,variableNames:["xmin","xmax","ymin","ymax"],variablesOptional:!0}}:{},definition({dependencyValues:e}){if(!e.graph)return{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}};let t=e.graph.stateValues.xmin,n=e.graph.stateValues.xmax,r=e.graph.stateValues.ymin,a=e.graph.stateValues.ymax;return[t,n,r,a].every(Number.isFinite)?{setValue:{graphXmin:t,graphXmax:n,graphYmin:r,graphYmax:a}}:{setValue:{graphXmin:null,graphXmax:null,graphYmin:null,graphYmax:null}}}},e.constraintResults={additionalStateVariablesDefined:[{variableName:"constraintUsedByComponent",isArray:!0,entryPrefixes:["constraintUsedByComponent"]}],isArray:!0,entryPrefixes:["constraintResult"],stateVariablesDeterminingDependencies:["independentComponentConstraints","arrayEntryPrefixForConstraints","arrayVariableForConstraints"],returnArraySizeDependencies:()=>({nDimensions:{dependencyType:"stateVariable",variableName:"nDimensions"}}),returnArraySize:({dependencyValues:e})=>[e.nDimensions],returnArrayDependenciesByKey({arrayKeys:e,stateValues:t}){let n={constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},scales:{dependencyType:"stateVariable",variableName:"scales"}},r=t.arrayEntryPrefixForConstraints,a={};if(t.independentComponentConstraints)for(let t of e)a[t]={x:{dependencyType:"parentStateVariable",variableName:r+(Number(t)+1)}};else{let e=t.arrayVariableForConstraints?t.arrayVariableForConstraints:"__null";n.xs={dependencyType:"parentStateVariable",variableName:e}}return{globalDependencies:n,dependenciesByKey:a}},arrayDefinitionByKey({globalDependencyValues:e,dependencyValuesByKey:t,arrayKeys:n}){if(e.independentComponentConstraints){let r={},a={};for(let i of n){let n=Number(i)+1,s={["x"+n]:t[i].x},o=!1;for(let t of e.constraintChildren){let r=t.stateValues.applyComponentConstraint({variables:s,scales:e.scales});r.constrained&&(s["x"+n]=convertValueToMathExpression(r.variables["x"+n]),o=!0)}r[i]=s["x"+n],a[i]=o}return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}{let t={},n=!1;for(let n in e.xs)t[`x${Number(n)+1}`]=e.xs[n];for(let r of e.constraintChildren){let a;if(a=r.stateValues.applyConstraint?r.stateValues.applyConstraint({variables:t,scales:e.scales}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:r.stateValues.applyComponentConstraint,scales:e.scales}),a.constrained){for(let e in a.variables)t[e]=convertValueToMathExpression(a.variables[e]);n=!0}}let r={},a={};for(let i in e.xs)r[i]=t[`x${Number(i)+1}`],a[i]=n;return{setValue:{constraintResults:r,constraintUsedByComponent:a}}}},inverseArrayDefinitionByKey:async function({desiredStateVariableValues:e,globalDependencyValues:t,dependencyValuesByKey:n,dependencyNamesByKey:r,stateValues:a,workspace:i}){if(t.independentComponentConstraints){let n=[];for(let a in e.constraintResults){let i=Number(a)+1,s={["x"+i]:convertValueToMathExpression(e.constraintResults[a])};for(let e of t.constraintChildren){let n=e.stateValues.applyComponentConstraint({variables:s,scales:t.scales});n.constrained&&(s["x"+i]=convertValueToMathExpression(n.variables["x"+i]))}n.push({setDependency:r[a].x,desiredValue:s["x"+i]})}return{success:!0,instructions:n}}{let n={};i.desiredConstraintResults||(i.desiredConstraintResults={}),Object.assign(i.desiredConstraintResults,e.constraintResults);let r=await a.constraintResults;for(let e in r){let t=Number(e)+1;e in i.desiredConstraintResults?n["x"+t]=convertValueToMathExpression(i.desiredConstraintResults[e]):n["x"+t]=convertValueToMathExpression(r[e])}for(let e of t.constraintChildren){let r;if(r=e.stateValues.applyConstraint?e.stateValues.applyConstraint({variables:n,scales:t.scales}):applyConstraintFromComponentConstraints({variables:n,applyComponentConstraint:e.stateValues.applyComponentConstraint,scales:t.scales}),r.constrained)for(let e in r.variables)n[e]=convertValueToMathExpression(r.variables[e])}let s={};for(let e in i.desiredConstraintResults)s[e]=n[`x${Number(e)+1}`];return{success:!0,instructions:[{setDependency:"xs",desiredValue:s}]}}}},e.constraintUsed={public:!0,shadowingInstructions:{createComponentOfType:"boolean"},returnDependencies:()=>({constraintUsedByComponent:{dependencyType:"stateVariable",variableName:"constraintUsedByComponent"}}),definition:function({dependencyValues:e}){let t=Object.values(e.constraintUsedByComponent).some((e=>e));return{setValue:{constraintUsed:t}}}},e}}class ConstraintComponent extends BaseComponent{static componentType="_constraint";static rendererType=void 0;static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!1}})},e}}class ConstrainToGrid extends ConstraintComponent{static componentType="constrainToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x1:s}}}return{}}if("x2"in t){let n=findFiniteNumericalValue(t.x2);if(!Number.isFinite(n))return{};let a=e.dy,i=e.yoffset,s=Math.round((n-i)/a)*a+i;if(Number.isFinite(s)){if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphYmin,n=e.constraintAncestor.stateValues.graphYmax):"graph"===r&&(t=e.graphAncestor.stateValues.ymin,n=e.graphAncestor.stateValues.ymax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return{constrained:!0,variables:{x2:s}}}return{}}if("x3"in t){let n=findFiniteNumericalValue(t.x3);if(!Number.isFinite(n))return{};let r=e.dz,a=e.zoffset,i=Math.round((n-a)/r)*r+a;return Number.isFinite(i)?{constrained:!0,variables:{x3:i}}:{}}return{}}}})},e}}class ConstrainToGraph extends ConstraintComponent{static componentType="constrainToGraph";static createAttributesObject(){let e=super.createAttributesObject();return e.buffer={createComponentOfType:"number",createStateVariable:"buffer",defaultValue:.01,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({}),definition:()=>({setValue:{independentComponentConstraints:!0}})},e.applyComponentConstraint={returnDependencies:()=>({constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},buffer:{dependencyType:"stateVariable",variableName:"buffer"},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),!r)return{};if("x1"in t){let n,a,i=findFiniteNumericalValue(t.x1);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphXmin,a=e.constraintAncestor.stateValues.graphXmax):(n=e.graphAncestor.stateValues.xmin,a=e.graphAncestor.stateValues.xmax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x1:Math.max(s,Math.min(o,i))}}}if("x2"in t){let n,a,i=findFiniteNumericalValue(t.x2);if(!Number.isFinite(i))return{};if("constraints"===r?(n=e.constraintAncestor.stateValues.graphYmin,a=e.constraintAncestor.stateValues.graphYmax):(n=e.graphAncestor.stateValues.ymin,a=e.graphAncestor.stateValues.ymax),!Number.isFinite(n)||!Number.isFinite(a))return{};let s=n,o=a,l=e.buffer;if(l>0){let e=l*(a-n);s+=e,o-=e}return{constrained:!0,variables:{x2:Math.max(s,Math.min(o,i))}}}return{}}}})},e}}class AttractToGrid extends ConstraintComponent{static componentType="attractToGrid";static createAttributesObject(){let e=super.createAttributesObject();return e.dx={createComponentOfType:"number",createStateVariable:"dx",defaultValue:1,public:!0},e.dy={createComponentOfType:"number",createStateVariable:"dy",defaultValue:1,public:!0},e.dz={createComponentOfType:"number",createStateVariable:"dz",defaultValue:1,public:!0},e.xoffset={createComponentOfType:"number",createStateVariable:"xoffset",defaultValue:0,public:!0},e.yoffset={createComponentOfType:"number",createStateVariable:"yoffset",defaultValue:0,public:!0},e.zoffset={createComponentOfType:"number",createStateVariable:"zoffset",defaultValue:0,public:!0},e.xthreshold={createComponentOfType:"number",createStateVariable:"xthreshold",defaultValue:.2,public:!0},e.ythreshold={createComponentOfType:"number",createStateVariable:"ythreshold",defaultValue:.2,public:!0},e.zthreshold={createComponentOfType:"number",createStateVariable:"zthreshold",defaultValue:.2,public:!0},e.includeGridlines={createComponentOfType:"boolean",createStateVariable:"includeGridlines",defaultValue:!1,public:!0},e.ignoreGraphBounds={createComponentOfType:"boolean",createStateVariable:"ignoreGraphBounds",defaultValue:!1,public:!0},e}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.independentComponentConstraints={returnDependencies:()=>({includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"}}),definition:({dependencyValues:e})=>({setValue:{independentComponentConstraints:e.includeGridlines}})},e.applyComponentConstraint={returnDependencies:()=>({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},constraintAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin","graphXmax","graphYmin","graphYmax"]},graphAncestor:{dependencyType:"ancestor",componentType:"graph",variableNames:["xmin","xmax","ymin","ymax"]},ignoreGraphBounds:{dependencyType:"stateVariable",variableName:"ignoreGraphBounds"}}),definition:({dependencyValues:e})=>({setValue:{applyComponentConstraint:function({variables:t,scales:n}){let r;if(null!==e.constraintAncestor&&null!==e.constraintAncestor.stateValues.graphXmin?r="constraints":null!==e.graphAncestor&&null!==e.graphAncestor.stateValues.xmin&&(r="graph"),"x1"in t){let n=findFiniteNumericalValue(t.x1);if(!Number.isFinite(n))return{};let a=e.dx,i=e.xoffset,s=Math.round((n-i)/a)*a+i;if(!Number.isFinite(s))return{};if(!e.ignoreGraphBounds){let t,n;"constraints"===r?(t=e.constraintAncestor.stateValues.graphXmin,n=e.constraintAncestor.stateValues.graphXmax):"graph"===r&&(t=e.graphAncestor.stateValues.xmin,n=e.graphAncestor.stateValues.xmax),void 0!==t&&(sn&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)n&&(s=Math.floor((n-i)/a)*a+i))}return Math.abs(n-s)({dx:{dependencyType:"stateVariable",variableName:"dx"},dy:{dependencyType:"stateVariable",variableName:"dy"},dz:{dependencyType:"stateVariable",variableName:"dz"},xoffset:{dependencyType:"stateVariable",variableName:"xoffset"},yoffset:{dependencyType:"stateVariable",variableName:"yoffset"},zoffset:{dependencyType:"stateVariable",variableName:"zoffset"},xthreshold:{dependencyType:"stateVariable",variableName:"xthreshold"},ythreshold:{dependencyType:"stateVariable",variableName:"ythreshold"},zthreshold:{dependencyType:"stateVariable",variableName:"zthreshold"},includeGridlines:{dependencyType:"stateVariable",variableName:"includeGridlines"},applyComponentConstraint:{dependencyType:"stateVariable",variableName:"applyComponentConstraint"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r={},a=!1;for(let i in t){let s=e.applyComponentConstraint({variables:{[i]:t[i]},scales:n});s.constrained&&(a=!0,r[i]=s.variables[i])}if(!a)return{};if(!e.includeGridlines){if(void 0!==t.x1&&void 0===r.x1)return{};if(void 0!==t.x2&&void 0===r.x2)return{};if(void 0!==t.x3&&void 0===r.x3)return{}}return{constrained:a,variables:r}}}})},e}}class ConstrainTo extends ConstraintComponent{static componentType="constrainTo";static returnChildGroups(){return[{group:"graphical",componentTypes:["_graphical"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r=1/0,a={},i=!1,s={};for(let e in t)s[e]=findFiniteNumericalValue(t[e]);for(let o of e.nearestPointFunctions){let e=o({variables:t,scales:n});if(void 0===e)continue;let l={},u=0;if(void 0!==s.x1){if(void 0===e.x1)continue;l.x1=e.x1,u+=Math.pow(s.x1-e.x1,2)}if(void 0!==s.x2){if(void 0===e.x2)continue;l.x2=e.x2,u+=Math.pow(s.x2-e.x2,2)}if(void 0!==s.x3){if(void 0===e.x3)continue;l.x3=e.x3,u+=Math.pow(s.x3-e.x3,2)}u({thresholdAttr:{dependencyType:"attributeComponent",attributeName:"threshold",variableNames:["value"]},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["graphXmin"]}}),definition({dependencyValues:e}){if(e.thresholdAttr)return{setValue:{threshold:e.thresholdAttr.stateValues.value}};{let t=.02;return null!==e.constraintsAncestor&&null!==e.constraintsAncestor.stateValues.graphXmin||(t=.5),{useEssentialOrDefaultValue:{threshold:{defaultValue:t}}}}},inverseDefinition:({desiredStateVariableValues:e,dependencyValues:t})=>t.thresholdAttr?{success:!0,instructions:[{setDependency:"thresholdAttr",desiredValue:e.threshold}]}:{success:!0,instructions:[{setEssentialValue:"threshold",value:e.threshold}]}},e.nearestPointFunctions={returnDependencies:()=>({graphicalChildren:{dependencyType:"child",childGroups:["graphical"],variableNames:["nearestPoint"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.graphicalChildren)n.stateValues.nearestPoint?t.push(n.stateValues.nearestPoint):console.warn(`cannot attract to ${n.componentName} as it doesn't have a nearestPoint state variable`);return{setValue:{nearestPointFunctions:t}}}},e.graphXscale={additionalStateVariablesDefined:["graphYscale"],returnDependencies:()=>({graphAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){if(!e.graphAncestor)return{setValue:{graphXscale:null,graphYscale:null}};return{setValue:{graphXscale:e.graphAncestor.stateValues.xscale,graphYscale:e.graphAncestor.stateValues.yscale}}}},e.applyConstraint={returnDependencies:()=>({nearestPointFunctions:{dependencyType:"stateVariable",variableName:"nearestPointFunctions"},threshold:{dependencyType:"stateVariable",variableName:"threshold"},constraintsAncestor:{dependencyType:"ancestor",componentType:"constraints",variableNames:["scales"]}}),definition({dependencyValues:e}){let t=1,n=1;return e.constraintsAncestor&&([t,n]=e.constraintsAncestor.stateValues.scales),{setValue:{applyConstraint:function({variables:r,scales:a}){let i=1/0,s={},o={};for(let e in r)o[e]=findFiniteNumericalValue(r[e]);for(let l of e.nearestPointFunctions){let e=l({variables:r,scales:a});if(void 0===e)continue;let u={},c=0;if(void 0!==o.x1){if(void 0===e.x1)continue;u.x1=e.x1,c+=Math.pow((o.x1-e.x1)/t,2)}if(void 0!==o.x2){if(void 0===e.x2)continue;u.x2=e.x2,c+=Math.pow((o.x2-e.x2)/n,2)}if(void 0!==o.x3){if(void 0===e.x3)continue;u.x3=e.x3,c+=Math.pow(o.x3-e.x3,2)}ce.threshold*e.threshold?{}:{constrained:!0,variables:s}}}}}},e}}class ConstraintUnion extends ConstraintComponent{static componentType="constraintUnion";static returnChildGroups(){return[{group:"constraints",componentTypes:["_constraint"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.applyConstraint={returnDependencies:()=>({constraintChildren:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r;if(1===e.constraintChildren.length){let a=e.constraintChildren[0];return r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n}),r}let a,i=1/0,s={};for(let[o,l]of e.constraintChildren.entries()){if(r=l.stateValues.applyConstraint?l.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:l.stateValues.applyComponentConstraint,scales:n}),!r.constrained)continue;let e=0;for(let n in r.variables){let a=findFiniteNumericalValue(t[n]),i=findFiniteNumericalValue(r.variables[n]);if(!Number.isFinite(a)||!Number.isFinite(i)){e=1/0;break}e+=Math.pow(a-i,2)}e({constraintChild:{dependencyType:"child",childGroups:["constraints"],variableNames:["applyConstraint","applyComponentConstraint"],variablesOptional:!0},independentComponentConstraints:{dependencyType:"stateVariable",variableName:"independentComponentConstraints"},threshold:{dependencyType:"stateVariable",variableName:"threshold"}}),definition:({dependencyValues:e})=>({setValue:{applyConstraint:function({variables:t,scales:n}){let r,a=e.constraintChild[0];if(!a)return{};r=a.stateValues.applyConstraint?a.stateValues.applyConstraint({variables:t,scales:n}):applyConstraintFromComponentConstraints({variables:t,applyComponentConstraint:a.stateValues.applyComponentConstraint,scales:n});let i=0;for(let e in r.variables){let n=findFiniteNumericalValue(t[e]),a=findFiniteNumericalValue(r.variables[e]);if(!Number.isFinite(n)||!Number.isFinite(a))return{};i+=Math.pow(n-a,2)}return i>e.threshold*e.threshold?{}:r}}})},e}}class Intersection extends CompositeComponent{static componentType="intersection";static assignNamesToReplacements=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e}static returnChildGroups(){return[{group:"lines",componentTypes:["line"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.lineChildren={returnDependencies:()=>({lineChildren:{dependencyType:"child",childGroups:["lines"],variableNames:["numericalCoeff0","numericalCoeffvar1","numericalCoeffvar2","nDimensions"]}}),definition:({dependencyValues:e})=>({setValue:{lineChildren:e.lineChildren}})},e.readyToExpandWhenResolved={returnDependencies:()=>({lineChildren:{dependencyType:"stateVariable",variableName:"lineChildren"}}),markStale:()=>({updateReplacements:!0}),definition:function(){return{setValue:{readyToExpandWhenResolved:!0}}}},e}static async createSerializedReplacements({component:e,components:t,componentInfoObjects:n}){let r=await e.stateValues.lineChildren,a=r.length;if(0===a)return{replacements:[]};if(1===a){let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}if(a>2)return console.warn("Haven't implemented intersection for more than two objects"),{replacements:[]};let i=r[0],s=r[1];if(2!==i.stateValues.nDimensions||2!==s.stateValues.nDimensions)return console.log("Intersection of lines implemented only in 2D"),{replacements:[]};let o=i.stateValues.numericalCoeffvar1,l=i.stateValues.numericalCoeffvar2,u=i.stateValues.numericalCoeff0,c=s.stateValues.numericalCoeffvar1,p=s.stateValues.numericalCoeffvar2,d=s.stateValues.numericalCoeff0;if(!(Number.isFinite(o)&&Number.isFinite(l)&&Number.isFinite(u)&&Number.isFinite(c)&&Number.isFinite(p)&&Number.isFinite(d)))return console.log("Intersection of lines implemented only for constant coefficients"),{replacements:[]};let m=o*p-c*l;if(Math.abs(m)<1e-14){if(Math.abs(d*o-u*c)>1e-14)return{replacements:[]};if(0===o&&0===l&&0===u||0===c&&0===p&&0===d)return{replacements:[]};{let a=r[0].componentName,i=await t[a].serialize({sourceAttributesToIgnoreRecursively:["isResponse"]});i.state||(i.state={}),i.state.draggable=!1,i.state.fixed=!0;let s=postProcessCopy({serializedComponents:[i],componentName:e.componentName}),o=e.attributes.newNamespace?.primitive;return s=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:s,parentName:e.componentName,parentCreatesNewNamespace:o,componentInfoObjects:n}).serializedComponents,{replacements:s}}}let h=(d*l-u*p)/m,f=(u*c-d*o)/m,y=[{componentType:"point",state:{coords:me$3.fromAst(["vector",h,f]),draggable:!1,fixed:!0}}],g=e.attributes.newNamespace?.primitive;return y=processAssignNames({assignNames:e.doenetAttributes.assignNames,serializedComponents:y,parentName:e.componentName,parentCreatesNewNamespace:g,componentInfoObjects:n}).serializedComponents,{replacements:y}}static async calculateReplacementChanges({component:e,components:t,componentInfoObjects:n}){let r=[],a=(await this.createSerializedReplacements({component:e,components:t,componentInfoObjects:n})).replacements,i=a.length,s=!0;if(i===e.replacements.length){s=!1;for(let t=0;t({children:{dependencyType:"child",childGroups:["anything"],variableNames:["width"]},columns:{dependencyType:"stateVariable",variableName:"columns"}}),definition:function({dependencyValues:e}){let t=[],n=e.children.map((e=>e.stateValues.width));if(null!==e.columns){let r;if(-1!==e.columns.indexOf(","))r=e.columns.split(",").map(Number);else if(-1!==e.columns.indexOf("-")){let[t,n]=e.columns.split("-");r=[];for(let e=Number(t);e<=n;e++)r.push(e)}else r=[Number(e.columns)];let a={},i={};for(let e of r){let t=[],r=0;for(let a=0;ai&&(i=n[t]);t.push(i),r+=Number(i)}a[e]=t,i[e]=r}let s=-1;for(let e of r){let e=Number.POSITIVE_INFINITY,n=-1;for(let t of r)i[t]<=e&&t>s&&(e=i[t],n=t);e=this.state.threshold?{}:{variables:{x1:p,x2:d},constraintIndices:[i+1],constrained:!0}}}class ConditionalContent extends CompositeComponent{static componentType="conditionalContent";static includeBlankStringChildren=!0;static assignNamesToReplacements=!0;static createsVariants=!0;static stateVariableToEvaluateAfterReplacements="readyToExpandWhenResolved";static keepChildrenSerialized({serializedComponent:e,componentInfoObjects:t}){if(void 0===e.children)return[];let n=t.componentIsSpecifiedType,r=[];for(let[t,a]of e.children.entries())n(a,"case")||n(a,"else")||r.push(t);return r}static createAttributesObject(){let e=super.createAttributesObject();return e.assignNamesSkip={createPrimitiveOfType:"number"},e.maximumNumberToShow={createComponentOfType:"number",createStateVariable:"maximumNumberToShow",defaultValue:null,public:!0},e.condition={createComponentOfType:"boolean"},e}static returnChildGroups(){return[{group:"cases",componentTypes:["case"]},{group:"elses",componentTypes:["else"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.baseConditionSatisfied={returnDependencies:()=>({conditionAttr:{dependencyType:"attributeComponent",attributeName:"condition",variableNames:["value"]}}),definition:function({dependencyValues:e}){let t=!0;return e.conditionAttr&&(t=e.conditionAttr.stateValues.value),{setValue:{baseConditionSatisfied:t}}}},e.nCases={additionalStateVariablesDefined:["caseChildren"],returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"]}}),definition:({dependencyValues:e})=>({setValue:{caseChildren:e.caseChildren,nCases:e.caseChildren.length}})},e.elseChild={returnDependencies:()=>({elseChild:{dependencyType:"child",childGroups:["elses"]}}),definition({dependencyValues:e}){let t=null;return e.elseChild.length>0&&(t=e.elseChild[0]),{setValue:{elseChild:t}}}},e.haveCasesOrElse={returnDependencies:()=>({nCases:{dependencyType:"stateVariable",variableName:"nCases"},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"}}),definition:({dependencyValues:e})=>({setValue:{haveCasesOrElse:e.nCases>0||null!==e.elseChild}})},e.selectedIndices={returnDependencies:()=>({caseChildren:{dependencyType:"child",childGroups:["cases"],variableNames:["conditionSatisfied"]},elseChild:{dependencyType:"stateVariable",variableName:"elseChild"},maximumNumberToShow:{dependencyType:"stateVariable",variableName:"maximumNumberToShow"}}),definition({dependencyValues:e}){let t=[];for(let[n,r]of e.caseChildren.entries())r.stateValues.conditionSatisfied&&t.push(n);if(0===t.length&&e.elseChild&&t.push(e.caseChildren.length),null!==e.maximumNumberToShow&&t.length>e.maximumNumberToShow){let n=Math.max(0,Math.floor(e.maximumNumberToShow));t=t.slice(0,n)}return{setValue:{selectedIndices:t}}}},e.readyToExpandWhenResolved={returnDependencies:()=>({baseConditionSatisfied:{dependencyType:"stateVariable",variableName:"baseConditionSatisfied"},haveCasesOrElse:{dependencyType:"stateVariable",variableName:"haveCasesOrElse"},selectedIndices:{dependencyType:"stateVariable",variableName:"selectedIndices"}}),markStale:()=>({updateReplacements:!0}),definition:()=>({setValue:{readyToExpandWhenResolved:!0}})},e.isVariantComponent={returnDependencies:()=>({}),definition:()=>({setValue:{isVariantComponent:!0}})},e.generatedVariantInfo={returnDependencies:({sharedParameters:e,componentInfoObjects:t})=>({variantSeed:{dependencyType:"value",value:e.variantSeed},variantDescendants:{dependencyType:"descendant",componentTypes:Object.keys(t.componentTypesCreatingVariants),variableNames:["isVariantComponent","generatedVariantInfo"],useReplacementsForComposites:!0,recurseToMatchedChildren:!1,variablesOptional:!0,includeNonActiveChildren:!0,ignoreReplacementsOfEncounteredComposites:!0}}),definition({dependencyValues:e,componentName:t}){let n={seed:e.variantSeed,meta:{createdBy:t}},r=n.subvariants=[];for(let t of e.variantDescendants)t.stateValues.isVariantComponent?r.push(t.stateValues.generatedVariantInfo):t.stateValues.generatedVariantInfo&&r.push(...t.stateValues.generatedVariantInfo.subvariants);return{setValue:{generatedVariantInfo:n}}}},e}static async createSerializedReplacements({component:e,components:t,workspace:n,componentInfoObjects:r}){let a=await this.getReplacements(e,t,r);return n.previousSelectedIndices=[...await e.stateValues.selectedIndices],n.previousBaseConditionSatisfied=await e.stateValues.baseConditionSatisfied,{replacements:a}}static async getReplacements(e,t,n){if(!await e.stateValues.baseConditionSatisfied)return[];let r=[];if(await e.stateValues.haveCasesOrElse){let n=await e.stateValues.caseChildren;for(let[a,i]of(await e.stateValues.selectedIndices).entries()){let s,o,l;ie===i[t]))){if(r.previousBaseConditionSatisfied===s)return[];if(!s){let t={changeType:"changeReplacementsToWithhold",replacementsToWithhold:e.replacements.length};return r.previousBaseConditionSatisfied=s,[t]}if(e.replacements.length===e.serializedChildren.length){let e={changeType:"changeReplacementsToWithhold",replacementsToWithhold:0};return r.previousBaseConditionSatisfied=s,[e]}}let o=[],l=await this.getReplacements(e,n,a),u={changeType:"add",changeTopLevelReplacements:!0,firstReplacementInd:0,numberReplacementsToReplace:e.replacements.length,serializedReplacements:l,replacementsToWithhold:0};return o.push(u),r.previousSelectedIndices=[...i],r.previousBaseConditionSatisfied=s,o}static setUpVariant({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n}){setUpVariantSeedAndRng({serializedComponent:e,sharedParameters:t,descendantVariantComponents:n,useSubpartVariantRng:!0})}get allPotentialRendererTypes(){let e=super.allPotentialRendererTypes;if(this.serializedChildren){let t=this.potentialRendererTypesFromSerializedComponents(this.serializedChildren);for(let n of t)e.includes(n)||e.push(n)}return e}}class AsList extends InlineComponent{static componentType="asList";static renderChildren=!0;static returnChildGroups(){return[{group:"inline",componentTypes:["_inline"]}]}static returnStateVariableDefinitions(){let e=super.returnStateVariableDefinitions();return e.text={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{text:t.join(", ")}}}},e.latex={public:!0,shadowingInstructions:{createComponentOfType:"text"},returnDependencies:()=>({inlineChildren:{dependencyType:"child",childGroups:["inline"],variableNames:["text","latex"],variablesOptional:!0}}),definition:function({dependencyValues:e}){let t=[];for(let n of e.inlineChildren)"object"!=typeof n?t.push(n.toString()):"string"==typeof n.stateValues.latex?t.push(n.stateValues.latex):"string"==typeof n.stateValues.text?t.push(n.stateValues.text):t.push("");return{setValue:{latex:t.join(", ")}}}},e}}function normalizeIndex(e){if(null!==e&&""!==e){if(Number.isFinite(Number(e)))return Number(e)-1;if("string"==typeof e)return lettersToNumber(e)}}function lettersToNumber(e){let t=0,n=(e=e.toUpperCase()).length,r=n;for(;(r-=1)>-1;){let a=e.charCodeAt(r)-64;if(a<1||a>26)return void console.warn("Cannot convert "+e+" to a number");t+=a*Math.pow(26,n-1-r)}return t--,t} /** * @license * Copyright (c) 2022 Handsoncode. All rights reserved. diff --git a/src/Viewer/renderers/graph.jsx b/src/Viewer/renderers/graph.jsx index 5ce030ff10..a85c170db0 100644 --- a/src/Viewer/renderers/graph.jsx +++ b/src/Viewer/renderers/graph.jsx @@ -148,7 +148,11 @@ export default React.memo(function Graph(props) { outerStyle = { display: "flex", justifyContent: SVs.horizontalAlign }; } - divStyle.border = "2px solid var(--canvastext)"; + if (SVs.showBorder) { + divStyle.border = "2px solid var(--canvastext)"; + } else { + divStyle.border = "none"; + } divStyle.marginBottom = "12px"; divStyle.marginTop = "12px"; divStyle.backgroundColor = "var(--canvas)";