@algorisys/tinyfly 0.120.0 → 0.121.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
- (function($){"use strict";function qi(t){return typeof t=="object"&&t!==null&&t.type==="cubic-bezier"}function zi(t){return typeof t=="object"&&t!==null&&t.type!=="cubic-bezier"}const We=2;function ji(t){return t.some(e=>e.interpolation!==void 0)?2:1}function Yn(t){return t.property==="text"&&"textConfig"in t}function Ge(t){return t.kind==="inertia"&&"inertia"in t}function Ze(t){return t.kind==="spring"&&"spring"in t}function Xi(t){return t.property==="motionPath"&&"motionPathConfig"in t}function Yi(t,e){if(!(e>0))return t;const n=1e3/e;return Math.floor(t/n+1e-9)*n}function Bn(t,e,n="start"){if(e<=1)return 0;if(typeof n=="number"){const s=Math.max(0,Math.min(e-1,n));return Math.abs(t-s)}switch(n){case"end":return e-1-t;case"center":return Math.abs(t-(e-1)/2);case"edges":return(e-1)/2-Math.abs(t-(e-1)/2);default:return t}}function Bi(t,e="start"){if(t<=1)return 0;let n=0;for(let s=0;s<t;s++)n=Math.max(n,Bn(s,t,e));return n}function Vn(t,e,n){if(n.offsets)return n.offsets[t]??0;const s=n.from??"start",i=Bn(t,e,s);if(n.amount!==void 0){const r=Bi(e,s);return r===0?0:n.amount*i/r}return n.each!==void 0?n.each*i:0}function Vi(t,e){return Array.from({length:t},(n,s)=>Vn(s,t,e))}function Qe(t,e){return t<=1?0:Math.max(...Vi(t,e))}const Yt=1,Hn=6e4,ye=Hn/Yt,Tt={stiffness:180,damping:12,mass:1,velocity:0,restDelta:.01,restSpeed:.1};class Hi{from;to;stiffness;damping;mass;restDelta;restSpeed;distance;samples;velocity;settledStep=null;constructor(e){this.from=e.from,this.to=e.to,this.stiffness=e.stiffness??Tt.stiffness,this.damping=e.damping??Tt.damping,this.mass=e.mass??Tt.mass,this.restDelta=e.restDelta??Tt.restDelta,this.restSpeed=e.restSpeed??Tt.restSpeed,this.distance=Math.abs(this.to-this.from)||1,this.samples=[this.from],this.velocity=e.velocity??Tt.velocity,this.isAtRest(this.from)&&(this.settledStep=0)}isAtRest(e){return Math.abs(e-this.to)<this.restDelta*this.distance&&Math.abs(this.velocity)<this.restSpeed*this.distance}valueAt(e){if(e<=0)return this.from;const n=Math.floor(e/Yt);if(this.simulateTo(n+1),this.settledStep!==null&&n>=this.settledStep)return this.to;const s=this.samples[Math.min(n,this.samples.length-1)],i=this.samples[Math.min(n+1,this.samples.length-1)],r=e/Yt-n;return s+(i-s)*r}settleTime(){return this.simulateTo(ye+1),this.settledStep!==null?this.settledStep*Yt:Hn}simulateTo(e){if(this.settledStep!==null)return;const n=Math.min(e,ye+1),s=Yt/1e3;for(;this.samples.length<n;){const i=this.samples[this.samples.length-1],r=i-this.to,o=-this.stiffness*r,c=-this.damping*this.velocity,l=(o+c)/this.mass;this.velocity+=l*s;const u=i+this.velocity*s;if(this.samples.push(u),this.isAtRest(u)){this.settledStep=this.samples.length-1;return}}this.samples.length>ye&&(this.settledStep=ye)}}const Un=4,Ui=.002,Wi=1e-4,Gi=6e4;function Ke(t){const e=t.friction??Un;return e>0?e:Un}function Zi(t){return t.from+t.velocity/Ke(t)}function Qi(t,e){if(e===void 0)return t;if(typeof e=="number")return e>0?Math.round(t/e)*e:t;if(e.length===0)return t;let n=e[0];for(const s of e)Math.abs(s-t)<Math.abs(n-t)&&(n=s);return n}function Wn(t){let e=Qi(Zi(t),t.end);return t.min!==void 0&&(e=Math.max(t.min,e)),t.max!==void 0&&(e=Math.min(t.max,e)),e}function Gn(t){const e=Math.abs(Wn(t)-t.from);if(e===0)return 0;const n=t.restDelta??Math.max(Wi,e*Ui);if(n>=e)return 0;const s=Math.log(e/n)/Ke(t);return Math.min(Gi,s*1e3)}function Zn(t,e){if(e<=0)return t.from;const n=Wn(t);if(e>=Gn(t))return n;const s=Ke(t);return t.from+(n-t.from)*(1-Math.exp(-s*e/1e3))}const Je=t=>t,Ki=t=>t*t,Ji=t=>1-(1-t)*(1-t),tr=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2,Qn=t=>t*t*t,Kn=t=>1-Math.pow(1-t,3),Jn=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,er={linear:Je,"ease-in":Qn,"ease-out":Kn,"ease-in-out":Jn,"ease-in-quad":Ki,"ease-out-quad":Ji,"ease-in-out-quad":tr,"ease-in-cubic":Qn,"ease-out-cubic":Kn,"ease-in-out-cubic":Jn};function nr(t){const[e,n,s,i]=t,r=3*e,o=3*(s-e)-r,c=1-r-o,l=3*n,u=3*(i-n)-l,h=1-l-u,d=p=>((c*p+o)*p+r)*p,f=p=>((h*p+u)*p+l)*p,y=p=>(3*c*p+2*o)*p+r,g=p=>{let a=p;for(let S=0;S<8;S++){const v=d(a)-p;if(Math.abs(v)<1e-7)return a;const w=y(a);if(Math.abs(w)<1e-7)break;a-=v/w}let m=0,b=1;for(a=p;m<b;){const S=d(a);if(Math.abs(S-p)<1e-7)return a;p>S?m=a:b=a,a=(m+b)/2}return a};return p=>{if(p<=0)return 0;if(p>=1)return 1;const a=g(p);return f(a)}}function tn(t,e="out"){if(e==="out")return t;const n=s=>1-t(1-s);return e==="in"?n:s=>s<.5?n(s*2)/2:t(s*2-1)/2+.5}function sr(t=1,e=.3){const n=Math.max(1,t),s=e/(2*Math.PI)*Math.asin(1/n);return i=>i<=0?0:i>=1?1:n*Math.pow(2,-10*i)*Math.sin((i-s)*(2*Math.PI)/e)+1}const ir=t=>{if(t<=0)return 0;if(t>=1)return 1;if(t<1/2.75)return 7.5625*t*t;if(t<2/2.75){const i=t-.5454545454545454;return 7.5625*i*i+.75}if(t<2.5/2.75){const i=t-.8181818181818182;return 7.5625*i*i+.9375}const s=t-2.625/2.75;return 7.5625*s*s+.984375};function rr(t=1.70158){return e=>{if(e<=0)return 0;if(e>=1)return 1;const n=e-1;return n*n*((t+1)*n+t)+1}}function or(t,e="end"){const n=Math.max(1,Math.floor(t));return s=>{if(s>=1)return 1;if(s<=0)return e==="start"||e==="both"?e==="start"?1/n:1/(n+1):0;const i=Math.floor(s*n);switch(e){case"start":return Math.min(1,(i+1)/n);case"both":return(i+1)/(n+1);case"none":return n===1?0:Math.min(1,i/(n-1));default:return i/n}}}function ar(t){switch(t.type){case"steps":return or(t.count,t.position);case"elastic":return tn(sr(t.amplitude,t.period),t.mode);case"bounce":return tn(ir,t.mode);case"back":return tn(rr(t.overshoot),t.mode)}}function cr(t){return t===void 0?Je:qi(t)?nr(t.points):zi(t)?ar(t):er[t]??Je}const ts=32,lr=256,Bt=new Map,ur=/[MmLlHhVvCcSsQqTtAaZz]/,hr=/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/,dr={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0};function fr(t){const e=[];let n=0,s=null;const i=()=>{for(;n<t.length&&/[\s,]/.test(t[n]);)n++};for(;n<t.length&&(i(),!(n>=t.length));){const r=t[n];if(ur.test(r)){s={type:r,args:[]},e.push(s),n++;continue}if(!s)break;const o=s.type==="A"||s.type==="a",c=s.args.length%7;if(o&&(c===3||c===4)){if(r!=="0"&&r!=="1")break;s.args.push(r==="1"?1:0),n++;continue}const l=hr.exec(t.slice(n));if(!l)break;s.args.push(parseFloat(l[0])),n+=l[0].length}return e}function pr(t,e,n,s,i,r,o,c,l){if(t===c&&e===l)return[];let u=Math.abs(n),h=Math.abs(s);if(u===0||h===0)return[[t,e,c,l,c,l]];const d=i*Math.PI/180,f=Math.cos(d),y=Math.sin(d),g=(t-c)/2,p=(e-l)/2,a=f*g+y*p,m=-y*g+f*p,b=a*a/(u*u)+m*m/(h*h);if(b>1){const q=Math.sqrt(b);u*=q,h*=q}const S=r===o?-1:1,v=u*u*h*h-u*u*m*m-h*h*a*a,w=u*u*m*m+h*h*a*a,k=S*Math.sqrt(Math.max(0,v/w)),x=k*u*m/h,M=-k*h*a/u,E=f*x-y*M+(t+c)/2,A=y*x+f*M+(e+l)/2,_=(q,H,tt,Xt)=>{const Xn=q*tt+H*Xt,Ue=Math.sqrt((q*q+H*H)*(tt*tt+Xt*Xt)),ge=Math.acos(Math.max(-1,Math.min(1,Xn/Ue)));return q*Xt-H*tt<0?-ge:ge},T=_(1,0,(a-x)/u,(m-M)/h);let C=_((a-x)/u,(m-M)/h,(-a-x)/u,(-m-M)/h);!o&&C>0&&(C-=2*Math.PI),o&&C<0&&(C+=2*Math.PI);const N=Math.max(1,Math.ceil(Math.abs(C)/(Math.PI/2))),P=C/N,F=4/3*Math.tan(P/4),L=q=>{const H=u*Math.cos(q),tt=h*Math.sin(q);return[f*H-y*tt+E,y*H+f*tt+A]},B=q=>{const H=-u*Math.sin(q),tt=h*Math.cos(q);return[f*H-y*tt,y*H+f*tt]},z=[];for(let q=0;q<N;q++){const H=T+q*P,tt=H+P,[Xt,Xn]=L(H),[Ue,ge]=q===N-1?[c,l]:L(tt),[Wc,Gc]=B(H),[Zc,Qc]=B(tt);z.push([Xt+F*Wc,Xn+F*Gc,Ue-F*Zc,ge-F*Qc,Ue,ge])}return z}function gt(t,e,n,s,i){const r=1-i;return r*r*r*t+3*r*r*i*e+3*r*i*i*n+i*i*i*s}function es(t,e,n,s,i){const r=1-i;return 3*r*r*(e-t)+6*r*i*(n-e)+3*i*i*(s-n)}function Vt(t,e,n,s){return{subpath:0,type:"L",points:[n,s],startX:t,startY:e,endX:n,endY:s,length:Math.hypot(n-t,s-e)}}function me(t,e,n){const[s,i,r,o,c,l]=n,u=[0];let h=t,d=e,f=0;for(let y=1;y<=ts;y++){const g=y/ts,p=gt(t,s,r,c,g),a=gt(e,i,o,l,g);f+=Math.hypot(p-h,a-d),u.push(f),h=p,d=a}return{subpath:0,type:"C",points:[s,i,r,o,c,l],startX:t,startY:e,endX:c,endY:l,length:f,lengths:u}}function be(t){const e=Bt.get(t);if(e)return e;const n=[];let s=0,i=0,r=0,o=0,c=null,l=null,u=-1;const h=new Set,d=p=>{u<0&&(u=0),p.subpath=u,n.push(p)};for(const{type:p,args:a}of fr(t)){const m=p.toUpperCase(),b=p!==m,S=dr[m];if(m==="Z"){(s!==r||i!==o)&&d(Vt(s,i,r,o)),u>=0&&h.add(u),s=r,i=o,c=l=null;continue}for(let v=0;v+S<=a.length;v+=S){const w=a.slice(v,v+S),k=b?s:0,x=b?i:0;let M=null,E=null;switch(m){case"M":v===0?(s=w[0]+k,i=w[1]+x,r=s,o=i,(u<0||n[n.length-1]?.subpath===u)&&u++):(d(Vt(s,i,w[0]+k,w[1]+x)),s=w[0]+k,i=w[1]+x);break;case"L":d(Vt(s,i,w[0]+k,w[1]+x)),s=w[0]+k,i=w[1]+x;break;case"H":d(Vt(s,i,w[0]+k,i)),s=w[0]+k;break;case"V":d(Vt(s,i,s,w[0]+x)),i=w[0]+x;break;case"C":{const A=[w[0]+k,w[1]+x,w[2]+k,w[3]+x,w[4]+k,w[5]+x];d(me(s,i,A)),M=[A[2],A[3]],s=A[4],i=A[5];break}case"S":{const[A,_]=c?[2*s-c[0],2*i-c[1]]:[s,i],T=[A,_,w[0]+k,w[1]+x,w[2]+k,w[3]+x];d(me(s,i,T)),M=[T[2],T[3]],s=T[4],i=T[5];break}case"Q":case"T":{let A=s,_=i;m==="Q"?(A=w[0]+k,_=w[1]+x):l&&(A=2*s-l[0],_=2*i-l[1]);const T=m==="Q"?w[2]+k:w[0]+k,C=m==="Q"?w[3]+x:w[1]+x;d(me(s,i,[s+2/3*(A-s),i+2/3*(_-i),T+2/3*(A-T),C+2/3*(_-C),T,C])),E=[A,_],s=T,i=C;break}case"A":{const A=w[5]+k,_=w[6]+x;let T=s,C=i;for(const N of pr(s,i,w[0],w[1],w[2],w[3],w[4],A,_))d(me(T,C,N)),T=N[4],C=N[5];s=A,i=_;break}}c=M,l=E}}const f=n.reduce((p,a)=>p+a.length,0),y=[];for(let p=0;p<n.length;){const a=n[p].subpath;let m=p,b=0;for(;m<n.length&&n[m].subpath===a;)b+=n[m++].length;const S=n[p],v=n[m-1],w=h.has(a)||Math.abs(v.endX-S.startX)<1e-9&&Math.abs(v.endY-S.startY)<1e-9;y.push({start:p,end:m,length:b,closed:w}),p=m}const g={segments:n,totalLength:f,subpaths:y};return Bt.size>=lr&&Bt.delete(Bt.keys().next().value),Bt.set(t,g),g}function gr(t,e){const n=t.lengths;if(e<=0)return 0;if(e>=t.length)return 1;let s=0,i=n.length-1;for(;s<i-1;){const c=s+i>>1;n[c]<e?s=c:i=c}const r=n[i]-n[s],o=r>0?(e-n[s])/r:0;return(s+o)/(n.length-1)}function yr(t,e){if(t.type==="L"){const d=t.length>0?Math.max(0,Math.min(1,e/t.length)):0;return{x:t.startX+(t.endX-t.startX)*d,y:t.startY+(t.endY-t.startY)*d,angle:Math.atan2(t.endY-t.startY,t.endX-t.startX)*180/Math.PI}}const[n,s,i,r,o,c]=t.points,l=gr(t,e);let u=es(t.startX,n,i,o,l),h=es(t.startY,s,r,c,l);if(Math.hypot(u,h)<1e-9){const d=l<.5?Math.min(1,l+.001):Math.max(0,l-.001),f=gt(t.startX,n,i,o,d),y=gt(t.startY,s,r,c,d),g=gt(t.startX,n,i,o,l),p=gt(t.startY,s,r,c,l);u=l<.5?f-g:g-f,h=l<.5?y-p:p-y}return{x:gt(t.startX,n,i,o,l),y:gt(t.startY,s,r,c,l),angle:Math.atan2(h,u)*180/Math.PI}}function ns(t,e,n=0,s=t.length){if(s<=n)return{x:0,y:0,angle:0};let i=0;for(let r=n;r<s;r++){const o=t[r];if(i+o.length>=e||r===s-1)return yr(o,e-i);i+=o.length}return{x:0,y:0,angle:0}}function mr(t,e){const{segments:n,totalLength:s}=be(t);return ns(n,Math.max(0,Math.min(1,e))*s)}const br=24,wr=320,vr=2.5,Ht=72,kr=.2,Mr=128,we=new Map;let en=0,mt;const ss=t=>Math.round(t*100)/100;function is(t,e){const{segments:n,subpaths:s,totalLength:i}=be(t);if(n.length===0)return[];if(e){const r=s.every(o=>o.closed);return[{segments:n,start:0,end:n.length,length:i,closed:r}]}return s.filter(r=>r.length>0).map(r=>({segments:n,start:r.start,end:r.end,length:r.length,closed:r.closed}))}function nn(t,e){const n=t.closed?(e%1+1)%1:Math.max(0,Math.min(1,e)),s=ns(t.segments,n*t.length,t.start,t.end);return[s.x,s.y]}function rs(t){const e=[];let n=0;for(let s=t.start;s<t.end;s++)n+=t.segments[s].length,t.length>0&&e.push(n/t.length);return e}function os(t,e){const n=[];for(let s=0;s<e;s++)n.push(nn(t,t.closed?s/e:s/(e-1)));return n}function as(t){let e=0,n=0;for(const[s,i]of t)e+=s,n+=i;return e/=t.length,n/=t.length,t.map(([s,i])=>[s-e,i-n])}function $r(t,e,n){const s=t.closed&&e.closed;if(n!==void 0)return{offset:s?Math.abs(n)%Ht/Ht:0,reversed:n<0};const i=as(os(t,Ht)),r=as(os(e,Ht)),o=Ht;let c={offset:0,reversed:!1},l=1/0;for(const u of[!1,!0]){const h=s?o:1;for(let d=0;d<h;d++){let f=0;for(let y=0;y<o&&f<l;y++){const g=s?u?(d-y+o)%o:(y+d)%o:u?o-1-y:y,p=i[y][0]-r[g][0],a=i[y][1]-r[g][1];f+=p*p+a*a}f<l&&(l=f,c={offset:s?d/o:0,reversed:u})}}return c}function Sr(t,e,n){return n?((e.reversed?e.offset-t:t+e.offset)%1+1)%1:e.reversed?1-t:t}function xr(t,e,n){return n?((e.reversed?e.offset-t:t-e.offset)%1+1)%1:e.reversed?1-t:t}function Ar(t,e,n){const s=t.closed&&e.closed,i=$r(t,e,n.shapeIndex),r=Math.max(br,Math.min(wr,Math.ceil(Math.max(t.length,e.length)/vr))),o=new Set,c=d=>o.add(Math.round(d*1e7)/1e7);for(let d=0;d<=r;d++)c(d/r);for(const d of rs(t))c(d);for(const d of rs(e))c(xr(d,i,s));let l=[...o].sort((d,f)=>d-f);s&&(l=l.filter(d=>d<1));const u=[],h=[];for(const d of l)u.push(...nn(t,d)),h.push(...nn(e,Sr(d,i,s)));return Er({from:u,to:h,closed:s})}function Er(t){const e=t.from.length/2;if(e<=3)return t;const n=new Uint8Array(e);n[0]=1,n[e-1]=1;const s=[[0,e-1]];for(;s.length>0;){const[o,c]=s.pop();let l=-1,u=kr;for(let h=o+1;h<c;h++){const d=Math.max(cs(t.from,o,c,h),cs(t.to,o,c,h));d>u&&(u=d,l=h)}l!==-1&&(n[l]=1,s.push([o,l],[l,c]))}const i=[],r=[];for(let o=0;o<e;o++)n[o]&&(i.push(t.from[o*2],t.from[o*2+1]),r.push(t.to[o*2],t.to[o*2+1]));return{from:i,to:r,closed:t.closed}}function cs(t,e,n,s){const i=t[e*2],r=t[e*2+1],o=t[n*2]-i,c=t[n*2+1]-r,l=t[s*2]-i,u=t[s*2+1]-r,h=o*o+c*c,d=h===0?0:Math.max(0,Math.min(1,(l*o+u*c)/h));return Math.hypot(l-d*o,u-d*c)}function Tr(t,e,n){const s=n.shapeIndex;if(mt&&mt.from===t&&mt.to===e&&mt.shapeIndex===s)return mt.plan;const r=we.get(String(s??"auto"))?.get(t)?.get(e);if(r)return mt={from:t,to:e,shapeIndex:s,plan:r},r;const o=be(t).subpaths.filter(y=>y.length>0).length===be(e).subpaths.filter(y=>y.length>0).length,c=is(t,!o),l=is(e,!o),u={pairs:c.map((y,g)=>Ar(y,l[g],n))};en>=Mr&&(we.clear(),en=0);const h=String(s??"auto"),d=we.get(h)??new Map;we.set(h,d);const f=d.get(t)??new Map;return d.set(t,f),f.set(e,u),en++,mt={from:t,to:e,shapeIndex:s,plan:u},u}function _r(t,e,n,s={}){if(!t)return e;if(!e)return t;const i=Math.max(0,Math.min(1,n));if(i===0)return t;if(i===1)return e;const r=Tr(t,e,s);if(r.pairs.length===0)return i<.5?t:e;let o="";for(const c of r.pairs){for(let l=0;l<c.from.length;l+=2){const u=ss(c.from[l]+(c.to[l]-c.from[l])*i),h=ss(c.from[l+1]+(c.to[l+1]-c.from[l+1])*i);o+=`${l===0?o?" M":"M":" L"}${u} ${h}`}c.closed&&(o+=" Z")}return o}function Pr(t){return/^\s*[Mm]\s*[-+]?(?:\d|\.\d)/.test(t)}const Or=.9995;function Ir(){return[0,0,0,1]}function Cr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Nr(t){return Math.hypot(t[0],t[1],t[2],t[3])}function Ut(t){const e=Nr(t);return e===0?Ir():[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function Fr(t,e,n){const s=Ut(t);let i=Ut(e),r=Cr(s,i);if(r<0&&(i=[-i[0],-i[1],-i[2],-i[3]],r=-r),r>Or)return Ut([s[0]+(i[0]-s[0])*n,s[1]+(i[1]-s[1])*n,s[2]+(i[2]-s[2])*n,s[3]+(i[3]-s[3])*n]);const o=Math.acos(r),c=Math.sin(o),l=Math.sin((1-n)*o)/c,u=Math.sin(n*o)/c;return Ut([s[0]*l+i[0]*u,s[1]*l+i[1]*u,s[2]*l+i[2]*u,s[3]*l+i[3]*u])}const dt=(t,e,n)=>t+(e-t)*n,ls=512,sn=new Map,rn=new Map;function us(t){const e=sn.get(t);if(e)return e;const n=t.replace("#",""),s=[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)];return sn.size<ls&&sn.set(t,s),s}const hs=t=>t.charCodeAt(0)===35,ds=t=>t.startsWith("rgb"),fs=t=>t.startsWith("rgba"),Lr=/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/,on=t=>Math.round(t).toString(16).padStart(2,"0");function Rr(t,e,n){return`#${on(t)}${on(e)}${on(n)}`}function ps(t){const e=rn.get(t);if(e)return e;const n=t.match(Lr);if(!n)throw new Error(`Invalid rgb color: ${t}`);const s=parseInt(n[1],10),i=parseInt(n[2],10),r=parseInt(n[3],10),o=n[4]!==void 0?[s,i,r,parseFloat(n[4])]:[s,i,r];return rn.size<ls&&rn.set(t,o),o}const Dr=(t,e,n)=>{if(hs(t)&&hs(e)){const[s,i,r]=us(t),[o,c,l]=us(e),u=dt(s,o,n),h=dt(i,c,n),d=dt(r,l,n);return Rr(u,h,d)}if((ds(t)||fs(t))&&(ds(e)||fs(e))){const s=ps(t),i=ps(e),r=Math.round(dt(s[0],i[0],n)),o=Math.round(dt(s[1],i[1],n)),c=Math.round(dt(s[2],i[2],n));if(s.length===4||i.length===4){const l=s[3]??1,u=i[3]??1,h=dt(l,u,n);return`rgba(${r}, ${o}, ${c}, ${h})`}return`rgb(${r}, ${o}, ${c})`}return n<1?t:e},qr=(t,e,n)=>{const s=Math.min(t.length,e.length),i=[];for(let r=0;r<s;r++)i.push(dt(t[r],e[r],n));return i},zr=(t,e,n)=>Fr(t,e,n),gs=(t,e,n)=>n<1?t:e,jr=(t,e,n)=>_r(t,e,n);function Xr(t,e){return e==="slerp"?zr:typeof t=="number"?dt:Array.isArray(t)?qr:typeof t=="string"?t.startsWith("#")||t.startsWith("rgb")?Dr:Pr(t)?jr:gs:gs}function Yr(t){const e=[...t.keyframes].sort((n,s)=>n.time-s.time);return{...t,keyframes:e}}function bt(t){return t.targets&&t.targets.length>0?t.targets:[t.target]}function _t(t,e,n,s){const i=n??0;return!s||e<=1?i:i+Vn(t,e,s)}class an{track;targets;constructor(e){this.track=e,this.targets=bt(e)}getValueAtTime(e){return this.valueForOffset(e-_t(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const r=_t(i,n,this.track.delay,this.track.stagger),o=this.valueForOffset(e-r);o!==void 0&&s.push({target:this.targets[i],value:o,start:r+this.track.keyframes[0].time})}return s}getDuration(){const{keyframes:e}=this.track;if(e.length===0)return 0;const n=e[e.length-1].time,s=this.track.stagger?Qe(this.targets.length,this.track.stagger):0;return n+(this.track.delay??0)+s+(this.track.endDelay??0)}getTrack(){return this.track}valueForOffset(e){const{keyframes:n}=this.track;if(n.length===0)return;if(n.length===1||e<=n[0].time)return n[0].value;if(e>=n[n.length-1].time)return n[n.length-1].value;const{from:s,to:i}=this.findSurroundingKeyframes(e);if(!s||!i)return;if(s.time===e)return s.value;const r=i.time-s.time,o=(e-s.time)/r,l=cr(i.easing)(o);return Xr(s.value,this.track.interpolation)(s.value,i.value,l)}findSurroundingKeyframes(e){const{keyframes:n}=this.track;for(let s=0;s<n.length-1;s++)if(e>=n[s].time&&e<=n[s+1].time)return{from:n[s],to:n[s+1]};return{from:null,to:null}}}class Br{track;targets;sampler;constructor(e){this.track=e,this.targets=bt(e),this.sampler=new Hi(e.spring)}getValueAtTime(e){return this.sampler.valueAt(e-_t(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const r=_t(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:this.sampler.valueAt(e-r),start:r})}return s}getDuration(){const e=this.track.stagger?Qe(this.targets.length,this.track.stagger):0;return this.sampler.settleTime()+(this.track.delay??0)+e}getTrack(){return this.track}}class Vr{track;targets;duration;constructor(e){this.track=e,this.targets=bt(e),this.duration=Gn(e.inertia)}getValueAtTime(e){return Zn(this.track.inertia,e-_t(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const r=_t(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:Zn(this.track.inertia,e-r),start:r})}return s}getDuration(){const e=this.track.stagger?Qe(this.targets.length,this.track.stagger):0;return this.duration+(this.track.delay??0)+e}getTrack(){return this.track}}function Hr(t,e){const n={...mr(t.pathData,e)};if(t.matrix){const[s,i,r,o,c,l]=t.matrix,{x:u,y:h}=n;n.x=s*u+r*h+c,n.y=i*u+o*h+l;const d=n.angle*Math.PI/180,f=Math.cos(d),y=Math.sin(d);n.angle=Math.atan2(i*f+o*y,s*f+r*y)*180/Math.PI}return t.autoRotate&&t.rotateOffset&&(n.angle+=t.rotateOffset),n}const cn={upperCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",lowerCase:"abcdefghijklmnopqrstuvwxyz",upperAndLowerCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",numbers:"0123456789"},Ur=20;function Wr(t){const e=cn[t??"upperCase"]??t??cn.upperCase,n=Array.from(e);return n.length>0?n:Array.from(cn.upperCase)}function Gr(t,e,n){let s=(t|0)^Math.imul(e+1,2654435761)^Math.imul(n+1,2246822507);return s=Math.imul(s^s>>>16,2146121005),s=Math.imul(s^s>>>15,2221713035),(s^s>>>16)>>>0}function Zr(t,e,n=0){const s=t.from??"",i=t.to,r=Math.max(0,Math.min(1,e));if(r<=0)return s;if(r>=1)return i;const o=Array.from(s),c=Array.from(i),l=t.rightToLeft??!1;if(t.mode==="type"){const b=Math.round(r*Math.max(o.length,c.length));return l?o.slice(0,Math.max(0,o.length-b)).join("")+c.slice(Math.max(0,c.length-b)).join(""):c.slice(0,b).join("")+o.slice(b).join("")}const u=Math.max(0,Math.min(.999,t.revealDelay??0)),h=Math.max(0,(r-u)/(1-u)),d=Math.floor(h*c.length),f=t.tweenLength===!1?c.length:Math.round(o.length+(c.length-o.length)*r),y=Wr(t.chars),g=t.refreshRate??Ur,p=g>0?Math.floor(n*g/1e3):0,a=t.seed??1;let m="";for(let b=0;b<f;b++){const S=l?b>=f-d:b<d,v=l?c[c.length-(f-b)]:c[b];S&&v!==void 0||v===" "||v===`
2
- `?m+=v:m+=y[Gr(a,b,p)%y.length]}return m}class Qr{id;name;_captions;_tracks=[];_trackPlayers=new Map;_motionPathTracks=new Map;_springTracks=new Map;_textTracks=new Map;_config;_currentTime=0;_playbackState="idle";_direction="forward";_loopIteration=0;_explicitDuration;_repeatDelayRemaining=0;_wrapAfterDelay=!1;onUpdate=null;onComplete=null;constructor(e){if(this.id=e.id,this.name=e.name,this._captions=e.captions,this._config=e.config??{},this._explicitDuration=e.config?.duration,e.tracks)for(const n of e.tracks)this.addTrack(n)}get tracks(){return[...this._tracks]}get duration(){return this._explicitDuration!==void 0?this._explicitDuration:this._calculateDuration()}setDuration(e){if(this._explicitDuration=e,e!==void 0)this._config={...this._config,duration:e};else if(this._config.duration!==void 0){const n={...this._config};delete n.duration,this._config=n}}get currentTime(){return this._currentTime}get playbackState(){return this._playbackState}get direction(){return this._direction}get loopIteration(){return this._loopIteration}get repeatDelayRemaining(){return this._repeatDelayRemaining}get speed(){return this._config.speed??1}set speed(e){this._config.speed=e}get drawingRate(){return this._config.drawingRate??0}set drawingRate(e){const n={...this._config};e>0?n.drawingRate=e:delete n.drawingRate,this._config=n}play(){const e=this.duration;this._direction==="forward"&&this._currentTime>=e&&e>0?(this._currentTime=0,this._loopIteration=0):this._direction==="reverse"&&this._currentTime<=0&&e>0&&(this._currentTime=e,this._loopIteration=0),this._playbackState="playing"}pause(){this._playbackState="paused"}stop(){this._playbackState="idle",this._repeatDelayRemaining=0,this._wrapAfterDelay=!1,this._currentTime=0,this._loopIteration=0,this._direction="forward"}seek(e){const n=this.duration>0?this.duration:1/0;this._currentTime=Math.max(0,Math.min(e,n)),this._repeatDelayRemaining=0,this._wrapAfterDelay=!1}reverse(){this._direction=this._direction==="forward"?"reverse":"forward"}tick(e){if(this._playbackState!=="playing")return;const n=this.duration;if(n<=0)return;let i=e*this.speed;if(this._repeatDelayRemaining>0){const c=Math.min(this._repeatDelayRemaining,i);if(this._repeatDelayRemaining-=c,i-=c,this._repeatDelayRemaining>0){this.onUpdate?.(this.getStateAtTime(this._currentTime));return}this._wrapAfterDelay&&(this._wrapAfterDelay=!1,this._currentTime=0)}const r=1e3;for(let c=0;c<r&&i>0&&this._playbackState==="playing";c++)if(this._direction==="forward"){const l=n-this._currentTime;if(i>=l){if(i-=l,this._currentTime=n,!this._handleEndReached())break}else this._currentTime+=i,i=0}else{const l=this._currentTime;if(i>=l){if(i-=l,this._currentTime=0,!this._handleStartReached())break}else this._currentTime-=i,i=0}const o=this.getStateAtTime(this._currentTime);this.onUpdate?.(o)}getStateAtTime(e){const n=new Map;if(e=Yi(e,this._config.drawingRate??0),this._hasSharedWrites())this._resolveShared(e,n);else for(const[s,i]of this._trackPlayers){const r=i.getTrack().property;for(const{target:o,value:c,start:l}of i.getTargetValues(e))this._write(n,s,o,r,c,e-l)}return{values:n,currentTime:this._currentTime,playbackState:this._playbackState,direction:this._direction,loopIteration:this._loopIteration}}_resolveShared(e,n){const s=new Map;for(const[i,r]of this._trackPlayers){const o=r.getTrack().property;for(const{target:c,value:l,start:u}of r.getTargetValues(e)){const h=`${c}\0${o}`,d=u<=e,f=s.get(h);(!f||(d!==f.started?d:d?u>=f.start:u<=f.start))&&s.set(h,{trackId:i,target:c,property:o,value:l,start:u,started:d})}}for(const{trackId:i,target:r,property:o,value:c,start:l}of s.values())this._write(n,i,r,o,c,e-l)}_write(e,n,s,i,r,o){if(r===void 0)return;let c=e.get(s);c||(c=new Map,e.set(s,c));const l=this._textTracks.get(n);if(l&&typeof r=="number"){c.set("text",Zr(l.textConfig,r,Math.max(0,o)));return}const u=this._motionPathTracks.get(n);if(u&&typeof r=="number"){const h=Hr(u.motionPathConfig,r);c.set("motionPathX",h.x),c.set("motionPathY",h.y),u.motionPathConfig.autoRotate&&c.set("motionPathRotate",h.angle)}else c.set(i,r)}_sharedWrites=null;_hasSharedWrites(){if(this._sharedWrites===null){const e=new Set;this._sharedWrites=!1;t:for(const n of this._tracks)for(const s of bt(n)){const i=`${s}\0${n.property}`;if(e.has(i)){this._sharedWrites=!0;break t}e.add(i)}}return this._sharedWrites}addTrack(e){if(this._tracks.push(e),this._sharedWrites=null,Ge(e)){this._trackPlayers.set(e.id,new Vr(e));return}if(Ze(e)){this._trackPlayers.set(e.id,new Br(e)),this._springTracks.set(e.id,e);return}if(Yn(e))this._trackPlayers.set(e.id,new an(e)),this._textTracks.set(e.id,e);else if(Xi(e)){const n={id:e.id,target:e.target,property:e.property,keyframes:e.keyframes,delay:e.delay,endDelay:e.endDelay,targets:e.targets,stagger:e.stagger};this._trackPlayers.set(e.id,new an(n)),this._motionPathTracks.set(e.id,e)}else this._trackPlayers.set(e.id,new an(e))}replaceTrack(e,n){const s=this._tracks.findIndex(r=>r.id===e);if(s<0)return;const i=this._tracks.slice(s+1);this.removeTrack(e);for(const r of i)this.removeTrack(r.id);this.addTrack(n);for(const r of i)this.addTrack(r)}removeTrack(e){this._tracks=this._tracks.filter(n=>n.id!==e),this._sharedWrites=null,this._trackPlayers.delete(e),this._motionPathTracks.delete(e),this._springTracks.delete(e),this._textTracks.delete(e)}getTracks(e={}){return this._tracks.filter(n=>this._matches(n,e))}removeTracks(e={}){const n=this.getTracks(e).map(s=>s.id);for(const s of n)this.removeTrack(s);return n}getTrackSpan(e){const n=this._trackPlayers.get(e);if(!n)return;const s=n.getTrack(),i=s.delay??0;if(Ze(s)||Ge(s))return{from:i,to:n.getDuration()};const r=s.keyframes;if(!(!r||r.length===0))return{from:r[0].time+i,to:n.getDuration()}}findConflicts(){const e=[];for(let n=0;n<this._tracks.length;n++){const s=this._tracks[n],i=this.getTrackSpan(s.id);if(i)for(let r=0;r<n;r++){const o=this._tracks[r];if(o.property!==s.property)continue;const c=bt(o).filter(d=>bt(s).includes(d));if(c.length===0)continue;const l=this.getTrackSpan(o.id);if(!l||!(l.from<=i.to&&i.from<=l.to))continue;const h=i.from>=l.from;for(const d of c)e.push({target:d,property:s.property,losingTrackId:h?o.id:s.id,winningTrackId:h?s.id:o.id})}}return e}_matches(e,n){if(n.id!==void 0&&e.id!==n.id||n.property!==void 0&&e.property!==n.property||n.target!==void 0&&!bt(e).includes(n.target))return!1;if(n.timeRange){const s=this.getTrackSpan(e.id);if(!s||s.to<n.timeRange.from||s.from>n.timeRange.to)return!1}return!0}toDefinition(){return{formatVersion:ji(this._tracks),id:this.id,name:this.name,config:{...this._config},tracks:[...this._tracks],...this.captions&&{captions:this.captions}}}get config(){return this._config}get markers(){return[...this._config.markers??[]].sort((e,n)=>e.time-n.time)}setMarkers(e){const n=e&&e.length>0?[...e].sort((i,r)=>i.time-r.time).map(i=>({...i})):void 0,s={...this._config};n?s.markers=n:delete s.markers,this._config=s}get captions(){return this._captions}setCaptions(e){const n={};for(const[s,i]of Object.entries(e??{}))n[s]={...i};this._captions=Object.keys(n).length>0?n:void 0}_armRepeatDelay(){this._repeatDelayRemaining=this._config.repeatDelay??0}_calculateDuration(){let e=0;for(const[,n]of this._trackPlayers)e=Math.max(e,n.getDuration());return e}_handleEndReached(){const e=this._config.loop??0;return e===-1||this._loopIteration<e?(this._loopIteration++,this._armRepeatDelay(),this._config.alternate?this._direction="reverse":this._repeatDelayRemaining>0?this._wrapAfterDelay=!0:this._currentTime=0,this._repeatDelayRemaining===0):(this._playbackState="idle",this.onComplete?.(),!1)}_handleStartReached(){const e=this._config.loop??0;return this._config.alternate&&(e===-1||this._loopIteration<e)?(this._loopIteration++,this._armRepeatDelay(),this._direction="forward",this._repeatDelayRemaining===0):(this._playbackState="idle",this.onComplete?.(),!1)}}const Kr=100;function Jr(t,e,n,s){const i=[],r=[],{duration:o,alternate:c}=s,l=(y,g,p,a)=>{r.push([y,g]);const m=[];t.forEach((b,S)=>{(p==="forward"?(a?b>=y:b>y)&&b<=g:(a?b<=y:b<y)&&b>=g)&&m.push(S)}),m.sort((b,S)=>(p==="forward"?t[b]-t[S]:t[S]-t[b])||b-S);for(const b of m)i.push({kind:"event",index:b,direction:p})};let u=e.time,h=e.direction,d=e.fresh===!0;const f=Math.min(Kr,Math.max(0,n.iteration-e.iteration));for(let y=0;y<f;y++){const g=h==="forward"?o:0;l(u,g,h,d),i.push({kind:"repeat"}),c?(h=h==="forward"?"reverse":"forward",u=g,d=!1):(u=h==="forward"?0:o,d=!0)}return f>0&&s.holding&&!c?{crossings:i,passes:r}:(l(u,n.time,h,d),{crossings:i,passes:r})}function to(t){return{...t,...Array.isArray(t.end)&&{end:[...t.end]}}}function Wt(t){const e=t.endDelay;return{...t.delay!==void 0&&{delay:t.delay},...e!==void 0&&{endDelay:e},...t.targets!==void 0&&{targets:[...t.targets]},...t.stagger!==void 0&&{stagger:{...t.stagger}}}}function eo(t){if(Ge(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"inertia",inertia:to(e.inertia),...Wt(e)}}if(Ze(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"spring",spring:{...e.spring},...Wt(e)}}if(Yn(t)){const e=t;return{id:e.id,target:e.target,property:"text",textConfig:{...e.textConfig},keyframes:[...e.keyframes].sort((n,s)=>n.time-s.time),...Wt(e)}}if(t.property==="motionPath"&&"motionPathConfig"in t){const e=t,n=[...e.keyframes].sort((s,i)=>s.time-i.time);return{id:e.id,target:e.target,property:"motionPath",motionPathConfig:{...e.motionPathConfig},keyframes:n,...Wt(e)}}return Yr({id:t.id,target:t.target,property:t.property,keyframes:t.keyframes,...t.interpolation!==void 0&&{interpolation:t.interpolation},...Wt(t)})}function ys(t){const e=t.formatVersion??1;if(e>We)throw new Error(`tinyfly: this animation uses format version ${e}, but this tinyfly reads up to version ${We}. Update tinyfly to play it.`);return new Qr({id:t.id,name:t.name,config:t.config,tracks:t.tracks.map(eo),captions:t.captions})}function wt(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0}function Pt(t){let e=t>>>0||2654435769;return{seed:t>>>0,next(){return e^=e<<13,e>>>=0,e^=e>>17,e^=e<<5,e>>>=0,e/4294967296}}}function vt(t,e=0,n=1){const s=1-t.next(),i=t.next();return e+n*Math.sqrt(-2*Math.log(s))*Math.cos(2*Math.PI*i)}function no(t,e){const n=t.toLowerCase(),s=e.toLowerCase();let i=Array.from({length:s.length+1},(r,o)=>o);for(let r=1;r<=n.length;r++){const o=[r];for(let c=1;c<=s.length;c++)o[c]=Math.min(i[c]+1,o[c-1]+1,i[c-1]+(n[r-1]===s[c-1]?0:1));i=o}return i[s.length]}function ms(t,e){const n=t.toLowerCase(),s=e.find(o=>o.toLowerCase().includes(n)||n.includes(o.toLowerCase()));if(s&&Math.min(t.length,s.length)>=3)return s;let i,r=1/0;for(const o of e){const c=no(t,o);c<r&&(r=c,i=o)}return i!==void 0&&r<=Math.max(2,Math.floor(t.length/3))?i:void 0}function j(t,e,n,s){const i=typeof e=="string"?ms(e,n):void 0;return`Unknown ${t} ${JSON.stringify(e)}${i?`: did you mean "${i}"?`:"."} Known: ${n.join(", ")}`}function so(t){const[e,n,s,i]=t;return[1-2*(n*n+s*s),2*(e*n+s*i),2*(e*s-n*i),0,2*(e*n-s*i),1-2*(e*e+s*s),2*(n*s+e*i),0,2*(e*s+n*i),2*(n*s-e*i),1-2*(e*e+n*n),0,0,0,0,1]}function io(t){return!Array.isArray(t)||t.length!==4?null:`matrix3d(${so(Ut(t)).map(n=>Math.round(n*1e6)/1e6+0).join(", ")})`}const ro=new Set(["blur","brightness","glow","glowColor","shadowX","shadowY","shadowBlur","shadowColor"]),oo="#ffffff",ao="rgba(0, 0, 0, 0.5)";function co(t){const e=[];if(t.blur!==void 0&&e.push(`blur(${Math.max(0,t.blur)}px)`),t.brightness!==void 0&&e.push(`brightness(${Math.max(0,t.brightness)})`),t.glow!==void 0&&e.push(`drop-shadow(0 0 ${Math.max(0,t.glow)}px ${t.glowColor??oo})`),t.shadowX!==void 0||t.shadowY!==void 0||t.shadowBlur!==void 0){const n=t.shadowX??0,s=t.shadowY??0,i=Math.max(0,t.shadowBlur??0);e.push(`drop-shadow(${n}px ${s}px ${i}px ${t.shadowColor??ao})`)}return e.length>0?e.join(" "):null}function lo(t,e){const n=t.childNodes.length===1?t.firstChild:null;if(n&&n.nodeType===3){const s=n;s.data!==e&&(s.data=e);return}t.textContent!==e&&(t.textContent=e)}function uo(t){if(!("ownerSVGElement"in t))return;const e=t.style;!e||e.transformBox||(e.transformBox="fill-box",e.transformOrigin||(e.transformOrigin="50% 50%"))}const bs=new Set(["width","height","top","right","bottom","left","margin","marginTop","marginRight","marginBottom","marginLeft","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","borderRadius","borderWidth","fontSize","lineHeight","letterSpacing","outlineWidth","gap","rowGap","columnGap"]),ho=new Set(["x","y","z","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skewX","skewY","quaternion","motionPathX","motionPathY","motionPathRotate"]),fo=["x","motionPathX","y","motionPathY","z","rotate","rotateZ","motionPathRotate","rotateX","rotateY","quaternion","scale","scaleX","scaleY","scaleZ","skewX","skewY"],po=new Set(["childPerspective","perspectiveOriginX","perspectiveOriginY"]),go=new Set(["originX","originY"]),yo=new Set(["clipTop","clipRight","clipBottom","clipLeft"]),mo=new Set(["drawOn"]),bo={fill:"backgroundColor",stroke:"borderColor",strokeWidth:"borderWidth",color:"color",backgroundColor:"backgroundColor",borderColor:"borderColor"},ws={fill:"fill",stroke:"stroke",strokeWidth:"strokeWidth",strokeDasharray:"strokeDasharray",strokeDashoffset:"strokeDashoffset",fillOpacity:"fillOpacity",strokeOpacity:"strokeOpacity"},wo="http://www.w3.org/2000/svg";class vs{targets=new Map;registerTarget(e,n){this.targets.set(e,n)}unregisterTarget(e){this.targets.delete(e)}getTarget(e){return this.targets.get(e)}clearTargets(){this.targets.clear()}applyState(e){for(const[n,s]of e.values){const i=this.targets.get(n);i&&this.applyProperties(i,s)}}applyProperties(e,n){let s=null,i=null,r=null,o=null,c=null;const l=n.has("motionPathX"),u=n.has("motionPathY"),h=n.has("motionPathRotate");for(const[g,p]of n)if(!(g==="x"&&l)&&!(g==="y"&&u)&&!((g==="rotate"||g==="rotateZ")&&h)&&!mo.has(g)){if(ho.has(g))(s??={})[g]=p;else if(po.has(g))typeof p=="number"&&((i??={})[g]=p);else if(go.has(g))typeof p=="number"&&((r??={})[g]=p);else if(yo.has(g))typeof p=="number"&&((o??={})[g]=p);else if(ro.has(g))(c??={})[g]=p;else if(g!=="perspective"){if(g!=="shine")if(g==="text"&&typeof p=="string")lo(e,p);else if(g==="d"&&typeof p=="string"){const a=e;(a.tagName?.toLowerCase()==="path"?a:a.querySelector?.("path"))?.setAttribute?.("d",p)}else this.applyStyleProperty(e,g,p)}}const d=n.get("shine");typeof d=="number"&&this.applyShine(e,d);const f=[],y=n.get("perspective");if(typeof y=="number"&&y>0&&f.push(`perspective(${y}px)`),s)for(const g of fo){const p=s[g];if(p===void 0)continue;const a=this.buildTransformPart(g,p);a&&f.push(a)}if(f.length>0&&(e.style.transform=f.join(" "),uo(e)),i&&(i.childPerspective!==void 0&&(e.style.perspective=`${i.childPerspective}px`),(i.perspectiveOriginX!==void 0||i.perspectiveOriginY!==void 0)&&(e.style.perspectiveOrigin=`${i.perspectiveOriginX??50}% ${i.perspectiveOriginY??50}%`)),r){const g=r.originX??50,p=r.originY??50;e.style.transformOrigin=`${g}% ${p}%`}if(o){const g=o.clipTop??0,p=o.clipRight??0,a=o.clipBottom??0,m=o.clipLeft??0;e.style.clipPath=`inset(${g}% ${p}% ${a}% ${m}%)`}if(c){const g=co(c);g&&(e.style.filter=g)}}buildTransformPart(e,n){if(e==="quaternion")return io(n);if(typeof n!="number")return null;switch(e){case"x":case"motionPathX":return`translateX(${n}px)`;case"y":case"motionPathY":return`translateY(${n}px)`;case"z":return`translateZ(${n}px)`;case"rotate":case"rotateZ":case"motionPathRotate":return`rotate(${n}deg)`;case"rotateX":return`rotateX(${n}deg)`;case"rotateY":return`rotateY(${n}deg)`;case"scale":return`scale(${n})`;case"scaleX":return`scaleX(${n})`;case"scaleY":return`scaleY(${n})`;case"scaleZ":return`scaleZ(${n})`;case"skewX":return`skewX(${n}deg)`;case"skewY":return`skewY(${n}deg)`;default:return null}}applyShine(e,n){e.dataset.shineBase||(e.dataset.shineBase=e.style.color||"currentColor");const s=e.dataset.shineBase,i=-20+n*140,r=e.style;r.color="transparent",r.backgroundImage=`linear-gradient(105deg, transparent 40%, rgba(255, 255, 255, 0.9) 50%, transparent 60%), linear-gradient(${s}, ${s})`,r.backgroundSize="250% 100%, 100% 100%",r.backgroundPosition=`${i}% 0, 0 0`,r.backgroundRepeat="no-repeat",r.webkitBackgroundClip="text",r.backgroundClip="text"}applyStyleProperty(e,n,s){let i;if(e.namespaceURI===wo&&n in ws){const c=Array.isArray(s)?s.join(", "):String(s);e.style[ws[n]]=c;return}else n==="fill"&&e.dataset?.elementType==="text"?i="color":i=bo[n]??n;let o;typeof s=="number"?bs.has(n)||bs.has(i)?o=`${s}px`:o=String(s):Array.isArray(s)?o=s.join(", "):o=s,e.style[i]=o}}class ks{media;offset;driftTolerance;constructor(e,n={}){this.media=e,this.offset=n.offset??0,this.driftTolerance=Math.max(0,n.driftTolerance??.15)}targetTime(e){return Math.max(0,e/1e3+this.offset)}update(e,n){const s=this.targetTime(e);n?(this.media.paused&&this.safePlay(),Math.abs(this.media.currentTime-s)>this.driftTolerance&&(this.media.currentTime=s)):(this.media.paused||this.media.pause(),this.media.currentTime!==s&&(this.media.currentTime=s))}seek(e){this.media.currentTime=this.targetTime(e)}setRate(e){this.media.playbackRate=e}dispose(){this.media.paused||this.media.pause()}safePlay(){const e=this.media.play();e&&typeof e.catch=="function"&&e.catch(()=>{})}}function vo(t,e,n,s,i){const r=n-i;if(r<0){e.paused||e.pause(),e.currentTime=0;return}t.update(r,s)}class ko{container;timeline=null;adapter;animationFrameId;lastTime;options;targets={};isDestroyed=!1;mediaSync;mediaTargets=[];symbolInstances=[];scenarioList=[];scenarioId;authored=new Map;markerList=[];listeners=new Set;playhead={time:0,iteration:0,direction:"forward"};stepping=!1;lastMarkerId=null;reducedQuery;onReducedChange=()=>this.applyReducedMotion();visibilityObserver;onScreen=!0;pausedByVisibility=!1;autoplayWhenSeen=!1;onDocumentVisibility=()=>this.updateVisibility();constructor(e,n={}){if(typeof e=="string"){const s=document.querySelector(e);if(!s)throw new Error(`Container not found: ${e}`);this.container=s}else this.container=e;this.options=n,this.adapter=new vs}async load(e){this.scenarioList=[],this.scenarioId=void 0,await this.loadSource(e)}async loadSource(e){let n;if(typeof e=="string"){const s=await fetch(e);if(!s.ok)throw new Error(`Failed to load animation: ${s.statusText}`);n=await s.json()}else n=e;this.useDefinition(n),this.showInitialFrame(),this.watchReducedMotion(),this.watchVisibility(),this.options.autoplay&&!this.reducedMotion&&(this.options.playWhenVisible&&!this.onScreen?this.autoplayWhenSeen=!0:this.play())}useDefinition(e){const n={...e.config};this.options.speed!==void 0&&(n.speed=this.options.speed),this.options.loop!==void 0&&(n.loop=this.options.loop),this.options.alternate!==void 0&&(n.alternate=this.options.alternate),this.timeline=ys({...e,config:n}),this.markerList=this.timeline.markers,this.lastMarkerId=null,this.options.onComplete&&(this.timeline.onComplete=this.options.onComplete),this.options.onUpdate&&(this.timeline.onUpdate=this.options.onUpdate),this.autoRegisterTargets(),this.setupSymbolInstances(),this.scanMedia()}async loadScenarios(e,n={}){if(e.length===0)throw new Error("tinyfly: loadScenarios needs at least one scenario");const s=new Set;for(const r of e){if(s.has(r.id))throw new Error(`tinyfly: scenario id "${r.id}" is used more than once`);s.add(r.id)}const i=n.initial===void 0?e[0]:e.find(r=>r.id===n.initial);if(!i)throw new Error(`tinyfly: there is no scenario "${n.initial}"`);this.scenarioList=[...e],this.scenarioId=i.id,await this.loadSource(i.timeline)}get scenarios(){return this.scenarioList.map(e=>({id:e.id,label:e.label??e.id}))}get scenario(){return this.scenarioId}setScenario(e){const n=this.scenarioList.find(c=>c.id===e);if(!n||!this.timeline)return!1;if(e===this.scenarioId)return!0;const s=this.isPlaying,i=this.currentTime>=this.duration-.5,r=this.currentMarker?.id;this.stopAnimationLoop(),this.stepping=!1,this.pausedByVisibility=!1,this.restoreAuthored(),this.scenarioId=e,this.useDefinition(n.timeline),this.lastMarkerId=null;let o=0;return this.reducedMotion||i?o=this.duration:r!==void 0&&(o=this.markers.find(c=>c.id===r)?.time??0),this.seek(o),s&&!this.reducedMotion?(this.stepping=this.options.stepMode===!0,this.startPlaying()):this.notify(),!0}rememberAuthored(e){if(this.authored.has(e))return;const n={style:e.getAttribute("style")};e.children.length===0&&(n.text=e.textContent??"");const s=e.tagName.toLowerCase()==="path"?e:e.querySelector("path");s&&(n.path={element:s,d:s.getAttribute("d")}),this.authored.set(e,n)}restoreAuthored(){for(const[e,n]of this.authored){n.style===null?e.removeAttribute("style"):e.setAttribute("style",n.style),n.text!==void 0&&e.textContent!==n.text&&(e.textContent=n.text),n.path&&(n.path.d===null?n.path.element.removeAttribute("d"):n.path.element.setAttribute("d",n.path.d));const s=e.dataset;s&&delete s.shineBase}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){for(const e of this.listeners)e()}get reducedMotion(){return this.reducedQuery?.matches===!0}get markers(){return this.markerList}get currentMarker(){const e=this.currentTime;let n;for(const s of this.markers)if(s.time<=e+.5)n=s;else break;return n}caption(e,n){const s=e?this.markers.find(o=>o.id===e):this.currentMarker;if(!s)return;const i=n??this.language(),r=o=>o?.[i]?.[s.id]??o?.[i.split("-")[0]]?.[s.id];return r(this.options.captions)??r(this.timeline?.captions)??s.label}next(){if(!this.timeline)return;const e=this.currentTime,n=this.markers.find(s=>s.time>e+.5);if(this.reducedMotion){this.seek(n?n.time:this.duration);return}e>=this.duration-.5||(this.stepping=n!==void 0,this.startPlaying())}prev(){if(!this.timeline)return;const e=this.currentTime,n=[...this.markers].reverse().find(s=>s.time<e-.5);this.pause(),this.seek(n?n.time:0)}goToMarker(e){const n=this.markers.find(s=>s.id===e);n&&(this.pause(),this.seek(n.time))}language(){return this.container.closest("[lang]")?.getAttribute("lang")||(typeof document<"u"?document.documentElement.lang:"")||"en"}showInitialFrame(){if(!this.timeline)return;const e=this.options.initialFrame??"start";if(e==="none")return;const n=e==="end"?this.timeline.duration:e==="start"?0:e;this.timeline.seek(Math.max(0,Math.min(this.timeline.duration,n))),this.applyState()}watchReducedMotion(){this.options.respectReducedMotion===!1||typeof window>"u"||typeof window.matchMedia!="function"||(this.reducedQuery??=window.matchMedia("(prefers-reduced-motion: reduce)"),this.reducedQuery.addEventListener?.("change",this.onReducedChange),this.reducedQuery.matches&&this.applyReducedMotion())}applyReducedMotion(){!this.reducedMotion||!this.timeline||(this.autoplayWhenSeen=!1,this.pause(),this.seek(this.timeline.duration))}watchVisibility(){if(!(!this.options.playWhenVisible||typeof window>"u")){if(typeof IntersectionObserver=="function"){this.visibilityObserver?.disconnect(),this.visibilityObserver=new IntersectionObserver(n=>{for(const s of n)this.onScreen=s.isIntersecting;this.updateVisibility()}),this.visibilityObserver.observe(this.container);const e=this.container.getBoundingClientRect?.();e&&(e.width>0||e.height>0)&&(this.onScreen=e.bottom>0&&e.top<window.innerHeight&&e.right>0&&e.left<window.innerWidth)}document.addEventListener("visibilitychange",this.onDocumentVisibility)}}updateVisibility(){const e=this.onScreen&&document.visibilityState!=="hidden";!e&&this.isPlaying?(this.pausedByVisibility=!0,this.pause()):e&&(this.pausedByVisibility||this.autoplayWhenSeen)&&!this.reducedMotion&&(this.pausedByVisibility=!1,this.autoplayWhenSeen=!1,this.startPlaying())}announceMarker(){if(!this.options.onMarker)return;const e=this.currentMarker,n=e?.id;n!==this.lastMarkerId&&(this.lastMarkerId=n,this.options.onMarker(e))}scanMedia(){this.mediaTargets=[],this.container.querySelectorAll("[data-tinyfly-media]").forEach(n=>{const s=n,i=Number(s.getAttribute("data-tinyfly-start")??"0")||0,r=s.getAttribute("data-volume");r!==null&&(s.volume=Math.max(0,Math.min(1,Number(r)||0))),this.mediaTargets.push({el:s,startTime:i,sync:new ks(s)})})}syncAllMedia(e,n){for(const s of this.mediaTargets)vo(s.sync,s.el,e,n,s.startTime)}loadFromString(e){const n=JSON.parse(e);this.load(n)}registerTarget(e,n){if(typeof n=="string"){const s=this.container.querySelector(n);s&&(this.rememberAuthored(s),this.targets[e]=s,this.adapter.registerTarget(e,s))}else this.rememberAuthored(n),this.targets[e]=n,this.adapter.registerTarget(e,n)}autoRegisterTargets(){this.container.querySelectorAll("[data-tinyfly]").forEach(n=>{const s=n.closest("[data-tinyfly-symbol]");if(s&&s!==n)return;const i=n.getAttribute("data-tinyfly");i&&this.registerTarget(i,n)}),this.timeline&&new Set(this.timeline.tracks.map(s=>s.target)).forEach(s=>{if(!this.targets[s]){const i=this.container.querySelector(`[data-tinyfly="${s}"]`)||this.container.querySelector(`.${s}`)||this.container.querySelector(`#${s}`);i&&this.registerTarget(s,i)}})}setupSymbolInstances(){this.symbolInstances=[];const e=this.options.symbols;if(!e||e.length===0)return;const n=new Map(e.map(s=>[s.id,s]));this.container.querySelectorAll("[data-tinyfly-symbol]").forEach(s=>{const i=s.getAttribute("data-tinyfly-symbol");if(!i)return;const r=n.get(i);if(!r||!r.timeline.tracks?.length)return;const o=new vs;s.querySelectorAll("[data-tinyfly]").forEach(c=>{const l=c.getAttribute("data-tinyfly");l&&o.registerTarget(l,c)}),this.symbolInstances.push({adapter:o,timeline:ys(r.timeline)})})}attachMedia(e,n){this.mediaSync=new ks(e,n),this.timeline&&(this.mediaSync.setRate(this.timeline.speed),this.mediaSync.update(this.timeline.currentTime,this.isPlaying))}detachMedia(){this.mediaSync?.dispose(),this.mediaSync=void 0}play(){!this.timeline||this.isDestroyed||(this.autoplayWhenSeen=!1,this.stepping=this.options.stepMode===!0,this.startPlaying())}startPlaying(){if(!this.timeline||this.isDestroyed)return;const e=this.timeline.playbackState==="idle";this.timeline.play(),e&&this.timeline.currentTime===0&&this.applyState(),this.playhead={time:this.timeline.currentTime,iteration:this.timeline.loopIteration,direction:this.timeline.direction},this.mediaSync?.update(this.timeline.currentTime,!0),this.syncAllMedia(this.timeline.currentTime,!0),this.startAnimationLoop(),this.notify()}pause(){this.timeline&&(this.stepping=!1,this.timeline.pause(),this.notify(),this.mediaSync?.update(this.timeline.currentTime,!1),this.syncAllMedia(this.timeline.currentTime,!1),this.stopAnimationLoop())}stop(){this.timeline&&(this.timeline.stop(),this.stopAnimationLoop(),this.applyState(),this.mediaSync?.update(this.timeline.currentTime,!1),this.syncAllMedia(this.timeline.currentTime,!1))}seek(e){this.timeline&&(this.timeline.seek(e),this.applyState(),this.playhead={time:this.timeline.currentTime,iteration:this.timeline.loopIteration,direction:this.timeline.direction},this.mediaSync?.seek(this.timeline.currentTime),this.syncAllMedia(this.timeline.currentTime,this.isPlaying))}setSpeed(e){this.timeline&&(this.timeline.speed=e,this.mediaSync?.setRate(e))}reverse(){this.timeline&&this.timeline.reverse()}get currentTime(){return this.timeline?.currentTime??0}get state(){return this.timeline?.getStateAtTime(this.timeline.currentTime)}get duration(){return this.timeline?.duration??0}get isPlaying(){return this.timeline?.playbackState==="playing"}destroy(){this.isDestroyed=!0,this.stopAnimationLoop(),this.reducedQuery?.removeEventListener?.("change",this.onReducedChange),this.visibilityObserver?.disconnect(),typeof document<"u"&&document.removeEventListener("visibilitychange",this.onDocumentVisibility),this.mediaSync?.dispose(),this.mediaSync=void 0;for(const e of this.mediaTargets)e.el.paused||e.el.pause();this.mediaTargets=[],this.adapter.clearTargets();for(const e of this.symbolInstances)e.adapter.clearTargets();this.symbolInstances=[],this.authored.clear(),this.timeline=null}startAnimationLoop(){if(this.animationFrameId!==void 0)return;this.lastTime=performance.now();const e=n=>{if(this.isDestroyed||!this.timeline)return;const s=n-(this.lastTime??n);this.lastTime=n;const i=this.playhead;this.timeline.tick(s),this.stopAtMarker(i),this.applyState();const r=this.timeline.playbackState==="playing";this.mediaSync?.update(this.timeline.currentTime,r),this.syncAllMedia(this.timeline.currentTime,r),this.timeline.playbackState==="playing"?this.animationFrameId=requestAnimationFrame(e):(this.animationFrameId=void 0,this.notify())};this.animationFrameId=requestAnimationFrame(e)}stopAtMarker(e){const n=this.timeline,s={time:n.currentTime,iteration:n.loopIteration,direction:n.direction};this.playhead=s;const i=this.markers;if(i.length===0)return;const{crossings:r}=Jr(i.map(o=>o.time),e,s,{duration:n.duration,alternate:n.config.alternate===!0,holding:n.repeatDelayRemaining>0});for(const o of r){if(o.kind!=="event")continue;const c=i[o.index];if(this.stepping||c.pause){this.stepping=!1,n.pause(),n.seek(c.time),this.playhead={time:c.time,iteration:n.loopIteration,direction:n.direction};return}}}stopAnimationLoop(){this.animationFrameId!==void 0&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}applyState(){if(!this.timeline)return;const e=this.timeline.currentTime;this.adapter.applyState(this.timeline.getStateAtTime(e)),this.announceMarker(),this.notify();for(const n of this.symbolInstances){const s=n.timeline.duration;n.adapter.applyState(n.timeline.getStateAtTime(s>0?e%s:e))}}}const Mo={play:"Play",pause:"Pause",prev:"Previous step",next:"Next step",restart:"Restart",scrub:"Position",speed:"Speed",reveal:"Reveal",step:"Step",of:"of",stepFormat:"{index} / {total}",scenario:"Scenario",fullscreen:"Full screen",exitFullscreen:"Exit full screen"},Ms="tinyfly-controls-style",$o=`
1
+ (function($){"use strict";function zi(t){return typeof t=="object"&&t!==null&&t.type==="cubic-bezier"}function qi(t){return typeof t=="object"&&t!==null&&t.type!=="cubic-bezier"}const Ge=2;function ji(t){return t.some(e=>e.interpolation!==void 0)?2:1}function Bn(t){return t.property==="text"&&"textConfig"in t}function Ze(t){return t.kind==="inertia"&&"inertia"in t}function Qe(t){return t.kind==="spring"&&"spring"in t}function Xi(t){return t.property==="motionPath"&&"motionPathConfig"in t}function Yi(t,e){if(!(e>0))return t;const n=1e3/e;return Math.floor(t/n+1e-9)*n}function Vn(t,e,n="start"){if(e<=1)return 0;if(typeof n=="number"){const s=Math.max(0,Math.min(e-1,n));return Math.abs(t-s)}switch(n){case"end":return e-1-t;case"center":return Math.abs(t-(e-1)/2);case"edges":return(e-1)/2-Math.abs(t-(e-1)/2);default:return t}}function Bi(t,e="start"){if(t<=1)return 0;let n=0;for(let s=0;s<t;s++)n=Math.max(n,Vn(s,t,e));return n}function Hn(t,e,n){if(n.offsets)return n.offsets[t]??0;const s=n.from??"start",i=Vn(t,e,s);if(n.amount!==void 0){const r=Bi(e,s);return r===0?0:n.amount*i/r}return n.each!==void 0?n.each*i:0}function Vi(t,e){return Array.from({length:t},(n,s)=>Hn(s,t,e))}function Ke(t,e){return t<=1?0:Math.max(...Vi(t,e))}const Ht=1,Un=6e4,we=Un/Ht,It={stiffness:180,damping:12,mass:1,velocity:0,restDelta:.01,restSpeed:.1};class Hi{from;to;stiffness;damping;mass;restDelta;restSpeed;distance;samples;velocity;settledStep=null;constructor(e){this.from=e.from,this.to=e.to,this.stiffness=e.stiffness??It.stiffness,this.damping=e.damping??It.damping,this.mass=e.mass??It.mass,this.restDelta=e.restDelta??It.restDelta,this.restSpeed=e.restSpeed??It.restSpeed,this.distance=Math.abs(this.to-this.from)||1,this.samples=[this.from],this.velocity=e.velocity??It.velocity,this.isAtRest(this.from)&&(this.settledStep=0)}isAtRest(e){return Math.abs(e-this.to)<this.restDelta*this.distance&&Math.abs(this.velocity)<this.restSpeed*this.distance}valueAt(e){if(e<=0)return this.from;const n=Math.floor(e/Ht);if(this.simulateTo(n+1),this.settledStep!==null&&n>=this.settledStep)return this.to;const s=this.samples[Math.min(n,this.samples.length-1)],i=this.samples[Math.min(n+1,this.samples.length-1)],r=e/Ht-n;return s+(i-s)*r}settleTime(){return this.simulateTo(we+1),this.settledStep!==null?this.settledStep*Ht:Un}simulateTo(e){if(this.settledStep!==null)return;const n=Math.min(e,we+1),s=Ht/1e3;for(;this.samples.length<n;){const i=this.samples[this.samples.length-1],r=i-this.to,o=-this.stiffness*r,c=-this.damping*this.velocity,l=(o+c)/this.mass;this.velocity+=l*s;const u=i+this.velocity*s;if(this.samples.push(u),this.isAtRest(u)){this.settledStep=this.samples.length-1;return}}this.samples.length>we&&(this.settledStep=we)}}const Wn=4,Ui=.002,Wi=1e-4,Gi=6e4;function Je(t){const e=t.friction??Wn;return e>0?e:Wn}function Zi(t){return t.from+t.velocity/Je(t)}function Qi(t,e){if(e===void 0)return t;if(typeof e=="number")return e>0?Math.round(t/e)*e:t;if(e.length===0)return t;let n=e[0];for(const s of e)Math.abs(s-t)<Math.abs(n-t)&&(n=s);return n}function Gn(t){let e=Qi(Zi(t),t.end);return t.min!==void 0&&(e=Math.max(t.min,e)),t.max!==void 0&&(e=Math.min(t.max,e)),e}function Zn(t){const e=Math.abs(Gn(t)-t.from);if(e===0)return 0;const n=t.restDelta??Math.max(Wi,e*Ui);if(n>=e)return 0;const s=Math.log(e/n)/Je(t);return Math.min(Gi,s*1e3)}function Qn(t,e){if(e<=0)return t.from;const n=Gn(t);if(e>=Zn(t))return n;const s=Je(t);return t.from+(n-t.from)*(1-Math.exp(-s*e/1e3))}const tn=t=>t,Ki=t=>t*t,Ji=t=>1-(1-t)*(1-t),tr=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2,Kn=t=>t*t*t,Jn=t=>1-Math.pow(1-t,3),ts=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,er={linear:tn,"ease-in":Kn,"ease-out":Jn,"ease-in-out":ts,"ease-in-quad":Ki,"ease-out-quad":Ji,"ease-in-out-quad":tr,"ease-in-cubic":Kn,"ease-out-cubic":Jn,"ease-in-out-cubic":ts};function nr(t){const[e,n,s,i]=t,r=3*e,o=3*(s-e)-r,c=1-r-o,l=3*n,u=3*(i-n)-l,h=1-l-u,d=p=>((c*p+o)*p+r)*p,f=p=>((h*p+u)*p+l)*p,y=p=>(3*c*p+2*o)*p+r,g=p=>{let a=p;for(let S=0;S<8;S++){const w=d(a)-p;if(Math.abs(w)<1e-7)return a;const v=y(a);if(Math.abs(v)<1e-7)break;a-=w/v}let m=0,b=1;for(a=p;m<b;){const S=d(a);if(Math.abs(S-p)<1e-7)return a;p>S?m=a:b=a,a=(m+b)/2}return a};return p=>{if(p<=0)return 0;if(p>=1)return 1;const a=g(p);return f(a)}}function en(t,e="out"){if(e==="out")return t;const n=s=>1-t(1-s);return e==="in"?n:s=>s<.5?n(s*2)/2:t(s*2-1)/2+.5}function sr(t=1,e=.3){const n=Math.max(1,t),s=e/(2*Math.PI)*Math.asin(1/n);return i=>i<=0?0:i>=1?1:n*Math.pow(2,-10*i)*Math.sin((i-s)*(2*Math.PI)/e)+1}const ir=t=>{if(t<=0)return 0;if(t>=1)return 1;if(t<1/2.75)return 7.5625*t*t;if(t<2/2.75){const i=t-.5454545454545454;return 7.5625*i*i+.75}if(t<2.5/2.75){const i=t-.8181818181818182;return 7.5625*i*i+.9375}const s=t-2.625/2.75;return 7.5625*s*s+.984375};function rr(t=1.70158){return e=>{if(e<=0)return 0;if(e>=1)return 1;const n=e-1;return n*n*((t+1)*n+t)+1}}function or(t,e="end"){const n=Math.max(1,Math.floor(t));return s=>{if(s>=1)return 1;if(s<=0)return e==="start"||e==="both"?e==="start"?1/n:1/(n+1):0;const i=Math.floor(s*n);switch(e){case"start":return Math.min(1,(i+1)/n);case"both":return(i+1)/(n+1);case"none":return n===1?0:Math.min(1,i/(n-1));default:return i/n}}}function ar(t){switch(t.type){case"steps":return or(t.count,t.position);case"elastic":return en(sr(t.amplitude,t.period),t.mode);case"bounce":return en(ir,t.mode);case"back":return en(rr(t.overshoot),t.mode)}}function cr(t){return t===void 0?tn:zi(t)?nr(t.points):qi(t)?ar(t):er[t]??tn}const es=32,lr=256,Ut=new Map,ur=/[MmLlHhVvCcSsQqTtAaZz]/,hr=/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/,dr={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0};function fr(t){const e=[];let n=0,s=null;const i=()=>{for(;n<t.length&&/[\s,]/.test(t[n]);)n++};for(;n<t.length&&(i(),!(n>=t.length));){const r=t[n];if(ur.test(r)){s={type:r,args:[]},e.push(s),n++;continue}if(!s)break;const o=s.type==="A"||s.type==="a",c=s.args.length%7;if(o&&(c===3||c===4)){if(r!=="0"&&r!=="1")break;s.args.push(r==="1"?1:0),n++;continue}const l=hr.exec(t.slice(n));if(!l)break;s.args.push(parseFloat(l[0])),n+=l[0].length}return e}function pr(t,e,n,s,i,r,o,c,l){if(t===c&&e===l)return[];let u=Math.abs(n),h=Math.abs(s);if(u===0||h===0)return[[t,e,c,l,c,l]];const d=i*Math.PI/180,f=Math.cos(d),y=Math.sin(d),g=(t-c)/2,p=(e-l)/2,a=f*g+y*p,m=-y*g+f*p,b=a*a/(u*u)+m*m/(h*h);if(b>1){const z=Math.sqrt(b);u*=z,h*=z}const S=r===o?-1:1,w=u*u*h*h-u*u*m*m-h*h*a*a,v=u*u*m*m+h*h*a*a,k=S*Math.sqrt(Math.max(0,w/v)),x=k*u*m/h,M=-k*h*a/u,A=f*x-y*M+(t+c)/2,E=y*x+f*M+(e+l)/2,_=(z,q,U,ct)=>{const wt=z*U+q*ct,mt=Math.sqrt((z*z+q*q)*(U*U+ct*ct)),ft=Math.acos(Math.max(-1,Math.min(1,wt/mt)));return z*ct-q*U<0?-ft:ft},T=_(1,0,(a-x)/u,(m-M)/h);let F=_((a-x)/u,(m-M)/h,(-a-x)/u,(-m-M)/h);!o&&F>0&&(F-=2*Math.PI),o&&F<0&&(F+=2*Math.PI);const R=Math.max(1,Math.ceil(Math.abs(F)/(Math.PI/2))),P=F/R,O=4/3*Math.tan(P/4),I=z=>{const q=u*Math.cos(z),U=h*Math.sin(z);return[f*q-y*U+A,y*q+f*U+E]},L=z=>{const q=-u*Math.sin(z),U=h*Math.cos(z);return[f*q-y*U,y*q+f*U]},D=[];for(let z=0;z<R;z++){const q=T+z*P,U=q+P,[ct,wt]=I(q),[mt,ft]=z===R-1?[c,l]:I(U),[Gc,Zc]=L(q),[Qc,Kc]=L(U);D.push([ct+O*Gc,wt+O*Zc,mt-O*Qc,ft-O*Kc,mt,ft])}return D}function bt(t,e,n,s,i){const r=1-i;return r*r*r*t+3*r*r*i*e+3*r*i*i*n+i*i*i*s}function ns(t,e,n,s,i){const r=1-i;return 3*r*r*(e-t)+6*r*i*(n-e)+3*i*i*(s-n)}function Wt(t,e,n,s){return{subpath:0,type:"L",points:[n,s],startX:t,startY:e,endX:n,endY:s,length:Math.hypot(n-t,s-e)}}function ke(t,e,n){const[s,i,r,o,c,l]=n,u=[0];let h=t,d=e,f=0;for(let y=1;y<=es;y++){const g=y/es,p=bt(t,s,r,c,g),a=bt(e,i,o,l,g);f+=Math.hypot(p-h,a-d),u.push(f),h=p,d=a}return{subpath:0,type:"C",points:[s,i,r,o,c,l],startX:t,startY:e,endX:c,endY:l,length:f,lengths:u}}function Me(t){const e=Ut.get(t);if(e)return e;const n=[];let s=0,i=0,r=0,o=0,c=null,l=null,u=-1;const h=new Set,d=p=>{u<0&&(u=0),p.subpath=u,n.push(p)};for(const{type:p,args:a}of fr(t)){const m=p.toUpperCase(),b=p!==m,S=dr[m];if(m==="Z"){(s!==r||i!==o)&&d(Wt(s,i,r,o)),u>=0&&h.add(u),s=r,i=o,c=l=null;continue}for(let w=0;w+S<=a.length;w+=S){const v=a.slice(w,w+S),k=b?s:0,x=b?i:0;let M=null,A=null;switch(m){case"M":w===0?(s=v[0]+k,i=v[1]+x,r=s,o=i,(u<0||n[n.length-1]?.subpath===u)&&u++):(d(Wt(s,i,v[0]+k,v[1]+x)),s=v[0]+k,i=v[1]+x);break;case"L":d(Wt(s,i,v[0]+k,v[1]+x)),s=v[0]+k,i=v[1]+x;break;case"H":d(Wt(s,i,v[0]+k,i)),s=v[0]+k;break;case"V":d(Wt(s,i,s,v[0]+x)),i=v[0]+x;break;case"C":{const E=[v[0]+k,v[1]+x,v[2]+k,v[3]+x,v[4]+k,v[5]+x];d(ke(s,i,E)),M=[E[2],E[3]],s=E[4],i=E[5];break}case"S":{const[E,_]=c?[2*s-c[0],2*i-c[1]]:[s,i],T=[E,_,v[0]+k,v[1]+x,v[2]+k,v[3]+x];d(ke(s,i,T)),M=[T[2],T[3]],s=T[4],i=T[5];break}case"Q":case"T":{let E=s,_=i;m==="Q"?(E=v[0]+k,_=v[1]+x):l&&(E=2*s-l[0],_=2*i-l[1]);const T=m==="Q"?v[2]+k:v[0]+k,F=m==="Q"?v[3]+x:v[1]+x;d(ke(s,i,[s+2/3*(E-s),i+2/3*(_-i),T+2/3*(E-T),F+2/3*(_-F),T,F])),A=[E,_],s=T,i=F;break}case"A":{const E=v[5]+k,_=v[6]+x;let T=s,F=i;for(const R of pr(s,i,v[0],v[1],v[2],v[3],v[4],E,_))d(ke(T,F,R)),T=R[4],F=R[5];s=E,i=_;break}}c=M,l=A}}const f=n.reduce((p,a)=>p+a.length,0),y=[];for(let p=0;p<n.length;){const a=n[p].subpath;let m=p,b=0;for(;m<n.length&&n[m].subpath===a;)b+=n[m++].length;const S=n[p],w=n[m-1],v=h.has(a)||Math.abs(w.endX-S.startX)<1e-9&&Math.abs(w.endY-S.startY)<1e-9;y.push({start:p,end:m,length:b,closed:v}),p=m}const g={segments:n,totalLength:f,subpaths:y};return Ut.size>=lr&&Ut.delete(Ut.keys().next().value),Ut.set(t,g),g}function gr(t,e){const n=t.lengths;if(e<=0)return 0;if(e>=t.length)return 1;let s=0,i=n.length-1;for(;s<i-1;){const c=s+i>>1;n[c]<e?s=c:i=c}const r=n[i]-n[s],o=r>0?(e-n[s])/r:0;return(s+o)/(n.length-1)}function yr(t,e){if(t.type==="L"){const d=t.length>0?Math.max(0,Math.min(1,e/t.length)):0;return{x:t.startX+(t.endX-t.startX)*d,y:t.startY+(t.endY-t.startY)*d,angle:Math.atan2(t.endY-t.startY,t.endX-t.startX)*180/Math.PI}}const[n,s,i,r,o,c]=t.points,l=gr(t,e);let u=ns(t.startX,n,i,o,l),h=ns(t.startY,s,r,c,l);if(Math.hypot(u,h)<1e-9){const d=l<.5?Math.min(1,l+.001):Math.max(0,l-.001),f=bt(t.startX,n,i,o,d),y=bt(t.startY,s,r,c,d),g=bt(t.startX,n,i,o,l),p=bt(t.startY,s,r,c,l);u=l<.5?f-g:g-f,h=l<.5?y-p:p-y}return{x:bt(t.startX,n,i,o,l),y:bt(t.startY,s,r,c,l),angle:Math.atan2(h,u)*180/Math.PI}}function ss(t,e,n=0,s=t.length){if(s<=n)return{x:0,y:0,angle:0};let i=0;for(let r=n;r<s;r++){const o=t[r];if(i+o.length>=e||r===s-1)return yr(o,e-i);i+=o.length}return{x:0,y:0,angle:0}}function mr(t,e){const{segments:n,totalLength:s}=Me(t);return ss(n,Math.max(0,Math.min(1,e))*s)}const br=24,vr=320,wr=2.5,Gt=72,kr=.2,Mr=128,$e=new Map;let nn=0,kt;const is=t=>Math.round(t*100)/100;function rs(t,e){const{segments:n,subpaths:s,totalLength:i}=Me(t);if(n.length===0)return[];if(e){const r=s.every(o=>o.closed);return[{segments:n,start:0,end:n.length,length:i,closed:r}]}return s.filter(r=>r.length>0).map(r=>({segments:n,start:r.start,end:r.end,length:r.length,closed:r.closed}))}function sn(t,e){const n=t.closed?(e%1+1)%1:Math.max(0,Math.min(1,e)),s=ss(t.segments,n*t.length,t.start,t.end);return[s.x,s.y]}function os(t){const e=[];let n=0;for(let s=t.start;s<t.end;s++)n+=t.segments[s].length,t.length>0&&e.push(n/t.length);return e}function as(t,e){const n=[];for(let s=0;s<e;s++)n.push(sn(t,t.closed?s/e:s/(e-1)));return n}function cs(t){let e=0,n=0;for(const[s,i]of t)e+=s,n+=i;return e/=t.length,n/=t.length,t.map(([s,i])=>[s-e,i-n])}function $r(t,e,n){const s=t.closed&&e.closed;if(n!==void 0)return{offset:s?Math.abs(n)%Gt/Gt:0,reversed:n<0};const i=cs(as(t,Gt)),r=cs(as(e,Gt)),o=Gt;let c={offset:0,reversed:!1},l=1/0;for(const u of[!1,!0]){const h=s?o:1;for(let d=0;d<h;d++){let f=0;for(let y=0;y<o&&f<l;y++){const g=s?u?(d-y+o)%o:(y+d)%o:u?o-1-y:y,p=i[y][0]-r[g][0],a=i[y][1]-r[g][1];f+=p*p+a*a}f<l&&(l=f,c={offset:s?d/o:0,reversed:u})}}return c}function Sr(t,e,n){return n?((e.reversed?e.offset-t:t+e.offset)%1+1)%1:e.reversed?1-t:t}function xr(t,e,n){return n?((e.reversed?e.offset-t:t-e.offset)%1+1)%1:e.reversed?1-t:t}function Ar(t,e,n){const s=t.closed&&e.closed,i=$r(t,e,n.shapeIndex),r=Math.max(br,Math.min(vr,Math.ceil(Math.max(t.length,e.length)/wr))),o=new Set,c=d=>o.add(Math.round(d*1e7)/1e7);for(let d=0;d<=r;d++)c(d/r);for(const d of os(t))c(d);for(const d of os(e))c(xr(d,i,s));let l=[...o].sort((d,f)=>d-f);s&&(l=l.filter(d=>d<1));const u=[],h=[];for(const d of l)u.push(...sn(t,d)),h.push(...sn(e,Sr(d,i,s)));return Er({from:u,to:h,closed:s})}function Er(t){const e=t.from.length/2;if(e<=3)return t;const n=new Uint8Array(e);n[0]=1,n[e-1]=1;const s=[[0,e-1]];for(;s.length>0;){const[o,c]=s.pop();let l=-1,u=kr;for(let h=o+1;h<c;h++){const d=Math.max(ls(t.from,o,c,h),ls(t.to,o,c,h));d>u&&(u=d,l=h)}l!==-1&&(n[l]=1,s.push([o,l],[l,c]))}const i=[],r=[];for(let o=0;o<e;o++)n[o]&&(i.push(t.from[o*2],t.from[o*2+1]),r.push(t.to[o*2],t.to[o*2+1]));return{from:i,to:r,closed:t.closed}}function ls(t,e,n,s){const i=t[e*2],r=t[e*2+1],o=t[n*2]-i,c=t[n*2+1]-r,l=t[s*2]-i,u=t[s*2+1]-r,h=o*o+c*c,d=h===0?0:Math.max(0,Math.min(1,(l*o+u*c)/h));return Math.hypot(l-d*o,u-d*c)}function Tr(t,e,n){const s=n.shapeIndex;if(kt&&kt.from===t&&kt.to===e&&kt.shapeIndex===s)return kt.plan;const r=$e.get(String(s??"auto"))?.get(t)?.get(e);if(r)return kt={from:t,to:e,shapeIndex:s,plan:r},r;const o=Me(t).subpaths.filter(y=>y.length>0).length===Me(e).subpaths.filter(y=>y.length>0).length,c=rs(t,!o),l=rs(e,!o),u={pairs:c.map((y,g)=>Ar(y,l[g],n))};nn>=Mr&&($e.clear(),nn=0);const h=String(s??"auto"),d=$e.get(h)??new Map;$e.set(h,d);const f=d.get(t)??new Map;return d.set(t,f),f.set(e,u),nn++,kt={from:t,to:e,shapeIndex:s,plan:u},u}function _r(t,e,n,s={}){if(!t)return e;if(!e)return t;const i=Math.max(0,Math.min(1,n));if(i===0)return t;if(i===1)return e;const r=Tr(t,e,s);if(r.pairs.length===0)return i<.5?t:e;let o="";for(const c of r.pairs){for(let l=0;l<c.from.length;l+=2){const u=is(c.from[l]+(c.to[l]-c.from[l])*i),h=is(c.from[l+1]+(c.to[l+1]-c.from[l+1])*i);o+=`${l===0?o?" M":"M":" L"}${u} ${h}`}c.closed&&(o+=" Z")}return o}function Pr(t){return/^\s*[Mm]\s*[-+]?(?:\d|\.\d)/.test(t)}const Or=.9995;function Ir(){return[0,0,0,1]}function Cr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Nr(t){return Math.hypot(t[0],t[1],t[2],t[3])}function Zt(t){const e=Nr(t);return e===0?Ir():[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function Fr(t,e,n){const s=Zt(t);let i=Zt(e),r=Cr(s,i);if(r<0&&(i=[-i[0],-i[1],-i[2],-i[3]],r=-r),r>Or)return Zt([s[0]+(i[0]-s[0])*n,s[1]+(i[1]-s[1])*n,s[2]+(i[2]-s[2])*n,s[3]+(i[3]-s[3])*n]);const o=Math.acos(r),c=Math.sin(o),l=Math.sin((1-n)*o)/c,u=Math.sin(n*o)/c;return Zt([s[0]*l+i[0]*u,s[1]*l+i[1]*u,s[2]*l+i[2]*u,s[3]*l+i[3]*u])}const pt=(t,e,n)=>t+(e-t)*n,us=512,rn=new Map,on=new Map;function hs(t){const e=rn.get(t);if(e)return e;const n=t.replace("#",""),s=[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)];return rn.size<us&&rn.set(t,s),s}const ds=t=>t.charCodeAt(0)===35,fs=t=>t.startsWith("rgb"),ps=t=>t.startsWith("rgba"),Lr=/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/,an=t=>Math.round(t).toString(16).padStart(2,"0");function Rr(t,e,n){return`#${an(t)}${an(e)}${an(n)}`}function gs(t){const e=on.get(t);if(e)return e;const n=t.match(Lr);if(!n)throw new Error(`Invalid rgb color: ${t}`);const s=parseInt(n[1],10),i=parseInt(n[2],10),r=parseInt(n[3],10),o=n[4]!==void 0?[s,i,r,parseFloat(n[4])]:[s,i,r];return on.size<us&&on.set(t,o),o}const Dr=(t,e,n)=>{if(ds(t)&&ds(e)){const[s,i,r]=hs(t),[o,c,l]=hs(e),u=pt(s,o,n),h=pt(i,c,n),d=pt(r,l,n);return Rr(u,h,d)}if((fs(t)||ps(t))&&(fs(e)||ps(e))){const s=gs(t),i=gs(e),r=Math.round(pt(s[0],i[0],n)),o=Math.round(pt(s[1],i[1],n)),c=Math.round(pt(s[2],i[2],n));if(s.length===4||i.length===4){const l=s[3]??1,u=i[3]??1,h=pt(l,u,n);return`rgba(${r}, ${o}, ${c}, ${h})`}return`rgb(${r}, ${o}, ${c})`}return n<1?t:e},zr=(t,e,n)=>{const s=Math.min(t.length,e.length),i=[];for(let r=0;r<s;r++)i.push(pt(t[r],e[r],n));return i},qr=(t,e,n)=>Fr(t,e,n),ys=(t,e,n)=>n<1?t:e,jr=(t,e,n)=>_r(t,e,n);function Xr(t,e){return e==="slerp"?qr:typeof t=="number"?pt:Array.isArray(t)?zr:typeof t=="string"?t.startsWith("#")||t.startsWith("rgb")?Dr:Pr(t)?jr:ys:ys}function Yr(t){const e=[...t.keyframes].sort((n,s)=>n.time-s.time);return{...t,keyframes:e}}function Mt(t){return t.targets&&t.targets.length>0?t.targets:[t.target]}function Ct(t,e,n,s){const i=n??0;return!s||e<=1?i:i+Hn(t,e,s)}class cn{track;targets;constructor(e){this.track=e,this.targets=Mt(e)}getValueAtTime(e){return this.valueForOffset(e-Ct(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const r=Ct(i,n,this.track.delay,this.track.stagger),o=this.valueForOffset(e-r);o!==void 0&&s.push({target:this.targets[i],value:o,start:r+this.track.keyframes[0].time})}return s}getDuration(){const{keyframes:e}=this.track;if(e.length===0)return 0;const n=e[e.length-1].time,s=this.track.stagger?Ke(this.targets.length,this.track.stagger):0;return n+(this.track.delay??0)+s+(this.track.endDelay??0)}getTrack(){return this.track}valueForOffset(e){const{keyframes:n}=this.track;if(n.length===0)return;if(n.length===1||e<=n[0].time)return n[0].value;if(e>=n[n.length-1].time)return n[n.length-1].value;const{from:s,to:i}=this.findSurroundingKeyframes(e);if(!s||!i)return;if(s.time===e)return s.value;const r=i.time-s.time,o=(e-s.time)/r,l=cr(i.easing)(o);return Xr(s.value,this.track.interpolation)(s.value,i.value,l)}findSurroundingKeyframes(e){const{keyframes:n}=this.track;for(let s=0;s<n.length-1;s++)if(e>=n[s].time&&e<=n[s+1].time)return{from:n[s],to:n[s+1]};return{from:null,to:null}}}class Br{track;targets;sampler;constructor(e){this.track=e,this.targets=Mt(e),this.sampler=new Hi(e.spring)}getValueAtTime(e){return this.sampler.valueAt(e-Ct(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const r=Ct(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:this.sampler.valueAt(e-r),start:r})}return s}getDuration(){const e=this.track.stagger?Ke(this.targets.length,this.track.stagger):0;return this.sampler.settleTime()+(this.track.delay??0)+e}getTrack(){return this.track}}class Vr{track;targets;duration;constructor(e){this.track=e,this.targets=Mt(e),this.duration=Zn(e.inertia)}getValueAtTime(e){return Qn(this.track.inertia,e-Ct(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,s=[];for(let i=0;i<n;i++){const r=Ct(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:Qn(this.track.inertia,e-r),start:r})}return s}getDuration(){const e=this.track.stagger?Ke(this.targets.length,this.track.stagger):0;return this.duration+(this.track.delay??0)+e}getTrack(){return this.track}}function Hr(t,e){const n={...mr(t.pathData,e)};if(t.matrix){const[s,i,r,o,c,l]=t.matrix,{x:u,y:h}=n;n.x=s*u+r*h+c,n.y=i*u+o*h+l;const d=n.angle*Math.PI/180,f=Math.cos(d),y=Math.sin(d);n.angle=Math.atan2(i*f+o*y,s*f+r*y)*180/Math.PI}return t.autoRotate&&t.rotateOffset&&(n.angle+=t.rotateOffset),n}const ln={upperCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",lowerCase:"abcdefghijklmnopqrstuvwxyz",upperAndLowerCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",numbers:"0123456789"},Ur=20;function Wr(t){const e=ln[t??"upperCase"]??t??ln.upperCase,n=Array.from(e);return n.length>0?n:Array.from(ln.upperCase)}function Gr(t,e,n){let s=(t|0)^Math.imul(e+1,2654435761)^Math.imul(n+1,2246822507);return s=Math.imul(s^s>>>16,2146121005),s=Math.imul(s^s>>>15,2221713035),(s^s>>>16)>>>0}function Zr(t,e,n=0){const s=t.from??"",i=t.to,r=Math.max(0,Math.min(1,e));if(r<=0)return s;if(r>=1)return i;const o=Array.from(s),c=Array.from(i),l=t.rightToLeft??!1;if(t.mode==="type"){const b=Math.round(r*Math.max(o.length,c.length));return l?o.slice(0,Math.max(0,o.length-b)).join("")+c.slice(Math.max(0,c.length-b)).join(""):c.slice(0,b).join("")+o.slice(b).join("")}const u=Math.max(0,Math.min(.999,t.revealDelay??0)),h=Math.max(0,(r-u)/(1-u)),d=Math.floor(h*c.length),f=t.tweenLength===!1?c.length:Math.round(o.length+(c.length-o.length)*r),y=Wr(t.chars),g=t.refreshRate??Ur,p=g>0?Math.floor(n*g/1e3):0,a=t.seed??1;let m="";for(let b=0;b<f;b++){const S=l?b>=f-d:b<d,w=l?c[c.length-(f-b)]:c[b];S&&w!==void 0||w===" "||w===`
2
+ `?m+=w:m+=y[Gr(a,b,p)%y.length]}return m}class Qr{id;name;_captions;_tracks=[];_trackPlayers=new Map;_motionPathTracks=new Map;_springTracks=new Map;_textTracks=new Map;_config;_currentTime=0;_playbackState="idle";_direction="forward";_loopIteration=0;_explicitDuration;_repeatDelayRemaining=0;_wrapAfterDelay=!1;onUpdate=null;onComplete=null;constructor(e){if(this.id=e.id,this.name=e.name,this._captions=e.captions,this._config=e.config??{},this._explicitDuration=e.config?.duration,e.tracks)for(const n of e.tracks)this.addTrack(n)}get tracks(){return[...this._tracks]}get duration(){return this._explicitDuration!==void 0?this._explicitDuration:this._calculateDuration()}setDuration(e){if(this._explicitDuration=e,e!==void 0)this._config={...this._config,duration:e};else if(this._config.duration!==void 0){const n={...this._config};delete n.duration,this._config=n}}get currentTime(){return this._currentTime}get playbackState(){return this._playbackState}get direction(){return this._direction}get loopIteration(){return this._loopIteration}get repeatDelayRemaining(){return this._repeatDelayRemaining}get speed(){return this._config.speed??1}set speed(e){this._config.speed=e}get drawingRate(){return this._config.drawingRate??0}set drawingRate(e){const n={...this._config};e>0?n.drawingRate=e:delete n.drawingRate,this._config=n}play(){const e=this.duration;this._direction==="forward"&&this._currentTime>=e&&e>0?(this._currentTime=0,this._loopIteration=0):this._direction==="reverse"&&this._currentTime<=0&&e>0&&(this._currentTime=e,this._loopIteration=0),this._playbackState="playing"}pause(){this._playbackState="paused"}stop(){this._playbackState="idle",this._repeatDelayRemaining=0,this._wrapAfterDelay=!1,this._currentTime=0,this._loopIteration=0,this._direction="forward"}seek(e){const n=this.duration>0?this.duration:1/0;this._currentTime=Math.max(0,Math.min(e,n)),this._repeatDelayRemaining=0,this._wrapAfterDelay=!1}reverse(){this._direction=this._direction==="forward"?"reverse":"forward"}tick(e){if(this._playbackState!=="playing")return;const n=this.duration;if(n<=0)return;let i=e*this.speed;if(this._repeatDelayRemaining>0){const c=Math.min(this._repeatDelayRemaining,i);if(this._repeatDelayRemaining-=c,i-=c,this._repeatDelayRemaining>0){this.onUpdate?.(this.getStateAtTime(this._currentTime));return}this._wrapAfterDelay&&(this._wrapAfterDelay=!1,this._currentTime=0)}const r=1e3;for(let c=0;c<r&&i>0&&this._playbackState==="playing";c++)if(this._direction==="forward"){const l=n-this._currentTime;if(i>=l){if(i-=l,this._currentTime=n,!this._handleEndReached())break}else this._currentTime+=i,i=0}else{const l=this._currentTime;if(i>=l){if(i-=l,this._currentTime=0,!this._handleStartReached())break}else this._currentTime-=i,i=0}const o=this.getStateAtTime(this._currentTime);this.onUpdate?.(o)}getStateAtTime(e){const n=new Map;if(e=Yi(e,this._config.drawingRate??0),this._hasSharedWrites())this._resolveShared(e,n);else for(const[s,i]of this._trackPlayers){const r=i.getTrack().property;for(const{target:o,value:c,start:l}of i.getTargetValues(e))this._write(n,s,o,r,c,e-l)}return{values:n,currentTime:this._currentTime,playbackState:this._playbackState,direction:this._direction,loopIteration:this._loopIteration}}_resolveShared(e,n){const s=new Map;for(const[i,r]of this._trackPlayers){const o=r.getTrack().property;for(const{target:c,value:l,start:u}of r.getTargetValues(e)){const h=`${c}\0${o}`,d=u<=e,f=s.get(h);(!f||(d!==f.started?d:d?u>=f.start:u<=f.start))&&s.set(h,{trackId:i,target:c,property:o,value:l,start:u,started:d})}}for(const{trackId:i,target:r,property:o,value:c,start:l}of s.values())this._write(n,i,r,o,c,e-l)}_write(e,n,s,i,r,o){if(r===void 0)return;let c=e.get(s);c||(c=new Map,e.set(s,c));const l=this._textTracks.get(n);if(l&&typeof r=="number"){c.set("text",Zr(l.textConfig,r,Math.max(0,o)));return}const u=this._motionPathTracks.get(n);if(u&&typeof r=="number"){const h=Hr(u.motionPathConfig,r);c.set("motionPathX",h.x),c.set("motionPathY",h.y),u.motionPathConfig.autoRotate&&c.set("motionPathRotate",h.angle)}else c.set(i,r)}_sharedWrites=null;_hasSharedWrites(){if(this._sharedWrites===null){const e=new Set;this._sharedWrites=!1;t:for(const n of this._tracks)for(const s of Mt(n)){const i=`${s}\0${n.property}`;if(e.has(i)){this._sharedWrites=!0;break t}e.add(i)}}return this._sharedWrites}addTrack(e){if(this._tracks.push(e),this._sharedWrites=null,Ze(e)){this._trackPlayers.set(e.id,new Vr(e));return}if(Qe(e)){this._trackPlayers.set(e.id,new Br(e)),this._springTracks.set(e.id,e);return}if(Bn(e))this._trackPlayers.set(e.id,new cn(e)),this._textTracks.set(e.id,e);else if(Xi(e)){const n={id:e.id,target:e.target,property:e.property,keyframes:e.keyframes,delay:e.delay,endDelay:e.endDelay,targets:e.targets,stagger:e.stagger};this._trackPlayers.set(e.id,new cn(n)),this._motionPathTracks.set(e.id,e)}else this._trackPlayers.set(e.id,new cn(e))}replaceTrack(e,n){const s=this._tracks.findIndex(r=>r.id===e);if(s<0)return;const i=this._tracks.slice(s+1);this.removeTrack(e);for(const r of i)this.removeTrack(r.id);this.addTrack(n);for(const r of i)this.addTrack(r)}removeTrack(e){this._tracks=this._tracks.filter(n=>n.id!==e),this._sharedWrites=null,this._trackPlayers.delete(e),this._motionPathTracks.delete(e),this._springTracks.delete(e),this._textTracks.delete(e)}getTracks(e={}){return this._tracks.filter(n=>this._matches(n,e))}removeTracks(e={}){const n=this.getTracks(e).map(s=>s.id);for(const s of n)this.removeTrack(s);return n}getTrackSpan(e){const n=this._trackPlayers.get(e);if(!n)return;const s=n.getTrack(),i=s.delay??0;if(Qe(s)||Ze(s))return{from:i,to:n.getDuration()};const r=s.keyframes;if(!(!r||r.length===0))return{from:r[0].time+i,to:n.getDuration()}}findConflicts(){const e=[];for(let n=0;n<this._tracks.length;n++){const s=this._tracks[n],i=this.getTrackSpan(s.id);if(i)for(let r=0;r<n;r++){const o=this._tracks[r];if(o.property!==s.property)continue;const c=Mt(o).filter(d=>Mt(s).includes(d));if(c.length===0)continue;const l=this.getTrackSpan(o.id);if(!l||!(l.from<=i.to&&i.from<=l.to))continue;const h=i.from>=l.from;for(const d of c)e.push({target:d,property:s.property,losingTrackId:h?o.id:s.id,winningTrackId:h?s.id:o.id})}}return e}_matches(e,n){if(n.id!==void 0&&e.id!==n.id||n.property!==void 0&&e.property!==n.property||n.target!==void 0&&!Mt(e).includes(n.target))return!1;if(n.timeRange){const s=this.getTrackSpan(e.id);if(!s||s.to<n.timeRange.from||s.from>n.timeRange.to)return!1}return!0}toDefinition(){return{formatVersion:ji(this._tracks),id:this.id,name:this.name,config:{...this._config},tracks:[...this._tracks],...this.captions&&{captions:this.captions}}}get config(){return this._config}get markers(){return[...this._config.markers??[]].sort((e,n)=>e.time-n.time)}setMarkers(e){const n=e&&e.length>0?[...e].sort((i,r)=>i.time-r.time).map(i=>({...i})):void 0,s={...this._config};n?s.markers=n:delete s.markers,this._config=s}get captions(){return this._captions}setCaptions(e){const n={};for(const[s,i]of Object.entries(e??{}))n[s]={...i};this._captions=Object.keys(n).length>0?n:void 0}_armRepeatDelay(){this._repeatDelayRemaining=this._config.repeatDelay??0}_calculateDuration(){let e=0;for(const[,n]of this._trackPlayers)e=Math.max(e,n.getDuration());return e}_handleEndReached(){const e=this._config.loop??0;return e===-1||this._loopIteration<e?(this._loopIteration++,this._armRepeatDelay(),this._config.alternate?this._direction="reverse":this._repeatDelayRemaining>0?this._wrapAfterDelay=!0:this._currentTime=0,this._repeatDelayRemaining===0):(this._playbackState="idle",this.onComplete?.(),!1)}_handleStartReached(){const e=this._config.loop??0;return this._config.alternate&&(e===-1||this._loopIteration<e)?(this._loopIteration++,this._armRepeatDelay(),this._direction="forward",this._repeatDelayRemaining===0):(this._playbackState="idle",this.onComplete?.(),!1)}}const Kr=100;function Jr(t,e,n,s){const i=[],r=[],{duration:o,alternate:c}=s,l=(y,g,p,a)=>{r.push([y,g]);const m=[];t.forEach((b,S)=>{(p==="forward"?(a?b>=y:b>y)&&b<=g:(a?b<=y:b<y)&&b>=g)&&m.push(S)}),m.sort((b,S)=>(p==="forward"?t[b]-t[S]:t[S]-t[b])||b-S);for(const b of m)i.push({kind:"event",index:b,direction:p})};let u=e.time,h=e.direction,d=e.fresh===!0;const f=Math.min(Kr,Math.max(0,n.iteration-e.iteration));for(let y=0;y<f;y++){const g=h==="forward"?o:0;l(u,g,h,d),i.push({kind:"repeat"}),c?(h=h==="forward"?"reverse":"forward",u=g,d=!1):(u=h==="forward"?0:o,d=!0)}return f>0&&s.holding&&!c?{crossings:i,passes:r}:(l(u,n.time,h,d),{crossings:i,passes:r})}function to(t){return{...t,...Array.isArray(t.end)&&{end:[...t.end]}}}function Qt(t){const e=t.endDelay;return{...t.delay!==void 0&&{delay:t.delay},...e!==void 0&&{endDelay:e},...t.targets!==void 0&&{targets:[...t.targets]},...t.stagger!==void 0&&{stagger:{...t.stagger}}}}function eo(t){if(Ze(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"inertia",inertia:to(e.inertia),...Qt(e)}}if(Qe(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"spring",spring:{...e.spring},...Qt(e)}}if(Bn(t)){const e=t;return{id:e.id,target:e.target,property:"text",textConfig:{...e.textConfig},keyframes:[...e.keyframes].sort((n,s)=>n.time-s.time),...Qt(e)}}if(t.property==="motionPath"&&"motionPathConfig"in t){const e=t,n=[...e.keyframes].sort((s,i)=>s.time-i.time);return{id:e.id,target:e.target,property:"motionPath",motionPathConfig:{...e.motionPathConfig},keyframes:n,...Qt(e)}}return Yr({id:t.id,target:t.target,property:t.property,keyframes:t.keyframes,...t.interpolation!==void 0&&{interpolation:t.interpolation},...Qt(t)})}function ms(t){const e=t.formatVersion??1;if(e>Ge)throw new Error(`tinyfly: this animation uses format version ${e}, but this tinyfly reads up to version ${Ge}. Update tinyfly to play it.`);return new Qr({id:t.id,name:t.name,config:t.config,tracks:t.tracks.map(eo),captions:t.captions})}function $t(t){let e=2166136261;for(let n=0;n<t.length;n++)e^=t.charCodeAt(n),e=Math.imul(e,16777619);return e>>>0}function Nt(t){let e=t>>>0||2654435769;return{seed:t>>>0,next(){return e^=e<<13,e>>>=0,e^=e>>17,e^=e<<5,e>>>=0,e/4294967296}}}function St(t,e=0,n=1){const s=1-t.next(),i=t.next();return e+n*Math.sqrt(-2*Math.log(s))*Math.cos(2*Math.PI*i)}function no(t,e){const n=t.toLowerCase(),s=e.toLowerCase();let i=Array.from({length:s.length+1},(r,o)=>o);for(let r=1;r<=n.length;r++){const o=[r];for(let c=1;c<=s.length;c++)o[c]=Math.min(i[c]+1,o[c-1]+1,i[c-1]+(n[r-1]===s[c-1]?0:1));i=o}return i[s.length]}function bs(t,e){const n=t.toLowerCase(),s=e.find(o=>o.toLowerCase().includes(n)||n.includes(o.toLowerCase()));if(s&&Math.min(t.length,s.length)>=3)return s;let i,r=1/0;for(const o of e){const c=no(t,o);c<r&&(r=c,i=o)}return i!==void 0&&r<=Math.max(2,Math.floor(t.length/3))?i:void 0}function Y(t,e,n,s){const i=typeof e=="string"?bs(e,n):void 0;return`Unknown ${t} ${JSON.stringify(e)}${i?`: did you mean "${i}"?`:"."} Known: ${n.join(", ")}`}function so(t){const[e,n,s,i]=t;return[1-2*(n*n+s*s),2*(e*n+s*i),2*(e*s-n*i),0,2*(e*n-s*i),1-2*(e*e+s*s),2*(n*s+e*i),0,2*(e*s+n*i),2*(n*s-e*i),1-2*(e*e+n*n),0,0,0,0,1]}function io(t){return!Array.isArray(t)||t.length!==4?null:`matrix3d(${so(Zt(t)).map(n=>Math.round(n*1e6)/1e6+0).join(", ")})`}const ro=new Set(["blur","brightness","glow","glowColor","shadowX","shadowY","shadowBlur","shadowColor"]),oo="#ffffff",ao="rgba(0, 0, 0, 0.5)";function co(t){const e=[];if(t.blur!==void 0&&e.push(`blur(${Math.max(0,t.blur)}px)`),t.brightness!==void 0&&e.push(`brightness(${Math.max(0,t.brightness)})`),t.glow!==void 0&&e.push(`drop-shadow(0 0 ${Math.max(0,t.glow)}px ${t.glowColor??oo})`),t.shadowX!==void 0||t.shadowY!==void 0||t.shadowBlur!==void 0){const n=t.shadowX??0,s=t.shadowY??0,i=Math.max(0,t.shadowBlur??0);e.push(`drop-shadow(${n}px ${s}px ${i}px ${t.shadowColor??ao})`)}return e.length>0?e.join(" "):null}function lo(t,e){const n=t.childNodes.length===1?t.firstChild:null;if(n&&n.nodeType===3){const s=n;s.data!==e&&(s.data=e);return}t.textContent!==e&&(t.textContent=e)}function uo(t){if(!("ownerSVGElement"in t))return;const e=t.style;!e||e.transformBox||(e.transformBox="fill-box",e.transformOrigin||(e.transformOrigin="50% 50%"))}const vs=new Set(["width","height","top","right","bottom","left","margin","marginTop","marginRight","marginBottom","marginLeft","padding","paddingTop","paddingRight","paddingBottom","paddingLeft","borderRadius","borderWidth","fontSize","lineHeight","letterSpacing","outlineWidth","gap","rowGap","columnGap"]),ho=new Set(["x","y","z","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skewX","skewY","quaternion","motionPathX","motionPathY","motionPathRotate"]),fo=["x","motionPathX","y","motionPathY","z","rotate","rotateZ","motionPathRotate","rotateX","rotateY","quaternion","scale","scaleX","scaleY","scaleZ","skewX","skewY"],po=new Set(["childPerspective","perspectiveOriginX","perspectiveOriginY"]),go=new Set(["originX","originY"]),yo=new Set(["clipTop","clipRight","clipBottom","clipLeft"]),mo=new Set(["drawOn"]),bo={fill:"backgroundColor",stroke:"borderColor",strokeWidth:"borderWidth",color:"color",backgroundColor:"backgroundColor",borderColor:"borderColor"},ws={fill:"fill",stroke:"stroke",strokeWidth:"strokeWidth",strokeDasharray:"strokeDasharray",strokeDashoffset:"strokeDashoffset",fillOpacity:"fillOpacity",strokeOpacity:"strokeOpacity"},vo="http://www.w3.org/2000/svg";class ks{targets=new Map;registerTarget(e,n){this.targets.set(e,n)}unregisterTarget(e){this.targets.delete(e)}getTarget(e){return this.targets.get(e)}clearTargets(){this.targets.clear()}applyState(e){for(const[n,s]of e.values){const i=this.targets.get(n);i&&this.applyProperties(i,s)}}applyProperties(e,n){let s=null,i=null,r=null,o=null,c=null;const l=n.has("motionPathX"),u=n.has("motionPathY"),h=n.has("motionPathRotate");for(const[g,p]of n)if(!(g==="x"&&l)&&!(g==="y"&&u)&&!((g==="rotate"||g==="rotateZ")&&h)&&!mo.has(g)){if(ho.has(g))(s??={})[g]=p;else if(po.has(g))typeof p=="number"&&((i??={})[g]=p);else if(go.has(g))typeof p=="number"&&((r??={})[g]=p);else if(yo.has(g))typeof p=="number"&&((o??={})[g]=p);else if(ro.has(g))(c??={})[g]=p;else if(g!=="perspective"){if(g!=="shine")if(g==="text"&&typeof p=="string")lo(e,p);else if(g==="d"&&typeof p=="string"){const a=e;(a.tagName?.toLowerCase()==="path"?a:a.querySelector?.("path"))?.setAttribute?.("d",p)}else this.applyStyleProperty(e,g,p)}}const d=n.get("shine");typeof d=="number"&&this.applyShine(e,d);const f=[],y=n.get("perspective");if(typeof y=="number"&&y>0&&f.push(`perspective(${y}px)`),s)for(const g of fo){const p=s[g];if(p===void 0)continue;const a=this.buildTransformPart(g,p);a&&f.push(a)}if(f.length>0&&(e.style.transform=f.join(" "),uo(e)),i&&(i.childPerspective!==void 0&&(e.style.perspective=`${i.childPerspective}px`),(i.perspectiveOriginX!==void 0||i.perspectiveOriginY!==void 0)&&(e.style.perspectiveOrigin=`${i.perspectiveOriginX??50}% ${i.perspectiveOriginY??50}%`)),r){const g=r.originX??50,p=r.originY??50;e.style.transformOrigin=`${g}% ${p}%`}if(o){const g=o.clipTop??0,p=o.clipRight??0,a=o.clipBottom??0,m=o.clipLeft??0;e.style.clipPath=`inset(${g}% ${p}% ${a}% ${m}%)`}if(c){const g=co(c);g&&(e.style.filter=g)}}buildTransformPart(e,n){if(e==="quaternion")return io(n);if(typeof n!="number")return null;switch(e){case"x":case"motionPathX":return`translateX(${n}px)`;case"y":case"motionPathY":return`translateY(${n}px)`;case"z":return`translateZ(${n}px)`;case"rotate":case"rotateZ":case"motionPathRotate":return`rotate(${n}deg)`;case"rotateX":return`rotateX(${n}deg)`;case"rotateY":return`rotateY(${n}deg)`;case"scale":return`scale(${n})`;case"scaleX":return`scaleX(${n})`;case"scaleY":return`scaleY(${n})`;case"scaleZ":return`scaleZ(${n})`;case"skewX":return`skewX(${n}deg)`;case"skewY":return`skewY(${n}deg)`;default:return null}}applyShine(e,n){e.dataset.shineBase||(e.dataset.shineBase=e.style.color||"currentColor");const s=e.dataset.shineBase,i=-20+n*140,r=e.style;r.color="transparent",r.backgroundImage=`linear-gradient(105deg, transparent 40%, rgba(255, 255, 255, 0.9) 50%, transparent 60%), linear-gradient(${s}, ${s})`,r.backgroundSize="250% 100%, 100% 100%",r.backgroundPosition=`${i}% 0, 0 0`,r.backgroundRepeat="no-repeat",r.webkitBackgroundClip="text",r.backgroundClip="text"}applyStyleProperty(e,n,s){let i;if(e.namespaceURI===vo&&n in ws){const c=Array.isArray(s)?s.join(", "):String(s);e.style[ws[n]]=c;return}else n==="fill"&&e.dataset?.elementType==="text"?i="color":i=bo[n]??n;let o;typeof s=="number"?vs.has(n)||vs.has(i)?o=`${s}px`:o=String(s):Array.isArray(s)?o=s.join(", "):o=s,e.style[i]=o}}class Ms{media;offset;driftTolerance;constructor(e,n={}){this.media=e,this.offset=n.offset??0,this.driftTolerance=Math.max(0,n.driftTolerance??.15)}targetTime(e){return Math.max(0,e/1e3+this.offset)}update(e,n){const s=this.targetTime(e);n?(this.media.paused&&this.safePlay(),Math.abs(this.media.currentTime-s)>this.driftTolerance&&(this.media.currentTime=s)):(this.media.paused||this.media.pause(),this.media.currentTime!==s&&(this.media.currentTime=s))}seek(e){this.media.currentTime=this.targetTime(e)}setRate(e){this.media.playbackRate=e}dispose(){this.media.paused||this.media.pause()}safePlay(){const e=this.media.play();e&&typeof e.catch=="function"&&e.catch(()=>{})}}function wo(t,e,n,s,i){const r=n-i;if(r<0){e.paused||e.pause(),e.currentTime=0;return}t.update(r,s)}class ko{container;timeline=null;adapter;animationFrameId;lastTime;options;targets={};isDestroyed=!1;mediaSync;mediaTargets=[];symbolInstances=[];scenarioList=[];scenarioId;authored=new Map;markerList=[];listeners=new Set;playhead={time:0,iteration:0,direction:"forward"};stepping=!1;lastMarkerId=null;reducedQuery;onReducedChange=()=>this.applyReducedMotion();visibilityObserver;onScreen=!0;pausedByVisibility=!1;autoplayWhenSeen=!1;onDocumentVisibility=()=>this.updateVisibility();constructor(e,n={}){if(typeof e=="string"){const s=document.querySelector(e);if(!s)throw new Error(`Container not found: ${e}`);this.container=s}else this.container=e;this.options=n,this.adapter=new ks}async load(e){this.scenarioList=[],this.scenarioId=void 0,await this.loadSource(e)}async loadSource(e){let n;if(typeof e=="string"){const s=await fetch(e);if(!s.ok)throw new Error(`Failed to load animation: ${s.statusText}`);n=await s.json()}else n=e;this.useDefinition(n),this.showInitialFrame(),this.watchReducedMotion(),this.watchVisibility(),this.options.autoplay&&!this.reducedMotion&&(this.options.playWhenVisible&&!this.onScreen?this.autoplayWhenSeen=!0:this.play())}useDefinition(e){const n={...e.config};this.options.speed!==void 0&&(n.speed=this.options.speed),this.options.loop!==void 0&&(n.loop=this.options.loop),this.options.alternate!==void 0&&(n.alternate=this.options.alternate),this.timeline=ms({...e,config:n}),this.markerList=this.timeline.markers,this.lastMarkerId=null,this.options.onComplete&&(this.timeline.onComplete=this.options.onComplete),this.options.onUpdate&&(this.timeline.onUpdate=this.options.onUpdate),this.autoRegisterTargets(),this.setupSymbolInstances(),this.scanMedia()}async loadScenarios(e,n={}){if(e.length===0)throw new Error("tinyfly: loadScenarios needs at least one scenario");const s=new Set;for(const r of e){if(s.has(r.id))throw new Error(`tinyfly: scenario id "${r.id}" is used more than once`);s.add(r.id)}const i=n.initial===void 0?e[0]:e.find(r=>r.id===n.initial);if(!i)throw new Error(`tinyfly: there is no scenario "${n.initial}"`);this.scenarioList=[...e],this.scenarioId=i.id,await this.loadSource(i.timeline)}get scenarios(){return this.scenarioList.map(e=>({id:e.id,label:e.label??e.id}))}get scenario(){return this.scenarioId}setScenario(e){const n=this.scenarioList.find(c=>c.id===e);if(!n||!this.timeline)return!1;if(e===this.scenarioId)return!0;const s=this.isPlaying,i=this.currentTime>=this.duration-.5,r=this.currentMarker?.id;this.stopAnimationLoop(),this.stepping=!1,this.pausedByVisibility=!1,this.restoreAuthored(),this.scenarioId=e,this.useDefinition(n.timeline),this.lastMarkerId=null;let o=0;return this.reducedMotion||i?o=this.duration:r!==void 0&&(o=this.markers.find(c=>c.id===r)?.time??0),this.seek(o),s&&!this.reducedMotion?(this.stepping=this.options.stepMode===!0,this.startPlaying()):this.notify(),!0}rememberAuthored(e){if(this.authored.has(e))return;const n={style:e.getAttribute("style")};e.children.length===0&&(n.text=e.textContent??"");const s=e.tagName.toLowerCase()==="path"?e:e.querySelector("path");s&&(n.path={element:s,d:s.getAttribute("d")}),this.authored.set(e,n)}restoreAuthored(){for(const[e,n]of this.authored){n.style===null?e.removeAttribute("style"):e.setAttribute("style",n.style),n.text!==void 0&&e.textContent!==n.text&&(e.textContent=n.text),n.path&&(n.path.d===null?n.path.element.removeAttribute("d"):n.path.element.setAttribute("d",n.path.d));const s=e.dataset;s&&delete s.shineBase}}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}notify(){for(const e of this.listeners)e()}get reducedMotion(){return this.reducedQuery?.matches===!0}get markers(){return this.markerList}get currentMarker(){const e=this.currentTime;let n;for(const s of this.markers)if(s.time<=e+.5)n=s;else break;return n}caption(e,n){const s=e?this.markers.find(o=>o.id===e):this.currentMarker;if(!s)return;const i=n??this.language(),r=o=>o?.[i]?.[s.id]??o?.[i.split("-")[0]]?.[s.id];return r(this.options.captions)??r(this.timeline?.captions)??s.label}next(){if(!this.timeline)return;const e=this.currentTime,n=this.markers.find(s=>s.time>e+.5);if(this.reducedMotion){this.seek(n?n.time:this.duration);return}e>=this.duration-.5||(this.stepping=n!==void 0,this.startPlaying())}prev(){if(!this.timeline)return;const e=this.currentTime,n=[...this.markers].reverse().find(s=>s.time<e-.5);this.pause(),this.seek(n?n.time:0)}goToMarker(e){const n=this.markers.find(s=>s.id===e);n&&(this.pause(),this.seek(n.time))}language(){return this.container.closest("[lang]")?.getAttribute("lang")||(typeof document<"u"?document.documentElement.lang:"")||"en"}showInitialFrame(){if(!this.timeline)return;const e=this.options.initialFrame??"start";if(e==="none")return;const n=e==="end"?this.timeline.duration:e==="start"?0:e;this.timeline.seek(Math.max(0,Math.min(this.timeline.duration,n))),this.applyState()}watchReducedMotion(){this.options.respectReducedMotion===!1||typeof window>"u"||typeof window.matchMedia!="function"||(this.reducedQuery??=window.matchMedia("(prefers-reduced-motion: reduce)"),this.reducedQuery.addEventListener?.("change",this.onReducedChange),this.reducedQuery.matches&&this.applyReducedMotion())}applyReducedMotion(){!this.reducedMotion||!this.timeline||(this.autoplayWhenSeen=!1,this.pause(),this.seek(this.timeline.duration))}watchVisibility(){if(!(!this.options.playWhenVisible||typeof window>"u")){if(typeof IntersectionObserver=="function"){this.visibilityObserver?.disconnect(),this.visibilityObserver=new IntersectionObserver(n=>{for(const s of n)this.onScreen=s.isIntersecting;this.updateVisibility()}),this.visibilityObserver.observe(this.container);const e=this.container.getBoundingClientRect?.();e&&(e.width>0||e.height>0)&&(this.onScreen=e.bottom>0&&e.top<window.innerHeight&&e.right>0&&e.left<window.innerWidth)}document.addEventListener("visibilitychange",this.onDocumentVisibility)}}updateVisibility(){const e=this.onScreen&&document.visibilityState!=="hidden";!e&&this.isPlaying?(this.pausedByVisibility=!0,this.pause()):e&&(this.pausedByVisibility||this.autoplayWhenSeen)&&!this.reducedMotion&&(this.pausedByVisibility=!1,this.autoplayWhenSeen=!1,this.startPlaying())}announceMarker(){if(!this.options.onMarker)return;const e=this.currentMarker,n=e?.id;n!==this.lastMarkerId&&(this.lastMarkerId=n,this.options.onMarker(e))}scanMedia(){this.mediaTargets=[],this.container.querySelectorAll("[data-tinyfly-media]").forEach(n=>{const s=n,i=Number(s.getAttribute("data-tinyfly-start")??"0")||0,r=s.getAttribute("data-volume");r!==null&&(s.volume=Math.max(0,Math.min(1,Number(r)||0))),this.mediaTargets.push({el:s,startTime:i,sync:new Ms(s)})})}syncAllMedia(e,n){for(const s of this.mediaTargets)wo(s.sync,s.el,e,n,s.startTime)}loadFromString(e){const n=JSON.parse(e);this.load(n)}registerTarget(e,n){if(typeof n=="string"){const s=this.container.querySelector(n);s&&(this.rememberAuthored(s),this.targets[e]=s,this.adapter.registerTarget(e,s))}else this.rememberAuthored(n),this.targets[e]=n,this.adapter.registerTarget(e,n)}autoRegisterTargets(){this.container.querySelectorAll("[data-tinyfly]").forEach(n=>{const s=n.closest("[data-tinyfly-symbol]");if(s&&s!==n)return;const i=n.getAttribute("data-tinyfly");i&&this.registerTarget(i,n)}),this.timeline&&new Set(this.timeline.tracks.map(s=>s.target)).forEach(s=>{if(!this.targets[s]){const i=this.container.querySelector(`[data-tinyfly="${s}"]`)||this.container.querySelector(`.${s}`)||this.container.querySelector(`#${s}`);i&&this.registerTarget(s,i)}})}setupSymbolInstances(){this.symbolInstances=[];const e=this.options.symbols;if(!e||e.length===0)return;const n=new Map(e.map(s=>[s.id,s]));this.container.querySelectorAll("[data-tinyfly-symbol]").forEach(s=>{const i=s.getAttribute("data-tinyfly-symbol");if(!i)return;const r=n.get(i);if(!r||!r.timeline.tracks?.length)return;const o=new ks;s.querySelectorAll("[data-tinyfly]").forEach(c=>{const l=c.getAttribute("data-tinyfly");l&&o.registerTarget(l,c)}),this.symbolInstances.push({adapter:o,timeline:ms(r.timeline)})})}attachMedia(e,n){this.mediaSync=new Ms(e,n),this.timeline&&(this.mediaSync.setRate(this.timeline.speed),this.mediaSync.update(this.timeline.currentTime,this.isPlaying))}detachMedia(){this.mediaSync?.dispose(),this.mediaSync=void 0}play(){!this.timeline||this.isDestroyed||(this.autoplayWhenSeen=!1,this.stepping=this.options.stepMode===!0,this.startPlaying())}startPlaying(){if(!this.timeline||this.isDestroyed)return;const e=this.timeline.playbackState==="idle";this.timeline.play(),e&&this.timeline.currentTime===0&&this.applyState(),this.playhead={time:this.timeline.currentTime,iteration:this.timeline.loopIteration,direction:this.timeline.direction},this.mediaSync?.update(this.timeline.currentTime,!0),this.syncAllMedia(this.timeline.currentTime,!0),this.startAnimationLoop(),this.notify()}pause(){this.timeline&&(this.stepping=!1,this.timeline.pause(),this.notify(),this.mediaSync?.update(this.timeline.currentTime,!1),this.syncAllMedia(this.timeline.currentTime,!1),this.stopAnimationLoop())}stop(){this.timeline&&(this.timeline.stop(),this.stopAnimationLoop(),this.applyState(),this.mediaSync?.update(this.timeline.currentTime,!1),this.syncAllMedia(this.timeline.currentTime,!1))}seek(e){this.timeline&&(this.timeline.seek(e),this.applyState(),this.playhead={time:this.timeline.currentTime,iteration:this.timeline.loopIteration,direction:this.timeline.direction},this.mediaSync?.seek(this.timeline.currentTime),this.syncAllMedia(this.timeline.currentTime,this.isPlaying))}setSpeed(e){this.timeline&&(this.timeline.speed=e,this.mediaSync?.setRate(e))}reverse(){this.timeline&&this.timeline.reverse()}get currentTime(){return this.timeline?.currentTime??0}get state(){return this.timeline?.getStateAtTime(this.timeline.currentTime)}get duration(){return this.timeline?.duration??0}get isPlaying(){return this.timeline?.playbackState==="playing"}destroy(){this.isDestroyed=!0,this.stopAnimationLoop(),this.reducedQuery?.removeEventListener?.("change",this.onReducedChange),this.visibilityObserver?.disconnect(),typeof document<"u"&&document.removeEventListener("visibilitychange",this.onDocumentVisibility),this.mediaSync?.dispose(),this.mediaSync=void 0;for(const e of this.mediaTargets)e.el.paused||e.el.pause();this.mediaTargets=[],this.adapter.clearTargets();for(const e of this.symbolInstances)e.adapter.clearTargets();this.symbolInstances=[],this.authored.clear(),this.timeline=null}startAnimationLoop(){if(this.animationFrameId!==void 0)return;this.lastTime=performance.now();const e=n=>{if(this.isDestroyed||!this.timeline)return;const s=n-(this.lastTime??n);this.lastTime=n;const i=this.playhead;this.timeline.tick(s),this.stopAtMarker(i),this.applyState();const r=this.timeline.playbackState==="playing";this.mediaSync?.update(this.timeline.currentTime,r),this.syncAllMedia(this.timeline.currentTime,r),this.timeline.playbackState==="playing"?this.animationFrameId=requestAnimationFrame(e):(this.animationFrameId=void 0,this.notify())};this.animationFrameId=requestAnimationFrame(e)}stopAtMarker(e){const n=this.timeline,s={time:n.currentTime,iteration:n.loopIteration,direction:n.direction};this.playhead=s;const i=this.markers;if(i.length===0)return;const{crossings:r}=Jr(i.map(o=>o.time),e,s,{duration:n.duration,alternate:n.config.alternate===!0,holding:n.repeatDelayRemaining>0});for(const o of r){if(o.kind!=="event")continue;const c=i[o.index];if(this.stepping||c.pause){this.stepping=!1,n.pause(),n.seek(c.time),this.playhead={time:c.time,iteration:n.loopIteration,direction:n.direction};return}}}stopAnimationLoop(){this.animationFrameId!==void 0&&(cancelAnimationFrame(this.animationFrameId),this.animationFrameId=void 0)}applyState(){if(!this.timeline)return;const e=this.timeline.currentTime;this.adapter.applyState(this.timeline.getStateAtTime(e)),this.announceMarker(),this.notify();for(const n of this.symbolInstances){const s=n.timeline.duration;n.adapter.applyState(n.timeline.getStateAtTime(s>0?e%s:e))}}}const Mo={play:"Play",pause:"Pause",prev:"Previous step",next:"Next step",restart:"Restart",scrub:"Position",speed:"Speed",reveal:"Reveal",step:"Step",of:"of",stepFormat:"{index} / {total}",scenario:"Scenario",fullscreen:"Full screen",exitFullscreen:"Exit full screen"},$s="tinyfly-controls-style",$o=`
3
3
  .tf-ctl { --tf-ctl-fg: #1d1d1f; --tf-ctl-bg: #f4f2ee; --tf-ctl-accent: #c2410c; --tf-ctl-radius: 8px;
4
4
  font: 14px/1.4 var(--tf-ctl-font, system-ui, sans-serif); color: var(--tf-ctl-fg); margin-top: 8px; }
5
5
  .tf-ctl-bar { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; padding: 6px; border-radius: var(--tf-ctl-radius); background: var(--tf-ctl-bg); }
@@ -47,7 +47,7 @@
47
47
  .tf-fullscreen > svg, .tf-fullscreen > canvas { grid-column: 1; grid-row: 1 / span 12; height: calc(100vh - 24px) !important; height: calc(100dvh - 24px) !important; }
48
48
  .tf-fullscreen > :not(svg):not(canvas) { grid-column: 2; }
49
49
  }
50
- `;let So=0;function xo(t){if(t.getElementById(Ms))return;const e=t.createElement("style");e.id=Ms,e.textContent=$o,t.head.appendChild(e)}function Ao(t,e,n={}){const s=e.ownerDocument;xo(s);const i={...Mo,...n.labels},r=n.speeds??[.5,1,2],o=()=>t.markers.length>0,c=()=>t.markers.some(P=>P.label!==void 0||t.caption(P.id)!==void 0),l=s.createElement("div");l.className="tf-ctl";const u=s.createElement("div");u.className="tf-ctl-bar",u.setAttribute("role","group");const h=(P,F,L,B="")=>{const z=s.createElement("button");return z.type="button",z.className=`tf-ctl-btn ${B}`.trim(),z.setAttribute("aria-label",P),z.title=P,z.textContent=F,z.addEventListener("click",L),z},d=h(i.restart,"⟲",()=>{t.pause(),t.seek(0)}),f=h(i.prev,"|◀",()=>t.prev()),y=h(i.play,"▶",()=>t.isPlaying?t.pause():p(),"tf-ctl-primary"),g=h(i.next,"▶|",()=>t.next()),p=()=>{t.currentTime>=t.duration-.5&&t.seek(0),t.play()},a=s.createElement("input");a.type="range",a.className="tf-ctl-scrub",a.min="0",a.max="1000",a.step="1",a.setAttribute("aria-label",i.scrub),a.addEventListener("input",()=>{t.pause(),t.seek(Number(a.value)/1e3*t.duration)});const m=s.createElement("span");m.className="tf-ctl-step";const b=s.createElement("select");b.className="tf-ctl-speed",b.setAttribute("aria-label",i.speed);for(const P of r){const F=s.createElement("option");F.value=String(P),F.textContent=`${P}×`,P===1&&(F.selected=!0),b.appendChild(F)}b.addEventListener("change",()=>t.setSpeed(Number(b.value))),u.append(d,f,y,g,a,m),r.length>0&&u.append(b),l.append(u);const S=n.fullscreen?Po(e,s,i):void 0;S&&u.append(S.button);const v=s.createElement("p");v.className="tf-ctl-caption",v.setAttribute("aria-live","polite"),n.captions!==!1&&l.append(v);const w=s.createElement("div");w.className="tf-ctl-question",w.hidden=!0;const k=s.createElement("span"),x=h(i.reveal,i.reveal,()=>t.play(),"tf-ctl-primary");w.append(k,x),l.append(w);const M=Eo(t,s,i.scenario,n.scenarioControl??"buttons");M&&l.append(M.element);const E=n.mount;E?E.appendChild(l):e.insertAdjacentElement("afterend",l);const A=()=>{const P=t.isPlaying;y.textContent=P?"❚❚":"▶",y.setAttribute("aria-label",P?i.pause:i.play),y.title=P?i.pause:i.play;const F=t.duration;s.activeElement!==a&&(a.value=String(F>0?Math.round(t.currentTime/F*1e3):0));const L=t.markers;if(f.hidden=g.hidden=m.hidden=L.length===0,L.length>0){const B=t.currentMarker,z=B?L.indexOf(B)+1:0;m.textContent=i.stepFormat.replace("{index}",String(z)).replace("{total}",String(L.length)),m.setAttribute("aria-label",`${i.step} ${z} ${i.of} ${L.length}`),f.disabled=t.currentTime<=.5,g.disabled=t.currentTime>=F-.5;const q=t.caption()??"";v.textContent!==q&&(v.textContent=q),v.hidden=!c();const H=!P&&B?.question!==void 0&&Math.abs(t.currentTime-B.time)<1;w.hidden=!H,H&&k.textContent!==B.question&&(k.textContent=B.question)}else w.hidden=!0,v.hidden=!0;M?.update()},_=t.subscribe(A);A();const T=n.keyboardScope??e;!T.hasAttribute("tabindex")&&T.tabIndex<0&&(T.tabIndex=0);const C=new WeakSet,N=P=>{if(C.has(P)||(C.add(P),P.defaultPrevented||P.altKey||P.ctrlKey||P.metaKey))return;const F=P.target;if(!(F.tagName==="INPUT"||F.tagName==="SELECT")&&!(P.key===" "&&F.tagName==="BUTTON"))switch(P.key){case" ":P.preventDefault(),t.isPlaying?t.pause():p();break;case"ArrowRight":if(!o())return;P.preventDefault(),t.next();break;case"ArrowLeft":if(!o())return;P.preventDefault(),t.prev();break;case"Home":P.preventDefault(),t.pause(),t.seek(0);break;case"f":case"F":if(!S)return;P.preventDefault(),S.active?S.exit():S.enter();break}};return T.addEventListener("keydown",N),l.addEventListener("keydown",N),{element:l,fullscreen:S&&{get active(){return S.active},enter:S.enter,exit:S.exit},destroy(){S?.destroy(),_(),T.removeEventListener("keydown",N),l.removeEventListener("keydown",N),l.remove()}}}function Eo(t,e,n,s){const i=t.scenarios;if(i.length<2)return;if(s==="slider"){const h=e.createElement("div");h.className="tf-ctl-choice-slider";const d=e.createElement("span");d.textContent=n,d.setAttribute("aria-hidden","true");const f=e.createElement("input");f.type="range",f.min="0",f.max=String(i.length-1),f.step="1",f.setAttribute("aria-label",n);const y=e.createElement("output");return y.setAttribute("aria-hidden","true"),f.addEventListener("input",()=>{const p=i[Number(f.value)];p&&t.setScenario(p.id)}),h.append(d,f,y),{element:h,update:()=>{const p=Math.max(0,i.findIndex(m=>m.id===t.scenario));e.activeElement!==f&&(f.value=String(p));const a=i[p].label;y.textContent!==a&&(y.textContent=a),f.setAttribute("aria-valuetext",a)}}}const r=e.createElement("fieldset");r.className="tf-ctl-choices";const o=e.createElement("legend");o.textContent=n,r.append(o);const c=`tf-ctl-scenario-${++So}`,l=i.map(h=>{const d=e.createElement("label");d.className="tf-ctl-choice";const f=e.createElement("input");f.type="radio",f.name=c,f.value=h.id,f.addEventListener("change",()=>{f.checked&&t.setScenario(h.id)});const y=e.createElement("span");return y.textContent=h.label,d.append(f,y),r.append(d),f});return{element:r,update:()=>{for(const h of l){const d=h.value===t.scenario;h.checked!==d&&(h.checked=d)}}}}const To='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>',_o='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>';function Po(t,e,n){const s=e,i=t,r=e.createElement("button");r.type="button",r.className="tf-ctl-btn tf-ctl-fullscreen";let o,c="";const l=()=>{const p=o!==void 0;r.innerHTML=p?_o:To;const a=p?n.exitFullscreen:n.fullscreen;r.setAttribute("aria-label",a),r.title=a,r.setAttribute("aria-pressed",String(p)),t.classList.toggle("tf-fullscreen",p),t.classList.toggle("tf-fullscreen-overlay",o==="overlay")},u=()=>s.fullscreenElement??s.webkitFullscreenElement??null,h=()=>{u()===t?o="native":o==="native"&&(o=void 0),l()},d=p=>{p.key==="Escape"&&g()},f=()=>{o="overlay",c=e.documentElement.style.overflow,e.documentElement.style.overflow="hidden",e.addEventListener("keydown",d),l()};async function y(){if(o)return;const p=i.requestFullscreen?.bind(i)??i.webkitRequestFullscreen?.bind(i),a=s.fullscreenEnabled??s.webkitFullscreenEnabled??!1;if(p&&a)try{if(await p(),u()===t){o="native",l();return}}catch{}f()}async function g(){if(o==="overlay")e.removeEventListener("keydown",d),e.documentElement.style.overflow=c,o=void 0,l();else if(o==="native"){o=void 0,l();const p=s.exitFullscreen?.bind(s)??s.webkitExitFullscreen?.bind(s);u()===t&&p&&await p()}}return r.addEventListener("click",()=>{o?g():y()}),e.addEventListener("fullscreenchange",h),e.addEventListener("webkitfullscreenchange",h),l(),{button:r,get active(){return o!==void 0},enter:y,exit:g,destroy(){g(),e.removeEventListener("fullscreenchange",h),e.removeEventListener("webkitfullscreenchange",h),r.remove()}}}const $s="tinyfly-choices-style",Oo=`
50
+ `;let So=0;function xo(t){if(t.getElementById($s))return;const e=t.createElement("style");e.id=$s,e.textContent=$o,t.head.appendChild(e)}function Ao(t,e,n={}){const s=e.ownerDocument;xo(s);const i={...Mo,...n.labels},r=n.speeds??[.5,1,2],o=()=>t.markers.length>0,c=()=>t.markers.some(P=>P.label!==void 0||t.caption(P.id)!==void 0),l=s.createElement("div");l.className="tf-ctl";const u=s.createElement("div");u.className="tf-ctl-bar",u.setAttribute("role","group");const h=(P,O,I,L="")=>{const D=s.createElement("button");return D.type="button",D.className=`tf-ctl-btn ${L}`.trim(),D.setAttribute("aria-label",P),D.title=P,D.textContent=O,D.addEventListener("click",I),D},d=h(i.restart,"⟲",()=>{t.pause(),t.seek(0)}),f=h(i.prev,"|◀",()=>t.prev()),y=h(i.play,"▶",()=>t.isPlaying?t.pause():p(),"tf-ctl-primary"),g=h(i.next,"▶|",()=>t.next()),p=()=>{t.currentTime>=t.duration-.5&&t.seek(0),t.play()},a=s.createElement("input");a.type="range",a.className="tf-ctl-scrub",a.min="0",a.max="1000",a.step="1",a.setAttribute("aria-label",i.scrub),a.addEventListener("input",()=>{t.pause(),t.seek(Number(a.value)/1e3*t.duration)});const m=s.createElement("span");m.className="tf-ctl-step";const b=s.createElement("select");b.className="tf-ctl-speed",b.setAttribute("aria-label",i.speed);for(const P of r){const O=s.createElement("option");O.value=String(P),O.textContent=`${P}×`,P===1&&(O.selected=!0),b.appendChild(O)}b.addEventListener("change",()=>t.setSpeed(Number(b.value))),u.append(d,f,y,g,a,m),r.length>0&&u.append(b),l.append(u);const S=n.fullscreen?Po(e,s,i):void 0;S&&u.append(S.button);const w=s.createElement("p");w.className="tf-ctl-caption",w.setAttribute("aria-live","polite"),n.captions!==!1&&l.append(w);const v=s.createElement("div");v.className="tf-ctl-question",v.hidden=!0;const k=s.createElement("span"),x=h(i.reveal,i.reveal,()=>t.play(),"tf-ctl-primary");v.append(k,x),l.append(v);const M=Eo(t,s,i.scenario,n.scenarioControl??"buttons");M&&l.append(M.element);const A=n.mount;A?A.appendChild(l):e.insertAdjacentElement("afterend",l);const E=()=>{const P=t.isPlaying;y.textContent=P?"❚❚":"▶",y.setAttribute("aria-label",P?i.pause:i.play),y.title=P?i.pause:i.play;const O=t.duration;s.activeElement!==a&&(a.value=String(O>0?Math.round(t.currentTime/O*1e3):0));const I=t.markers;if(f.hidden=g.hidden=m.hidden=I.length===0,I.length>0){const L=t.currentMarker,D=L?I.indexOf(L)+1:0;m.textContent=i.stepFormat.replace("{index}",String(D)).replace("{total}",String(I.length)),m.setAttribute("aria-label",`${i.step} ${D} ${i.of} ${I.length}`),f.disabled=t.currentTime<=.5,g.disabled=t.currentTime>=O-.5;const z=t.caption()??"";w.textContent!==z&&(w.textContent=z),w.hidden=!c();const q=!P&&L?.question!==void 0&&Math.abs(t.currentTime-L.time)<1;v.hidden=!q,q&&k.textContent!==L.question&&(k.textContent=L.question)}else v.hidden=!0,w.hidden=!0;M?.update()},_=t.subscribe(E);E();const T=n.keyboardScope??e;!T.hasAttribute("tabindex")&&T.tabIndex<0&&(T.tabIndex=0);const F=new WeakSet,R=P=>{if(F.has(P)||(F.add(P),P.defaultPrevented||P.altKey||P.ctrlKey||P.metaKey))return;const O=P.target;if(!(O.tagName==="INPUT"||O.tagName==="SELECT")&&!(P.key===" "&&O.tagName==="BUTTON"))switch(P.key){case" ":P.preventDefault(),t.isPlaying?t.pause():p();break;case"ArrowRight":if(!o())return;P.preventDefault(),t.next();break;case"ArrowLeft":if(!o())return;P.preventDefault(),t.prev();break;case"Home":P.preventDefault(),t.pause(),t.seek(0);break;case"f":case"F":if(!S)return;P.preventDefault(),S.active?S.exit():S.enter();break}};return T.addEventListener("keydown",R),l.addEventListener("keydown",R),{element:l,fullscreen:S&&{get active(){return S.active},enter:S.enter,exit:S.exit},destroy(){S?.destroy(),_(),T.removeEventListener("keydown",R),l.removeEventListener("keydown",R),l.remove()}}}function Eo(t,e,n,s){const i=t.scenarios;if(i.length<2)return;if(s==="slider"){const h=e.createElement("div");h.className="tf-ctl-choice-slider";const d=e.createElement("span");d.textContent=n,d.setAttribute("aria-hidden","true");const f=e.createElement("input");f.type="range",f.min="0",f.max=String(i.length-1),f.step="1",f.setAttribute("aria-label",n);const y=e.createElement("output");return y.setAttribute("aria-hidden","true"),f.addEventListener("input",()=>{const p=i[Number(f.value)];p&&t.setScenario(p.id)}),h.append(d,f,y),{element:h,update:()=>{const p=Math.max(0,i.findIndex(m=>m.id===t.scenario));e.activeElement!==f&&(f.value=String(p));const a=i[p].label;y.textContent!==a&&(y.textContent=a),f.setAttribute("aria-valuetext",a)}}}const r=e.createElement("fieldset");r.className="tf-ctl-choices";const o=e.createElement("legend");o.textContent=n,r.append(o);const c=`tf-ctl-scenario-${++So}`,l=i.map(h=>{const d=e.createElement("label");d.className="tf-ctl-choice";const f=e.createElement("input");f.type="radio",f.name=c,f.value=h.id,f.addEventListener("change",()=>{f.checked&&t.setScenario(h.id)});const y=e.createElement("span");return y.textContent=h.label,d.append(f,y),r.append(d),f});return{element:r,update:()=>{for(const h of l){const d=h.value===t.scenario;h.checked!==d&&(h.checked=d)}}}}const To='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>',_o='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>';function Po(t,e,n){const s=e,i=t,r=e.createElement("button");r.type="button",r.className="tf-ctl-btn tf-ctl-fullscreen";let o,c="";const l=()=>{const p=o!==void 0;r.innerHTML=p?_o:To;const a=p?n.exitFullscreen:n.fullscreen;r.setAttribute("aria-label",a),r.title=a,r.setAttribute("aria-pressed",String(p)),t.classList.toggle("tf-fullscreen",p),t.classList.toggle("tf-fullscreen-overlay",o==="overlay")},u=()=>s.fullscreenElement??s.webkitFullscreenElement??null,h=()=>{u()===t?o="native":o==="native"&&(o=void 0),l()},d=p=>{p.key==="Escape"&&g()},f=()=>{o="overlay",c=e.documentElement.style.overflow,e.documentElement.style.overflow="hidden",e.addEventListener("keydown",d),l()};async function y(){if(o)return;const p=i.requestFullscreen?.bind(i)??i.webkitRequestFullscreen?.bind(i),a=s.fullscreenEnabled??s.webkitFullscreenEnabled??!1;if(p&&a)try{if(await p(),u()===t){o="native",l();return}}catch{}f()}async function g(){if(o==="overlay")e.removeEventListener("keydown",d),e.documentElement.style.overflow=c,o=void 0,l();else if(o==="native"){o=void 0,l();const p=s.exitFullscreen?.bind(s)??s.webkitExitFullscreen?.bind(s);u()===t&&p&&await p()}}return r.addEventListener("click",()=>{o?g():y()}),e.addEventListener("fullscreenchange",h),e.addEventListener("webkitfullscreenchange",h),l(),{button:r,get active(){return o!==void 0},enter:y,exit:g,destroy(){g(),e.removeEventListener("fullscreenchange",h),e.removeEventListener("webkitfullscreenchange",h),r.remove()}}}const Ss="tinyfly-choices-style",Oo=`
51
51
  [data-tinyfly-choose] { cursor: pointer; }
52
52
  [data-tinyfly-choose]:focus-visible { outline: 2px solid var(--tf-ctl-accent, #c2410c); outline-offset: 2px; }
53
- `;function Io(t){if(t.getElementById($s))return;const e=t.createElement("style");e.id=$s,e.textContent=Oo,t.head.appendChild(e)}function Co(t,e){const n=Array.from(e.querySelectorAll("[data-tinyfly-choose]"));if(n.length===0)return()=>{};Io(e.ownerDocument);const s=[],i=[];for(const c of n){const l=c.getAttribute("data-tinyfly-choose")??"",u=[],h=(g,p)=>{c.hasAttribute(g)||(c.setAttribute(g,p),u.push(g))};h("role","button"),h("tabindex","0");const d=t.scenarios.find(g=>g.id===l)?.label;d!==void 0&&h("aria-label",d),c.setAttribute("aria-pressed","false"),u.push("aria-pressed"),s.push({element:c,attributes:u});const f=()=>t.setScenario(l),y=g=>{const p=g.key;p!=="Enter"&&p!==" "||(g.preventDefault(),f())};c.addEventListener("click",f),c.addEventListener("keydown",y),i.push(()=>{c.removeEventListener("click",f),c.removeEventListener("keydown",y)})}const r=()=>{for(const{element:c}of s)c.setAttribute("aria-pressed",String(c.getAttribute("data-tinyfly-choose")===t.scenario))},o=t.subscribe(r);return r(),()=>{o();for(const c of i)c();for(const{element:c,attributes:l}of s)for(const u of l)c.removeAttribute(u)}}const Ss=new WeakMap,No=new WeakMap;let Fo=0;function Gt(t,e,n){if(t)try{return JSON.parse(t)}catch(s){console.warn(`tinyfly: invalid ${e} JSON on`,n,s);return}}async function Lo(t,e={}){const n=Ss.get(t);if(n)return n;const s=Array.from(t.querySelectorAll("script[data-tinyfly-timeline]")),i=s[0],r=t.getAttribute("data-src"),o=Do(t.getAttribute("data-markers")),c=s.length>1||i?.hasAttribute("data-scenario")?Ro(s,o,t):void 0;if(c&&c.length===0)return;let l=i&&!c?Gt(i.textContent,"timeline",t):void 0;if(!l&&r&&o){const y=await fetch(r);y.ok&&(l=await y.json())}if(l&&o&&(l=xs(l,o)),!l&&!r&&!c){console.warn('tinyfly: embed has no timeline (a <script type="application/json" data-tinyfly-timeline> or data-src)',t);return}const u=Gt(t.querySelector("script[data-tinyfly-captions]")?.textContent,"captions",t),h={playWhenVisible:!0,...e.player,...u&&{captions:u},...Gt(t.getAttribute("data-options"),"data-options",t)};qo(t);const d=new ko(t,h),f={element:t,player:d};if(Ss.set(t,f),t.setAttribute("data-tinyfly-mounted",""),c){const y=t.getAttribute("data-scenario")??void 0;await d.loadScenarios(c,{initial:c.some(g=>g.id===y)?y:void 0}),No.set(t,Co(d,t))}else await d.load(l??r);if(t.getAttribute("data-controls")!=="false"){const y=Gt(t.getAttribute("data-labels"),"data-labels",t),g=t.querySelector("figcaption"),p=t.getAttribute("data-scenario-legend"),a=t.getAttribute("data-scenario-control");f.controls=Ao(d,t,{...e.controls,...t.getAttribute("data-fullscreen")==="true"?{fullscreen:!0}:{},...a==="slider"||a==="buttons"?{scenarioControl:a}:{},labels:{...e.controls?.labels,...y,...p?{scenario:p}:{}},mount:void 0}),g?t.insertBefore(f.controls.element,g):t.appendChild(f.controls.element)}return f}function Ro(t,e,n){const s=[];return t.forEach((i,r)=>{const o=Gt(i.textContent,"timeline",n);if(!o)return;const c=i.getAttribute("data-scenario")||`scenario-${r+1}`;if(s.some(u=>u.id===c)){console.warn(`tinyfly: scenario id "${c}" is used more than once; the later one is skipped`,n);return}const l=i.getAttribute("data-scenario-label")??void 0;s.push({id:c,label:l,timeline:e?xs(o,e):o})}),s}function xs(t,e){return t.config.markers?.length?t:{...t,config:{...t.config,markers:e.map((n,s)=>({id:`step-${s+1}`,time:n}))}}}function Do(t){if(!t)return;const e=t.split(/[\s,]+/).filter(Boolean).map(Number).filter(n=>Number.isFinite(n)&&n>=0).sort((n,s)=>n-s);return e.length>0?e:void 0}function qo(t){const e=t.querySelector("svg");if(!e||e.hasAttribute("role")||e.hasAttribute("aria-hidden"))return;const n=t.getAttribute("data-alt"),s=t.querySelector("figcaption");e.setAttribute("role","img"),n?e.setAttribute("aria-label",n):s&&(s.id||=`tinyfly-caption-${++Fo}`,e.setAttribute("aria-labelledby",s.id))}const ln=["grid","axes","vector","basis","point","function","parametric","polygon","line","label","equation","tangent","riemann","area","taylor","histogram","distribution","galton","scatter","bayes","graph","venn","clock","network","heatmap","contours","descent","classifier","kmeans"],ve={dark:{background:"#0f1117",ink:"#f2f2f2",grid:"#29abca",ghost:"rgba(255,255,255,0.18)",axes:"#f2f2f2",colors:{blue:"#58c4dd",green:"#83c167",red:"#fc6255",yellow:"#ffd75e",purple:"#b189f0",orange:"#ff9b4d",teal:"#5cd0b3",pink:"#f58ad1",ink:"#f2f2f2",grey:"#8a8f99"}},light:{background:"#fbfaf7",ink:"#1f2430",grid:"#7fb3d5",ghost:"rgba(31,36,48,0.14)",axes:"#1f2430",colors:{blue:"#2f6fd0",green:"#2f9a4a",red:"#d64545",yellow:"#c99a00",purple:"#7b4fc9",orange:"#e0761f",teal:"#178f7c",pink:"#c94f9c",ink:"#1f2430",grey:"#7a808c"}},chalk:{background:"#23332b",ink:"#eef0e6",grid:"rgba(238,240,230,0.35)",ghost:"rgba(238,240,230,0.14)",axes:"#eef0e6",colors:{blue:"#9fd3f0",green:"#b9e39a",red:"#f59a8f",yellow:"#f6e58d",purple:"#d0b5f2",orange:"#f7c08a",teal:"#a3e4d4",pink:"#f4b6dc",ink:"#eef0e6",grey:"#a9b0a6"}}},Zt=[1,0,0,1],it=([t,e,n,s],[i,r])=>[t*i+e*r,n*i+s*r];function zo(t,e){const[n,s,i,r]=t,[o,c,l,u]=e;return[n*o+s*l,n*c+s*u,i*o+r*l,i*c+r*u]}const Qt=([t,e,n,s])=>t*s-e*n;function jo(t){const e=Qt(t);if(Math.abs(e)<1e-12)return;const[n,s,i,r]=t;return[r/e,-s/e,-i/e,n/e]}const Xo=(t,e,n)=>t.map((s,i)=>s+(e[i]-s)*n),Yo=t=>[Math.cos(t),-Math.sin(t),Math.sin(t),Math.cos(t)];function As(t){const[e,n,s,i]=t,r=e+i,o=Qt(t),c=r*r-4*o,l=1e-9;if(c<-l)return[];const u=Math.sqrt(Math.max(0,c)),h=u<l?[r/2]:[(r+u)/2,(r-u)/2],d=[];for(const f of h){const g=[[e-f,n],[s,i-f]].reduce((b,S)=>Math.hypot(...S)>Math.hypot(...b)?S:b);if(Math.hypot(...g)<l){d.push({value:f,vector:[1,0]},{value:f,vector:[0,1]});continue}const p=[-g[1],g[0]],a=Math.hypot(...p),m=p[0]<-l||Math.abs(p[0])<=l&&p[1]<0?-1:1;d.push({value:f,vector:[m*p[0]/a+0,m*p[1]/a+0]})}return d}function Ot(t){return Array.isArray(t)&&t.length===4&&t.every(Number.isFinite)}const Bo=Object.freeze(Object.defineProperty({__proto__:null,IDENTITY:Zt,apply:it,determinant:Qt,eigen:As,inverse:jo,isMat2:Ot,lerp:Xo,multiply:zo,rotation:Yo},Symbol.toStringTag,{value:"Module"})),Vo=(t,e)=>[t[0]+e[0],t[1]+e[1]],un=(t,e)=>[t[0]-e[0],t[1]-e[1]],hn=(t,e)=>[t[0]*e,t[1]*e],Ho=(t,e)=>t[0]*e[0]+t[1]*e[1],Uo=(t,e)=>t[0]*e[1]-t[1]*e[0],Es=t=>Math.hypot(t[0],t[1]);function Kt(t){const e=Es(t);return e===0?[0,0]:[t[0]/e,t[1]/e]}const Jt=(t,e,n)=>[t[0]+(e[0]-t[0])*n,t[1]+(e[1]-t[1])*n];function ct(t){return Array.isArray(t)&&t.length===2&&t.every(Number.isFinite)}const Wo=Object.freeze(Object.defineProperty({__proto__:null,add:Vo,cross:Uo,dot:Ho,isVec2:ct,length:Es,lerp:Jt,normalize:Kt,scale:hn,sub:un},Symbol.toStringTag,{value:"Module"}));function Ts(t){const e={};for(const[n,s]of Object.entries(t))if(typeof s=="number")e[n]=s;else if(Ot(s)){const[i,r,o,c]=s;Object.assign(e,{[`${n}.a`]:i,[`${n}.b`]:r,[`${n}.c`]:o,[`${n}.d`]:c,[`${n}.det`]:Qt(s)})}else ct(s)&&Object.assign(e,{[`${n}.x`]:s[0],[`${n}.y`]:s[1],[`${n}.length`]:Math.hypot(s[0],s[1])});return e}function O(t,e,n){return e?Object.prototype.hasOwnProperty.call(t.colors,e)?t.colors[e]:e:n}function It(t,e){if(typeof e!="string")return e;const n=t[e];if(!ct(n))throw new Error(`math figure: value "${e}" is not an [x, y] vector`);return n}function kt(t,e){if(e===void 0)return Zt;const n=t[e];if(!Ot(n))throw new Error(`math figure: value "${e}" is not a [a, b, c, d] matrix`);return n}function I(t,e){if(typeof e=="number")return e;const n=t[e];if(typeof n!="number")throw new Error(`math figure: value "${e}" is not a number`);return n}function Ct(t,e){const n=i=>i===void 0?void 0:I(t,i),s=i=>i===void 0?void 0:Math.round(I(t,i));switch(e.kind){case"normal":return{kind:"normal",mean:n(e.mean),sd:n(e.sd)};case"uniform":return{kind:"uniform",min:n(e.min),max:n(e.max)};case"exponential":return{kind:"exponential",rate:n(e.rate)};case"binomial":return{kind:"binomial",n:s(e.n),p:n(e.p)};case"poisson":return{kind:"poisson",rate:n(e.rate)};case"dice":return{kind:"dice",count:s(e.count),sides:s(e.sides)};case"mean":return{kind:"mean",of:Ct(t,e.of),count:s(e.count)}}}function dn(t){const{width:e,height:n}=t,s=t.x??[-5,5],i=e/(s[1]-s[0]),r=t.y??[-(n/i)/2,n/i/2],o=n/(r[1]-r[0]);return{width:e,height:n,x:s,y:r,unitX:i,unitY:o,scale:Math.min(e,n)/600,toScreen:([c,l])=>[(c-s[0])*i,(r[1]-l)*o],toWorld:([c,l])=>[s[0]+c/i,r[1]-l/o]}}const _s='"Latin Modern Math", "STIX Two Math", "Cambria Math", "Times New Roman", "Liberation Serif", "Noto Serif", Times, serif',Ps='"Latin Modern Math", "STIX Two Math", "Cambria Math", "DejaVu Math TeX Gyre", "DejaVu Serif", serif',Go=t=>/^[A-Za-z0-9\u0370-\u03ff.,;:!?()[\]'"/ ]+$/.test(t)?_s:Ps,Os=.25,te=.05,Is={a:.5,b:.56,c:.44,d:.56,e:.44,f:.31,g:.5,h:.56,i:.28,j:.31,k:.53,l:.28,m:.83,n:.56,o:.5,p:.56,q:.53,r:.39,s:.39,t:.39,u:.56,v:.53,w:.72,x:.53,y:.53,z:.44,A:.75,B:.71,C:.72,D:.76,E:.68,F:.65,G:.78,H:.75,I:.36,J:.51,K:.78,L:.63,M:.92,N:.75,O:.78,P:.68,Q:.78,R:.74,S:.56,T:.72,U:.75,V:.75,W:1.03,X:.75,Y:.75,Z:.61};function fn(t){return t.length!==1?t.length*.5:/[0-9]/.test(t)?.5:Object.prototype.hasOwnProperty.call(Is,t)?Is[t]+.04:"()[]".includes(t)?.39:"{}".includes(t)?.5:"|".includes(t)||",.;:!".includes(t)||"'’‘".includes(t)?.28:"-‐".includes(t)?.33:"′″".includes(t)?.3:"+−=<>±×÷≤≥≠≈∼≡∝→←↔⇒⇔∈∉⊂⊃⊆⊇∪∩∧∨".includes(t)?.78:"·∘".includes(t)?.28:"∑∏".includes(t)?1.05:"∫".includes(t)?.56:"∞".includes(t)||"…⋯".includes(t)?1:/[Α-Ω]/.test(t)?.72:/[α-ω]/.test(t)?.56:.6}function Cs(t){return"gjpqy(),;[]{}|∫".includes(t)||"βγζημξρφχψ".includes(t)?{height:.72,depth:.22}:"∑∏".includes(t)?{height:.75,depth:.25}:/[a-z]/.test(t)&&!"bdfhklt".includes(t)?{height:.45,depth:0}:{height:.7,depth:0}}const Mt='system-ui, -apple-system, "Segoe UI", sans-serif',Ns=(t,e)=>Math.hypot(e[0]-t[0],e[1]-t[1]);function V(t,e){if(e>=1)return t;if(e<=0)return[];const n=t.map(r=>r.slice(1).reduce((o,c,l)=>o+Ns(r[l],c),0));let s=n.reduce((r,o)=>r+o,0)*e;const i=[];for(const[r,o]of t.entries()){if(s<=0)break;if(n[r]<=s){i.push(o),s-=n[r];continue}const c=[o[0]];for(let l=1;l<o.length;l++){const u=Ns(o[l-1],o[l]);if(u>=s){const h=u===0?0:s/u;c.push([o[l-1][0]+(o[l][0]-o[l-1][0])*h,o[l-1][1]+(o[l][1]-o[l-1][1])*h]);break}c.push(o[l]),s-=u}i.push(c),s=0}return i}function pn(t,e){const n=e.align??"center",s=n==="left"?0:n==="right"?-t.width:-t.width/2,i=e.baseline==="baseline"?0:(t.height-t.depth)/2;return[e.x+s*e.size,e.y+i*e.size]}function Fs(t,e,n){const[s,i]=e,r=n.size,o=n.opacity??1;return t.map(c=>{const l=(c.color&&n.palette?.[c.color])??c.color??n.color,u=o*(c.opacity??1),h=`${n.idPrefix}${c.id}`;if(c.kind==="glyph")return{type:"text",id:h,text:c.text,x:s+(c.x+c.width/2)*r,y:i+c.y*r,size:c.size*r,font:Go(c.text),italic:c.italic,color:l,align:"center",opacity:u};if(c.kind==="rule"){const d=s+c.x*r,f=i+c.y*r,y=c.width*r,g=Math.max(1,c.height*r);return{type:"line",id:h,points:[[d,f],[d+y,f],[d+y,f+g],[d,f+g]],closed:!0,fill:l,opacity:u}}return{type:"line",id:h,points:c.points.map(([d,f])=>[s+d*r,i+f*r]),stroke:l,width:Math.max(1,c.width*r),opacity:u}})}function G(t,e){return Fs(t.pieces,pn(t,e),e)}function Zo(t,e){const n=Math.max(Math.abs(t.x[0]),Math.abs(t.x[1]),Math.abs(t.y[0]),Math.abs(t.y[1])),[s,i,r,o]=e,c=Math.hypot(s,i,r,o),l=c===0?0:Math.abs(Qt(e))/c;return Math.min(n*12,n/Math.max(l,.08))+1}function Ls(t,e,n){const s=Zo(t,e),i=Math.min(120,Math.ceil(s/n)),r=[];for(let o=-i;o<=i;o++){const c=o*n;r.push({line:[it(e,[c,-s]),it(e,[c,s])].map(t.toScreen),axis:o===0}),r.push({line:[it(e,[-s,c]),it(e,[s,c])].map(t.toScreen),axis:o===0})}return r}function Qo(t,e){const{plane:n,theme:s}=e,i=t.step??1,r=[],o=1.4*n.scale;if(t.ghost)for(const[l,{line:u}]of Ls(n,[1,0,0,1],i).entries())r.push({type:"line",id:`${t.id}.ghost.${l}`,points:u,stroke:s.ghost,width:o,opacity:e.opacity});const c=O(s,t.color,s.grid);for(const[l,{line:u,axis:h}]of Ls(n,kt(e.values,t.transform),i).entries()){const[d]=V([u],e.draw);d&&r.push({type:"line",id:`${t.id}.${l}`,points:d,stroke:h?s.ink:c,width:h?o*1.6:o,opacity:e.opacity})}return r}function Ko(t,e){const{plane:n,theme:s}=e,i=O(s,t.color,s.axes),r=2*n.scale,o=e.opacity,c=V([[n.toScreen([n.x[0],0]),n.toScreen([n.x[1],0])]],e.draw),l=V([[n.toScreen([0,n.y[0]]),n.toScreen([0,n.y[1]])]],e.draw),u=[...c,...l].map((p,a)=>({type:"line",id:`${t.id}.${a?"y":"x"}`,points:p,stroke:i,width:r,opacity:o})),h=t.ticks??1;if(h<=0||e.draw<1)return u;const d=5*n.scale,f=13*n.scale,y=(p,a)=>{const m=[];for(let b=Math.ceil(p/h)*h;b<=a+1e-9;b+=h)Math.abs(b)>1e-9&&m.push(Number(b.toFixed(6)));return m},g=p=>String(p).replace("-","−");for(const p of y(n.x[0],n.x[1])){const[a,m]=n.toScreen([p,0]);u.push({type:"line",id:`${t.id}.tick.x${p}`,points:[[a,m-d],[a,m+d]],stroke:i,width:r*.8,opacity:o}),t.labels!==!1&&u.push({type:"text",id:`${t.id}.label.x${p}`,text:g(p),x:a,y:m+d+f*1.1,size:f,font:Mt,color:i,align:"center",opacity:o*.8})}for(const p of y(n.y[0],n.y[1])){const[a,m]=n.toScreen([0,p]);u.push({type:"line",id:`${t.id}.tick.y${p}`,points:[[a-d,m],[a+d,m]],stroke:i,width:r*.8,opacity:o}),t.labels!==!1&&u.push({type:"text",id:`${t.id}.label.y${p}`,text:g(p),x:a-d-f*.4,y:m+f*.35,size:f,font:Mt,color:i,align:"right",opacity:o*.8})}return u}const gn={alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",varepsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",pi:"π",rho:"ρ",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",varphi:"φ",chi:"χ",psi:"ψ",omega:"ω",Gamma:"Γ",Delta:"Δ",Theta:"Θ",Lambda:"Λ",Xi:"Ξ",Pi:"Π",Sigma:"Σ",Phi:"Φ",Psi:"Ψ",Omega:"Ω"},ke={cdot:["·","bin"],times:["×","bin"],div:["÷","bin"],pm:["±","bin"],mp:["∓","bin"],circ:["∘","bin"],cup:["∪","bin"],cap:["∩","bin"],land:["∧","bin"],lor:["∨","bin"],setminus:["∖","bin"],triangle:["△","bin"],oplus:["⊕","bin"],otimes:["⊗","bin"],ominus:["⊖","bin"],varnothing:["∅","ord"],complement:["∁","ord"],nsubseteq:["⊈","rel"],ni:["∋","rel"],mapsfrom:["↤","rel"],gets:["←","rel"],vdash:["⊢","rel"],models:["⊨","rel"],le:["≤","rel"],leq:["≤","rel"],ge:["≥","rel"],geq:["≥","rel"],ne:["≠","rel"],neq:["≠","rel"],approx:["≈","rel"],sim:["∼","rel"],equiv:["≡","rel"],propto:["∝","rel"],to:["→","rel"],rightarrow:["→","rel"],leftarrow:["←","rel"],mapsto:["↦","rel"],Rightarrow:["⇒","rel"],implies:["⇒","rel"],iff:["⇔","rel"],Leftrightarrow:["⇔","rel"],in:["∈","rel"],notin:["∉","rel"],subset:["⊂","rel"],subseteq:["⊆","rel"],supset:["⊃","rel"],mid:["|","rel"],perp:["⊥","rel"],infty:["∞","ord"],partial:["∂","ord"],nabla:["∇","ord"],forall:["∀","ord"],exists:["∃","ord"],emptyset:["∅","ord"],neg:["¬","ord"],ldots:["…","ord"],cdots:["⋯","ord"],prime:["′","ord"],hbar:["ℏ","ord"],ell:["ℓ","ord"],degree:["°","ord"],lVert:["‖","open"],rVert:["‖","close"],langle:["⟨","open"],rangle:["⟩","close"],lbrace:["{","open"],rbrace:["}","close"]},yn={sum:["∑",!0],prod:["∏",!0],int:["∫",!1],oint:["∮",!1]},mn={sin:!1,cos:!1,tan:!1,log:!1,ln:!1,exp:!1,det:!1,tr:!1,rank:!1,sinh:!1,cosh:!1,tanh:!1,sec:!1,csc:!1,cot:!1,arcsin:!1,arccos:!1,arctan:!1,gcd:!1,lcm:!1,deg:!1,dim:!1,ker:!1,softmax:!1,lim:!0,max:!0,min:!0,argmax:!0,argmin:!0,arg:!1,sup:!0,inf:!0,Pr:!1,E:!1,Var:!1},bn={",":3/18,":":4/18,";":5/18,"!":-3/18,quad:1,qquad:2},Rs=new Set(["pmatrix","bmatrix","vmatrix","matrix"]);class Ds extends Error{source;position;constructor(e,n,s){super(`${e} at ${s+1} in "${n}"`),this.name="TexError",this.source=n,this.position=s}}const qs=[...Object.keys(gn),...Object.keys(ke),...Object.keys(yn),...Object.keys(mn),...Object.keys(bn).filter(t=>t.length>1),"frac","binom","sqrt","vec","hat","bar","text","color","id","val","begin","end","left","right"].sort();function zs(t){if(typeof t!="string")throw new TypeError("parseTex: expected a string");let e=0;const n=()=>{for(;e<t.length&&/\s/.test(t[e]);)e++},s=(h,d=e)=>{throw new Ds(h,t,d)},i=()=>{const h=e;if(/[A-Za-z]/.test(t[e]??""))for(;/[A-Za-z]/.test(t[e]??"");)e++;else e<t.length?e++:s("A backslash with no command");return t.slice(h,e)},r=h=>{n(),t[e]!=="{"&&s(`Expected "{" for ${h}`);const d=t.indexOf("}",e);d<0&&s(`Missing "}" for ${h}`);const f=t.slice(e+1,d);return e=d+1,f},o=h=>{if(n(),e>=t.length&&s(`Missing ${h}`),t[e]==="{"){e++;const f=c("}");return e++,{type:"group",body:f}}const d=l();return d||s(`Missing ${h}`),d},c=h=>{const d=[];for(;;){if(n(),e>=t.length)return h==="}"&&s('Missing "}"'),h==="cell"&&s("Missing \\end"),d;if(h==="}"&&t[e]==="}"||(t[e]==="}"&&s('Unexpected "}"'),h==="cell"&&(t[e]==="&"||t.startsWith("\\\\",e)||t.startsWith("\\end",e))))return d;if(t[e]==="^"||t[e]==="_"){const y=e,g=t[e]==="^";e++;const p=o(g?"superscript":"subscript");let a=d.pop()??{type:"group",body:[]};a.type!=="scripts"&&(a={type:"scripts",base:a}),a.type==="scripts"&&((g&&a.sup||!g&&a.sub)&&s(`Double ${g?"superscript":"subscript"}`,y),g?a.sup=p:a.sub=p),d.push(a);continue}if(t[e]==="'"){e++;const y={type:"symbol",text:"′",cls:"ord",italic:!1},g=d.pop()??{type:"group",body:[]};d.push(g.type==="scripts"&&!g.sup?{...g,sup:y}:{type:"scripts",base:g,sup:y});continue}const f=l();f&&d.push(f)}},l=()=>{const h=t[e];if(h==="{"){e++;const d=c("}");return e++,{type:"group",body:d}}if(h==="&"&&s('"&" outside a matrix'),h==="\\"){const d=e;e++;const f=i();if(f==="\\"&&s('"\\\\" outside a matrix',d),f in bn)return{type:"space",width:bn[f]};if(f==="{"||f==="}")return{type:"symbol",text:f,cls:f==="{"?"open":"close",italic:!1};if(f==="|")return{type:"symbol",text:"‖",cls:"ord",italic:!1};if(Object.prototype.hasOwnProperty.call(gn,f))return{type:"symbol",text:gn[f],cls:"ord",italic:f[0]===f[0].toLowerCase()};if(Object.prototype.hasOwnProperty.call(ke,f)){const[g,p]=ke[f];return{type:"symbol",text:g,cls:p,italic:!1}}if(Object.prototype.hasOwnProperty.call(yn,f)){const[g,p]=yn[f];return{type:"bigop",text:g,limits:p}}if(Object.prototype.hasOwnProperty.call(mn,f))return{type:"opname",text:f,limits:mn[f]};switch(f){case"frac":return{type:"frac",num:o("numerator"),den:o("denominator")};case"binom":{const g=o("\\binom's top"),p=o("\\binom's bottom");return{type:"group",body:[{type:"symbol",text:"(",cls:"open",italic:!1},{type:"frac",num:g,den:p,bar:!1},{type:"symbol",text:")",cls:"close",italic:!1}]}}case"sqrt":return{type:"sqrt",body:o("the square root's body")};case"vec":case"hat":case"bar":return{type:"accent",accent:f,body:o(`\\${f}'s body`)};case"text":return{type:"text",text:r("\\text")};case"color":{const g=r("\\color").trim();return/^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)$/.test(g)||s(`"${g}" is not a colour name or #hex`,d),{type:"color",color:g,body:o("\\color's body")}}case"id":{const g=r("\\id").trim();return/^[\w.-]+$/.test(g)||s(`"${g}" is not a term id (letters, digits, _ . -)`,d),{type:"id",id:g,body:o("\\id's body")}}case"val":{const g=r("\\val").trim(),p=/^([A-Za-z_][\w.]*)(?::(\d))?$/.exec(g);return p||s(`"${g}" is not a value name (name or name:digits)`,d),{type:"value",name:p[1],digits:p[2]===void 0?2:Number(p[2])}}case"left":case"right":{n();const g=t[e]==="\\"?(e++,i()):t[e++];if(g===".")return{type:"space",width:0};const a={"(":"(",")":")","[":"[","]":"]","|":"|","{":"{","}":"}",langle:"⟨",rangle:"⟩","|.":"‖"}[g];return a||s(`"${g}" is not a delimiter`,d),{type:"symbol",text:a,cls:f==="left"?"open":"close",italic:!1}}case"begin":{const g=r("\\begin").trim();Rs.has(g)||s(`Unknown environment "${g}" (use ${[...Rs].join(", ")})`,d);const p=[[]];for(;;){const a=c("cell");if(p[p.length-1].push({type:"group",body:a}),t[e]==="&")e++;else if(t.startsWith("\\\\",e))e+=2,p.push([]);else{e+=4;const m=r("\\end").trim();m!==g&&s(`\\begin{${g}} ended by \\end{${m}}`);break}}return p.length>1&&p[p.length-1].every(a=>a.type==="group"&&a.body.length===0)&&p.pop(),{type:"matrix",delimiters:g,rows:p}}case"end":return s("\\end without \\begin",d)}const y=ms(f,qs);return s(`Unknown command "\\${f}"${y?` (did you mean "\\${y}"?)`:""}`,d)}return e++,/[A-Za-z]/.test(h)?{type:"symbol",text:h,cls:"ord",italic:!0}:/[0-9.]/.test(h)?{type:"symbol",text:h,cls:"ord",italic:!1}:h==="+"?{type:"symbol",text:"+",cls:"bin",italic:!1}:h==="-"?{type:"symbol",text:"−",cls:"bin",italic:!1}:h==="*"?{type:"symbol",text:"∗",cls:"bin",italic:!1}:"=<>".includes(h)?{type:"symbol",text:h,cls:"rel",italic:!1}:"([".includes(h)?{type:"symbol",text:h,cls:"open",italic:!1}:")]".includes(h)?{type:"symbol",text:h,cls:"close",italic:!1}:",;".includes(h)?{type:"symbol",text:h,cls:"punct",italic:!1}:"|/!:".includes(h)?{type:"symbol",text:h,cls:h===":"?"rel":"ord",italic:!1}:s(`Unexpected "${h}"`,e-1)};return{type:"group",body:c("")}}const lt=[1,1,.7,.5],Jo=t=>t<=1?2:3,ta=t=>Math.min(3,t+1),wn=()=>({width:0,height:0,depth:0,pieces:[]});function ut(t,e,n){return t.pieces.map(s=>s.kind==="stroke"?{...s,points:s.points.map(([i,r])=>[i+e,r+n])}:{...s,x:s.x+e,y:s.y+n})}function Nt(t,e){if(t.id)return t.id;const n=(t.counts.get(e)??0)+1;return t.counts.set(e,n),`${e}#${n}`}function js(t,e,n,s=1,i=t){const r=lt[n.level]*s,o=fn(t)*r,{height:c,depth:l}=Cs(t);return{width:o,height:c*r,depth:l*r,pieces:[{kind:"glyph",text:t,x:0,y:0,width:o,size:r,italic:e,...n.color?{color:n.color}:{},id:Nt(n,i)}]}}function vn(t,e,n){const s=wn(),i=Nt(e,n),r=lt[e.level];for(const o of t){const c=(o===" "?.28:/[A-Za-z]/.test(o)?fn(o)-.04:fn(o))*r;if(o!==" "){const{height:l,depth:u}=Cs(o);s.pieces.push({kind:"glyph",text:o,x:s.width,y:0,width:c,size:r,italic:!1,...e.color?{color:e.color}:{},id:i}),s.height=Math.max(s.height,l*r),s.depth=Math.max(s.depth,u*r)}s.width+=c}return s}function kn(t){switch(t.type){case"symbol":return t.cls;case"bigop":case"opname":return"op";case"scripts":return kn(t.base);case"id":case"color":return kn(t.body);default:return"ord"}}function ea(t,e){return t==="bin"||e==="bin"?4:t==="rel"||e==="rel"?t==="open"||e==="close"||e==="punct"?0:5:t==="punct"||t==="op"&&(e==="ord"||e==="op")||e==="op"&&t==="ord"?3:0}function na(t,e){const n=wn();let s;return t.forEach(i=>{if(i.type==="space"){n.width+=i.width*lt[e.level];return}let r=kn(i);r==="bin"&&(s===void 0||s==="bin"||s==="rel"||s==="open"||s==="punct"||s==="op")&&(r="ord"),s!==void 0&&e.level<=1&&(n.width+=ea(s,r)/18*lt[e.level]);const o=et(i,e);n.pieces.push(...ut(o,n.width,0)),n.width+=o.width,n.height=Math.max(n.height,o.height),n.depth=Math.max(n.depth,o.depth),s=r}),n}function sa(t,e){if(!Number.isFinite(t))return t>0?"∞":t<0?"−∞":"?";const n=t.toFixed(e),s=n.includes(".")?n.replace(/\.?0+$/,""):n;return(s==="-0"?"0":s).replace("-","−")}function et(t,e){const n=lt[e.level];switch(t.type){case"symbol":return js(t.text,t.italic,e);case"group":return na(t.body,e);case"space":return{...wn(),width:t.width*n};case"text":return vn(t.text,e,`text:${t.text}`);case"opname":return vn(t.text,e,t.text);case"value":{const s=e.values[t.name];if(s===void 0)throw new Error(`\\val{${t.name}}: no value named "${t.name}"`);return vn(sa(s,t.digits),{...e,id:e.id??`val:${t.name}`},`val:${t.name}`)}case"bigop":return js(t.text,!1,e,e.level===0?1.4:1.1);case"color":return et(t.body,{...e,color:t.color});case"id":return et(t.body,{...e,id:t.id});case"scripts":return ia(t,e);case"frac":return ra(t,e);case"sqrt":return oa(t,e);case"accent":return aa(t,e);case"matrix":return ca(t,e)}}function ia(t,e){const n=et(t.base,e),s={...e,level:Jo(e.level)},i=t.sup?et(t.sup,s):void 0,r=t.sub?et(t.sub,s):void 0,o=lt[e.level],c=e.level===0&&(t.base.type==="bigop"&&t.base.limits||t.base.type==="opname"&&t.base.limits),l={...n,pieces:[...n.pieces]};if(c){const y=Math.max(n.width,i?.width??0,r?.width??0),g=ut(n,(y-n.width)/2,0);let p=n.height,a=n.depth;const m=.12*o;if(i){const b=-(n.height+m+i.depth);g.push(...ut(i,(y-i.width)/2,b)),p=-b+i.height}if(r){const b=n.depth+m+r.height;g.push(...ut(r,(y-r.width)/2,b)),a=b+r.depth}return{width:y,height:p,depth:a,pieces:g}}let u=i?Math.max(.42*o,n.height-.3*o,i.depth+.25*o):0,h=r?Math.max(.2*o,n.depth+.12*o,r.height-.4*o):0;if(i&&r){const y=u-i.depth-(r.height-h);y<.2*o&&(h+=.2*o-y)}const d=n.width+.03*o;let f=n.width;return i?(l.pieces.push(...ut(i,d,-u)),l.height=Math.max(l.height,u+i.height),f=Math.max(f,d+i.width)):u=0,r&&(l.pieces.push(...ut(r,d,h)),l.depth=Math.max(l.depth,h+r.depth),f=Math.max(f,d+r.width)),l.width=f+.04*o,l}function ra(t,e){const n={...e,level:ta(e.level)},s=et(t.num,n),i=et(t.den,n),r=lt[e.level],o=te*r,c=Os*r,l=(e.level===0?.16:.1)*r,u=.1*r,h=Math.max(s.width,i.width)+u*2,d=-(c+o/2+l+s.depth),f=-c+o/2+l+i.height;return{width:h,height:-d+s.height,depth:f+i.depth,pieces:[...ut(s,(h-s.width)/2,d),...t.bar===!1?[]:[{kind:"rule",x:0,y:-c-o/2,width:h,height:o,...e.color?{color:e.color}:{},id:Nt(e,"frac")}],...ut(i,(h-i.width)/2,f)]}}function oa(t,e){const n=et(t.body,e),s=lt[e.level],i=Math.max(n.height,.7*s)+.14*s,r=Math.max(n.depth,.05*s)+.05*s,o=.56*s,c=o+n.width+.08*s,l=[[.02*s,-.36*s],[.13*s,-.44*s],[.3*s,r],[o-.04*s,-i],[c,-i]];return{width:c,height:i+te*s,depth:r,pieces:[{kind:"stroke",points:l,width:te*s,...e.color?{color:e.color}:{},id:Nt(e,"sqrt")},...ut(n,o,0)]}}function aa(t,e){const n=et(t.body,e),s=lt[e.level],i=-(n.height+.12*s),r=.04*s,o=Math.max(n.width-.02*s,r+.3*s),c=e.color?{color:e.color}:{},l=Nt(e,t.accent);let u;if(t.accent==="vec"){const h=.12*s;u=[[[r,i],[o,i]],[[o-h,i-h*.7],[o,i],[o-h,i+h*.7]]]}else if(t.accent==="hat"){const h=(r+o)/2;u=[[[h-.16*s,i+.02*s],[h,i-.12*s],[h+.16*s,i+.02*s]]]}else u=[[[r,i],[o,i]]];return{width:Math.max(n.width,o+.02*s),height:-i+.14*s,depth:n.depth,pieces:[...n.pieces,...u.map(h=>({kind:"stroke",points:h,width:te*s*.9,...c,id:l}))]}}function ca(t,e){const n={...e,level:Math.max(e.level,1)},s=lt[n.level],i=t.rows.map(k=>k.map(x=>et(x,n))),r=Math.max(...i.map(k=>k.length)),o=Array.from({length:r},(k,x)=>Math.max(0,...i.map(M=>M[x]?.width??0))),c=i.map(k=>Math.max(.7*s,...k.map(x=>x.height))),l=i.map(k=>Math.max(.2*s,...k.map(x=>x.depth))),u=.9*s,h=.25*s,d=t.delimiters==="matrix"?0:.55*s,f=o.reduce((k,x)=>k+x,0)+u*(r-1),y=c.reduce((k,x,M)=>k+x+l[M],0)+h*(i.length-1),g=-Os*s-y/2,p=[];let a=g;i.forEach((k,x)=>{a+=c[x];let M=d;k.forEach((E,A)=>{p.push(...ut(E,M+(o[A]-E.width)/2,a)),M+=o[A]+u}),a+=l[x]+h});const m=f+d*2,b=g+y,S=e.color?{color:e.color}:{},v=(k,x)=>({kind:"stroke",points:k,width:te*s*1.1,...S,id:Nt(e,x)}),w=.08*s;if(t.delimiters==="pmatrix"){const k=x=>{const M=x===1?d*.75:m-d*.75,E=x*d*.5;return Array.from({length:17},(A,_)=>{const T=_/16;return[M-E*Math.sin(Math.PI*T),g-w+(y+w*2)*T]})};p.push(v(k(1),"("),v(k(-1),")"))}else if(t.delimiters==="bmatrix"){const k=d*.35,x=d*.2,M=m-d*.2;p.push(v([[x+k,g-w],[x,g-w],[x,b+w],[x+k,b+w]],"["),v([[M-k,g-w],[M,g-w],[M,b+w],[M-k,b+w]],"]"))}else t.delimiters==="vmatrix"&&p.push(v([[d*.4,g-w],[d*.4,b+w]],"|"),v([[m-d*.4,g-w],[m-d*.4,b+w]],"|"));return{width:m,height:-g+w,depth:b+w,pieces:p}}function U(t,e={}){const n=typeof t=="string"?zs(t):t,s={level:e.style==="inline"?1:0,values:e.values??{},counts:new Map},i=et(n,s);return{width:i.width,height:i.height,depth:i.depth,pieces:i.pieces}}function Me(t,e,n,s,i,r){const o=26*r.plane.scale,[c,l]=Kt(n),u=U(t,{values:r.scope,style:"inline"}),h=o*(.55+Math.abs(c)*u.width*.5);return G(u,{x:e[0]+c*h,y:e[1]+l*h,size:o,color:s,opacity:r.opacity,idPrefix:`${i}.label.`})}function Xs(t,e,n,s,i,r){const o=r.plane.toScreen(e),c=r.plane.toScreen(n),[l]=V([[o,c]],r.draw);if(!l)return[];const u=Math.hypot(c[0]-o[0],c[1]-o[1]),h=Math.min(i*3.6,u*.45);return[{type:"arrow",id:t,points:l,stroke:s,width:i,head:h,opacity:r.opacity}]}function la(t,e){const n=kt(e.values,t.transform),s=it(n,t.from===void 0?[0,0]:It(e.values,t.from)),i=it(n,It(e.values,t.to)),r=O(e.theme,t.color,e.theme.colors.yellow),o=Xs(t.id,s,i,r,(t.width??4)*e.plane.scale,e);if(t.label&&e.draw>=1){const c=e.plane.toScreen(i),l=e.plane.toScreen(s),u=un(c,l);if(t.labelAt==="middle"){const h=[(c[0]+l[0])/2,(c[1]+l[1])/2];o.push(...Me(t.label,h,[u[1],-u[0]],r,t.id,e))}else o.push(...Me(t.label,c,u,r,t.id,e))}return o}function ua(t,e){const n=kt(e.values,t.transform),s=4.5*e.plane.scale,i=e.plane.toScreen([0,0]),r=[],o=[["i",[1,0],e.theme.colors.green,"\\hat{i}"],["j",[0,1],e.theme.colors.red,"\\hat{j}"]];for(const[c,l,u,h]of o){const d=it(n,l);if(r.push(...Xs(`${t.id}.${c}`,[0,0],d,u,s,e)),t.labels!==!1&&e.draw>=1){const f=e.plane.toScreen(d);r.push(...Me(h,f,un(f,i),u,`${t.id}.${c}`,e))}}return r}function ha(t,e){const n=t.on!==void 0?[e.scope[`${t.id}.x`],e.scope[`${t.id}.y`]]:It(e.values,t.at);if(!Number.isFinite(n[0])||!Number.isFinite(n[1]))return[];const s=it(kt(e.values,t.transform),n),[i,r]=e.plane.toScreen(s),o=O(e.theme,t.color,e.theme.colors.yellow),c=(t.radius??6)*e.plane.scale*Math.min(1,e.draw*2),l=t.hollow?{type:"circle",id:t.id,x:i,y:r,r:c,fill:e.theme.background,stroke:o,width:2.5*e.plane.scale,opacity:e.opacity}:{type:"circle",id:t.id,x:i,y:r,r:c,fill:o,opacity:e.opacity},u=c>0?[l]:[];return t.label&&e.draw>=1&&u.push(...Me(t.label,[i,r],[.7,-.7],o,t.id,e)),u}const $e={sin:{arity:1,apply:Math.sin},cos:{arity:1,apply:Math.cos},tan:{arity:1,apply:Math.tan},asin:{arity:1,apply:Math.asin},acos:{arity:1,apply:Math.acos},atan:{arity:1,apply:Math.atan},atan2:{arity:2,apply:Math.atan2},sinh:{arity:1,apply:Math.sinh},cosh:{arity:1,apply:Math.cosh},tanh:{arity:1,apply:Math.tanh},exp:{arity:1,apply:Math.exp},ln:{arity:1,apply:Math.log},log:{arity:1,apply:Math.log10},log2:{arity:1,apply:Math.log2},sqrt:{arity:1,apply:Math.sqrt},abs:{arity:1,apply:Math.abs},floor:{arity:1,apply:Math.floor},ceil:{arity:1,apply:Math.ceil},round:{arity:1,apply:Math.round},sign:{arity:1,apply:Math.sign},min:{arity:2,apply:Math.min},max:{arity:2,apply:Math.max},sigmoid:{arity:1,apply:t=>1/(1+Math.exp(-t))},relu:{arity:1,apply:t=>Math.max(0,t)}},ee={pi:Math.PI,e:Math.E,tau:Math.PI*2};class $t extends Error{source;position;constructor(e,n,s){super(`${e} at ${s+1} in "${n}"`),this.name="ExpressionError",this.source=n,this.position=s}}function da(t){const e=[];let n=0;for(;n<t.length;){const s=t[n];if(/\s/.test(s)){n++;continue}const i=/^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(t.slice(n));if(i){e.push({kind:"number",value:Number(i[0]),at:n}),n+=i[0].length;continue}const r=/^[A-Za-z_][A-Za-z_0-9]*/.exec(t.slice(n));if(r){e.push({kind:"name",value:r[0],at:n}),n+=r[0].length;continue}if("+-*/^(),".includes(s)){e.push({kind:"op",value:s,at:n}),n++;continue}throw new $t(`Unexpected "${s}"`,t,n)}return e.push({kind:"end",at:t.length}),e}function rt(t){if(typeof t!="string")throw new TypeError("parseExpression: expected a string");const e=da(t);let n=0;const s=()=>e[n],i=f=>{const y=s();return y.kind==="op"&&y.value===f},r=f=>{if(!i(f))throw new $t(`Expected "${f}"`,t,s().at);n++},o=()=>{let f=c();for(;i("+")||i("-");)f={type:"binary",operator:e[n++].value,left:f,right:c()};return f},c=()=>{let f=l();for(;;)if(i("*")||i("/"))f={type:"binary",operator:e[n++].value,left:f,right:l()};else if(s().kind==="name"||s().kind==="number"||i("("))f={type:"binary",operator:"*",left:f,right:u()};else return f},l=()=>i("-")||i("+")?{type:"unary",operator:e[n++].value,operand:l()}:u(),u=()=>{const f=h();return i("^")?(n++,{type:"binary",operator:"^",left:f,right:l()}):f},h=()=>{const f=s();if(f.kind==="number")return n++,{type:"number",value:f.value};if(f.kind==="name"){if(n++,!i("("))return{type:"name",name:f.value};const y=Object.prototype.hasOwnProperty.call($e,f.value)?$e[f.value]:void 0;if(!y)throw new $t(`Unknown function "${f.value}"`,t,f.at);n++;const g=[];if(!i(")"))for(g.push(o());i(",");)n++,g.push(o());if(r(")"),g.length!==y.arity)throw new $t(`"${f.value}" takes ${y.arity} argument${y.arity===1?"":"s"}, got ${g.length}`,t,f.at);return{type:"call",name:f.value,args:g}}if(i("(")){n++;const y=o();return r(")"),y}throw new $t(f.kind==="end"?"Unexpected end":`Unexpected "${f.value}"`,t,f.at)},d=o();if(s().kind!=="end")throw new $t(`Unexpected "${s().value}"`,t,s().at);return d}function Mn(t){const e=new Set,n=s=>{s.type==="name"&&!(s.name in ee)?e.add(s.name):s.type==="unary"?n(s.operand):s.type==="binary"?(n(s.left),n(s.right)):s.type==="call"&&s.args.forEach(n)};return n(t),[...e].sort()}const R=t=>({type:"number",value:t}),ne=R(0),X=R(1),W=t=>t.type==="number",nt=(t,e)=>t.type==="number"&&t.value===e;function yt(t,e){return W(t)&&W(e)?R(t.value+e.value):nt(t,0)?e:nt(e,0)?t:{type:"binary",operator:"+",left:t,right:e}}function ht(t,e){return W(t)&&W(e)?R(t.value-e.value):nt(e,0)?t:nt(t,0)?Se(e):{type:"binary",operator:"-",left:t,right:e}}function D(t,e){return W(t)&&W(e)?R(t.value*e.value):nt(t,0)||nt(e,0)?ne:nt(t,1)?e:nt(e,1)?t:W(e)?D(e,t):W(t)&&e.type==="binary"&&e.operator==="*"&&W(e.left)?D(R(t.value*e.left.value),e.right):{type:"binary",operator:"*",left:t,right:e}}function Z(t,e){return nt(t,0)?ne:nt(e,1)?t:W(t)&&W(e)&&e.value!==0?R(t.value/e.value):{type:"binary",operator:"/",left:t,right:e}}function ft(t,e){return nt(e,0)?X:nt(e,1)?t:W(t)&&W(e)?R(t.value**e.value):{type:"binary",operator:"^",left:t,right:e}}function Se(t){return W(t)?R(-t.value):t.type==="unary"&&t.operator==="-"?t.operand:{type:"unary",operator:"-",operand:t}}const Q=(t,...e)=>({type:"call",name:t,args:e});function St(t,e){switch(t.type){case"number":return!0;case"name":return t.name!==e;case"unary":return St(t.operand,e);case"binary":return St(t.left,e)&&St(t.right,e);case"call":return t.args.every(n=>St(n,e))}}function K(t,e="x"){if(St(t,e))return ne;switch(t.type){case"number":return ne;case"name":return t.name===e?X:ne;case"unary":return t.operator==="-"?Se(K(t.operand,e)):K(t.operand,e);case"binary":{const{left:n,right:s}=t,i=()=>K(n,e),r=()=>K(s,e);switch(t.operator){case"+":return yt(i(),r());case"-":return ht(i(),r());case"*":return yt(D(i(),s),D(n,r()));case"/":return Z(ht(D(i(),s),D(n,r())),ft(s,R(2)));case"^":if(St(s,e)){const o=W(s)?R(s.value-1):ht(s,X);return D(D(s,ft(n,o)),i())}return St(n,e)?D(D(t,Q("ln",n)),r()):D(t,yt(D(r(),Q("ln",n)),Z(D(s,i()),n)))}break}case"call":{const[n,s]=t.args,i=()=>K(n,e),r=o=>D(o,i());switch(t.name){case"sin":return r(Q("cos",n));case"cos":return r(Se(Q("sin",n)));case"tan":return r(Z(X,ft(Q("cos",n),R(2))));case"asin":return r(Z(X,Q("sqrt",ht(X,ft(n,R(2))))));case"acos":return r(Se(Z(X,Q("sqrt",ht(X,ft(n,R(2)))))));case"atan":return r(Z(X,yt(X,ft(n,R(2)))));case"sinh":return r(Q("cosh",n));case"cosh":return r(Q("sinh",n));case"tanh":return r(ht(X,ft(Q("tanh",n),R(2))));case"exp":return r(t);case"ln":return r(Z(X,n));case"log":return r(Z(X,D(n,R(Math.LN10))));case"log2":return r(Z(X,D(n,R(Math.LN2))));case"sqrt":return r(Z(X,D(R(2),t)));case"abs":return r(Q("sign",n));case"sigmoid":return r(D(t,ht(X,t)));case"relu":return r(Z(yt(Q("sign",n),X),R(2)));case"atan2":{const o=K(s,e);return Z(ht(D(s,i()),D(n,o)),yt(ft(n,R(2)),ft(s,R(2))))}case"min":case"max":{const o=t.name==="max"?1:-1,c=K(s,e),l=Z(yt(X,D(R(o),Q("sign",ht(n,s)))),R(2));return yt(D(l,i()),D(ht(X,l),c))}}throw new Error(`differentiate: "${t.name}" has no derivative rule`)}}throw new Error("differentiate: malformed expression")}function Ys(t,e,n="x"){let s=t;for(let i=0;i<e;i++)s=K(s,n);return s}function se(t){switch(t.type){case"number":return t.value<0?`(${t.value})`:String(t.value);case"name":return t.name;case"unary":return`(${t.operator}${se(t.operand)})`;case"binary":return`(${se(t.left)} ${t.operator} ${se(t.right)})`;case"call":return`${t.name}(${t.args.map(se).join(", ")})`}}function st(t,e={}){switch(t.type){case"number":return t.value;case"name":{if(Object.prototype.hasOwnProperty.call(e,t.name))return e[t.name];if(Object.prototype.hasOwnProperty.call(ee,t.name))return ee[t.name];throw new Error(`evaluate: unknown name "${t.name}"`)}case"unary":{const n=st(t.operand,e);return t.operator==="-"?-n:n}case"binary":{const n=st(t.left,e),s=st(t.right,e);switch(t.operator){case"+":return n+s;case"-":return n-s;case"*":return n*s;case"/":return n/s;case"^":return n**s}break}case"call":return $e[t.name].apply(...t.args.map(n=>st(n,e)))}throw new Error("evaluate: malformed expression")}const xe=new Map;function J(t,e="x"){let n=xe.get(t);n||(n=rt(t),xe.size<256&&xe.set(t,n));const s=n;return(i,r={})=>st(s,{...r,[e]:i})}const $n=new Map;function Ae(t,e,n="x"){if(!Number.isInteger(e)||e<0)throw new Error(`compileDerivative: order must be a whole number ≥ 0, got ${e}`);const s=`${n}|${e}|${t}`;let i=$n.get(s);if(!i){let o=xe.get(t);o||(o=rt(t)),i=Ys(o,e,n),$n.size<512&&$n.set(s,i)}const r=i;return(o,c={})=>st(r,{...c,[n]:o})}const Ee=480;function Bs(t,e){const n=[];let s=[];return t.forEach((i,r)=>{const o=t[r-1];(!i||o&&Math.abs(i[1]-o[1])>e*1.5)&&(s.length>=2&&n.push(s),s=[]),i&&s.push(i)}),s.length>=2&&n.push(s),n}function Vs(t,e){const n=Math.max(e.plane.width,e.plane.height)*20;if(!(!Number.isFinite(t[0])||!Number.isFinite(t[1])))return[Math.max(-n,Math.min(n,t[0])),Math.max(-n,Math.min(n,t[1]))]}function Hs(t,e,n,s,i,r){return V(e,i.draw).map((o,c)=>({type:"line",id:`${t}.${c}`,points:o,stroke:n,width:s,opacity:i.opacity,...r?{dash:r}:{}}))}function Te(t,e,n,s,i,r,o,c){const l=Array.from({length:Ee+1},(u,h)=>{const d=n+(s-n)*h/Ee;return Vs(o.plane.toScreen([d,e(d)]),o)});return Hs(t,Bs(l,o.plane.height),i,r,o,c)}function fa(t,e){const n=t.derivative?Ae(t.expr,t.derivative):J(t.expr,"x"),[s,i]=t.domain??e.plane.x,r=O(e.theme,t.color,e.theme.colors.blue),o=t.dashed?[10*e.plane.scale,8*e.plane.scale]:void 0;return Te(t.id,c=>n(c,e.scope),s,i,r,(t.width??3.5)*e.plane.scale,e,o)}function pa(t,e){const n=J(t.x,"t"),s=J(t.y,"t"),i=kt(e.values,t.transform),[r,o]=t.t??[0,Math.PI*2],c=Array.from({length:Ee+1},(u,h)=>{const d=r+(o-r)*h/Ee;return Vs(e.plane.toScreen(it(i,[n(d,e.scope),s(d,e.scope)])),e)}),l=O(e.theme,t.color,e.theme.colors.blue);return Hs(t.id,Bs(c,e.plane.height),l,(t.width??3.5)*e.plane.scale,e)}const ga=[[0,0],[1,0],[1,1],[0,1]];function ya(t,e){const n=kt(e.values,t.transform),s=(t.points??ga).map(c=>it(n,c)),i=s.map(e.plane.toScreen),r=O(e.theme,t.color,e.theme.colors.yellow),o=[{type:"line",id:`${t.id}.fill`,points:i,closed:!0,fill:r,opacity:e.opacity*(t.fillOpacity??.3)*e.draw},...V([[...i,i[0]]],e.draw).map(c=>({type:"line",id:`${t.id}.outline`,points:c,stroke:r,width:2.5*e.plane.scale,opacity:e.opacity}))];if(t.label&&e.draw>=1){const c=s.reduce((h,d)=>[h[0]+d[0]/s.length,h[1]+d[1]/s.length],[0,0]),[l,u]=e.plane.toScreen(c);o.push(...G(U(t.label,{values:e.scope,style:"inline"}),{x:l,y:u,size:24*e.plane.scale,color:e.theme.ink,opacity:e.opacity,idPrefix:`${t.id}.label.`}))}return o}function ma(t,e){const n=t.eigen?As(kt(e.values,t.eigen)).map(o=>o.vector):t.along!==void 0?[It(e.values,t.along)]:[],s=Math.max(Math.abs(e.plane.x[0]),Math.abs(e.plane.x[1]),Math.abs(e.plane.y[0]),Math.abs(e.plane.y[1]))*1.5,i=O(e.theme,t.color,e.theme.colors.yellow),r=(t.width??2.5)*e.plane.scale;return n.flatMap((o,c)=>{const l=Math.hypot(o[0],o[1]);if(l===0)return[];const u=hn(o,s/l),h=[hn(u,-1),u].map(e.plane.toScreen);return V([h],e.draw).map(d=>({type:"line",id:`${t.id}.${c}`,points:d,stroke:i,width:r,opacity:e.opacity,...t.dashed?{dash:[10*e.plane.scale,8*e.plane.scale]}:{}}))})}const ot=(t,e,n)=>t+(e-t)*n;function Us(t,e,n){return t.kind==="stroke"?{...t,points:t.points.map(([s,i])=>[s+e,i+n])}:{...t,x:t.x+e,y:t.y+n}}function ba(t,e,n){if(t.kind==="glyph"&&e.kind==="glyph"&&t.text===e.text)return{...e,x:ot(t.x,e.x,n),y:ot(t.y,e.y,n),width:ot(t.width,e.width,n),size:ot(t.size,e.size,n)};if(t.kind==="rule"&&e.kind==="rule")return{...e,x:ot(t.x,e.x,n),y:ot(t.y,e.y,n),width:ot(t.width,e.width,n),height:ot(t.height,e.height,n)};if(t.kind==="stroke"&&e.kind==="stroke"&&t.points.length===e.points.length)return{...e,width:ot(t.width,e.width,n),points:t.points.map(([s,i],r)=>[ot(s,e.points[r][0],n),ot(i,e.points[r][1],n)])}}const wa=t=>t*t*(3-2*t);function Ws(t,e,n){const s=Math.min(1,Math.max(0,n)),i=t.layout.pieces.map(y=>Us(y,t.x,t.y)),r=e.layout.pieces.map(y=>Us(y,e.x,e.y));if(s===0)return i.map(y=>({...y,opacity:1}));if(s===1)return r.map(y=>({...y,opacity:1}));const o=y=>{const g=new Map;for(const p of y)g.set(p.id,[...g.get(p.id)??[],p]);return g},c=o(i),l=o(r),u=[],h=wa(s),d=Math.max(0,1-s*2),f=Math.max(0,s*2-1);for(const y of new Set([...c.keys(),...l.keys()])){const g=c.get(y)??[],p=l.get(y)??[],a=Math.max(g.length,p.length);for(let m=0;m<a;m++){const b=g[m],S=p[m],v=b&&S?ba(b,S,h):void 0;if(v){u.push({...v,opacity:1});continue}b&&u.push({...b,opacity:d}),S&&u.push({...S,opacity:f})}}return u.filter(y=>y.opacity>0)}function Sn(t,e,n,s){const i=n.size*.35;let r=1/0,o=1/0,c=-1/0,l=-1/0;for(const u of e){const[h,d]=pn(u,n);r=Math.min(r,h-i),c=Math.max(c,h+u.width*n.size+i),o=Math.min(o,d-u.height*n.size-i),l=Math.max(l,d+u.depth*n.size+i)}return[{type:"line",id:`${t}.backdrop`,points:[[r,o],[c,o],[c,l],[r,l]],closed:!0,fill:s.theme.background,opacity:(n.opacity??1)*.85}]}function Gs(t,e,n){const s=It(n.values,t);return e?s:n.plane.toScreen(s)}function va(t,e){const[n,s]=Gs(t.at,t.screen,e),i=(t.size??28)*e.plane.scale,r=O(e.theme,t.color,e.theme.ink),o={x:n,y:s,size:i,color:r,align:t.align,opacity:e.opacity*e.draw,idPrefix:`${t.id}.`,palette:e.theme.colors},c=U(t.tex,{values:e.scope});return[...t.backdrop??t.screen??!1?Sn(t.id,[c],o,e):[],...G(c,o)]}function ka(t,e){const[n,s]=Gs(t.at,t.screen,e),i=(t.size??36)*e.plane.scale,r=O(e.theme,t.color,e.theme.ink),o=t.steps.length-1,c=Math.min(o,Math.max(0,e.prop("step")??t.step??0)),l=Math.floor(c),u=c-l,h={x:n,y:s,size:i,color:r,align:t.align,opacity:e.opacity*e.draw,idPrefix:`${t.id}.`,palette:e.theme.colors},d=a=>U(t.steps[a],{values:e.scope}),f=t.backdrop??t.screen??!1;if(u===0||l>=o){const a=d(l);return[...f?Sn(t.id,[a],h,e):[],...G(a,h)]}const y=a=>{const[m,b]=pn(a,h);return{layout:a,x:m/i,y:b/i}},g=d(l),p=d(l+1);return[...f?Sn(t.id,[g,p],h,e):[],...Fs(Ws(y(g),y(p),u),[0,0],h)]}const ie=["normal","uniform","exponential","binomial","poisson","dice","mean"];function Zs(t){switch(t.kind){case"binomial":return[0,t.n];case"dice":return[t.count??2,(t.count??2)*(t.sides??6)];case"poisson":return[0,1/0];default:return[-1/0,1/0]}}function re(t){return t.kind==="binomial"||t.kind==="poisson"||t.kind==="dice"}const _e=(()=>{const t=[0];return e=>{for(let n=t.length;n<=e;n++)t[n]=t[n-1]+Math.log(n);return t[e]}})(),xn=(t,e)=>Math.exp(_e(t)-_e(e)-_e(t-e));function pt(t,e){switch(t.kind){case"normal":{const{mean:n=0,sd:s=1}=t;return Math.exp(-(((e-n)/s)**2)/2)/(s*Math.sqrt(2*Math.PI))}case"uniform":{const{min:n=0,max:s=1}=t;return e>=n&&e<=s?1/(s-n):0}case"exponential":{const{rate:n=1}=t;return e<0?0:n*Math.exp(-n*e)}case"binomial":return!Number.isInteger(e)||e<0||e>t.n?0:xn(t.n,e)*t.p**e*(1-t.p)**(t.n-e);case"poisson":return!Number.isInteger(e)||e<0?0:Math.exp(e*Math.log(t.rate)-t.rate-_e(e));case"dice":{const{count:n=2,sides:s=6}=t;if(!Number.isInteger(e)||e<n||e>n*s)return 0;let i=0;for(let r=0;r<=Math.floor((e-n)/s);r++)i+=(r%2?-1:1)*xn(n,r)*xn(e-s*r-1,n-1);return i/s**n}case"mean":return t.count===1?pt(t.of,e):pt({kind:"normal",mean:Ft(t.of),sd:Lt(t.of)/Math.sqrt(t.count)},e)}}function Ft(t){switch(t.kind){case"normal":return t.mean??0;case"uniform":return((t.min??0)+(t.max??1))/2;case"exponential":return 1/(t.rate??1);case"binomial":return t.n*t.p;case"poisson":return t.rate;case"dice":return(t.count??2)*((t.sides??6)+1)/2;case"mean":return Ft(t.of)}}function Lt(t){switch(t.kind){case"normal":return t.sd??1;case"uniform":return((t.max??1)-(t.min??0))/Math.sqrt(12);case"exponential":return 1/(t.rate??1);case"binomial":return Math.sqrt(t.n*t.p*(1-t.p));case"poisson":return Math.sqrt(t.rate);case"dice":return Math.sqrt((t.count??2)*((t.sides??6)**2-1)/12);case"mean":return Lt(t.of)/Math.sqrt(t.count)}}function An(t,e){switch(t.kind){case"normal":return vt(e,t.mean??0,t.sd??1);case"uniform":return(t.min??0)+e.next()*((t.max??1)-(t.min??0));case"exponential":return-Math.log(1-e.next())/(t.rate??1);case"binomial":{let n=0;for(let s=0;s<t.n;s++)e.next()<t.p&&n++;return n}case"poisson":{const n=Math.exp(-t.rate);let s=0,i=e.next();for(;i>n;)s++,i*=e.next();return s}case"dice":{let n=0;for(let s=0;s<(t.count??2);s++)n+=1+Math.floor(e.next()*(t.sides??6));return n}case"mean":{let n=0;for(let s=0;s<t.count;s++)n+=An(t.of,e);return n/t.count}}}const Pe=new Map;function En(t,e,n){const s=`${JSON.stringify(t)}|${e}`;let i=Pe.get(s);if(i||(i=[],Pe.size>64&&Pe.clear(),Pe.set(s,i)),i.length<n){const r=Pt(typeof e=="number"?e:wt(e)),o=[];for(let c=0;c<n;c++)o.push(An(t,r));i.splice(0,i.length,...o)}return i.slice(0,n)}function Tn(t){if(!t||typeof t!="object"||!ie.includes(t.kind))return`kind must be one of ${ie.join(", ")}`;const e=(n,s)=>n!==void 0&&!(n>0)?`${s} must be positive`:void 0;switch(t.kind){case"normal":return e(t.sd,"sd");case"uniform":return(t.max??1)>(t.min??0)?void 0:"max must be greater than min";case"exponential":return e(t.rate,"rate");case"binomial":return Number.isInteger(t.n)&&t.n>=0&&t.n<=1e3&&t.p>=0&&t.p<=1?void 0:"n must be a whole number 0..1000 and p in 0..1";case"poisson":return t.rate>0&&t.rate<=200?void 0:"rate must be in (0, 200]";case"dice":return Number.isInteger(t.count??2)&&(t.count??2)>=1&&(t.count??2)<=50&&Number.isInteger(t.sides??6)&&(t.sides??6)>=2?void 0:"count must be 1..50 and sides a whole number ≥ 2";case"mean":return Number.isInteger(t.count)&&t.count>=1&&t.count<=200?Tn(t.of):"count must be a whole number 1..200"}}function _n(t){const e=Ft(t),n=Lt(t);if(re(t)){const[s,i]=Zs(t),r=Math.max(s,Math.floor(e-4*n)),o=Math.min(i,Math.ceil(e+4*n));return[r-.5,o+.5,o-r+1]}return[e-4*n,e+4*n,30]}function Qs(t,[e,n,s],i){const r=(n-e)/s,o=new Array(s).fill(0);for(const l of t){const u=Math.floor((l-e)/r);u>=0&&u<s?o[u]++:l===n&&o[s-1]++}const c=t.length||1;return o.map((l,u)=>({left:e+u*r,right:e+(u+1)*r,count:l,height:i==="density"?l/(c*r):l}))}function Ks(t){if(t.length===0)return{mean:0,sd:0};const e=t.reduce((s,i)=>s+i,0)/t.length,n=t.reduce((s,i)=>s+(i-e)**2,0)/t.length;return{mean:e,sd:Math.sqrt(n)}}function Pn(t,e,n){const s=Pt(typeof e=="number"?e:wt(e));return Array.from({length:Math.max(0,Math.floor(n))},()=>{const i=s.next();if(t.kind==="uniform"){const o=s.next();return[t.x[0]+i*(t.x[1]-t.x[0]),t.y[0]+o*(t.y[1]-t.y[0])]}const r=t.x[0]+i*(t.x[1]-t.x[0]);return[r,t.slope*r+t.intercept+t.noise*vt(s)]})}function On(t){const e=t.length;if(e<2)return;const n=t.reduce((l,u)=>l+u[0],0)/e,s=t.reduce((l,u)=>l+u[1],0)/e;let i=0,r=0,o=0;for(const[l,u]of t)i+=(l-n)*(u-s),r+=(l-n)**2,o+=(u-s)**2;if(r===0)return;const c=i/r;return{slope:c,intercept:s-c*n,r:o===0?0:i/Math.sqrt(r*o)}}function Js(t,e,n){const s=Math.min(1,Math.max(0,t)),i=s*Math.min(1,Math.max(0,e)),r=(1-s)*Math.min(1,Math.max(0,n)),o=i+r;return{truePositive:i,falsePositive:r,positive:o,posterior:o>0?i/o:0}}function In(t,e,n){const s=Pt(wt(`${t}:${e}`));return Array.from({length:n},()=>s.next()<.5)}const Oe=t=>t.filter(Boolean).length;function ti(t,e){const n=t.length,s=Math.min(1,Math.max(0,e))*n,i=Math.min(n-1,Math.floor(s)),r=s-i,c=t.slice(0,i).filter(Boolean).length-i/2,l=c+(t[i]?.5:-.5),u=.18*Math.sin(Math.PI*r);return{x:c+(l-c)*r,depth:i+r-u}}const Cn=(t,e,n,s,i)=>[[e,n],[s,n],[s,i],[e,i]].map(t.plane.toScreen),Ie=t=>Math.min(2e4,Math.max(0,Math.floor(t)));function Ma(t,e){const n=Ct(e.values,t.distribution),s=En(n,t.seed??t.id,Ie(I(e.values,t.count))),i=Qs(s,t.bins??_n(n),t.scale??"density"),r=O(e.theme,t.color,e.theme.colors.blue),o=e.opacity*e.draw,c=i.flatMap((l,u)=>l.height>0?[{type:"line",id:`${t.id}.${u}`,points:Cn(e,l.left,0,l.right,l.height),closed:!0,fill:r,stroke:e.theme.background,width:1*e.plane.scale,opacity:o*(t.fillOpacity??.75)}]:[]);if(t.curve&&(t.scale??"density")==="density"){const[l,u]=t.bins??_n(n),h=O(e.theme,"yellow",e.theme.colors.yellow);c.push(...Te(`${t.id}.curve`,d=>pt(re(n)?{kind:"normal",mean:Ft(n),sd:Lt(n)}:n,d),l,u,h,3*e.plane.scale,{...e,draw:1}))}return c}function $a(t,e){const n=Ct(e.values,t.distribution),s=O(e.theme,t.color,e.theme.colors.blue),[i,r]=t.domain??e.plane.x,o=t.shade?[I(e.values,t.shade[0]),I(e.values,t.shade[1])].sort((u,h)=>u-h):void 0,c=O(e.theme,"yellow",e.theme.colors.yellow);if(re(n)){const u=[],h=Math.max(0,Math.ceil(i)),d=Math.floor(r),f=h+Math.ceil((d-h+1)*e.draw);for(let y=h;y<f&&y<=d;y++){const g=pt(n,y);if(g<=0)continue;const p=o&&y>=o[0]&&y<=o[1];u.push({type:"line",id:`${t.id}.${y}`,points:Cn(e,y-.4,0,y+.4,g),closed:!0,fill:p?c:s,opacity:e.opacity*(t.fillOpacity??.8)})}return u}const l=[];if(o&&e.draw>=1){const[u,h]=[Math.max(o[0],i),Math.min(o[1],r)];if(h>u){const f=Array.from({length:121},(g,p)=>{const a=u+(h-u)*p/120;return[a,pt(n,a)]}),y=[[u,0],...f,[h,0]].map(e.plane.toScreen);l.push({type:"line",id:`${t.id}.shade`,points:y,closed:!0,fill:c,opacity:e.opacity*(t.fillOpacity??.4)})}}return l.push(...Te(t.id,u=>pt(n,u),i,r,s,(t.width??3.5)*e.plane.scale,e)),l}function Sa(t,e){const n=t.rows??10,s=t.spacing??.5,i=t.top??e.plane.y[1]-s,r=s*.9,o=(w,k)=>[w*s,i-k*r],c=O(e.theme,"grey",e.theme.colors.grey),l=O(e.theme,t.color,e.theme.colors.yellow),u=s*.19*e.plane.unitX,h=[];for(let w=0;w<n;w++)for(let k=0;k<=w;k++){const[x,M]=e.plane.toScreen(o(k-w/2,w));h.push({type:"circle",id:`${t.id}.peg.${w}.${k}`,x,y:M,r:u*.45,fill:c,opacity:e.opacity*e.draw})}const d=n+.3,f=Math.max(n+2,(i-e.plane.y[0])/r-.2);for(let w=0;w<=n+1;w++){const k=w-(n+1)/2,x=V([[o(k,d),o(k,f)].map(e.plane.toScreen)],e.draw);for(const M of x)h.push({type:"line",id:`${t.id}.bin.${w}`,points:M,stroke:c,width:1.2*e.plane.scale,opacity:e.opacity*.6})}const y=V([[o(-(n+1)/2,f),o((n+1)/2,f)].map(e.plane.toScreen)],e.draw);for(const w of y)h.push({type:"line",id:`${t.id}.floor`,points:w,stroke:c,width:1.2*e.plane.scale,opacity:e.opacity*.6});const g=Math.max(0,I(e.values,t.balls)),p=Math.floor(g),a=t.seed??t.id,m=new Array(n+1).fill(0),b=2*u/e.plane.unitY/r,S=(w,k)=>({x:w-n/2+(k%2?.22:-.22),depth:f-b*(Math.floor(k/2)+.5)});for(let w=0;w<p;w++){const k=Oe(In(a,w,n)),x=S(k,m[k]),[M,E]=e.plane.toScreen(o(x.x,x.depth));m[k]++,h.push({type:"circle",id:`${t.id}.ball.${w}`,x:M,y:E,r:u,fill:l,opacity:e.opacity})}const v=g-p;if(v>0){const w=In(a,p,n),k=Math.min(1,v/.8);let{x,depth:M}=ti(w,k);if(M-=1,v>.8){const _=((v-.8)/.2)**2,T=Oe(w),C=S(T,m[T]),N={x:Oe(w)-n/2,depth:n-1};M=N.depth+(C.depth-N.depth)*_,x=N.x+(C.x-N.x)*_}const[E,A]=e.plane.toScreen(o(x,M));h.push({type:"circle",id:`${t.id}.falling`,x:E,y:A,r:u,fill:l,opacity:e.opacity})}return h}function xa(t,e){const n=ei(t,e),s=Pn(n,t.seed??t.id,Ie(I(e.values,t.count))),i=O(e.theme,t.color,e.theme.colors.blue),r=O(e.theme,t.insideColor,e.theme.colors.yellow),o=t.inside?rt(t.inside):void 0,c=(t.radius??3)*e.plane.scale,l=s.map(([u,h],d)=>{const[f,y]=e.plane.toScreen([u,h]),g=o?st(o,{...e.scope,x:u,y:h})<=0:!1;return{type:"circle",id:`${t.id}.${d}`,x:f,y,r:c,fill:g?r:i,opacity:e.opacity*e.draw*.85}});if(t.fit){const u=On(s);if(u){const[h,d]=e.plane.x;l.push({type:"line",id:`${t.id}.fit`,points:[[h,u.slope*h+u.intercept],[d,u.slope*d+u.intercept]].map(e.plane.toScreen),stroke:O(e.theme,"red",e.theme.colors.red),width:3*e.plane.scale,opacity:e.opacity})}}return l}function ei(t,e){const n=t.points;return n.kind==="uniform"?n:{kind:"linear",slope:I(e.values,n.slope),intercept:I(e.values,n.intercept),noise:I(e.values,n.noise),x:n.x}}function Aa(t,e){const n=I(e.values,t.prior),s=I(e.values,t.truePositive),i=I(e.values,t.falsePositive),r=e.plane.x[1]-e.plane.x[0],o=e.plane.y[1]-e.plane.y[0],[c,l]=t.size??[r*.8,o*.7],[u,h]=t.at??[e.plane.x[0]+r*.1,e.plane.y[0]+o*.08],d=u+c*Math.min(1,Math.max(0,n)),f=O(e.theme,t.color,e.theme.colors.yellow),y=O(e.theme,"red",e.theme.colors.red),g=O(e.theme,"grey",e.theme.colors.grey),p=e.opacity*e.draw,a=(w,k,x,M,E,A,_)=>({type:"line",id:`${t.id}.${w}`,points:Cn(e,k,x,M,E),closed:!0,fill:A,stroke:e.theme.background,width:2*e.plane.scale,opacity:p*_}),m=h+l,b=m-l*Math.min(1,Math.max(0,s)),S=m-l*Math.min(1,Math.max(0,i)),v=[a("tp",u,b,d,m,f,.85),a("fn",u,h,d,b,g,.35),a("fp",d,S,u+c,m,y,.8),a("tn",d,h,u+c,S,g,.2)];if(t.labels!==!1&&e.draw>=1){const w=20*e.plane.scale,k=(x,M,E,A)=>{const[_,T]=e.plane.toScreen(E);v.push(...G(U(M,{values:e.scope,style:"inline"}),{x:_,y:T,size:w,color:A,opacity:e.opacity,idPrefix:`${t.id}.label.${x}.`}))};k("prior",`\\text{has it: } \\val{${t.id}.prior:3}`,[u+c/2,h-o*.04],e.theme.ink),k("tp",`\\text{has it, tests positive: } \\val{${t.id}.truePositive:3}`,[u+c/2,h-o*.09],f),k("fp",`\\text{does not, tests positive: } \\val{${t.id}.falsePositive:3}`,[u+c/2,h-o*.14],y),k("posterior",`P(\\text{has it} \\mid +) = \\val{${t.id}.posterior:3}`,[u+c/2,h+l+o*.05],f)}return v}const Nn=["bfs","dfs","dijkstra"];function Ce(t,e,n){const s=new Map(t.map((r,o)=>[r,o])),i=new Map(t.map(r=>[r,[]]));for(const r of e){const o=r.weight??1;i.get(r.from)?.push({to:r.to,weight:o}),n||i.get(r.to)?.push({to:r.from,weight:o})}for(const r of i.values())r.sort((o,c)=>(s.get(o.to)??0)-(s.get(c.to)??0));return i}function Ea(t,e){const n=[],s=new Set([t]),i=[{node:t}];for(;i.length>0;){const{node:r,parent:o}=i.shift();for(const{to:c}of e.get(r)??[])s.has(c)||(s.add(c),i.push({node:c,parent:r}));n.push({node:r,...o!==void 0?{parent:o}:{},frontier:i.map(c=>c.node)})}return n}function Ta(t,e){const n=[],s=new Set,i=[{node:t}];for(;i.length>0;){const{node:r,parent:o}=i.pop();if(s.has(r))continue;s.add(r);const c=(e.get(r)??[]).filter(({to:l})=>!s.has(l)).reverse();for(const{to:l}of c)i.push({node:l,parent:r});n.push({node:r,...o!==void 0?{parent:o}:{},frontier:[...new Set(i.map(l=>l.node).filter(l=>!s.has(l)))].reverse()})}return n}function _a(t,e,n){const s=[],i=Object.fromEntries(e.map(l=>[l,1/0])),r={},o=new Map(e.map((l,u)=>[l,u]));i[t]=0;const c=new Set;for(;;){let l;for(const h of e)c.has(h)||i[h]===1/0||(l===void 0||i[h]<i[l]||i[h]===i[l]&&o.get(h)<o.get(l))&&(l=h);if(l===void 0)break;c.add(l);for(const{to:h,weight:d}of n.get(l)??[])c.has(h)||i[l]+d<i[h]&&(i[h]=i[l]+d,r[h]=l);const u=e.filter(h=>!c.has(h)&&i[h]<1/0).sort((h,d)=>i[h]-i[d]);s.push({node:l,...r[l]!==void 0?{parent:r[l]}:{},frontier:u,distances:{...i}})}return s}const Ne=new Map;function ni(t,e,n,s,i=!1){const r=JSON.stringify([t,e,n,s,i]),o=Ne.get(r);if(o)return o;if(!n.includes(e))throw new Error(`graph search: no node "${e}"`);const c=Ce(n,s,i),l=t==="bfs"?Ea(e,c):t==="dfs"?Ta(e,c):_a(e,n,c);return Ne.size>64&&Ne.clear(),Ne.set(r,l),l}function si(t,e,n){const s=Ce(e,n,!0),i=Ce(e,n,!1),r=new Map,o=new Set([t]),c=[t];for(;c.length;){const y=c.shift(),g=(s.get(y)?.length?s.get(y):i.get(y)??[]).map(p=>p.to).filter(p=>!o.has(p));g.forEach(p=>o.add(p)),r.set(y,g),c.push(...g)}const l=new Map;let u=0;const h=(y,g)=>{const p=r.get(y)??[],a=p.length===0?u++:p.map(m=>h(m,g+1)).reduce((m,b,S,v)=>m+b/v.length,0);return l.set(y,[a,g===0?0:-g]),a};h(t,0);const d=[...l.values()].map(([y])=>y),f=(Math.min(...d)+Math.max(...d))/2;for(const[y,[g,p]]of l)l.set(y,[g-f,p]);return l}const Pa={"∪":"|","∩":"&","∖":"-","△":"^","¬":"!","\\":"-"};function Fn(t){const e=[...t].map(u=>Pa[u]??u).join("");let n=0;const s=()=>{for(;/\s/.test(e[n]??"");)n++},i=u=>{throw new Error(`set expression: ${u} at ${n+1} in "${t}"`)},r=()=>{s();let u;if(e[n]==="!")n++,u={type:"not",operand:r()};else if(e[n]==="(")n++,u=c(),s(),e[n]!==")"&&i('expected ")"'),n++;else{const h=/^[A-Za-z]\w*/.exec(e.slice(n));h||i(n>=e.length?"unexpected end":`unexpected "${e[n]}"`),n+=h[0].length,u={type:"set",name:h[0]}}for(s();e[n]==="'";)n++,u={type:"not",operand:u},s();return u},o=()=>{let u=r();for(s();e[n]==="&";)n++,u={type:"op",operator:"&",left:u,right:r()},s();return u},c=()=>{let u=o();for(s();e[n]==="|"||e[n]==="-"||e[n]==="^";)u={type:"op",operator:e[n++],left:u,right:o()},s();return u},l=c();return s(),n<e.length&&i(`unexpected "${e[n]}"`),l}function oe(t){return t.type==="set"?[t.name]:t.type==="not"?oe(t.operand):[...new Set([...oe(t.left),...oe(t.right)])]}function ae(t,e){switch(t.type){case"set":return e.has(t.name);case"not":return!ae(t.operand,e);case"op":{const n=ae(t.left,e),s=ae(t.right,e);return t.operator==="&"?n&&s:t.operator==="|"?n||s:t.operator==="-"?n&&!s:n!==s}}}function ii(t,e){const n=[];for(let s=0;s<1<<e.length;s++){const i=e.filter((r,o)=>s&1<<o);ae(t,new Set(i))&&n.push(i)}return n}function ri(t,e,n,s,i=64){return Array.from({length:i},(r,o)=>{const c=o/i*2*Math.PI;return[t+n*Math.cos(c),e+s*Math.sin(c)]})}function Fe(t){return t.edges.map(e=>Array.isArray(e)?{from:e[0],to:e[1],...e[2]!==void 0?{weight:e[2]}:{}}:e)}function oi(t){const e=new Map;if(t.tree){const[n,s]=t.tree.spacing??[1.2,1.2],[i,r]=t.tree.at??[0,0];for(const[o,[c,l]]of si(t.tree.root,t.nodes.map(u=>u.id),Fe(t)))e.set(o,[i+c*n,r+l*s])}for(const n of t.nodes)n.at&&e.set(n.id,n.at);return e}function ai(t,e){if(!t.search)return;const n=ni(t.search.kind,t.search.start,t.nodes.map(r=>r.id),Fe(t),t.directed),s=t.step===void 0?n.length:Math.min(n.length,Math.max(0,I(e,t.step))),i=Math.floor(s);return{events:n,done:i,partial:i<n.length?s-i:0}}const Oa={bfs:"queue",dfs:"stack",dijkstra:"open"};function Ia(t,e){const{plane:n,theme:s}=e,i=oi(t),r=Fe(t),o=ai(t,e.values),c=(t.radius??18)*n.scale,l=O(s,t.color,s.ink),u=O(s,"grey",s.colors.grey),h=O(s,"yellow",s.colors.yellow),d=O(s,"blue",s.colors.blue),f=[],y=o?o.events.slice(0,o.done):[],g=new Set(y.map(M=>M.node)),p=new Set(y.filter(M=>M.parent!==void 0).map(M=>`${M.parent}>${M.node}`)),a=y.at(-1),m=new Set(a?.frontier??[]),b=o&&o.partial>0?o.events[o.done]:void 0,S=(M,E)=>p.has(`${M}>${E}`)||!t.directed&&p.has(`${E}>${M}`),v=M=>n.toScreen(i.get(M)??[0,0]),w=(M,E)=>{const A=v(M),_=v(E),[T,C]=Kt([_[0]-A[0],_[1]-A[1]]);return[[A[0]+T*c,A[1]+C*c],[_[0]-T*c,_[1]-C*c]]},k=t.weights??t.search?.kind==="dijkstra";if(r.forEach((M,E)=>{const[A,_]=w(M.from,M.to),T=S(M.from,M.to),C=T?h:u,N=(T?4:2)*n.scale,[P]=V([[A,_]],e.draw);if(P&&(f.push(t.directed?{type:"arrow",id:`${t.id}.edge.${E}`,points:P,stroke:C,width:N,head:11*n.scale,opacity:e.opacity}:{type:"line",id:`${t.id}.edge.${E}`,points:P,stroke:C,width:N,opacity:e.opacity}),k&&e.draw>=1)){const F=[(A[0]+_[0])/2,(A[1]+_[1])/2],[L,B]=Kt([-(_[1]-A[1]),_[0]-A[0]]),z=14*n.scale;f.push({type:"text",id:`${t.id}.weight.${E}`,text:String(M.weight??1),x:F[0]+L*z*.9,y:F[1]+B*z*.9+z*.35,size:z,font:Mt,color:T?h:u,align:"center",opacity:e.opacity})}}),b?.parent!==void 0){const[M,E]=w(b.parent,b.node),[A]=V([[M,E]],b.parent?o.partial:1);A&&f.push({type:"line",id:`${t.id}.reaching`,points:A,stroke:h,width:4*n.scale,opacity:e.opacity})}const x=a?.distances;for(const M of t.nodes){const[E,A]=v(M.id),_=g.has(M.id),T=b?.node===M.id&&o.partial>=.999,C=!_&&m.has(M.id),N=_||T?h:C?d:s.background;f.push({type:"circle",id:`${t.id}.node.${M.id}`,x:E,y:A,r:c,fill:N,stroke:_?h:C?d:l,width:2*n.scale,opacity:e.opacity*Math.min(1,e.draw*1.5)}),a?.node===M.id&&f.push({type:"circle",id:`${t.id}.current`,x:E,y:A,r:c*1.35,stroke:h,width:2*n.scale,opacity:e.opacity*.8});const P=_||C||T?s.background:l;if(f.push(...G(U(M.label??M.id,{style:"inline"}),{x:E,y:A,size:c*.95,color:P,opacity:e.opacity*e.draw,idPrefix:`${t.id}.label.${M.id}.`})),x){const F=x[M.id],L=13*n.scale;f.push({type:"text",id:`${t.id}.distance.${M.id}`,text:F===1/0?"∞":String(Math.round(F*100)/100),x:E,y:A+c+L*1.15,size:L,font:Mt,color:d,align:"center",opacity:e.opacity})}}if(t.frontier&&t.search&&e.draw>=1){const[M,E]=t.frontier,A=16*n.scale,_=Oa[t.search.kind];f.push({type:"text",id:`${t.id}.frontier.name`,text:`${_}:`,x:M,y:E+A*.35,size:A,font:Mt,color:u,align:"left",opacity:e.opacity});const T=A*1.9;[...m].forEach((C,N)=>{const P=M+A*4+N*(T+A*.4),F=t.nodes.find(L=>L.id===C)?.label??C;f.push({type:"line",id:`${t.id}.frontier.box.${N}`,points:[[P,E-T/2],[P+T,E-T/2],[P+T,E+T/2],[P,E+T/2]],closed:!0,fill:d,opacity:e.opacity*.9}),f.push(...G(U(F,{style:"inline"}),{x:P+T/2,y:E,size:A*1.05,color:s.background,opacity:e.opacity,idPrefix:`${t.id}.frontier.label.${N}.`}))})}return f}function Ca(t){return t===2?[[-.6,0],[.6,0]]:[0,1,2].map(e=>{const n=Math.PI/2+e*2*Math.PI/3;return[.62*Math.cos(n),.62*Math.sin(n)-.1]})}function Na(t,e){const{plane:n,theme:s}=e,i=t.radius??1.5,[r,o]=t.at??[0,0],c=Ca(t.sets.length).map(([a,m])=>[r+a*i,o+m*i]),l=c.map(([a,m])=>ri(a,m,i,i,96).map(n.toScreen)),u=c.map(([a])=>a),h=c.map(([,a])=>a),d=i*.35,f=[[Math.min(...u)-i-d,Math.min(...h)-i-d],[Math.max(...u)+i+d,Math.min(...h)-i-d],[Math.max(...u)+i+d,Math.max(...h)+i+d],[Math.min(...u)-i-d,Math.max(...h)+i+d]].map(n.toScreen),y=[],g=t.sets.map(a=>a.id);if(t.highlight){const a=O(s,t.highlightColor,s.colors.yellow);ii(Fn(t.highlight),g).forEach((m,b)=>{y.push({type:"line",id:`${t.id}.region.${b}`,points:f,closed:!0,fill:a,opacity:e.opacity*e.draw*.55,clip:g.map((S,v)=>({points:l[v],outside:!m.includes(S)}))})})}if(t.universe!==!1){y.push({type:"line",id:`${t.id}.universe`,points:f,closed:!0,stroke:O(s,"grey",s.colors.grey),width:2*n.scale,opacity:e.opacity});const[a,m]=f[3];y.push(...G(U("U",{style:"inline"}),{x:a+16*n.scale,y:m+20*n.scale,size:22*n.scale,color:O(s,"grey",s.colors.grey),opacity:e.opacity,idPrefix:`${t.id}.universe.`}))}const p=["blue","red","green"];return t.sets.forEach((a,m)=>{const b=O(s,a.color??p[m],s.colors.blue);for(const x of V([[...l[m],l[m][0]]],e.draw))y.push({type:"line",id:`${t.id}.set.${a.id}`,points:x,stroke:b,width:3*n.scale,opacity:e.opacity});const[S,v]=Kt([c[m][0]-r||(m===0?-1:1),c[m][1]-o]),[w,k]=n.toScreen([c[m][0]+S*i*.78,c[m][1]+v*i*.78+(t.sets.length===2?i*.85:0)]);y.push(...G(U(a.label??a.id,{style:"inline"}),{x:w,y:k,size:26*n.scale,color:b,opacity:e.opacity*e.draw,idPrefix:`${t.id}.label.${a.id}.`}))}),y}const ci=(t,e)=>(Math.round(t)%e+e)%e;function Fa(t,e){const{plane:n,theme:s}=e,i=t.modulus,[r,o]=t.at??[0,0],c=t.radius??2,l=I(e.values,t.value),u=O(s,t.color,s.ink),h=O(s,"yellow",s.colors.yellow),d=(g,p)=>{const a=Math.PI/2-g/i*2*Math.PI;return n.toScreen([r+Math.cos(a)*c*p,o+Math.sin(a)*c*p])},f=[];for(const g of V([ri(r,o,c,c,120).map(n.toScreen)],e.draw))f.push({type:"line",id:`${t.id}.face`,points:g,stroke:u,width:3*n.scale,opacity:e.opacity});const y=ci(l,i);for(let g=0;g<i;g++){const[p,a]=d(g,.8),m=Math.min(26,220/i+8)*n.scale;f.push({type:"line",id:`${t.id}.tick.${g}`,points:[d(g,.95),d(g,1)],stroke:u,width:2*n.scale,opacity:e.opacity*e.draw}),f.push({type:"text",id:`${t.id}.hour.${g}`,text:String(g),x:p,y:a+m*.35,size:m,font:Mt,color:g===y?h:u,align:"center",opacity:e.opacity*e.draw})}if(e.draw>=1){const g=n.toScreen([r,o]);f.push({type:"arrow",id:`${t.id}.hand`,points:[g,d(l,.62)],stroke:h,width:5*n.scale,head:16*n.scale,opacity:e.opacity}),f.push({type:"circle",id:`${t.id}.pin`,x:g[0],y:g[1],r:6*n.scale,fill:h,opacity:e.opacity})}return f}const Ln=["sigmoid","tanh","relu"],li=(t,e)=>t==="sigmoid"?1/(1+Math.exp(-e)):t==="tanh"?Math.tanh(e):Math.max(0,e);function ui(t,e){const n=Pt(typeof e=="number"?e:wt(e)),s=[],i=[];for(let r=0;r<t.length-1;r++){const o=1.6/Math.sqrt(t[r]);s.push(Array.from({length:t[r+1]},()=>Array.from({length:t[r]},()=>vt(n)*o))),i.push(Array.from({length:t[r+1]},()=>vt(n)*.3))}return{layers:t,weights:s,biases:i}}function hi(t,e,n){const s=[e.slice(0,t.layers[0])];for(let i=0;i<t.weights.length;i++){const r=s[i];s.push(t.weights[i].map((o,c)=>li(n,o.reduce((l,u,h)=>l+u*(r[h]??0),t.biases[i][c]))))}return s}const ce=["viridis","heat","diverging"],La={viridis:[[68,1,84],[59,82,139],[33,145,140],[94,201,98],[253,231,37]],heat:[[20,12,30],[120,28,60],[214,70,40],[250,160,50],[252,240,180]],diverging:[[49,99,185],[140,180,225],[245,245,245],[235,140,120],[190,40,50]]};function Le(t,e){const n=La[t],s=Math.min(1,Math.max(0,Number.isFinite(e)?e:0))*(n.length-1),i=Math.min(n.length-2,Math.floor(s)),r=s-i,[o,c,l]=n[i].map((u,h)=>Math.round(u+(n[i+1][h]-u)*r));return`rgb(${o}, ${c}, ${l})`}function di(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(e){const s=e[1].length===3?[...e[1]].map(i=>i+i).join(""):e[1];return[0,2,4].map(i=>parseInt(s.slice(i,i+2),16))}const n=/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i.exec(t.trim());return n?[Number(n[1]),Number(n[2]),Number(n[3])]:void 0}function Rn(t,e,n){const s=di(t),i=di(e);if(!s||!i)return t;const r=Math.min(1,Math.max(0,n)),[o,c,l]=s.map((u,h)=>Math.round(i[h]+(u-i[h])*r));return`rgb(${o}, ${c}, ${l})`}function fi(t,e,n,s,i,r){r+=1e-9*Math.max(1,Math.abs(r));const o=[],c=t.length,l=t[0]?.length??0,u=(d,f,y,g)=>{(f>g||f===g&&d>y)&&([d,f,y,g]=[y,g,d,f]);const p=t[f][d]-r,a=t[g][y]-r,m=p===a?.5:p/(p-a);return[e+(d+(y-d)*m)*s,n+(f+(g-f)*m)*i]};for(let d=0;d<c-1;d++)for(let f=0;f<l-1;f++){const y=[t[d][f],t[d][f+1],t[d+1][f+1],t[d+1][f]];if(y.some(a=>!Number.isFinite(a)))continue;const g=[],p=[[0,1,f,d,f+1,d],[1,2,f+1,d,f+1,d+1],[2,3,f+1,d+1,f,d+1],[3,0,f,d+1,f,d]];for(const[a,m,b,S,v,w]of p)y[a]>=r!=y[m]>=r&&g.push(u(b,S,v,w));if(g.length===2)o.push([g[0],g[1]]);else if(g.length===4){const a=(y[0]+y[1]+y[2]+y[3])/4>=r,m=y[0]>=r;a===m?o.push([g[0],g[1]],[g[2],g[3]]):o.push([g[0],g[3]],[g[1],g[2]])}}const h=1e-6*Math.min(Math.abs(s),Math.abs(i));return Ra(o.filter(([d,f])=>Math.hypot(f[0]-d[0],f[1]-d[1])>h))}function Ra(t){const e=([o,c])=>`${Math.round(o*1e6)},${Math.round(c*1e6)}`,n=new Map;t.forEach(([o,c],l)=>{for(const u of[o,c])n.set(e(u),[...n.get(e(u))??[],l])});const s=new Set,i=[],r=o=>{for(;;){const c=o[o.length-1],l=(n.get(e(c))??[]).find(d=>!s.has(d));if(l===void 0)return;s.add(l);const[u,h]=t[l];o.push(e(u)===e(c)?h:u)}};return t.forEach(([o,c],l)=>{if(s.has(l))return;s.add(l);const u=[o,c];r(u),u.reverse(),r(u),i.push(u)}),i}function pi(t,[e,n],[s,i],r){const o=(n-e)/r,c=(i-s)/r;return{values:Array.from({length:r+1},(u,h)=>Array.from({length:r+1},(d,f)=>t(e+f*o,s+h*c))),x0:e,y0:s,dx:o,dy:c}}function gi(t,e,n,s,i=0,r={}){const o=rt(t),c=K(o,"x"),l=K(o,"y"),u=(f,y)=>{const g={...r,x:f,y};return[st(c,g),st(l,g)]},h=[e];let d=[0,0];for(let f=0;f<s;f++){const[y,g]=h[h.length-1],[p,a]=u(y,g);d=[i*d[0]-n*p,i*d[1]-n*a];const m=[y+d[0],g+d[1]];if(!Number.isFinite(m[0])||!Number.isFinite(m[1])||Math.abs(m[0])>1e6||Math.abs(m[1])>1e6)break;h.push(m)}return h}function Re(t){const e=rt(t);return(n,s,i={})=>st(e,{...i,x:n,y:s})}function Dn(t,e,n,s){const i=Pt(typeof s=="number"?s:wt(s)),r=[];for(let o=0;o<e;o++)t.forEach(([c,l],u)=>r.push({point:[c+vt(i)*n,l+vt(i)*n],label:u}));return r}const Da=t=>1/(1+Math.exp(-t)),le=(t,[e,n])=>Da(t.w[0]*e+t.w[1]*n+t.b);function yi(t,e,n,s={w:[0,0],b:0}){const i=[s];for(let r=0;r<e;r++){const{w:o,b:c}=i[i.length-1];let l=0,u=0,h=0;for(const{point:f,label:y}of t){const g=le({w:o,b:c},f)-y;l+=g*f[0],u+=g*f[1],h+=g}const d=t.length||1;i.push({w:[o[0]-n*l/d,o[1]-n*u/d],b:c-n*h/d})}return i}function mi(t,e){return e.length===0?0:e.filter(({point:n,label:s})=>(le(t,n)>=.5?1:0)===s).length/e.length}function bi(t,e){if(e.length===0)return 0;const n=1e-12;return-e.reduce((s,{point:i,label:r})=>{const o=le(t,i);return s+Math.log(r?o+n:1-o+n)},0)/e.length}const De=(t,e)=>(t[0]-e[0])**2+(t[1]-e[1])**2;function qe(t,e){return t.map(n=>{let s=0;for(let i=1;i<e.length;i++)De(n,e[i])<De(n,e[s])&&(s=i);return s})}function wi(t,e,n=20,s=t.slice(0,e)){const i=[s.map(r=>[r[0],r[1]])];for(let r=0;r<n;r++){const o=i[i.length-1],c=qe(t,o),l=o.map((h,d)=>{const f=t.filter((y,g)=>c[g]===d);return f.length===0?h:[f.reduce((y,g)=>y+g[0],0)/f.length,f.reduce((y,g)=>y+g[1],0)/f.length]}),u=l.some((h,d)=>De(h,o[d])>1e-12);if(i.push(l),!u)break}return i}function vi(t,e){const n=qe(t,e);return t.reduce((s,i,r)=>s+De(i,e[n[r]]),0)}const ze=(t,e,n)=>{let s=t.get(e);return s===void 0&&(s=n(),t.size>32&&t.clear(),t.set(e,s)),s},je=t=>Number.isFinite(t)?t:0,ki=t=>({x:t.plane.x,y:t.plane.y,w:t.plane.x[1]-t.plane.x[0],h:t.plane.y[1]-t.plane.y[0]});function Mi(t,e){const n=ui(t.layers,t.seed??t.id),s=Array.from({length:t.layers[0]},(o,c)=>t.inputs?.[c]===void 0?.5:I(e,t.inputs[c])),i=hi(n,s,t.activation??"sigmoid"),r=t.flow===void 0?t.layers.length-1:Math.min(t.layers.length-1,Math.max(0,je(I(e,t.flow))));return{network:n,activations:i,flow:r}}function qa(t,e){const{plane:n,theme:s}=e,{network:i,activations:r,flow:o}=Mi(t,e.values),c=ki(e),[l,u]=t.size??[c.w*.75,c.h*.7],[h,d]=t.at??[(c.x[0]+c.x[1])/2,(c.y[0]+c.y[1])/2],f=(t.radius??16)*n.scale,y=t.layers,g=(v,w)=>{const k=h-l/2+(y.length===1?l/2:v/(y.length-1)*l),x=Math.min(u/Math.max(1,y[v]-1),u*.3),M=d+((y[v]-1)/2-w)*x;return n.toScreen([k,M])},p=O(s,"blue",s.colors.blue),a=O(s,"red",s.colors.red),m=[],b=Math.max(...i.weights.flat(2).map(Math.abs),1e-9);i.weights.forEach((v,w)=>{v.forEach((k,x)=>{k.forEach((M,E)=>{const A=g(w,E),_=g(w+1,x),T=Math.min(1,Math.max(0,o-w)),C=M>=0?p:a,N=(.6+3*(Math.abs(M)/b))*n.scale;for(const P of V([[A,_]],e.draw))m.push({type:"line",id:`${t.id}.w.${w}.${x}.${E}`,points:P,stroke:C,width:N,opacity:e.opacity*(.18+.5*T)});if(T>0&&T<1){const[P,F]=Jt(A,_,T);m.push({type:"circle",id:`${t.id}.pulse.${w}.${x}.${E}`,x:P,y:F,r:f*.22,fill:O(s,"yellow",s.colors.yellow),opacity:e.opacity*(.5+.5*Math.abs(r[w][E]??0))})}})})}),y.forEach((v,w)=>{const k=Math.min(1,Math.max(0,o-w+1));for(let x=0;x<v;x++){const[M,E]=g(w,x),A=r[w][x]??0,_=t.activation==="relu"?Math.min(1,A/2):t.activation==="tanh"?(A+1)/2:A;m.push({type:"circle",id:`${t.id}.node.${w}.${x}`,x:M,y:E,r:f,fill:s.background,stroke:O(s,t.color,s.ink),width:2*n.scale,opacity:e.opacity*Math.min(1,e.draw*1.5)}),k>0&&m.push({type:"circle",id:`${t.id}.value.${w}.${x}`,x:M,y:E,r:f*.86,fill:Le("viridis",_),opacity:e.opacity*k})}});const S=(v,w,k,x)=>m.push(...G(U(v,{values:e.scope,style:"inline"}),{x:w[0],y:w[1],size:20*n.scale,color:s.ink,align:k,opacity:e.opacity*e.draw,idPrefix:`${t.id}.${x}.`}));return t.labels?.inputs?.forEach((v,w)=>{const[k,x]=g(0,w);S(v,[k-f*1.5,x],"right",`in${w}`)}),t.labels?.outputs?.forEach((v,w)=>{const[k,x]=g(y.length-1,w);S(v,[k+f*1.5,x],"left",`out${w}`)}),m}const za=t=>{const e=Math.max(...t),n=t.map(i=>Math.exp(i-e)),s=n.reduce((i,r)=>i+r,0);return n.map(i=>i/s)};function ja(t,e){if(t.cells){const u=ki(e),[h,d]=t.size??[u.w*.7,u.h*.7],f=t.at??[(u.x[0]+u.x[1])/2-h/2,(u.y[0]+u.y[1])/2-d/2];return{cells:t.softmax?t.cells.map(za):t.cells,box:[f,[f[0]+h,f[1]+d]]}}const[[n,s],[i,r]]=t.region??[e.plane.x,e.plane.y],o=t.resolution??48,c=Re(t.expr);return{cells:Array.from({length:o},(u,h)=>Array.from({length:o},(d,f)=>c(n+(f+.5)/o*(s-n),r-(h+.5)/o*(r-i),e.scope))),box:[[n,i],[s,r]]}}function Xa(t,e){const{plane:n,theme:s}=e,{cells:i,box:r}=ja(t,e),o=i.flat().filter(Number.isFinite),[c,l]=t.range??[Math.min(...o),Math.max(...o)],u=i.length,h=i[0]?.length??0,[[d,f],[y,g]]=r,p=(y-d)/h,a=(g-f)/u,m=[],b=t.colormap??"viridis",S=Math.ceil(u*e.draw);for(let w=0;w<S;w++)for(let k=0;k<h;k++){const x=i[w][k];if(!Number.isFinite(x))continue;const M=l===c?.5:(x-c)/(l-c),E=d+k*p,A=g-w*a,_=[[E,A-a],[E+p*1.01,A-a],[E+p*1.01,A+a*.01],[E,A+a*.01]].map(n.toScreen);if(m.push({type:"line",id:`${t.id}.${w}.${k}`,points:_,closed:!0,fill:Rn(Le(b,M),s.background,e.opacity)}),t.values){const[T,C]=n.toScreen([E+p/2,A-a/2]),N=Math.min(16*n.scale,Math.abs(p*n.unitX)*.32);m.push({type:"text",id:`${t.id}.v.${w}.${k}`,text:x.toFixed(2).replace(/^0/,""),x:T,y:C+N*.35,size:N,font:Mt,color:M>.6?"#111":"#eee",align:"center",opacity:e.opacity})}}const v=Math.min(22*n.scale,Math.abs(a*n.unitY)*.6);return t.rowLabels?.forEach((w,k)=>{const[x,M]=n.toScreen([d,g-(k+.5)*a]);m.push(...G(U(w,{style:"inline"}),{x:x-v*.5,y:M,size:v,color:s.ink,align:"right",opacity:e.opacity*e.draw,idPrefix:`${t.id}.row.${k}.`}))}),t.colLabels?.forEach((w,k)=>{const[x,M]=n.toScreen([d+(k+.5)*p,g]);m.push(...G(U(w,{style:"inline"}),{x,y:M-v*.8,size:v,color:s.ink,opacity:e.opacity*e.draw,idPrefix:`${t.id}.col.${k}.`}))}),m}const Ya=new Map;function Ba(t,e){const n=t.region??[e.plane.x,e.plane.y],s=t.resolution??80,i=Object.entries(e.scope).filter(([l])=>!l.includes(".")),r=ze(Ya,JSON.stringify([t.expr,t.levels,n,s,i]),()=>{const l=Re(t.expr),u=pi((p,a)=>l(p,a,e.scope),n[0],n[1],s),h=u.values.flat().filter(Number.isFinite),d=Math.min(...h),f=Math.max(...h),y=typeof t.levels=="number"?t.levels:10;return(Array.isArray(t.levels)?t.levels:Array.from({length:y},(p,a)=>d+(f-d)*(a+1)/(y+1))).map(p=>fi(u.values,u.x0,u.y0,u.dx,u.dy,p))}),o=[],c=t.colormap??"viridis";return r.forEach((l,u)=>{const h=t.color?O(e.theme,t.color,e.theme.ink):Le(c,r.length===1?.6:.15+.85*u/(r.length-1));V(l.map(d=>d.map(e.plane.toScreen)),e.draw).forEach((d,f)=>{o.push({type:"line",id:`${t.id}.${u}.${f}`,points:d,stroke:h,width:(t.width??1.8)*e.plane.scale,opacity:e.opacity})})}),o}const Va=new Map;function $i(t,e,n){const s=It(e,t.start),i=I(e,t.rate),r=t.momentum===void 0?0:I(e,t.momentum),o=Math.min(500,Math.max(0,je(I(e,t.steps)))),c=Object.entries(n).filter(([f])=>!f.includes(".")),l=ze(Va,JSON.stringify([t.expr,s,i,r,c]),()=>gi(t.expr,s,i,500,r,n)),u=Math.min(l.length-1,Math.floor(o)),h=u<l.length-1?o-u:0,d=h>0?Jt(l[u],l[u+1],h):l[u];return{path:l.slice(0,u+1),here:d,step:u,diverged:l.length<501&&o>l.length-1}}function Ha(t,e){const{path:n,here:s}=$i(t,e.values,e.scope),i=O(e.theme,t.color,e.theme.colors.red),r=[...n,s].map(e.plane.toScreen),o=[];r.length>=2&&o.push({type:"line",id:`${t.id}.path`,points:r,stroke:i,width:(t.width??2.5)*e.plane.scale,opacity:e.opacity*.9}),n.forEach((u,h)=>{const[d,f]=e.plane.toScreen(u);o.push({type:"circle",id:`${t.id}.step.${h}`,x:d,y:f,r:3*e.plane.scale,fill:i,opacity:e.opacity*.8})});const[c,l]=e.plane.toScreen(s);return o.push({type:"circle",id:`${t.id}.ball`,x:c,y:l,r:8*e.plane.scale,fill:O(e.theme,"yellow",e.theme.colors.yellow),stroke:e.theme.background,width:2*e.plane.scale,opacity:e.opacity}),o}const Ua=new Map;function Si(t,e){const n=t.centres??[[-1.5,-1],[1.5,1]],s=Math.min(500,Math.max(0,je(I(e,t.epochs)))),[i,r,o]=t.start??[.9,-1.1,.8],{data:c,models:l}=ze(Ua,JSON.stringify([n,t.count,t.spread,t.seed??t.id,t.rate,i,r,o]),()=>{const g=Dn(n,t.count??40,t.spread??.9,t.seed??t.id);return{data:g,models:yi(g,500,t.rate??.5,{w:[i,r],b:o})}}),u=Math.floor(s),h=s-u,d=l[u],f=l[Math.min(l.length-1,u+1)],y={w:Jt(d.w,f.w,h),b:d.b+(f.b-d.b)*h};return{data:c,model:y,epochs:s}}function Wa(t,e){const{plane:n,theme:s}=e,{data:i,model:r}=Si(t,e.values),o=[],c=[O(s,"blue",s.colors.blue),O(s,"orange",s.colors.orange)];if(t.probability!==!1){const[d,f]=n.x,[y,g]=n.y,p=(f-d)/32,a=(g-y)/32;for(let m=0;m<32;m++)for(let b=0;b<32;b++){const S=le(r,[d+(b+.5)*p,y+(m+.5)*a]),v=[[d+b*p,y+m*a],[d+(b+1.02)*p,y+m*a],[d+(b+1.02)*p,y+(m+1.02)*a],[d+b*p,y+(m+1.02)*a]].map(n.toScreen);o.push({type:"line",id:`${t.id}.p.${m}.${b}`,points:v,closed:!0,fill:Rn(S>=.5?c[1]:c[0],s.background,e.opacity*Math.abs(S-.5)*.5)})}}i.forEach(({point:h,label:d},f)=>{const[y,g]=n.toScreen(h);o.push({type:"circle",id:`${t.id}.pt.${f}`,x:y,y:g,r:4.5*n.scale,fill:c[d],stroke:s.background,width:1*n.scale,opacity:e.opacity*e.draw})});const[l,u]=r.w;if(Math.hypot(l,u)>1e-6){const[h,d]=n.x,[f,y]=n.y,g=Math.abs(u)>Math.abs(l)?[[h,-(l*h+r.b)/u],[d,-(l*d+r.b)/u]]:[[-(u*f+r.b)/l,f],[-(u*y+r.b)/l,y]];o.push({type:"line",id:`${t.id}.boundary`,points:g.map(n.toScreen),stroke:s.ink,width:3*n.scale,opacity:e.opacity,dash:[12*n.scale,8*n.scale]})}return o}const Ga=new Map;function xi(t,e){const{points:n,history:s}=ze(Ga,JSON.stringify([t.centres,t.count,t.spread,t.seed??t.id,t.k]),()=>{const l=Dn(t.centres,t.count??30,t.spread??.7,t.seed??t.id).map(f=>f.point),u=t.k??t.centres.length,h=[l.reduce((f,y)=>f+y[0],0)/l.length,l.reduce((f,y)=>f+y[1],0)/l.length],d=[...l].sort((f,y)=>Math.hypot(f[0]-h[0],f[1]-h[1])-Math.hypot(y[0]-h[0],y[1]-h[1])).slice(0,u);return{points:l,history:wi(l,u,20,d)}}),i=Math.min(s.length-1,Math.max(0,je(I(e,t.iteration)))),r=Math.floor(i),o=i-r,c=s[r].map((l,u)=>Jt(l,s[Math.min(s.length-1,r+1)][u],o));return{points:n,history:s,centroids:c,owners:qe(n,s[r]),iteration:i,iterations:s.length-1}}function Za(t,e){const{plane:n,theme:s}=e,{points:i,centroids:r,owners:o,history:c,iteration:l}=xi(t,e.values),u=["blue","orange","green","pink","purple","teal"].map(d=>O(s,d,s.colors.blue)),h=[];return i.forEach((d,f)=>{const[y,g]=n.toScreen(d);h.push({type:"circle",id:`${t.id}.pt.${f}`,x:y,y:g,r:4.5*n.scale,fill:u[o[f]%u.length],opacity:e.opacity*e.draw*.85})}),r.forEach((d,f)=>{const y=c.slice(0,Math.floor(l)+1).map(m=>m[f]);y.push(d),y.length>=2&&h.push({type:"line",id:`${t.id}.trail.${f}`,points:y.map(n.toScreen),stroke:u[f%u.length],width:2*n.scale,opacity:e.opacity*.7,dash:[6*n.scale,5*n.scale]});const[g,p]=n.toScreen(d),a=11*n.scale;h.push({type:"line",id:`${t.id}.centroid.${f}`,points:[[g,p-a],[g+a,p],[g,p+a],[g-a,p]],closed:!0,fill:u[f%u.length],stroke:s.ink,width:2.5*n.scale,opacity:e.opacity})}),h}function Qa(t,e,n){switch(t.kind){case"network":{const{activations:s}=Mi(t,e);return Object.fromEntries(s[s.length-1].map((i,r)=>[`${t.id}.out${r}`,i]))}case"descent":{const{here:s,step:i}=$i(t,e,n);return{[`${t.id}.x`]:s[0],[`${t.id}.y`]:s[1],[`${t.id}.loss`]:Re(t.expr)(s[0],s[1],n),[`${t.id}.step`]:i}}case"classifier":{const{data:s,model:i,epochs:r}=Si(t,e);return{[`${t.id}.accuracy`]:mi(i,s),[`${t.id}.loss`]:bi(i,s),[`${t.id}.epoch`]:Math.floor(r)}}case"kmeans":{const{points:s,centroids:i,iteration:r,iterations:o}=xi(t,e);return{[`${t.id}.inertia`]:vi(s,i),[`${t.id}.iteration`]:Math.floor(r),[`${t.id}.iterations`]:o}}}}function Xe(t,e,n,s=512){if(e===n)return 0;const i=(n-e)/s;let r=t(e)+t(n);for(let o=1;o<s;o++)r+=t(e+o*i)*(o%2?4:2);return r*i/3}function Ai(t,e,n,s,i){const r=(n-e)/s;return Array.from({length:s},(o,c)=>{const l=e+c*r,u=l+r;if(i==="trapezoid")return[l,u,t(l),t(u)];const h=t(i==="left"?l:i==="right"?u:(l+u)/2);return[l,u,h,h]})}const Ei=t=>Math.min(400,Math.max(1,Math.round(t)));function Ti(t,e,n){const s={},i={...n};for(const r of t)switch(r.kind){case"tangent":{const o=J(r.expr),c=I(e,r.at),l=r.h===void 0?0:I(e,r.h),u=Math.abs(l)>1e-9?(o(c+l,i)-o(c,i))/l:Ae(r.expr,1)(c,i);Object.assign(s,{[`${r.id}.slope`]:u,[`${r.id}.x`]:c,[`${r.id}.y`]:o(c,i)});break}case"riemann":{const o=J(r.expr),c=I(e,r.from),l=I(e,r.to),u=Ei(I(e,r.n)),d=Ai(f=>o(f,i),c,l,u,r.rule??"left").reduce((f,[y,g,p,a])=>f+(p+a)/2*(g-y),0);Object.assign(s,{[`${r.id}.sum`]:d,[`${r.id}.exact`]:Xe(f=>o(f,i),c,l),[`${r.id}.n`]:u});break}case"area":{const o=J(r.expr),c=r.lower?J(r.lower):()=>0;s[`${r.id}.value`]=Xe(l=>o(l,i)-c(l,i),I(e,r.from),I(e,r.to));break}case"point":if(r.on!==void 0&&r.x!==void 0){const o=I(e,r.x);Object.assign(s,{[`${r.id}.x`]:o,[`${r.id}.y`]:J(r.on)(o,i)})}break;case"histogram":{const o=En(Ct(e,r.distribution),r.seed??r.id,Ie(I(e,r.count))),{mean:c,sd:l}=Ks(o);Object.assign(s,{[`${r.id}.count`]:o.length,[`${r.id}.mean`]:c,[`${r.id}.sd`]:l});break}case"distribution":{const o=Ct(e,r.distribution);let c=0;if(r.shade){const[l,u]=[I(e,r.shade[0]),I(e,r.shade[1])].sort((h,d)=>h-d);if(re(o))for(let h=Math.max(0,Math.ceil(l));h<=Math.floor(u)&&h<=5e3;h++)c+=pt(o,h);else c=Xe(h=>pt(o,h),l,u,2048)}Object.assign(s,{[`${r.id}.p`]:c,[`${r.id}.mean`]:Ft(o),[`${r.id}.sd`]:Lt(o)});break}case"galton":s[`${r.id}.landed`]=Math.max(0,Math.floor(I(e,r.balls)));break;case"scatter":{const o=Pn(ei(r,{values:e}),r.seed??r.id,Ie(I(e,r.count))),c=r.inside?rt(r.inside):void 0,l=c?o.filter(([h,d])=>st(c,{...i,x:h,y:d})<=0).length:0,u=On(o);Object.assign(s,{[`${r.id}.count`]:o.length,[`${r.id}.inside`]:l,[`${r.id}.ratio`]:o.length?l/o.length:0,[`${r.id}.slope`]:u?.slope??0,[`${r.id}.intercept`]:u?.intercept??0,[`${r.id}.r`]:u?.r??0});break}case"bayes":{const o=I(e,r.prior),c=Js(o,I(e,r.truePositive),I(e,r.falsePositive));Object.assign(s,{[`${r.id}.prior`]:o,[`${r.id}.posterior`]:c.posterior,[`${r.id}.positive`]:c.positive,[`${r.id}.truePositive`]:c.truePositive,[`${r.id}.falsePositive`]:c.falsePositive});break}case"graph":{const o=ai(r,e);if(o&&(s[`${r.id}.visited`]=o.done,s[`${r.id}.steps`]=o.events.length,r.search?.kind==="dijkstra")){const c=o.events[o.done-1]?.distances??{};for(const l of r.nodes)s[`${r.id}.d.${l.id}`]=c[l.id]??1/0}break}case"clock":{const o=I(e,r.value);Object.assign(s,{[`${r.id}.hour`]:ci(o,r.modulus),[`${r.id}.turns`]:Math.floor(Math.round(o)/r.modulus)});break}case"network":case"descent":case"classifier":case"kmeans":Object.assign(s,Qa(r,e,i));break;case"taylor":s[`${r.id}.order`]=Math.min(20,Math.max(0,I(e,r.order))),s[`${r.id}.degree`]=Math.floor(s[`${r.id}.order`]);break}return s}function Ka(t,e){const n=J(t.expr),s=I(e.values,t.at),i=t.h===void 0?0:I(e.values,t.h),r=n(s,e.scope),o=e.scope[`${t.id}.slope`];if(!Number.isFinite(r)||!Number.isFinite(o))return[];const c=t.length!==void 0?t.length/2:Math.max(Math.abs(e.plane.x[0]-s),Math.abs(e.plane.x[1]-s)),l=[[s-c,r-o*c],[s+c,r+o*c]],u=O(e.theme,t.color,e.theme.colors.yellow),h=e.plane.toScreen([s,r]),d=l.map(e.plane.toScreen),f=[d[0],d[1]].flatMap((y,g)=>V([[h,y]],e.draw).map(p=>({type:"line",id:`${t.id}.${g}`,points:p,stroke:u,width:(t.width??3)*e.plane.scale,opacity:e.opacity})));if(t.points!==!1){const y=6*e.plane.scale;if(f.push({type:"circle",id:`${t.id}.point`,x:h[0],y:h[1],r:y,fill:u,opacity:e.opacity}),Math.abs(i)>1e-9){const[g,p]=e.plane.toScreen([s+i,n(s+i,e.scope)]);Number.isFinite(p)&&f.push({type:"circle",id:`${t.id}.secant`,x:g,y:p,r:y,fill:u,opacity:e.opacity})}}if(t.label&&e.draw>=1){const y=24*e.plane.scale,g=U(t.label,{values:e.scope,style:"inline"});f.push(...G(g,{x:h[0],y:h[1]-y*1.6,size:y,color:u,opacity:e.opacity,idPrefix:`${t.id}.label.`}))}return f}function Ja(t,e){const n=J(t.expr),s=I(e.values,t.from),i=I(e.values,t.to),r=Ei(I(e.values,t.n)),o=Ai(h=>n(h,e.scope),s,i,r,t.rule??"left"),c=O(e.theme,t.color,e.theme.colors.blue),l=Math.ceil(o.length*e.draw),u=Math.max(.5,Math.min(1.5,60/r))*e.plane.scale;return o.slice(0,l).flatMap(([h,d,f,y],g)=>{if(!Number.isFinite(f)||!Number.isFinite(y))return[];const p=[[h,0],[d,0],[d,y],[h,f]].map(e.plane.toScreen),m=(f+y)/2<0?O(e.theme,"red",e.theme.colors.red):c;return[{type:"line",id:`${t.id}.${g}`,points:p,closed:!0,fill:m,stroke:m,width:u,opacity:e.opacity*(t.fillOpacity??.35)}]})}function tc(t,e){const n=J(t.expr),s=t.lower?J(t.lower):()=>0,i=I(e.values,t.from),r=i+(I(e.values,t.to)-i)*e.draw;if(i===r)return[];const o=240,c=O(e.theme,t.color,e.theme.colors.blue),l=O(e.theme,t.negativeColor,e.theme.colors.red),u=e.opacity*(t.fillOpacity??.4),h=[];let d=[],f=[],y;const g=()=>{d.length>=2&&h.push({type:"line",id:`${t.id}.${h.length}`,points:[...d,...f.reverse()].map(e.plane.toScreen),closed:!0,fill:y?c:l,opacity:u}),d=[],f=[]};let p;for(let a=0;a<=o;a++){const m=i+(r-i)*a/o,b=n(m,e.scope),S=s(m,e.scope);if(!Number.isFinite(b)||!Number.isFinite(S)){g(),p=void 0;continue}const v=b-S>=0;if(p&&y!==void 0&&v!==y){const w=p.fy-p.gy,k=b-S,x=w/(w-k),M=p.x+(m-p.x)*x,E=p.gy+(S-p.gy)*x;d.push([M,E]),f.push([M,E]),g(),d.push([M,E]),f.push([M,E])}y=v,d.push([m,b]),f.push([m,S]),p={x:m,fy:b,gy:S}}return g(),h}const ec=Array.from({length:22},(t,e)=>e).map(t=>t===0?1:Array.from({length:t},(e,n)=>n+1).reduce((e,n)=>e*n,1));function nc(t,e){const n=I(e.values,t.at),s=e.scope[`${t.id}.order`],i=Math.floor(s),r=s-i,o=Array.from({length:Math.min(20,i+1)+1},(d,f)=>Ae(t.expr,f)(n,e.scope)/ec[f]),c=d=>{let f=0,y=1;for(let g=0;g<=i;g++)f+=o[g]*y,y*=d-n;return r>0&&i<20?f+r*o[i+1]*y:f},l=O(e.theme,t.color,e.theme.colors.yellow),[u,h]=t.domain??e.plane.x;return Te(t.id,d=>c(d),u,h,l,(t.width??3.5)*e.plane.scale,e)}function sc(t,e){switch(t.kind){case"grid":return Qo(t,e);case"axes":return Ko(t,e);case"vector":return la(t,e);case"basis":return ua(t,e);case"point":return ha(t,e);case"function":return fa(t,e);case"parametric":return pa(t,e);case"polygon":return ya(t,e);case"line":return ma(t,e);case"label":return va(t,e);case"equation":return ka(t,e);case"tangent":return Ka(t,e);case"riemann":return Ja(t,e);case"area":return tc(t,e);case"taylor":return nc(t,e);case"histogram":return Ma(t,e);case"distribution":return $a(t,e);case"galton":return Sa(t,e);case"scatter":return xa(t,e);case"bayes":return Aa(t,e);case"graph":return Ia(t,e);case"venn":return Na(t,e);case"clock":return Fa(t,e);case"network":return qa(t,e);case"heatmap":return Xa(t,e);case"contours":return Ba(t,e);case"descent":return Ha(t,e);case"classifier":return Wa(t,e);case"kmeans":return Za(t,e)}}const _i=t=>Math.min(1,Math.max(0,t));function Rt(t,e={}){const n=ve[t.theme??"dark"],s=dn(t),i={...t.values},r=new Map;for(const[h,d]of Object.entries(e))h.indexOf(".")<0?typeof d!="string"&&(i[h]=d):typeof d=="number"&&r.set(h,d);const o=Ts(i),c={...o,...Ti(t.items,i,o)},l=[];for(const h of t.items){const d=g=>r.get(`${h.id}.${g}`),f=_i(d("draw")??h.draw??1),y=_i(d("opacity")??h.opacity??1);f<=0||y<=0||l.push(...sc(h,{plane:s,theme:n,values:i,scope:c,draw:f,opacity:y,prop:d}))}const u=t.background==="none"?void 0:t.background??n.background;return{width:t.width,height:t.height,...u?{background:u}:{},shapes:l}}const ic=new Set(["x","y","z","t","opacity","rotate","rotateX","rotateY","scale","scaleX","scaleY","skewX","skewY","originX","originY","perspective","width","height","fill","stroke","fillStyle","strokeStyle","lineWidth","strokeWidth","filter","blur","visible","clipTop","clipRight","clipBottom","clipLeft","quaternion"]);function xt(t){const e=a=>{throw new Error(`math figure: ${a}`)};(!t||typeof t!="object")&&e("expected a figure object"),(!(t.width>0)||!(t.height>0))&&e("width and height must be positive numbers (px)");for(const a of["x","y"]){const m=t[a];m!==void 0&&!(Array.isArray(m)&&m.length===2&&m.every(Number.isFinite)&&m[0]<m[1])&&e(`${a} must be [min, max] with min < max`)}t.theme!==void 0&&!(t.theme in ve)&&e(j("theme",t.theme,Object.keys(ve))),Array.isArray(t.items)||e("items must be an array");const n=t.values??{};for(const[a,m]of Object.entries(n))/^[A-Za-z_]\w*$/.test(a)||e(`value name "${a}" must be letters, digits and _ (starting with a letter)`),ic.has(a)&&e(`"${a}" cannot name a value: it is ${a==="x"||a==="t"?"the variable of functions and curves":"a property of the figure itself (its place, size or look)"}`),typeof m=="number"&&Number.isFinite(m)||ct(m)||Ot(m)||e(`value "${a}" must be a number, an [x, y] vector or an [a, b, c, d] matrix`);const s=Ts(n),i=Object.keys(n).filter(a=>typeof n[a]=="number"),r=(a,m,b)=>{b!==void 0&&(typeof b=="string"?(b in n||e(`${a.id}.${m}: ${j("value",b,Object.keys(n))}`),ct(n[b])||e(`${a.id}.${m}: value "${b}" is not an [x, y] vector`)):ct(b)||e(`${a.id}.${m} must be [x, y] or the name of a vector value`))},o=(a,m,b)=>{b!==void 0&&(b in n||e(`${a.id}.${m}: ${j("value",b,Object.keys(n))}`),Ot(n[b])||e(`${a.id}.${m}: value "${b}" is not an [a, b, c, d] matrix`))},c=(a,m,b,S)=>{let v=[];try{v=Mn(rt(b))}catch(w){e(`${a.id}.${m}: ${w.message}`)}for(const w of v)w!==S&&!(w in ee)&&!i.includes(w)&&e(`${a.id}.${m}: "${w}" is neither ${S} nor a number value (${j("value",w,[S,...i])})`)},l=[],u=(a,m,b)=>{l.push([a,m,b])},h=(a,m,b)=>{b!==void 0&&(typeof b=="string"?(b in n||e(`${a.id}.${m}: ${j("value",b,i)}`),typeof n[b]!="number"&&e(`${a.id}.${m}: value "${b}" is not a number`)):Number.isFinite(b)||e(`${a.id}.${m} must be a number or the name of a number value`))},d=(a,m,b)=>{(!b||typeof b!="object"||!ie.includes(b.kind))&&e(`${a.id}.${m}: ${j("distribution",b?.kind,ie)}`);for(const[v,w]of Object.entries(b))v!=="kind"&&(v==="of"?d(a,`${m}.of`,w):h(a,`${m}.${v}`,w));const S=Tn(Ct(n,b));S&&e(`${a.id}.${m}: ${S}`)},f=(a,m,b)=>{let S=[];try{S=Mn(rt(b))}catch(v){e(`${a.id}.${m}: ${v.message}`)}for(const v of S)v!=="x"&&v!=="y"&&!i.includes(v)&&e(`${a.id}.${m}: "${v}" is neither x, y nor a number value`)},y=(a,m,b,S)=>{try{let v=rt(b);for(let w=0;w<S;w++)v=K(v)}catch(v){e(`${a.id}.${m}: ${v.message} (calculus needs functions with derivatives)`)}},g=new Set;for(const a of t.items)switch((!a||typeof a!="object")&&e("every item must be an object"),ln.includes(a.kind)||e(j("item kind",a.kind,ln)),(typeof a.id!="string"||!/^[A-Za-z_][\w-]*$/.test(a.id))&&e(`a ${a.kind} needs an id (letters, digits, _ and -)`),g.has(a.id)&&e(`two items have the id "${a.id}"`),a.id in n&&e(`"${a.id}" is both an item id and a value name`),g.add(a.id),a.kind){case"grid":a.step!==void 0&&!(a.step>0)&&e(`${a.id}.step must be positive`),o(a,"transform",a.transform);break;case"vector":r(a,"to",a.to),r(a,"from",a.from),o(a,"transform",a.transform),a.label&&u(a,"label",a.label);break;case"basis":o(a,"transform",a.transform);break;case"point":a.at===void 0==(a.on===void 0)&&e(`${a.id} needs at, or on with x (a point on a curve)`),a.on!==void 0&&(a.x===void 0&&e(`${a.id}: a point on a curve needs x`),c(a,"on",a.on,"x"),h(a,"x",a.x)),r(a,"at",a.at),o(a,"transform",a.transform),a.label&&u(a,"label",a.label);break;case"function":c(a,"expr",a.expr,"x"),a.derivative!==void 0&&((!Number.isInteger(a.derivative)||a.derivative<0||a.derivative>8)&&e(`${a.id}.derivative must be a whole number from 0 to 8`),y(a,"expr",a.expr,a.derivative));break;case"tangent":c(a,"expr",a.expr,"x"),y(a,"expr",a.expr,1),h(a,"at",a.at),h(a,"h",a.h),a.label&&u(a,"label",a.label);break;case"riemann":c(a,"expr",a.expr,"x"),h(a,"from",a.from),h(a,"to",a.to),h(a,"n",a.n),a.rule!==void 0&&!["left","right","midpoint","trapezoid"].includes(a.rule)&&e(`${a.id}.rule: ${j("rule",a.rule,["left","right","midpoint","trapezoid"])}`);break;case"area":c(a,"expr",a.expr,"x"),a.lower!==void 0&&c(a,"lower",a.lower,"x"),h(a,"from",a.from),h(a,"to",a.to);break;case"histogram":d(a,"distribution",a.distribution),h(a,"count",a.count),a.bins!==void 0&&!(Array.isArray(a.bins)&&a.bins.length===3&&a.bins[1]>a.bins[0]&&Number.isInteger(a.bins[2])&&a.bins[2]>=1&&a.bins[2]<=500)&&e(`${a.id}.bins must be [from, to, count] with from < to and a whole count 1..500`);break;case"distribution":d(a,"distribution",a.distribution),a.shade&&a.shade.forEach((m,b)=>h(a,`shade[${b}]`,m));break;case"galton":a.rows!==void 0&&!(Number.isInteger(a.rows)&&a.rows>=1&&a.rows<=30)&&e(`${a.id}.rows must be a whole number 1..30`),h(a,"balls",a.balls);break;case"scatter":(!a.points||!["uniform","linear"].includes(a.points.kind))&&e(`${a.id}.points: ${j("points kind",a.points?.kind,["uniform","linear"])}`),a.points.kind==="linear"&&(h(a,"points.slope",a.points.slope),h(a,"points.intercept",a.points.intercept),h(a,"points.noise",a.points.noise)),h(a,"count",a.count),a.inside&&f(a,"inside",a.inside);break;case"bayes":h(a,"prior",a.prior),h(a,"truePositive",a.truePositive),h(a,"falsePositive",a.falsePositive);break;case"graph":{(!Array.isArray(a.nodes)||a.nodes.length===0)&&e(`${a.id}.nodes needs at least one node`);const m=a.nodes.map(w=>w.id);new Set(m).size!==m.length&&e(`${a.id}: two nodes share an id`);const b=(w,k)=>{m.includes(k)||e(`${a.id}.${w}: ${j("node",k,m)}`)};Array.isArray(a.edges)||e(`${a.id}.edges must be an array`),Fe(a).forEach((w,k)=>{b(`edges[${k}]`,w.from),b(`edges[${k}]`,w.to),w.weight!==void 0&&!(w.weight>=0)&&e(`${a.id}.edges[${k}]: weights must be ≥ 0 (shortest paths need them)`)}),a.tree&&b("tree.root",a.tree.root);const S=oi(a),v=m.filter(w=>!S.has(w));v.length&&e(`${a.id}: nodes ${v.join(", ")} have no "at" and are not reached from the tree root`),a.search&&(Nn.includes(a.search.kind)||e(`${a.id}.search: ${j("search",a.search.kind,Nn)}`),b("search.start",a.search.start)),h(a,"step",a.step),a.nodes.forEach(w=>w.label!==void 0&&u(a,`nodes.${w.id}.label`,w.label));break}case"venn":{(!Array.isArray(a.sets)||a.sets.length<2||a.sets.length>3)&&e(`${a.id}.sets: give two or three sets`);const m=a.sets.map(b=>b.id);if(m.every(b=>/^[A-Za-z]\w*$/.test(b))||e(`${a.id}.sets: ids must be names like A, B, Evens`),a.highlight)try{for(const b of oe(Fn(a.highlight)))m.includes(b)||e(`${a.id}.highlight: ${j("set",b,m)}`)}catch(b){e(`${a.id}.highlight: ${b.message}`)}a.sets.forEach(b=>b.label!==void 0&&u(a,`sets.${b.id}.label`,b.label));break}case"network":(!Array.isArray(a.layers)||a.layers.length<2||a.layers.length>8||!a.layers.every(m=>Number.isInteger(m)&&m>=1&&m<=12))&&e(`${a.id}.layers: give 2 to 8 layers of 1 to 12 nodes, like [3, 4, 2]`),a.activation!==void 0&&!Ln.includes(a.activation)&&e(`${a.id}.activation: ${j("activation",a.activation,Ln)}`),a.inputs&&a.inputs.length>a.layers[0]&&e(`${a.id}.inputs: more inputs than the ${a.layers[0]} input nodes`),a.inputs?.forEach((m,b)=>h(a,`inputs[${b}]`,m)),h(a,"flow",a.flow),a.labels?.inputs?.forEach((m,b)=>u(a,`labels.inputs[${b}]`,m)),a.labels?.outputs?.forEach((m,b)=>u(a,`labels.outputs[${b}]`,m));break;case"heatmap":a.cells===void 0==(a.expr===void 0)&&e(`${a.id} needs exactly one of cells or expr`),a.cells&&!(Array.isArray(a.cells)&&a.cells.length>=1&&a.cells.length<=64&&a.cells.every(m=>Array.isArray(m)&&m.length===a.cells[0].length&&m.length<=64&&m.every(Number.isFinite)))&&e(`${a.id}.cells must be up to 64 equal rows of up to 64 numbers`),a.expr&&f(a,"expr",a.expr),a.resolution!==void 0&&!(Number.isInteger(a.resolution)&&a.resolution>=4&&a.resolution<=120)&&e(`${a.id}.resolution must be 4..120`),a.colormap!==void 0&&!ce.includes(a.colormap)&&e(`${a.id}.colormap: ${j("colormap",a.colormap,ce)}`),a.rowLabels?.forEach((m,b)=>u(a,`rowLabels[${b}]`,m)),a.colLabels?.forEach((m,b)=>u(a,`colLabels[${b}]`,m));break;case"contours":f(a,"expr",a.expr),a.colormap!==void 0&&!ce.includes(a.colormap)&&e(`${a.id}.colormap: ${j("colormap",a.colormap,ce)}`),a.resolution!==void 0&&!(Number.isInteger(a.resolution)&&a.resolution>=8&&a.resolution<=200)&&e(`${a.id}.resolution must be 8..200`);break;case"descent":f(a,"expr",a.expr);for(const m of["x","y"])try{K(rt(a.expr),m)}catch(b){e(`${a.id}.expr: ${b.message} (descent needs a gradient)`)}r(a,"start",a.start),h(a,"rate",a.rate),h(a,"steps",a.steps),h(a,"momentum",a.momentum);break;case"classifier":h(a,"epochs",a.epochs),a.count!==void 0&&!(Number.isInteger(a.count)&&a.count>=1&&a.count<=500)&&e(`${a.id}.count must be 1..500 points per cluster`),a.centres!==void 0&&!(a.centres.length===2&&a.centres.every(ct))&&e(`${a.id}.centres must be two [x, y] points`);break;case"kmeans":(!Array.isArray(a.centres)||a.centres.length<1||a.centres.length>6||!a.centres.every(ct))&&e(`${a.id}.centres: give 1 to 6 [x, y] cluster centres`),a.k!==void 0&&!(Number.isInteger(a.k)&&a.k>=1&&a.k<=6)&&e(`${a.id}.k must be 1..6`),h(a,"iteration",a.iteration);break;case"clock":(!Number.isInteger(a.modulus)||a.modulus<2||a.modulus>60)&&e(`${a.id}.modulus must be a whole number 2..60`),h(a,"value",a.value);break;case"taylor":c(a,"expr",a.expr,"x"),y(a,"expr",a.expr,3),h(a,"at",a.at),h(a,"order",a.order);break;case"parametric":c(a,"x",a.x,"t"),c(a,"y",a.y,"t"),o(a,"transform",a.transform);break;case"polygon":a.points!==void 0&&!(Array.isArray(a.points)&&a.points.length>=3&&a.points.every(ct))&&e(`${a.id}.points must be three or more [x, y] points`),o(a,"transform",a.transform),a.label&&u(a,"label",a.label);break;case"line":a.along===void 0==(a.eigen===void 0)&&e(`${a.id} needs exactly one of along or eigen`),r(a,"along",a.along),o(a,"eigen",a.eigen);break;case"label":r(a,"at",a.at),u(a,"tex",a.tex);break;case"equation":r(a,"at",a.at),(!Array.isArray(a.steps)||a.steps.length===0)&&e(`${a.id}.steps needs at least one TeX step`),a.steps.forEach((m,b)=>u(a,`steps[${b}]`,m));break}const p={...s,...Ti(t.items,n,s)};for(const[a,m,b]of l)try{U(b,{values:p})}catch(S){e(`${a.id}.${m}: ${S.message}`)}return t}function Pi(t,e){if(t.length<2)return{shaft:t,head:void 0};const n=t[t.length-1],s=t[t.length-2],i=n[0]-s[0],r=n[1]-s[1],o=Math.hypot(i,r);if(o===0||e<=0)return{shaft:t,head:void 0};const c=i/o,l=r/o,u=Math.min(e,o),h=[n[0]-c*u,n[1]-l*u],d=u*.55;return{shaft:[...t.slice(0,-1),h],head:[n,[h[0]-l*d,h[1]+c*d],[h[0]+l*d,h[1]-c*d]]}}const Y=t=>String(Math.round(t*100)/100),at=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),ue=(t,e=!1)=>t.map(([n,s],i)=>`${i?"L":"M"}${Y(n)} ${Y(s)}`).join("")+(e?"Z":""),Ye=t=>t.opacity!==void 0&&t.opacity<1?` opacity="${Y(t.opacity)}"`:"";function Oi(t){switch(t.type){case"line":{if(t.points.length<2)return"";if(t.clip?.length){const i=t.clip.map(({points:o,outside:c})=>{const l=c?`M-1000000 -1000000H1000000V1000000H-1000000Z${ue(o,!0)}`:ue(o,!0),u=`tfclip${wt(`${c?"o":"i"}${l}`).toString(36)}`;return{id:u,def:`<clipPath id="${u}"><path d="${l}"${c?' clip-rule="evenodd"':""}/></clipPath>`}}),r=Oi({...t,clip:void 0});return`<defs>${i.map(o=>o.def).join("")}</defs>`+i.reduceRight((o,c)=>`<g clip-path="url(#${c.id})">${o}</g>`,r)}const e=t.fill?` fill="${at(t.fill)}"`:' fill="none"',n=t.stroke&&(t.width??1)>0?` stroke="${at(t.stroke)}" stroke-width="${Y(t.width??1)}"`:"",s=t.dash?.length?` stroke-dasharray="${t.dash.map(Y).join(" ")}"`:"";return`<path d="${ue(t.points,t.closed)}"${e}${n}${s}${Ye(t)}/>`}case"arrow":{const{shaft:e,head:n}=Pi(t.points,t.head),s=at(t.stroke),i=e.length>=2?`<path d="${ue(e)}" fill="none" stroke="${s}" stroke-width="${Y(t.width)}"/>`:"",r=n?`<path d="${ue(n,!0)}" fill="${s}"/>`:"";return`<g${Ye(t)}>${i}${r}</g>`}case"circle":{const e=t.fill?` fill="${at(t.fill)}"`:' fill="none"',n=t.stroke?` stroke="${at(t.stroke)}" stroke-width="${Y(t.width??1)}"`:"";return`<circle cx="${Y(t.x)}" cy="${Y(t.y)}" r="${Y(t.r)}"${e}${n}${Ye(t)}/>`}case"text":{const e=t.align==="center"?"middle":t.align==="right"?"end":"start",n=t.italic?' font-style="italic"':"";return`<text x="${Y(t.x)}" y="${Y(t.y)}" font-size="${Y(t.size)}" font-family="${at(t.font)}"${n} text-anchor="${e}" fill="${at(t.color)}"${Ye(t)}>${at(t.text)}</text>`}}}function Be(t){return`${t.background?`<rect width="${Y(t.width)}" height="${Y(t.height)}" fill="${at(t.background)}"/>`:""}<g stroke-linecap="round" stroke-linejoin="round">${t.shapes.map(Oi).join("")}</g>`}function Ii(t,e={}){const n=e.title?`<title>${at(e.title)}</title>`:"",s=e.title?` role="img" aria-label="${at(e.title)}"`:"";return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${Y(t.width)} ${Y(t.height)}" width="${Y(t.width)}" height="${Y(t.height)}"${s}>${n}${Be(t)}</svg>`}const rc="http://www.w3.org/2000/svg",qn=new WeakMap;function oc(t,e){const n=t?.values.get(e);return n?Object.fromEntries(n):{}}async function Ci(t,e={}){const n=qn.get(t);if(n)return n;const s=t.querySelector("script[data-tinyfly-figure]");let i;try{i=xt(JSON.parse(s?.textContent??"null"))}catch(f){console.warn("tinyfly: math figure is missing or invalid",t,f);return}const r=t.getAttribute("data-target")??"fig";let o=t.querySelector("svg[data-tinyfly-math-svg]");o||(o=t.ownerDocument.createElementNS(rc,"svg"),o.setAttribute("data-tinyfly-math-svg",""),o.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`),o.setAttribute("style","display:block;width:100%;height:auto"),t.insertBefore(o,t.querySelector("figcaption")));const c=f=>{o.innerHTML=Be(Rt(i,f))};if(c({}),!(t.querySelector("script[data-tinyfly-timeline]")||t.hasAttribute("data-src"))){const f={element:t,figure:i,redraw:()=>c({})};return qn.set(t,f),f}const u=await Lo(t,e);if(!u)return;const h=()=>c(oc(u.player.state,r));u.player.subscribe(h),h();const d={...u,figure:i,redraw:h};return qn.set(t,d),d}async function Ni(t=document,e={}){const n=Array.from(t.querySelectorAll("[data-tinyfly-math]"));return(await Promise.all(n.map(i=>Ci(i,e)))).filter(i=>i!==void 0)}function ac(){if(!(typeof document<"u"?document.currentScript:null)?.hasAttribute("data-tinyfly-auto"))return;const e=()=>{Ni()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}function Ve(t,e,n=!1){t.beginPath(),e.forEach(([s,i],r)=>r===0?t.moveTo(s,i):t.lineTo(s,i)),n&&t.closePath()}function Fi(t,e){switch(t.globalAlpha=e.opacity??1,e.type){case"line":if(e.points.length<2)return;if(e.clip?.length){t.save();for(const{points:n,outside:s}of e.clip)Ve(t,n,!0),s?(t.rect(-1e6,-1e6,2e6,2e6),t.clip("evenodd")):t.clip();Fi(t,{...e,clip:void 0}),t.restore();return}Ve(t,e.points,e.closed),e.fill&&(t.fillStyle=e.fill,t.fill()),e.stroke&&(e.width??1)>0&&(t.strokeStyle=e.stroke,t.lineWidth=e.width??1,t.setLineDash(e.dash??[]),t.stroke(),t.setLineDash([]));return;case"arrow":{const{shaft:n,head:s}=Pi(e.points,e.head);t.strokeStyle=e.stroke,t.fillStyle=e.stroke,t.lineWidth=e.width,n.length>=2&&(Ve(t,n),t.stroke()),s&&(Ve(t,s,!0),t.fill());return}case"circle":t.beginPath(),t.arc(e.x,e.y,e.r,0,Math.PI*2),e.fill&&(t.fillStyle=e.fill,t.fill()),e.stroke&&(t.strokeStyle=e.stroke,t.lineWidth=e.width??1,t.stroke());return;case"text":t.font=`${e.italic?"italic ":""}${e.size}px ${e.font}`,t.textAlign=e.align,t.textBaseline="alphabetic",t.fillStyle=e.color,t.fillText(e.text,e.x,e.y)}}function Li(t,e){t.save(),t.beginPath(),t.rect(0,0,e.width,e.height),t.clip(),e.background&&(t.fillStyle=e.background,t.fillRect(0,0,e.width,e.height)),t.lineCap="round",t.lineJoin="round";for(const n of e.shapes)Fi(t,n);t.restore()}function Ri(t){const e={};for(const[n,s]of Object.entries(t.values??{})){const i=typeof s=="number"?"number":s.length===2?"[x, y] vector":"[a, b, c, d] matrix";e[n]={description:`The value ${n} (a ${i})`,kind:typeof s=="number"?"number":"list"}}for(const n of t.items)e[`${n.id}.draw`]={description:`How much of the ${n.kind} "${n.id}" is drawn`,unit:"0..1",min:0,max:1},e[`${n.id}.opacity`]={description:`Opacity of the ${n.kind} "${n.id}"`,unit:"0..1",min:0,max:1},n.kind==="equation"&&(e[`${n.id}.step`]={description:`Which step of "${n.id}" shows; in between, terms glide`,unit:"step",min:0,max:n.steps.length-1});return e}function Di(t,e={}){xt(t);const n=Ri(t),s={...t.values??{}};return{type:"custom",x:e.x??0,y:e.y??0,width:t.width,height:t.height,props:s,acceptsProp:i=>Object.prototype.hasOwnProperty.call(n,i),draw(i,r){Li(i,Rt(t,r.props??{}))},about:{kind:"math figure",summary:`A ${t.width}×${t.height} maths figure with ${t.items.map(i=>`${i.kind} "${i.id}"`).join(", ")}. Animate its values by name and each item's draw / opacity (an equation's step).`,props:n}}}function cc(t,e,n,s={}){const i=new Set(n.items.map(l=>l.id)),r=l=>{if(!i.has(l))throw new Error(`mathSteps: no item "${l}" (items: ${[...i].join(", ")})`)},o={...n.values??{}};for(const l of n.items)o[`${l.id}.draw`]=l.draw??1,o[`${l.id}.opacity`]=l.opacity??1,l.kind==="equation"&&(o[`${l.id}.step`]=l.step??0);for(const l of s.hidden??[])r(l),o[`${l}.draw`]=0;t.initial(e,o);const c={toValue(l,u,h){if(!(l in o))throw new Error(`mathSteps: no value "${l}" (values: ${Object.keys(n.values??{}).join(", ")})`);return t.to(e,{[l]:u},{duration:1200,...h}),c},applyMatrix(l,u={}){const{name:h="M",...d}=u;if(l.length!==4||!l.every(Number.isFinite))throw new Error("mathSteps.applyMatrix: expected [a, b, c, d]");return c.toValue(h,l,{duration:1600,...d})},drawOn(l,u){return r(l),t.to(e,{[`${l}.draw`]:1},{duration:900,...u}),c},fadeIn(l,u){return r(l),t.set(e,{[`${l}.draw`]:1,[`${l}.opacity`]:0}),t.to(e,{[`${l}.opacity`]:1},{duration:500,...u}),c},fadeOut(l,u){return r(l),t.to(e,{[`${l}.opacity`]:0},{duration:500,...u}),c},showStep(l,u,h){return r(l),t.to(e,{[`${l}.step`]:u},{duration:900,...h}),c}};return c}const Dt={kind:"math",create:"mathSurface(figure, { x, y })",anchors:{box:"the whole figure","item:ID":"everything an item draws","tip:ID":"the tip of a vector (tip:basis.i, tip:basis.j for î and ĵ)","point:ID":"a point (also a point riding a curve)","node:GRAPH:NODE":"a node of a graph item","term:ID:TEXT":"glyphs of an equation or label, matched by their text (term:eq:2x, term:eq#2:x for the second)","value:NAME":"a value of the figure (for the set edit; the box is the whole figure)"},edits:{drawOn:"item:ID — draws the item on (default 900 ms)",erase:"item:ID — undraws it (default 600 ms)",show:"item:ID — fades it in (default 500 ms)",hide:"item:ID — fades it out (default 500 ms)",step:"item:ID of an equation, { to } — moves to that step, terms gliding (default 900 ms)",set:"value:NAME, { value } — tweens a value: a number, [x, y] or [a, b, c, d] (default 1200 ms)"}},lc=(t,e,n)=>typeof t=="number"&&typeof e=="number"?t+(e-t)*n:Array.isArray(t)&&Array.isArray(e)?t.map((s,i)=>s+((e[i]??s)-s)*n):n<1?t:e;function uc(t,e){const n=[...t].sort((s,i)=>s.time-i.time);if(e<=n[0].time)return n[0].value;for(let s=1;s<n.length;s++)if(e<=n[s].time){const i=n[s-1],r=n[s];return r.time===i.time?r.value:lc(i.value,r.value,(e-i.time)/(r.time-i.time))}return n[n.length-1].value}function hc(t){let e=1/0,n=1/0,s=-1/0,i=-1/0;const r=(o,c)=>{e=Math.min(e,o),s=Math.max(s,o),n=Math.min(n,c),i=Math.max(i,c)};for(const o of t)if(o.type==="line"||o.type==="arrow")o.points.forEach(([c,l])=>r(c,l));else if(o.type==="circle")r(o.x-o.r,o.y-o.r),r(o.x+o.r,o.y+o.r);else{const c=o.size*.55*o.text.length,l=o.align==="center"?o.x-c/2:o.align==="right"?o.x-c:o.x;r(l,o.y-o.size*.75),r(l+c,o.y+o.size*.25)}return Number.isFinite(e)?{left:e,top:n,right:s,bottom:i}:void 0}const zn=t=>t.replace(/\s+/g,"").replace(/-/g,"−").replace(/\*/g,"∗");function dc(t,e={}){xt(t);const n=e.x??0,s=e.y??0,i=Di(t,{x:n,y:s}),r=new Map,o=t.items.map(p=>p.id),c=p=>({left:n+p.left,top:s+p.top,right:n+p.right,bottom:s+p.bottom,width:p.right-p.left,height:p.bottom-p.top,x:n+(p.left+p.right)/2,y:s+(p.top+p.bottom)/2}),l=c({left:0,top:0,right:t.width,bottom:t.height}),u=p=>{if(!p.includes(".")){const S=t.values?.[p];if(S===void 0)throw new Error(`mathSurface: ${j("value",p,Object.keys(t.values??{}))}`);return S}const[a,m]=p.split("."),b=t.items.find(S=>S.id===a);return m==="step"?b.kind==="equation"?b.step??0:0:b[m]??1},h=(p,a)=>{const m=r.get(p);return m?.length?uc(m,a):u(p)},d=(p,a,m,b)=>{const S=h(p,m.at);r.set(p,[...r.get(p)??[],{time:m.at,value:S},{time:m.at+(m.duration??b),value:a,...m.easing?{easing:m.easing}:{}}])},f=p=>{const a={};for(const m of r.keys())a[m]=h(m,p);return a},y=(p,a)=>{const m=a.split(":")[0].split("#")[0].split(".")[0];if(!o.includes(m))throw new Error(`mathSurface: ${p}: ${j("item",m,o)}`);return m},g={kind:"math",target:i,box:l,about:Dt,anchor(p,a=1/0){const m=p.indexOf(":"),b=m<0?p:p.slice(0,m),S=m<0?"":p.slice(m+1);if(b==="box"||b==="value")return l;if(!["item","tip","point","node","term"].includes(b))throw new Error(`mathSurface: ${j("anchor",b,Object.keys(Dt.anchors).map(M=>M.split(":")[0]))}`);const v=Rt(t,f(a)).shapes,w=M=>v.filter(E=>E.id===M||E.id.startsWith(`${M}.`));let k=[];if(b==="item")k=w(y(p,S));else if(b==="tip"){y(p,S);const M=v.find(T=>T.type==="arrow"&&(T.id===S||T.id===`${S}.0`));if(!M||M.type!=="arrow")throw new Error(`mathSurface: no vector at "${p}" (a vector item id, or basis.i / basis.j)`);const[E,A]=M.points[M.points.length-1],_=M.width*2.5;return c({left:E-_,top:A-_,right:E+_,bottom:A+_})}else if(b==="point")k=v.filter(M=>M.id===y(p,S)&&M.type==="circle");else if(b==="node"){const[M,E]=S.split(":");y(p,M),k=v.filter(A=>A.id===`${M}.node.${E}`)}else{const M=/^([^:#]+)(?:#(\d+))?:(.+)$/.exec(S);if(!M)throw new Error(`mathSurface: "${p}" should be term:ID:TEXT`);const[,E,A,_]=M;y(p,E);const T=w(E).filter(L=>L.type==="text"&&!L.id.includes(".backdrop")),C=zn(_),N=T.map(L=>zn(L.text)).join("");let P=-1;for(let L=0,B=0;L<Number(A??1)&&(P=N.indexOf(C,B),!(P<0));L++,B=P+1);if(P<0)throw new Error(`mathSurface: no "${_}" in ${E} (it reads "${N}")`);let F=0;k=T.filter(L=>{const B=zn(L.text).length,z=F<P+C.length&&F+B>P;return F+=B,z})}const x=hc(k);if(!x)throw new Error(`mathSurface: "${p}" is not drawn at ${a===1/0?"the end":`${a} ms`}`);return c(x)},edit(p,a,m){if(!(p in Dt.edits))throw new Error(`mathSurface.edit: ${j("edit",p,Object.keys(Dt.edits))}`);for(const b of Array.isArray(a)?a:[a]){const[S,v=""]=[b.slice(0,b.indexOf(":")),b.slice(b.indexOf(":")+1)];if(p==="set"){if(S!=="value")throw new Error(`mathSurface.edit: set takes value:NAME, not "${b}"`);if(m.value===void 0)throw new Error("mathSurface.edit: set needs `value`");u(v),d(v,m.value,m,1200);continue}if(S!=="item")throw new Error(`mathSurface.edit: ${p} takes item:ID, not "${b}"`);const w=y(b,v);if(p==="drawOn")d(`${w}.draw`,1,m,900);else if(p==="erase")d(`${w}.draw`,0,m,600);else if(p==="show")d(`${w}.opacity`,1,m,500);else if(p==="hide")d(`${w}.opacity`,0,m,500);else{if(typeof m.to!="number")throw new Error("mathSurface.edit: step needs `to`, the step number");d(`${w}.step`,m.to,m,900)}}return g},piece(p){throw new Error(`mathSurface: parts of a figure do not come loose ("${p}"); change it with edits (${Object.keys(Dt.edits).join(", ")})`)},follow(){throw new Error("mathSurface: parts of a figure do not come loose; use edits instead")},fling(){throw new Error("mathSurface: parts of a figure do not come loose; use edits instead")},move(){throw new Error("mathSurface: parts of a figure do not come loose; use edits instead")},ride:p=>p,tracks(p){return[...r].map(([a,m])=>({id:`${p}-${a}`,target:p,property:a,keyframes:[...m].sort((b,S)=>b.time-S.time).map(b=>({time:b.time,value:b.value,...b.easing?{easing:b.easing}:{}}))}))}};return g}const fc="http://www.w3.org/2000/svg";function pc(t,e,n={}){xt(e);const s={...e.values??{}};for(const v of n.sliders??[])if(typeof s[v.value]!="number")throw new Error(`mathExplorable: slider value "${v.value}" is not a number value of the figure`);for(const v of n.drag??[]){if("vector"in v&&!ct(s[v.vector]))throw new Error(`mathExplorable: "${v.vector}" is not a vector value of the figure`);if("matrix"in v&&!Ot(s[v.matrix]))throw new Error(`mathExplorable: "${v.matrix}" is not a matrix value of the figure`)}const i=dn(e),r=t.ownerDocument,o=r.createElementNS(fc,"svg");o.setAttribute("viewBox",`0 0 ${e.width} ${e.height}`),o.setAttribute("style","display:block;width:100%;height:auto;touch-action:none"),o.setAttribute("role","img"),t.appendChild(o);const c=n.drag??[],l=v=>{if("vector"in v)return s[v.vector];const[w,k,x,M]=s[v.matrix];return v.column===0?[w,x]:[k,M]},u=()=>{const v=c.map(w=>{const[k,x]=i.toScreen(l(w));return`<circle cx="${k}" cy="${x}" r="${14*i.scale}" fill="rgba(255,255,255,0.08)" stroke="rgba(255,255,255,0.55)" stroke-width="${1.5*i.scale}" style="cursor:grab"/>`});o.innerHTML=Be(Rt(e,s))+v.join(""),n.onChange?.({...s})},h=(v,w)=>{if(!(v in s))throw new Error(`mathExplorable: no value "${v}"`);s[v]=w;const k=d.get(v);k&&typeof w=="number"&&(k.value=String(w),f.get(v).textContent=String(w)),u()},d=new Map,f=new Map;let y;if(n.sliders?.length){y=r.createElement("div"),y.setAttribute("style","display:flex;flex-wrap:wrap;gap:8px 18px;align-items:center;padding:8px 0;font:14px system-ui,sans-serif");for(const v of n.sliders){const w=r.createElement("label");w.setAttribute("style","display:flex;align-items:center;gap:6px");const k=r.createElement("input");k.type="range",k.min=String(v.min),k.max=String(v.max),k.step=String(v.step??(v.max-v.min)/100),k.value=String(s[v.value]),k.setAttribute("aria-label",v.label??v.value);const x=r.createElement("output");x.textContent=String(s[v.value]),k.addEventListener("input",()=>h(v.value,Number(k.value))),w.append(v.label??v.value,k,x),y.appendChild(w),d.set(v.value,k),f.set(v.value,x)}t.appendChild(y)}const g=n.snap??.1,p=v=>{const w=o.getBoundingClientRect(),k=(v.clientX-w.left)/(w.width||e.width)*e.width,x=(v.clientY-w.top)/(w.height||e.height)*e.height,[M,E]=i.toWorld([k,x]),A=_=>g>0?Math.round(_/g)*g:_;return[Number(A(M).toFixed(6)),Number(A(E).toFixed(6))]};let a;const m=v=>{const w=o.getBoundingClientRect(),k=e.width/(w.width||e.width),x=[(v.clientX-w.left)*k,(v.clientY-w.top)*k];let M;for(const E of c){const[A,_]=i.toScreen(l(E)),T=Math.hypot(A-x[0],_-x[1]);T<30*i.scale*Math.max(1,k)&&(!M||T<M.distance)&&(M={handle:E,distance:T})}M&&(a=M.handle,o.setPointerCapture?.(v.pointerId),v.preventDefault())},b=v=>{if(!a)return;const[w,k]=p(v);if("vector"in a)h(a.vector,[w,k]);else{const[x,M,E,A]=s[a.matrix];h(a.matrix,a.column===0?[w,M,k,A]:[x,w,E,k])}},S=()=>{a=void 0};return o.addEventListener("pointerdown",m),o.addEventListener("pointermove",b),o.addEventListener("pointerup",S),o.addEventListener("pointercancel",S),u(),{get values(){return{...s}},set:h,destroy(){o.removeEventListener("pointerdown",m),o.removeEventListener("pointermove",b),o.removeEventListener("pointerup",S),o.removeEventListener("pointercancel",S),y?.remove()}}}const he=(t,e,n)=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{},...t.x?{x:t.x}:{},values:e,items:n}),He="\\begin{bmatrix} \\val{M.a} & \\val{M.b} \\\\ \\val{M.c} & \\val{M.d} \\end{bmatrix}",jn=t=>[(t.width??600)*.05,(t.height??600)*.1];function gc(t={}){return he(t,{M:t.matrix??Zt},[{id:"grid",kind:"grid",transform:"M",ghost:!0},{id:"square",kind:"polygon",transform:"M",color:"yellow",fillOpacity:.25},{id:"basis",kind:"basis",transform:"M"},{id:"matrix",kind:"label",tex:He,at:jn(t),screen:!0,align:"left"}])}function yc(t={}){return he(t,{M:t.matrix??Zt},[{id:"grid",kind:"grid",transform:"M",ghost:!0},{id:"square",kind:"polygon",transform:"M",color:"yellow",fillOpacity:.35,label:"\\det = \\val{M.det}"},{id:"basis",kind:"basis",transform:"M"},{id:"matrix",kind:"label",tex:He,at:jn(t),screen:!0,align:"left"}])}function mc(t){return he(t,{M:Zt,A:t.matrix},[{id:"grid",kind:"grid",transform:"M",ghost:!0},{id:"eigen",kind:"line",eigen:"A",color:"yellow",width:3},{id:"basis",kind:"basis",transform:"M"},{id:"matrix",kind:"label",tex:He,at:jn(t),screen:!0,align:"left"}])}function bc(t){const e=[t.u[0]+t.v[0],t.u[1]+t.v[1]];return he(t,{u:t.u,v:t.v,s:e},[{id:"grid",kind:"grid",ghost:!1,color:"grey",opacity:.5},{id:"axes",kind:"axes"},{id:"arrowU",kind:"vector",to:"u",color:"green",label:"\\vec{u}",labelAt:"middle"},{id:"arrowV",kind:"vector",from:"u",to:"s",color:"red",label:"\\vec{v}",labelAt:"middle"},{id:"sum",kind:"vector",to:"s",color:"yellow",label:"\\vec{u} + \\vec{v}"}])}function wc(t){const e=[{id:"axes",kind:"axes"},{id:"spanU",kind:"line",along:"u",color:"green",dashed:!0},{id:"arrowU",kind:"vector",to:"u",color:"green",label:"\\vec{u}"}],n={u:t.u};return t.v&&(n.v=t.v,e.splice(2,0,{id:"spanV",kind:"line",along:"v",color:"red",dashed:!0}),e.push({id:"arrowV",kind:"vector",to:"v",color:"red",label:"\\vec{v}"})),he(t,n,e)}const qt=(t,e,n)=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{},...t.x?{x:t.x}:{},...t.y?{y:t.y}:{},values:e,items:[{id:"axes",kind:"axes"},{id:"f",kind:"function",expr:t.expr,color:"blue"},...n]});function vc(t){return qt(t,{a:t.at??1},[{id:"tangent",kind:"tangent",expr:t.expr,at:"a",color:"yellow",label:"\\text{slope} = \\val{tangent.slope}"}])}function kc(t){return qt(t,{a:t.at??1,h:t.h??2},[{id:"secant",kind:"tangent",expr:t.expr,at:"a",h:"h",color:"yellow",label:"\\frac{\\Delta y}{\\Delta x} = \\val{secant.slope}"}])}function Mc(t){const e=qt(t,{n:t.n??4},[{id:"sum",kind:"riemann",expr:t.expr,from:t.from,to:t.to,n:"n",rule:t.rule??"left",color:"teal"}]);return e.items.push(e.items.splice(1,1)[0]),e.items.push({id:"readout",kind:"label",screen:!0,align:"left",size:24,at:[(t.width??600)*.05,(t.height??600)*.08],tex:"n = \\val{sum.n:0} \\quad \\text{sum} = \\val{sum.sum:3} \\quad \\int = \\val{sum.exact:3}"}),e}function $c(t){const e=qt(t,{b:t.to},[{id:"area",kind:"area",expr:t.expr,from:t.from,to:"b",color:"teal"}]);return e.items.push(e.items.splice(1,1)[0]),e.items.push({id:"readout",kind:"label",screen:!0,align:"left",size:26,at:[(t.width??600)*.05,(t.height??600)*.09],tex:`\\int_{${t.from}}^{\\val{b:2}} f(x)\\,dx = \\val{area.value:3}`}),e}function Sc(t){const e=qt(t,{order:t.order??1},[{id:"taylor",kind:"taylor",expr:t.expr,at:t.at??0,order:"order",color:"yellow"},{id:"centre",kind:"point",on:t.expr,x:t.at??0,color:"yellow"}]);return e.items.push({id:"readout",kind:"label",screen:!0,align:"left",size:26,at:[(t.width??600)*.05,(t.height??600)*.09],tex:"\\text{degree } \\val{taylor.degree:0}"}),e}function xc(t){const e=qt(t,{p:t.from??t.at-2},[{id:"hole",kind:"point",at:[t.at,t.limit],hollow:!0,color:"blue",radius:7},{id:"moving",kind:"point",on:t.expr,x:"p",color:"yellow"}]);return e.items.push({id:"readout",kind:"label",screen:!0,align:"left",size:26,at:[(t.width??600)*.05,(t.height??600)*.09],tex:"f(\\val{moving.x:3}) = \\val{moving.y:4}"}),e}const At=(t,e,n,s)=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{},x:t.x??e.x,y:t.y??e.y,values:n,items:s}),zt=(t,e)=>({id:"readout",kind:"label",screen:!0,align:"left",size:24,at:[(t.width??600)*.05,(t.height??600)*.08],tex:e});function Ac(t={}){const[e,n]=t.shade??[-1,1];return At(t,{x:[-4,4],y:[-.08,.55]},{mu:t.mean??0,sigma:t.sd??1,a:e,b:n},[{id:"axes",kind:"axes",ticks:1,labels:!0},{id:"dist",kind:"distribution",distribution:{kind:"normal",mean:"mu",sd:"sigma"},shade:["a","b"]},zt(t,"P(\\val{a:2} \\le X \\le \\val{b:2}) = \\val{dist.p:3}")])}function Ec(t={}){const e=t.n??10;return At(t,{x:[-1,e+1],y:[-.04,.4]},{n:e,p:t.p??.5},[{id:"axes",kind:"axes",ticks:Math.max(1,Math.round(e/10))},{id:"dist",kind:"distribution",distribution:{kind:"binomial",n:"n",p:"p"}},zt(t,"n = \\val{n:0} \\quad p = \\val{p:2} \\quad \\mu = \\val{dist.mean:2}")])}function Tc(t={}){return At(t,{x:[-.2,3.2],y:[-.2,3]},{k:t.k??1,samples:t.samples??2e3},[{id:"axes",kind:"axes",ticks:1},{id:"hist",kind:"histogram",distribution:{kind:"mean",of:t.of??{kind:"exponential",rate:1},count:"k"},count:"samples",bins:[0,3,45],curve:!0,color:"teal"},zt(t,"k = \\val{k:0} \\text{ draws averaged} \\quad \\bar{x} = \\val{hist.mean:3} \\quad s = \\val{hist.sd:3}")])}function _c(t={}){const e=t.rows??10;return At(t,{x:[-(e+2)*.25,(e+2)*.25],y:[-12,1]},{balls:t.balls??0},[{id:"board",kind:"galton",rows:e,balls:"balls",spacing:.5,top:0},zt(t,"\\val{board.landed:0} \\text{ balls}")])}function Pc(t={}){return At(t,{x:[-1.3,1.3],y:[-1.3,1.3]},{count:t.count??0},[{id:"square",kind:"polygon",points:[[-1,-1],[1,-1],[1,1],[-1,1]],color:"grey",fillOpacity:0},{id:"circle",kind:"parametric",x:"cos(t)",y:"sin(t)",color:"yellow",width:2.5},{id:"pts",kind:"scatter",points:{kind:"uniform",x:[-1,1],y:[-1,1]},count:"count",inside:"x^2 + y^2 - 1",color:"blue",radius:2.2},zt(t,"\\frac{\\text{inside}}{\\text{all}} = \\frac{\\val{pts.inside:0}}{\\val{pts.count:0}} = \\val{pts.ratio:4} \\approx \\frac{\\pi}{4}")])}function Oc(t={}){return At(t,{x:[-1,11],y:[-2,10]},{slope:t.slope??.6,intercept:t.intercept??1,noise:t.noise??1,count:t.count??60},[{id:"axes",kind:"axes",ticks:2},{id:"pts",kind:"scatter",points:{kind:"linear",slope:"slope",intercept:"intercept",noise:"noise",x:[0,10]},count:"count",fit:!0,radius:3.5},zt(t,"y = \\val{pts.slope:2}\\,x + \\val{pts.intercept:2} \\quad r = \\val{pts.r:2}")])}function Ic(t={}){return At(t,{x:[0,1],y:[0,1]},{prior:t.prior??.1,sensitivity:t.sensitivity??.9,falsePositive:t.falsePositive??.1},[{id:"test",kind:"bayes",prior:"prior",truePositive:"sensitivity",falsePositive:"falsePositive",at:[.08,.2],size:[.84,.66]}])}const Et=t=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{}}),de=(t,e)=>({id:"readout",kind:"label",screen:!0,align:"left",size:22,at:[(t.width??600)*.05,(t.height??600)*.07],tex:e}),fe={nodes:[{id:"A",at:[-3,1.5]},{id:"B",at:[-1,2.5]},{id:"C",at:[-1,.5]},{id:"D",at:[1,2.5]},{id:"E",at:[1,.5]},{id:"F",at:[-1,-1.5]},{id:"G",at:[3,1.5]},{id:"H",at:[1.5,-1.5]}],edges:[["A","B",4],["A","C",2],["B","D",5],["C","B",1],["C","E",8],["C","F",3],["D","G",3],["E","G",2],["E","D",2],["F","H",6],["H","E",1]]};function Cc(t={}){const{width:e,height:n}=Et(t);return{...Et(t),x:[-4.2,4.2],y:[-3.6,3.6],values:{step:0},items:[{id:"g",kind:"graph",nodes:t.nodes??fe.nodes,edges:t.edges??fe.edges.map(([s,i])=>[s,i]),search:{kind:t.search??"bfs",start:t.start??"A"},step:"step",frontier:[e*.06,n*.92]},de(t,"\\text{visited } \\val{g.visited:0} \\text{ of } \\val{g.steps:0}")]}}function Nc(t={}){const{width:e,height:n}=Et(t),s=t.target??"G";return{...Et(t),x:[-4.2,4.2],y:[-3.6,3.6],values:{step:0},items:[{id:"g",kind:"graph",nodes:t.nodes??fe.nodes,edges:t.edges??fe.edges,search:{kind:"dijkstra",start:t.start??"A"},step:"step",frontier:[e*.06,n*.92]},de(t,`d(${s}) = \\val{g.d.${s}:0}`)]}}function Fc(t={}){const e=Math.min(6,Math.max(1,t.n??5)),n=[],s=[],i=c=>{const l=`c${n.length}`;return n.push({id:l,label:`F_{${c}}`}),c>=2&&(s.push([l,i(c-1)]),s.push([l,i(c-2)])),l};i(e);const r=n.filter(c=>!s.some(([l])=>l===c.id)).length,o=Math.max(r*.75,4);return{...Et(t),x:[-o,o],y:[-(e+.2)*1.05,1.2],values:{step:0},items:[{id:"calls",kind:"graph",nodes:n,edges:s,directed:!0,tree:{root:"c0",spacing:[1.3,1.05],at:[0,0]},search:{kind:"dfs",start:"c0"},step:"step",radius:17},de(t,"\\text{calls made: } \\val{calls.visited:0} \\text{ of } \\val{calls.steps:0}")]}}function Lc(t={}){const n=[{id:"venn",kind:"venn",sets:(t.sets??["A","B"]).map(s=>({id:s})),highlight:t.highlight??"A & B",radius:1.6,at:[0,-.3]}];return t.label!==void 0&&n.push(de(t,t.label)),{...Et(t),x:[-4,4],y:[-4,4],items:n}}function Rc(t={}){const e=t.modulus??12;return{...Et(t),x:[-3,3],y:[-3,3],values:{value:t.value??0},items:[{id:"clock",kind:"clock",modulus:e,value:"value",radius:2.2,at:[0,-.2]},de(t,`\\val{value:0} \\equiv \\val{clock.hour:0} \\pmod{${e}}`.replace("\\pmod","\\;(\\text{mod } ").replace(`{${e}}`,`${e})`))]}}const jt=t=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{}}),pe=(t,e)=>({id:"readout",kind:"label",screen:!0,align:"left",size:22,at:[(t.width??600)*.05,(t.height??600)*.07],tex:e});function Dc(t={}){const e=t.layers??[3,5,4,2],n=Array.from({length:e[0]},(s,i)=>t.inputs?.[i]??[.9,.2,.6,.4,.8][i%5]);return{...jt(t),x:[-5,5],y:[-5,5],values:{flow:e.length-1,...Object.fromEntries(n.map((s,i)=>[`in${i}`,s]))},items:[{id:"net",kind:"network",layers:e,activation:t.activation??"sigmoid",seed:t.seed??"net",flow:"flow",at:[0,-.3],size:[7,6.5],inputs:n.map((s,i)=>`in${i}`),labels:{inputs:n.map((s,i)=>`x_{${i+1}}`),outputs:Array.from({length:e[e.length-1]},(s,i)=>`y_{${i+1}}`)}},pe(t,e[e.length-1]>=2?"y_1 = \\val{net.out0:2} \\quad y_2 = \\val{net.out1:2}":"y = \\val{net.out0:2}")]}}function qc(t={}){const e=t.expr??"(x^2 + 8 y^2) / 4";return{...jt(t),x:[-4,4],y:[-4,4],values:{steps:0,rate:t.rate??.2,momentum:t.momentum??0,sx:t.start?.[0]??-3.5,sy:t.start?.[1]??2},items:[{id:"field",kind:"heatmap",expr:e,resolution:40,colormap:"viridis",opacity:.35},{id:"levels",kind:"contours",expr:e,levels:9,colormap:"viridis"},{id:"gd",kind:"descent",expr:e,start:[t.start?.[0]??-3.5,t.start?.[1]??2],rate:"rate",steps:"steps",momentum:"momentum"},pe(t,"\\text{step } \\val{gd.step:0} \\quad f = \\val{gd.loss:3}")]}}function zc(t={}){const e=t.tokens??["The","cat","sat","on","the","mat"],n=Pt(wt(t.seed??"attention")),s=t.scores??e.map((r,o)=>e.map((c,l)=>(o===l?2.2:0)+(l===o-1?1.4:0)+vt(n)*.8)),i=e.map(r=>`\\text{${r}}`);return{...jt(t),x:[-5,5],y:[-5,5],items:[{id:"attn",kind:"heatmap",cells:s,softmax:!0,range:[0,1],colormap:"heat",at:[-3,-4],size:[7,7],rowLabels:i,colLabels:i,values:!0}]}}function jc(t={}){return{...jt(t),x:[-4,4],y:[-4,4],values:{epochs:0},items:[{id:"clf",kind:"classifier",epochs:"epochs",centres:[[-1.1,-.7],[1.1,.9]],rate:t.rate??.3,spread:t.spread??1.15},pe(t,"\\text{epoch } \\val{clf.epoch:0} \\quad \\text{accuracy } \\val{clf.accuracy:2} \\quad \\text{loss } \\val{clf.loss:3}")]}}function Xc(t={}){return{...jt(t),x:[-4.5,4.5],y:[-4.5,4.5],values:{iteration:0},items:[{id:"km",kind:"kmeans",centres:t.centres??[[-2.2,1.6],[2,2],[.4,-2.2]],k:t.k,iteration:"iteration",spread:.75},pe(t,"\\text{iteration } \\val{km.iteration:0} \\quad \\text{inertia } \\val{km.inertia:1}")]}}function Yc(t={}){return{...jt(t),x:[-4,4],y:[-2,3],items:[{id:"axes",kind:"axes"},{id:"sigmoid",kind:"function",expr:"sigmoid(x)",color:"blue"},{id:"tanh",kind:"function",expr:"tanh(x)",color:"yellow"},{id:"relu",kind:"function",expr:"relu(x)",color:"red"},pe(t,"\\color{blue}{\\sigma(x)} \\quad \\color{yellow}{\\tanh x} \\quad \\color{red}{\\text{ReLU}(x)}")]}}function Bc(t){return xt(t)}function Vc(t,e={},n={}){return Ii(Rt(xt(t),e),n)}const Hc={opacity:1,scale:1,scaleX:1,scaleY:1};function Uc(t){const e=new Map,n=new Map,s=[],i={};let r=0,o=0,c;const l=(y,g)=>`${y}\0${g}`,u=(y,g)=>{const p=l(y,g);let a=e.get(p);if(!a){const m=n.get(p)??Hc[g]??(g==="text"?"":0);a={id:`${y}-${g}`,target:y,property:g,keyframes:[{time:0,value:m}]},e.set(p,a)}return a},h=(y,g)=>{const p=y.keyframes[y.keyframes.length-1];p.time<g&&y.keyframes.push({time:g,value:p.value})},d=(y,g,p,a,m)=>{for(const[S,v]of Object.entries(g)){const w=u(y,S);if(typeof v=="string"&&!/^#|^rgb/.test(v)){h(w,p),w.keyframes.push({time:p+1,value:v});continue}h(w,p),w.keyframes.push({time:p+Math.max(a,1),value:v,...m&&{easing:m}})}const b=p+Math.max(a,1);return o=Math.max(o,b),b},f={get time(){return r},at(y){return r=Math.max(0,y),f},wait(y){return r+=y,o=Math.max(o,r),f},initial(y,g){for(const[p,a]of Object.entries(g)){const m=l(y,p);n.set(m,a);const b=e.get(m);b&&(b.keyframes[0].value=a)}return f},set(y,g){const p=c?c.start:r;return d(y,g,p,1,{type:"steps",count:1,position:"start"}),f},to(y,g,p={}){const a=(c?c.start:r)+(p.delay??0),m=d(y,g,a,p.duration??400,p.easing??"ease-in-out");return c?c.end=Math.max(c.end,m):r=m,f},together(y){const g=c;c={start:g?g.start:r,end:g?g.start:r},y();const p=c.end;return c=g,g?g.end=Math.max(g.end,p):r=p,f},marker(y,g={}){const{captions:p,...a}=g;s.push({id:y,time:r,...a});for(const[m,b]of Object.entries(p??{}))(i[m]??={})[y]=b;return o=Math.max(o,r),f},definition(){return{formatVersion:We,id:t.id,...t.name&&{name:t.name},config:{duration:o,...s.length>0&&{markers:[...s].sort((y,g)=>y.time-g.time)}},tracks:[...e.values()].map(y=>({...y,keyframes:y.keyframes.map(g=>({...g}))})),...Object.keys(i).length>0&&{captions:i}}}};return f}ac(),$.ACTIVATIONS=Ln,$.COLORMAPS=ce,$.CONSTANTS=ee,$.DISTRIBUTION_KINDS=ie,$.ExpressionError=$t,$.FUNCTIONS=$e,$.ITEM_KINDS=ln,$.MATH_FONT=_s,$.MATH_SURFACE=Dt,$.MATH_SYMBOL_FONT=Ps,$.MATH_THEMES=ve,$.MATRIX_TEX=He,$.SAMPLE_GRAPH=fe,$.SEARCH_KINDS=Nn,$.SYMBOLS=ke,$.TEX_COMMANDS=qs,$.TexError=Ds,$.accuracy=mi,$.activate=li,$.activationFigure=Yc,$.adjacency=Ce,$.areaFigure=$c,$.assign=qe,$.attentionFigure=zc,$.ballAt=ti,$.ballPath=In,$.bayesAreas=Js,$.bayesFigure=Ic,$.binOf=Oe,$.binSamples=Qs,$.binomialFigure=Ec,$.blendOver=Rn,$.blobs=Dn,$.clockFigure=Rc,$.cltFigure=Tc,$.colorAt=Le,$.compile=J,$.compileDerivative=Ae,$.contourLines=fi,$.decisionBoundaryFigure=jc,$.defaultBins=_n,$.density=pt,$.descentPath=gi,$.determinantFigure=yc,$.differentiate=K,$.displayListToSvg=Ii,$.displayListToSvgContent=Be,$.distributionProblem=Tn,$.drawDisplayList=Li,$.eigenFigure=mc,$.evaluate=st,$.expressionNames=Mn,$.expressionToString=se,$.forward=hi,$.galtonFigure=_c,$.gradientDescentFigure=qc,$.graphSearchFigure=Cc,$.inRegion=ae,$.inertia=vi,$.integrate=Xe,$.isDiscrete=re,$.kmeansFigure=Xc,$.kmeansHistory=wi,$.layoutFigure=Rt,$.layoutTex=U,$.leastSquares=On,$.lesson=Uc,$.limitFigure=xc,$.linearMapFigure=gc,$.logLoss=bi,$.mat2=Bo,$.mathExplorable=pc,$.mathFigure=Bc,$.mathFigureProps=Ri,$.mathFigureToSvg=Vc,$.mathSteps=cc,$.mathSurface=dc,$.mathTarget=Di,$.meanOf=Ft,$.monteCarloPiFigure=Pc,$.morphEquation=Ws,$.mountAllMath=Ni,$.mountMath=Ci,$.neuralNetworkFigure=Dc,$.normalFigure=Ac,$.nthDerivative=Ys,$.parseExpression=rt,$.parseSetExpression=Fn,$.parseTex=zs,$.planeOf=dn,$.predict=le,$.recursionTreeFigure=Fc,$.regionCells=ii,$.regressionFigure=Oc,$.riemannFigure=Mc,$.sample=An,$.sampleGrid=pi,$.samples=En,$.scatterPoints=Pn,$.sdOf=Lt,$.searchEvents=ni,$.secantFigure=kc,$.seededNetwork=ui,$.setNames=oe,$.shortestPathFigure=Nc,$.spanFigure=wc,$.summary=Ks,$.supportOf=Zs,$.surface=Re,$.tangentFigure=vc,$.taylorFigure=Sc,$.texToShapes=G,$.trainLogistic=yi,$.treeLayout=si,$.trimPolylines=V,$.validateMathFigure=xt,$.vec2=Wo,$.vectorSumFigure=bc,$.vennFigure=Lc,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})})(this.tinyfly=this.tinyfly||{});
53
+ `;function Io(t){if(t.getElementById(Ss))return;const e=t.createElement("style");e.id=Ss,e.textContent=Oo,t.head.appendChild(e)}function Co(t,e){const n=Array.from(e.querySelectorAll("[data-tinyfly-choose]"));if(n.length===0)return()=>{};Io(e.ownerDocument);const s=[],i=[];for(const c of n){const l=c.getAttribute("data-tinyfly-choose")??"",u=[],h=(g,p)=>{c.hasAttribute(g)||(c.setAttribute(g,p),u.push(g))};h("role","button"),h("tabindex","0");const d=t.scenarios.find(g=>g.id===l)?.label;d!==void 0&&h("aria-label",d),c.setAttribute("aria-pressed","false"),u.push("aria-pressed"),s.push({element:c,attributes:u});const f=()=>t.setScenario(l),y=g=>{const p=g.key;p!=="Enter"&&p!==" "||(g.preventDefault(),f())};c.addEventListener("click",f),c.addEventListener("keydown",y),i.push(()=>{c.removeEventListener("click",f),c.removeEventListener("keydown",y)})}const r=()=>{for(const{element:c}of s)c.setAttribute("aria-pressed",String(c.getAttribute("data-tinyfly-choose")===t.scenario))},o=t.subscribe(r);return r(),()=>{o();for(const c of i)c();for(const{element:c,attributes:l}of s)for(const u of l)c.removeAttribute(u)}}const xs=new WeakMap,No=new WeakMap;let Fo=0;function Kt(t,e,n){if(t)try{return JSON.parse(t)}catch(s){console.warn(`tinyfly: invalid ${e} JSON on`,n,s);return}}async function Lo(t,e={}){const n=xs.get(t);if(n)return n;const s=Array.from(t.querySelectorAll("script[data-tinyfly-timeline]")),i=s[0],r=t.getAttribute("data-src"),o=Do(t.getAttribute("data-markers")),c=s.length>1||i?.hasAttribute("data-scenario")?Ro(s,o,t):void 0;if(c&&c.length===0)return;let l=i&&!c?Kt(i.textContent,"timeline",t):void 0;if(!l&&r&&o){const y=await fetch(r);y.ok&&(l=await y.json())}if(l&&o&&(l=As(l,o)),!l&&!r&&!c){console.warn('tinyfly: embed has no timeline (a <script type="application/json" data-tinyfly-timeline> or data-src)',t);return}const u=Kt(t.querySelector("script[data-tinyfly-captions]")?.textContent,"captions",t),h={playWhenVisible:!0,...e.player,...u&&{captions:u},...Kt(t.getAttribute("data-options"),"data-options",t)};zo(t);const d=new ko(t,h),f={element:t,player:d};if(xs.set(t,f),t.setAttribute("data-tinyfly-mounted",""),c){const y=t.getAttribute("data-scenario")??void 0;await d.loadScenarios(c,{initial:c.some(g=>g.id===y)?y:void 0}),No.set(t,Co(d,t))}else await d.load(l??r);if(t.getAttribute("data-controls")!=="false"){const y=Kt(t.getAttribute("data-labels"),"data-labels",t),g=t.querySelector("figcaption"),p=t.getAttribute("data-scenario-legend"),a=t.getAttribute("data-scenario-control");f.controls=Ao(d,t,{...e.controls,...t.getAttribute("data-fullscreen")==="true"?{fullscreen:!0}:{},...a==="slider"||a==="buttons"?{scenarioControl:a}:{},labels:{...e.controls?.labels,...y,...p?{scenario:p}:{}},mount:void 0}),g?t.insertBefore(f.controls.element,g):t.appendChild(f.controls.element)}return f}function Ro(t,e,n){const s=[];return t.forEach((i,r)=>{const o=Kt(i.textContent,"timeline",n);if(!o)return;const c=i.getAttribute("data-scenario")||`scenario-${r+1}`;if(s.some(u=>u.id===c)){console.warn(`tinyfly: scenario id "${c}" is used more than once; the later one is skipped`,n);return}const l=i.getAttribute("data-scenario-label")??void 0;s.push({id:c,label:l,timeline:e?As(o,e):o})}),s}function As(t,e){return t.config.markers?.length?t:{...t,config:{...t.config,markers:e.map((n,s)=>({id:`step-${s+1}`,time:n}))}}}function Do(t){if(!t)return;const e=t.split(/[\s,]+/).filter(Boolean).map(Number).filter(n=>Number.isFinite(n)&&n>=0).sort((n,s)=>n-s);return e.length>0?e:void 0}function zo(t){const e=t.querySelector("svg");if(!e||e.hasAttribute("role")||e.hasAttribute("aria-hidden"))return;const n=t.getAttribute("data-alt"),s=t.querySelector("figcaption");e.setAttribute("role","img"),n?e.setAttribute("aria-label",n):s&&(s.id||=`tinyfly-caption-${++Fo}`,e.setAttribute("aria-labelledby",s.id))}const un=["grid","axes","vector","basis","point","function","parametric","polygon","line","label","equation","tangent","riemann","area","taylor","histogram","distribution","galton","scatter","bayes","graph","venn","clock","network","heatmap","contours","descent","classifier","kmeans"],Se={dark:{background:"#0f1117",ink:"#f2f2f2",grid:"#29abca",ghost:"rgba(255,255,255,0.18)",axes:"#f2f2f2",colors:{blue:"#58c4dd",green:"#83c167",red:"#fc6255",yellow:"#ffd75e",purple:"#b189f0",orange:"#ff9b4d",teal:"#5cd0b3",pink:"#f58ad1",ink:"#f2f2f2",grey:"#8a8f99"}},light:{background:"#fbfaf7",ink:"#1f2430",grid:"#7fb3d5",ghost:"rgba(31,36,48,0.14)",axes:"#1f2430",colors:{blue:"#2f6fd0",green:"#2f9a4a",red:"#d64545",yellow:"#c99a00",purple:"#7b4fc9",orange:"#e0761f",teal:"#178f7c",pink:"#c94f9c",ink:"#1f2430",grey:"#7a808c"}},chalk:{background:"#23332b",ink:"#eef0e6",grid:"rgba(238,240,230,0.35)",ghost:"rgba(238,240,230,0.14)",axes:"#eef0e6",colors:{blue:"#9fd3f0",green:"#b9e39a",red:"#f59a8f",yellow:"#f6e58d",purple:"#d0b5f2",orange:"#f7c08a",teal:"#a3e4d4",pink:"#f4b6dc",ink:"#eef0e6",grey:"#a9b0a6"}}},Jt=[1,0,0,1],it=([t,e,n,s],[i,r])=>[t*i+e*r,n*i+s*r];function qo(t,e){const[n,s,i,r]=t,[o,c,l,u]=e;return[n*o+s*l,n*c+s*u,i*o+r*l,i*c+r*u]}const te=([t,e,n,s])=>t*s-e*n;function jo(t){const e=te(t);if(Math.abs(e)<1e-12)return;const[n,s,i,r]=t;return[r/e,-s/e,-i/e,n/e]}const Xo=(t,e,n)=>t.map((s,i)=>s+(e[i]-s)*n),Yo=t=>[Math.cos(t),-Math.sin(t),Math.sin(t),Math.cos(t)];function Es(t){const[e,n,s,i]=t,r=e+i,o=te(t),c=r*r-4*o,l=1e-9;if(c<-l)return[];const u=Math.sqrt(Math.max(0,c)),h=u<l?[r/2]:[(r+u)/2,(r-u)/2],d=[];for(const f of h){const g=[[e-f,n],[s,i-f]].reduce((b,S)=>Math.hypot(...S)>Math.hypot(...b)?S:b);if(Math.hypot(...g)<l){d.push({value:f,vector:[1,0]},{value:f,vector:[0,1]});continue}const p=[-g[1],g[0]],a=Math.hypot(...p),m=p[0]<-l||Math.abs(p[0])<=l&&p[1]<0?-1:1;d.push({value:f,vector:[m*p[0]/a+0,m*p[1]/a+0]})}return d}function Ft(t){return Array.isArray(t)&&t.length===4&&t.every(Number.isFinite)}const Bo=Object.freeze(Object.defineProperty({__proto__:null,IDENTITY:Jt,apply:it,determinant:te,eigen:Es,inverse:jo,isMat2:Ft,lerp:Xo,multiply:qo,rotation:Yo},Symbol.toStringTag,{value:"Module"})),Vo=(t,e)=>[t[0]+e[0],t[1]+e[1]],hn=(t,e)=>[t[0]-e[0],t[1]-e[1]],dn=(t,e)=>[t[0]*e,t[1]*e],Ho=(t,e)=>t[0]*e[0]+t[1]*e[1],Uo=(t,e)=>t[0]*e[1]-t[1]*e[0],Ts=t=>Math.hypot(t[0],t[1]);function ee(t){const e=Ts(t);return e===0?[0,0]:[t[0]/e,t[1]/e]}const ne=(t,e,n)=>[t[0]+(e[0]-t[0])*n,t[1]+(e[1]-t[1])*n];function lt(t){return Array.isArray(t)&&t.length===2&&t.every(Number.isFinite)}const Wo=Object.freeze(Object.defineProperty({__proto__:null,add:Vo,cross:Uo,dot:Ho,isVec2:lt,length:Ts,lerp:ne,normalize:ee,scale:dn,sub:hn},Symbol.toStringTag,{value:"Module"}));function _s(t){const e={};for(const[n,s]of Object.entries(t))if(typeof s=="number")e[n]=s;else if(Ft(s)){const[i,r,o,c]=s;Object.assign(e,{[`${n}.a`]:i,[`${n}.b`]:r,[`${n}.c`]:o,[`${n}.d`]:c,[`${n}.det`]:te(s)})}else lt(s)&&Object.assign(e,{[`${n}.x`]:s[0],[`${n}.y`]:s[1],[`${n}.length`]:Math.hypot(s[0],s[1])});return e}function C(t,e,n){return e?Object.prototype.hasOwnProperty.call(t.colors,e)?t.colors[e]:e:n}function Lt(t,e){if(typeof e!="string")return e;const n=t[e];if(!lt(n))throw new Error(`math figure: value "${e}" is not an [x, y] vector`);return n}function xt(t,e){if(e===void 0)return Jt;const n=t[e];if(!Ft(n))throw new Error(`math figure: value "${e}" is not a [a, b, c, d] matrix`);return n}function N(t,e){if(typeof e=="number")return e;const n=t[e];if(typeof n!="number")throw new Error(`math figure: value "${e}" is not a number`);return n}function Rt(t,e){const n=i=>i===void 0?void 0:N(t,i),s=i=>i===void 0?void 0:Math.round(N(t,i));switch(e.kind){case"normal":return{kind:"normal",mean:n(e.mean),sd:n(e.sd)};case"uniform":return{kind:"uniform",min:n(e.min),max:n(e.max)};case"exponential":return{kind:"exponential",rate:n(e.rate)};case"binomial":return{kind:"binomial",n:s(e.n),p:n(e.p)};case"poisson":return{kind:"poisson",rate:n(e.rate)};case"dice":return{kind:"dice",count:s(e.count),sides:s(e.sides)};case"mean":return{kind:"mean",of:Rt(t,e.of),count:s(e.count)}}}function fn(t){const{width:e,height:n}=t,s=t.x??[-5,5],i=e/(s[1]-s[0]),r=t.y??[-(n/i)/2,n/i/2],o=n/(r[1]-r[0]);return{width:e,height:n,x:s,y:r,unitX:i,unitY:o,scale:Math.min(e,n)/600,toScreen:([c,l])=>[(c-s[0])*i,(r[1]-l)*o],toWorld:([c,l])=>[s[0]+c/i,r[1]-l/o]}}const Ps='"Latin Modern Math", "STIX Two Math", "Cambria Math", "Times New Roman", "Liberation Serif", "Noto Serif", Times, serif',Os='"Latin Modern Math", "STIX Two Math", "Cambria Math", "DejaVu Math TeX Gyre", "DejaVu Serif", serif',Go=t=>/^[A-Za-z0-9\u0370-\u03ff.,;:!?()[\]'"/ ]+$/.test(t)?Ps:Os,Is=.25,se=.05,Cs={a:.5,b:.56,c:.44,d:.56,e:.44,f:.31,g:.5,h:.56,i:.28,j:.31,k:.53,l:.28,m:.83,n:.56,o:.5,p:.56,q:.53,r:.39,s:.39,t:.39,u:.56,v:.53,w:.72,x:.53,y:.53,z:.44,A:.75,B:.71,C:.72,D:.76,E:.68,F:.65,G:.78,H:.75,I:.36,J:.51,K:.78,L:.63,M:.92,N:.75,O:.78,P:.68,Q:.78,R:.74,S:.56,T:.72,U:.75,V:.75,W:1.03,X:.75,Y:.75,Z:.61};function pn(t){return t.length!==1?t.length*.5:/[0-9]/.test(t)?.5:Object.prototype.hasOwnProperty.call(Cs,t)?Cs[t]+.04:"()[]".includes(t)?.39:"{}".includes(t)?.5:"|".includes(t)||",.;:!".includes(t)||"'’‘".includes(t)?.28:"-‐".includes(t)?.33:"′″".includes(t)?.3:"+−=<>±×÷≤≥≠≈∼≡∝→←↔⇒⇔∈∉⊂⊃⊆⊇∪∩∧∨".includes(t)?.78:"·∘".includes(t)?.28:"∑∏".includes(t)?1.05:"∫".includes(t)?.56:"∞".includes(t)||"…⋯".includes(t)?1:/[Α-Ω]/.test(t)?.72:/[α-ω]/.test(t)?.56:.6}function Ns(t){return"gjpqy(),;[]{}|∫".includes(t)||"βγζημξρφχψ".includes(t)?{height:.72,depth:.22}:"∑∏".includes(t)?{height:.75,depth:.25}:/[a-z]/.test(t)&&!"bdfhklt".includes(t)?{height:.45,depth:0}:{height:.7,depth:0}}const At='system-ui, -apple-system, "Segoe UI", sans-serif',Fs=(t,e)=>Math.hypot(e[0]-t[0],e[1]-t[1]);function H(t,e){if(e>=1)return t;if(e<=0)return[];const n=t.map(r=>r.slice(1).reduce((o,c,l)=>o+Fs(r[l],c),0));let s=n.reduce((r,o)=>r+o,0)*e;const i=[];for(const[r,o]of t.entries()){if(s<=0)break;if(n[r]<=s){i.push(o),s-=n[r];continue}const c=[o[0]];for(let l=1;l<o.length;l++){const u=Fs(o[l-1],o[l]);if(u>=s){const h=u===0?0:s/u;c.push([o[l-1][0]+(o[l][0]-o[l-1][0])*h,o[l-1][1]+(o[l][1]-o[l-1][1])*h]);break}c.push(o[l]),s-=u}i.push(c),s=0}return i}function gn(t,e){const n=e.align??"center",s=n==="left"?0:n==="right"?-t.width:-t.width/2,i=e.baseline==="baseline"?0:(t.height-t.depth)/2;return[e.x+s*e.size,e.y+i*e.size]}function Ls(t,e,n){const[s,i]=e,r=n.size,o=n.opacity??1;return t.map(c=>{const l=(c.color&&n.palette?.[c.color])??c.color??n.color,u=o*(c.opacity??1),h=`${n.idPrefix}${c.id}`;if(c.kind==="glyph")return{type:"text",id:h,text:c.text,x:s+(c.x+c.width/2)*r,y:i+c.y*r,size:c.size*r,font:Go(c.text),italic:c.italic,color:l,align:"center",opacity:u};if(c.kind==="rule"){const d=s+c.x*r,f=i+c.y*r,y=c.width*r,g=Math.max(1,c.height*r);return{type:"line",id:h,points:[[d,f],[d+y,f],[d+y,f+g],[d,f+g]],closed:!0,fill:l,opacity:u}}return{type:"line",id:h,points:c.points.map(([d,f])=>[s+d*r,i+f*r]),stroke:l,width:Math.max(1,c.width*r),opacity:u}})}function Z(t,e){return Ls(t.pieces,gn(t,e),e)}function Zo(t,e){const n=Math.max(Math.abs(t.x[0]),Math.abs(t.x[1]),Math.abs(t.y[0]),Math.abs(t.y[1])),[s,i,r,o]=e,c=Math.hypot(s,i,r,o),l=c===0?0:Math.abs(te(e))/c;return Math.min(n*12,n/Math.max(l,.08))+1}function Rs(t,e,n){const s=Zo(t,e),i=Math.min(120,Math.ceil(s/n)),r=[];for(let o=-i;o<=i;o++){const c=o*n;r.push({line:[it(e,[c,-s]),it(e,[c,s])].map(t.toScreen),axis:o===0}),r.push({line:[it(e,[-s,c]),it(e,[s,c])].map(t.toScreen),axis:o===0})}return r}function Qo(t,e){const{plane:n,theme:s}=e,i=t.step??1,r=[],o=1.4*n.scale;if(t.ghost)for(const[l,{line:u}]of Rs(n,[1,0,0,1],i).entries())r.push({type:"line",id:`${t.id}.ghost.${l}`,points:u,stroke:s.ghost,width:o,opacity:e.opacity});const c=C(s,t.color,s.grid);for(const[l,{line:u,axis:h}]of Rs(n,xt(e.values,t.transform),i).entries()){const[d]=H([u],e.draw);d&&r.push({type:"line",id:`${t.id}.${l}`,points:d,stroke:h?s.ink:c,width:h?o*1.6:o,opacity:e.opacity})}return r}function Ko(t,e){const{plane:n,theme:s}=e,i=C(s,t.color,s.axes),r=2*n.scale,o=e.opacity,c=H([[n.toScreen([n.x[0],0]),n.toScreen([n.x[1],0])]],e.draw),l=H([[n.toScreen([0,n.y[0]]),n.toScreen([0,n.y[1]])]],e.draw),u=[...c,...l].map((p,a)=>({type:"line",id:`${t.id}.${a?"y":"x"}`,points:p,stroke:i,width:r,opacity:o})),h=t.ticks??1;if(h<=0||e.draw<1)return u;const d=5*n.scale,f=13*n.scale,y=(p,a)=>{const m=[];for(let b=Math.ceil(p/h)*h;b<=a+1e-9;b+=h)Math.abs(b)>1e-9&&m.push(Number(b.toFixed(6)));return m},g=p=>String(p).replace("-","−");for(const p of y(n.x[0],n.x[1])){const[a,m]=n.toScreen([p,0]);u.push({type:"line",id:`${t.id}.tick.x${p}`,points:[[a,m-d],[a,m+d]],stroke:i,width:r*.8,opacity:o}),t.labels!==!1&&u.push({type:"text",id:`${t.id}.label.x${p}`,text:g(p),x:a,y:m+d+f*1.1,size:f,font:At,color:i,align:"center",opacity:o*.8})}for(const p of y(n.y[0],n.y[1])){const[a,m]=n.toScreen([0,p]);u.push({type:"line",id:`${t.id}.tick.y${p}`,points:[[a-d,m],[a+d,m]],stroke:i,width:r*.8,opacity:o}),t.labels!==!1&&u.push({type:"text",id:`${t.id}.label.y${p}`,text:g(p),x:a-d-f*.4,y:m+f*.35,size:f,font:At,color:i,align:"right",opacity:o*.8})}return u}const yn={alpha:"α",beta:"β",gamma:"γ",delta:"δ",epsilon:"ε",varepsilon:"ε",zeta:"ζ",eta:"η",theta:"θ",iota:"ι",kappa:"κ",lambda:"λ",mu:"μ",nu:"ν",xi:"ξ",pi:"π",rho:"ρ",sigma:"σ",tau:"τ",upsilon:"υ",phi:"φ",varphi:"φ",chi:"χ",psi:"ψ",omega:"ω",Gamma:"Γ",Delta:"Δ",Theta:"Θ",Lambda:"Λ",Xi:"Ξ",Pi:"Π",Sigma:"Σ",Phi:"Φ",Psi:"Ψ",Omega:"Ω"},xe={cdot:["·","bin"],times:["×","bin"],div:["÷","bin"],pm:["±","bin"],mp:["∓","bin"],circ:["∘","bin"],cup:["∪","bin"],cap:["∩","bin"],land:["∧","bin"],lor:["∨","bin"],setminus:["∖","bin"],triangle:["△","bin"],oplus:["⊕","bin"],otimes:["⊗","bin"],ominus:["⊖","bin"],varnothing:["∅","ord"],complement:["∁","ord"],nsubseteq:["⊈","rel"],ni:["∋","rel"],mapsfrom:["↤","rel"],gets:["←","rel"],vdash:["⊢","rel"],models:["⊨","rel"],le:["≤","rel"],leq:["≤","rel"],ge:["≥","rel"],geq:["≥","rel"],ne:["≠","rel"],neq:["≠","rel"],approx:["≈","rel"],sim:["∼","rel"],equiv:["≡","rel"],propto:["∝","rel"],to:["→","rel"],rightarrow:["→","rel"],leftarrow:["←","rel"],mapsto:["↦","rel"],Rightarrow:["⇒","rel"],implies:["⇒","rel"],iff:["⇔","rel"],Leftrightarrow:["⇔","rel"],in:["∈","rel"],notin:["∉","rel"],subset:["⊂","rel"],subseteq:["⊆","rel"],supset:["⊃","rel"],mid:["|","rel"],perp:["⊥","rel"],infty:["∞","ord"],partial:["∂","ord"],nabla:["∇","ord"],forall:["∀","ord"],exists:["∃","ord"],emptyset:["∅","ord"],neg:["¬","ord"],ldots:["…","ord"],cdots:["⋯","ord"],prime:["′","ord"],hbar:["ℏ","ord"],ell:["ℓ","ord"],degree:["°","ord"],lVert:["‖","open"],rVert:["‖","close"],langle:["⟨","open"],rangle:["⟩","close"],lbrace:["{","open"],rbrace:["}","close"]},mn={sum:["∑",!0],prod:["∏",!0],int:["∫",!1],oint:["∮",!1]},bn={sin:!1,cos:!1,tan:!1,log:!1,ln:!1,exp:!1,det:!1,tr:!1,rank:!1,sinh:!1,cosh:!1,tanh:!1,sec:!1,csc:!1,cot:!1,arcsin:!1,arccos:!1,arctan:!1,gcd:!1,lcm:!1,deg:!1,dim:!1,ker:!1,softmax:!1,lim:!0,max:!0,min:!0,argmax:!0,argmin:!0,arg:!1,sup:!0,inf:!0,Pr:!1,E:!1,Var:!1},vn={",":3/18,":":4/18,";":5/18,"!":-3/18,quad:1,qquad:2},Ds=new Set(["pmatrix","bmatrix","vmatrix","matrix"]);class zs extends Error{source;position;constructor(e,n,s){super(`${e} at ${s+1} in "${n}"`),this.name="TexError",this.source=n,this.position=s}}const qs=[...Object.keys(yn),...Object.keys(xe),...Object.keys(mn),...Object.keys(bn),...Object.keys(vn).filter(t=>t.length>1),"frac","binom","sqrt","vec","hat","bar","text","color","id","val","begin","end","left","right"].sort();function js(t){if(typeof t!="string")throw new TypeError("parseTex: expected a string");let e=0;const n=()=>{for(;e<t.length&&/\s/.test(t[e]);)e++},s=(h,d=e)=>{throw new zs(h,t,d)},i=()=>{const h=e;if(/[A-Za-z]/.test(t[e]??""))for(;/[A-Za-z]/.test(t[e]??"");)e++;else e<t.length?e++:s("A backslash with no command");return t.slice(h,e)},r=h=>{n(),t[e]!=="{"&&s(`Expected "{" for ${h}`);const d=t.indexOf("}",e);d<0&&s(`Missing "}" for ${h}`);const f=t.slice(e+1,d);return e=d+1,f},o=h=>{if(n(),e>=t.length&&s(`Missing ${h}`),t[e]==="{"){e++;const f=c("}");return e++,{type:"group",body:f}}const d=l();return d||s(`Missing ${h}`),d},c=h=>{const d=[];for(;;){if(n(),e>=t.length)return h==="}"&&s('Missing "}"'),h==="cell"&&s("Missing \\end"),d;if(h==="}"&&t[e]==="}"||(t[e]==="}"&&s('Unexpected "}"'),h==="cell"&&(t[e]==="&"||t.startsWith("\\\\",e)||t.startsWith("\\end",e))))return d;if(t[e]==="^"||t[e]==="_"){const y=e,g=t[e]==="^";e++;const p=o(g?"superscript":"subscript");let a=d.pop()??{type:"group",body:[]};a.type!=="scripts"&&(a={type:"scripts",base:a}),a.type==="scripts"&&((g&&a.sup||!g&&a.sub)&&s(`Double ${g?"superscript":"subscript"}`,y),g?a.sup=p:a.sub=p),d.push(a);continue}if(t[e]==="'"){e++;const y={type:"symbol",text:"′",cls:"ord",italic:!1},g=d.pop()??{type:"group",body:[]};d.push(g.type==="scripts"&&!g.sup?{...g,sup:y}:{type:"scripts",base:g,sup:y});continue}const f=l();f&&d.push(f)}},l=()=>{const h=t[e];if(h==="{"){e++;const d=c("}");return e++,{type:"group",body:d}}if(h==="&"&&s('"&" outside a matrix'),h==="\\"){const d=e;e++;const f=i();if(f==="\\"&&s('"\\\\" outside a matrix',d),f in vn)return{type:"space",width:vn[f]};if(f==="{"||f==="}")return{type:"symbol",text:f,cls:f==="{"?"open":"close",italic:!1};if(f==="|")return{type:"symbol",text:"‖",cls:"ord",italic:!1};if(Object.prototype.hasOwnProperty.call(yn,f))return{type:"symbol",text:yn[f],cls:"ord",italic:f[0]===f[0].toLowerCase()};if(Object.prototype.hasOwnProperty.call(xe,f)){const[g,p]=xe[f];return{type:"symbol",text:g,cls:p,italic:!1}}if(Object.prototype.hasOwnProperty.call(mn,f)){const[g,p]=mn[f];return{type:"bigop",text:g,limits:p}}if(Object.prototype.hasOwnProperty.call(bn,f))return{type:"opname",text:f,limits:bn[f]};switch(f){case"frac":return{type:"frac",num:o("numerator"),den:o("denominator")};case"binom":{const g=o("\\binom's top"),p=o("\\binom's bottom");return{type:"group",body:[{type:"symbol",text:"(",cls:"open",italic:!1},{type:"frac",num:g,den:p,bar:!1},{type:"symbol",text:")",cls:"close",italic:!1}]}}case"sqrt":return{type:"sqrt",body:o("the square root's body")};case"vec":case"hat":case"bar":return{type:"accent",accent:f,body:o(`\\${f}'s body`)};case"text":return{type:"text",text:r("\\text")};case"color":{const g=r("\\color").trim();return/^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)$/.test(g)||s(`"${g}" is not a colour name or #hex`,d),{type:"color",color:g,body:o("\\color's body")}}case"id":{const g=r("\\id").trim();return/^[\w.-]+$/.test(g)||s(`"${g}" is not a term id (letters, digits, _ . -)`,d),{type:"id",id:g,body:o("\\id's body")}}case"val":{const g=r("\\val").trim(),p=/^([A-Za-z_][\w.]*)(?::(\d))?$/.exec(g);return p||s(`"${g}" is not a value name (name or name:digits)`,d),{type:"value",name:p[1],digits:p[2]===void 0?2:Number(p[2])}}case"left":case"right":{n();const g=t[e]==="\\"?(e++,i()):t[e++];if(g===".")return{type:"space",width:0};const a={"(":"(",")":")","[":"[","]":"]","|":"|","{":"{","}":"}",langle:"⟨",rangle:"⟩","|.":"‖"}[g];return a||s(`"${g}" is not a delimiter`,d),{type:"symbol",text:a,cls:f==="left"?"open":"close",italic:!1}}case"begin":{const g=r("\\begin").trim();Ds.has(g)||s(`Unknown environment "${g}" (use ${[...Ds].join(", ")})`,d);const p=[[]];for(;;){const a=c("cell");if(p[p.length-1].push({type:"group",body:a}),t[e]==="&")e++;else if(t.startsWith("\\\\",e))e+=2,p.push([]);else{e+=4;const m=r("\\end").trim();m!==g&&s(`\\begin{${g}} ended by \\end{${m}}`);break}}return p.length>1&&p[p.length-1].every(a=>a.type==="group"&&a.body.length===0)&&p.pop(),{type:"matrix",delimiters:g,rows:p}}case"end":return s("\\end without \\begin",d)}const y=bs(f,qs);return s(`Unknown command "\\${f}"${y?` (did you mean "\\${y}"?)`:""}`,d)}return e++,/[A-Za-z]/.test(h)?{type:"symbol",text:h,cls:"ord",italic:!0}:/[0-9.]/.test(h)?{type:"symbol",text:h,cls:"ord",italic:!1}:h==="+"?{type:"symbol",text:"+",cls:"bin",italic:!1}:h==="-"?{type:"symbol",text:"−",cls:"bin",italic:!1}:h==="*"?{type:"symbol",text:"∗",cls:"bin",italic:!1}:"=<>".includes(h)?{type:"symbol",text:h,cls:"rel",italic:!1}:"([".includes(h)?{type:"symbol",text:h,cls:"open",italic:!1}:")]".includes(h)?{type:"symbol",text:h,cls:"close",italic:!1}:",;".includes(h)?{type:"symbol",text:h,cls:"punct",italic:!1}:"|/!:".includes(h)?{type:"symbol",text:h,cls:h===":"?"rel":"ord",italic:!1}:s(`Unexpected "${h}"`,e-1)};return{type:"group",body:c("")}}const ut=[1,1,.7,.5],Jo=t=>t<=1?2:3,ta=t=>Math.min(3,t+1),wn=()=>({width:0,height:0,depth:0,pieces:[]});function ht(t,e,n){return t.pieces.map(s=>s.kind==="stroke"?{...s,points:s.points.map(([i,r])=>[i+e,r+n])}:{...s,x:s.x+e,y:s.y+n})}function Dt(t,e){if(t.id)return t.id;const n=(t.counts.get(e)??0)+1;return t.counts.set(e,n),`${e}#${n}`}function Xs(t,e,n,s=1,i=t){const r=ut[n.level]*s,o=pn(t)*r,{height:c,depth:l}=Ns(t);return{width:o,height:c*r,depth:l*r,pieces:[{kind:"glyph",text:t,x:0,y:0,width:o,size:r,italic:e,...n.color?{color:n.color}:{},id:Dt(n,i)}]}}function kn(t,e,n){const s=wn(),i=Dt(e,n),r=ut[e.level];for(const o of t){const c=(o===" "?.28:/[A-Za-z]/.test(o)?pn(o)-.04:pn(o))*r;if(o!==" "){const{height:l,depth:u}=Ns(o);s.pieces.push({kind:"glyph",text:o,x:s.width,y:0,width:c,size:r,italic:!1,...e.color?{color:e.color}:{},id:i}),s.height=Math.max(s.height,l*r),s.depth=Math.max(s.depth,u*r)}s.width+=c}return s}function Mn(t){switch(t.type){case"symbol":return t.cls;case"bigop":case"opname":return"op";case"scripts":return Mn(t.base);case"id":case"color":return Mn(t.body);default:return"ord"}}function ea(t,e){return t==="bin"||e==="bin"?4:t==="rel"||e==="rel"?t==="open"||e==="close"||e==="punct"?0:5:t==="punct"||t==="op"&&(e==="ord"||e==="op")||e==="op"&&t==="ord"?3:0}function na(t,e){const n=wn();let s;return t.forEach(i=>{if(i.type==="space"){n.width+=i.width*ut[e.level];return}let r=Mn(i);r==="bin"&&(s===void 0||s==="bin"||s==="rel"||s==="open"||s==="punct"||s==="op")&&(r="ord"),s!==void 0&&e.level<=1&&(n.width+=ea(s,r)/18*ut[e.level]);const o=et(i,e);n.pieces.push(...ht(o,n.width,0)),n.width+=o.width,n.height=Math.max(n.height,o.height),n.depth=Math.max(n.depth,o.depth),s=r}),n}function sa(t,e){if(!Number.isFinite(t))return t>0?"∞":t<0?"−∞":"?";const n=t.toFixed(e),s=n.includes(".")?n.replace(/\.?0+$/,""):n;return(s==="-0"?"0":s).replace("-","−")}function et(t,e){const n=ut[e.level];switch(t.type){case"symbol":return Xs(t.text,t.italic,e);case"group":return na(t.body,e);case"space":return{...wn(),width:t.width*n};case"text":return kn(t.text,e,`text:${t.text}`);case"opname":return kn(t.text,e,t.text);case"value":{const s=e.values[t.name];if(s===void 0)throw new Error(`\\val{${t.name}}: no value named "${t.name}"`);return kn(sa(s,t.digits),{...e,id:e.id??`val:${t.name}`},`val:${t.name}`)}case"bigop":return Xs(t.text,!1,e,e.level===0?1.4:1.1);case"color":return et(t.body,{...e,color:t.color});case"id":return et(t.body,{...e,id:t.id});case"scripts":return ia(t,e);case"frac":return ra(t,e);case"sqrt":return oa(t,e);case"accent":return aa(t,e);case"matrix":return ca(t,e)}}function ia(t,e){const n=et(t.base,e),s={...e,level:Jo(e.level)},i=t.sup?et(t.sup,s):void 0,r=t.sub?et(t.sub,s):void 0,o=ut[e.level],c=e.level===0&&(t.base.type==="bigop"&&t.base.limits||t.base.type==="opname"&&t.base.limits),l={...n,pieces:[...n.pieces]};if(c){const y=Math.max(n.width,i?.width??0,r?.width??0),g=ht(n,(y-n.width)/2,0);let p=n.height,a=n.depth;const m=.12*o;if(i){const b=-(n.height+m+i.depth);g.push(...ht(i,(y-i.width)/2,b)),p=-b+i.height}if(r){const b=n.depth+m+r.height;g.push(...ht(r,(y-r.width)/2,b)),a=b+r.depth}return{width:y,height:p,depth:a,pieces:g}}let u=i?Math.max(.42*o,n.height-.3*o,i.depth+.25*o):0,h=r?Math.max(.2*o,n.depth+.12*o,r.height-.4*o):0;if(i&&r){const y=u-i.depth-(r.height-h);y<.2*o&&(h+=.2*o-y)}const d=n.width+.03*o;let f=n.width;return i?(l.pieces.push(...ht(i,d,-u)),l.height=Math.max(l.height,u+i.height),f=Math.max(f,d+i.width)):u=0,r&&(l.pieces.push(...ht(r,d,h)),l.depth=Math.max(l.depth,h+r.depth),f=Math.max(f,d+r.width)),l.width=f+.04*o,l}function ra(t,e){const n={...e,level:ta(e.level)},s=et(t.num,n),i=et(t.den,n),r=ut[e.level],o=se*r,c=Is*r,l=(e.level===0?.16:.1)*r,u=.1*r,h=Math.max(s.width,i.width)+u*2,d=-(c+o/2+l+s.depth),f=-c+o/2+l+i.height;return{width:h,height:-d+s.height,depth:f+i.depth,pieces:[...ht(s,(h-s.width)/2,d),...t.bar===!1?[]:[{kind:"rule",x:0,y:-c-o/2,width:h,height:o,...e.color?{color:e.color}:{},id:Dt(e,"frac")}],...ht(i,(h-i.width)/2,f)]}}function oa(t,e){const n=et(t.body,e),s=ut[e.level],i=Math.max(n.height,.7*s)+.14*s,r=Math.max(n.depth,.05*s)+.05*s,o=.56*s,c=o+n.width+.08*s,l=[[.02*s,-.36*s],[.13*s,-.44*s],[.3*s,r],[o-.04*s,-i],[c,-i]];return{width:c,height:i+se*s,depth:r,pieces:[{kind:"stroke",points:l,width:se*s,...e.color?{color:e.color}:{},id:Dt(e,"sqrt")},...ht(n,o,0)]}}function aa(t,e){const n=et(t.body,e),s=ut[e.level],i=-(n.height+.12*s),r=.04*s,o=Math.max(n.width-.02*s,r+.3*s),c=e.color?{color:e.color}:{},l=Dt(e,t.accent);let u;if(t.accent==="vec"){const h=.12*s;u=[[[r,i],[o,i]],[[o-h,i-h*.7],[o,i],[o-h,i+h*.7]]]}else if(t.accent==="hat"){const h=(r+o)/2;u=[[[h-.16*s,i+.02*s],[h,i-.12*s],[h+.16*s,i+.02*s]]]}else u=[[[r,i],[o,i]]];return{width:Math.max(n.width,o+.02*s),height:-i+.14*s,depth:n.depth,pieces:[...n.pieces,...u.map(h=>({kind:"stroke",points:h,width:se*s*.9,...c,id:l}))]}}function ca(t,e){const n={...e,level:Math.max(e.level,1)},s=ut[n.level],i=t.rows.map(k=>k.map(x=>et(x,n))),r=Math.max(...i.map(k=>k.length)),o=Array.from({length:r},(k,x)=>Math.max(0,...i.map(M=>M[x]?.width??0))),c=i.map(k=>Math.max(.7*s,...k.map(x=>x.height))),l=i.map(k=>Math.max(.2*s,...k.map(x=>x.depth))),u=.9*s,h=.25*s,d=t.delimiters==="matrix"?0:.55*s,f=o.reduce((k,x)=>k+x,0)+u*(r-1),y=c.reduce((k,x,M)=>k+x+l[M],0)+h*(i.length-1),g=-Is*s-y/2,p=[];let a=g;i.forEach((k,x)=>{a+=c[x];let M=d;k.forEach((A,E)=>{p.push(...ht(A,M+(o[E]-A.width)/2,a)),M+=o[E]+u}),a+=l[x]+h});const m=f+d*2,b=g+y,S=e.color?{color:e.color}:{},w=(k,x)=>({kind:"stroke",points:k,width:se*s*1.1,...S,id:Dt(e,x)}),v=.08*s;if(t.delimiters==="pmatrix"){const k=x=>{const M=x===1?d*.75:m-d*.75,A=x*d*.5;return Array.from({length:17},(E,_)=>{const T=_/16;return[M-A*Math.sin(Math.PI*T),g-v+(y+v*2)*T]})};p.push(w(k(1),"("),w(k(-1),")"))}else if(t.delimiters==="bmatrix"){const k=d*.35,x=d*.2,M=m-d*.2;p.push(w([[x+k,g-v],[x,g-v],[x,b+v],[x+k,b+v]],"["),w([[M-k,g-v],[M,g-v],[M,b+v],[M-k,b+v]],"]"))}else t.delimiters==="vmatrix"&&p.push(w([[d*.4,g-v],[d*.4,b+v]],"|"),w([[m-d*.4,g-v],[m-d*.4,b+v]],"|"));return{width:m,height:-g+v,depth:b+v,pieces:p}}function W(t,e={}){const n=typeof t=="string"?js(t):t,s={level:e.style==="inline"?1:0,values:e.values??{},counts:new Map},i=et(n,s);return{width:i.width,height:i.height,depth:i.depth,pieces:i.pieces}}function Ae(t,e,n,s,i,r){const o=26*r.plane.scale,[c,l]=ee(n),u=W(t,{values:r.scope,style:"inline"}),h=o*(.55+Math.abs(c)*u.width*.5);return Z(u,{x:e[0]+c*h,y:e[1]+l*h,size:o,color:s,opacity:r.opacity,idPrefix:`${i}.label.`})}function Ys(t,e,n,s,i,r){const o=r.plane.toScreen(e),c=r.plane.toScreen(n),[l]=H([[o,c]],r.draw);if(!l)return[];const u=Math.hypot(c[0]-o[0],c[1]-o[1]),h=Math.min(i*3.6,u*.45);return[{type:"arrow",id:t,points:l,stroke:s,width:i,head:h,opacity:r.opacity}]}function la(t,e){const n=xt(e.values,t.transform),s=it(n,t.from===void 0?[0,0]:Lt(e.values,t.from)),i=it(n,Lt(e.values,t.to)),r=C(e.theme,t.color,e.theme.colors.yellow),o=Ys(t.id,s,i,r,(t.width??4)*e.plane.scale,e);if(t.label&&e.draw>=1){const c=e.plane.toScreen(i),l=e.plane.toScreen(s),u=hn(c,l);if(t.labelAt==="middle"){const h=[(c[0]+l[0])/2,(c[1]+l[1])/2];o.push(...Ae(t.label,h,[u[1],-u[0]],r,t.id,e))}else o.push(...Ae(t.label,c,u,r,t.id,e))}return o}function ua(t,e){const n=xt(e.values,t.transform),s=4.5*e.plane.scale,i=e.plane.toScreen([0,0]),r=[],o=[["i",[1,0],e.theme.colors.green,"\\hat{i}"],["j",[0,1],e.theme.colors.red,"\\hat{j}"]];for(const[c,l,u,h]of o){const d=it(n,l);if(r.push(...Ys(`${t.id}.${c}`,[0,0],d,u,s,e)),t.labels!==!1&&e.draw>=1){const f=e.plane.toScreen(d);r.push(...Ae(h,f,hn(f,i),u,`${t.id}.${c}`,e))}}return r}function ha(t,e){const n=t.on!==void 0?[e.scope[`${t.id}.x`],e.scope[`${t.id}.y`]]:Lt(e.values,t.at);if(!Number.isFinite(n[0])||!Number.isFinite(n[1]))return[];const s=it(xt(e.values,t.transform),n),[i,r]=e.plane.toScreen(s),o=C(e.theme,t.color,e.theme.colors.yellow),c=(t.radius??6)*e.plane.scale*Math.min(1,e.draw*2),l=t.hollow?{type:"circle",id:t.id,x:i,y:r,r:c,fill:e.theme.background,stroke:o,width:2.5*e.plane.scale,opacity:e.opacity}:{type:"circle",id:t.id,x:i,y:r,r:c,fill:o,opacity:e.opacity},u=c>0?[l]:[];return t.label&&e.draw>=1&&u.push(...Ae(t.label,[i,r],[.7,-.7],o,t.id,e)),u}const Ee={sin:{arity:1,apply:Math.sin},cos:{arity:1,apply:Math.cos},tan:{arity:1,apply:Math.tan},asin:{arity:1,apply:Math.asin},acos:{arity:1,apply:Math.acos},atan:{arity:1,apply:Math.atan},atan2:{arity:2,apply:Math.atan2},sinh:{arity:1,apply:Math.sinh},cosh:{arity:1,apply:Math.cosh},tanh:{arity:1,apply:Math.tanh},exp:{arity:1,apply:Math.exp},ln:{arity:1,apply:Math.log},log:{arity:1,apply:Math.log10},log2:{arity:1,apply:Math.log2},sqrt:{arity:1,apply:Math.sqrt},abs:{arity:1,apply:Math.abs},floor:{arity:1,apply:Math.floor},ceil:{arity:1,apply:Math.ceil},round:{arity:1,apply:Math.round},sign:{arity:1,apply:Math.sign},min:{arity:2,apply:Math.min},max:{arity:2,apply:Math.max},sigmoid:{arity:1,apply:t=>1/(1+Math.exp(-t))},relu:{arity:1,apply:t=>Math.max(0,t)}},ie={pi:Math.PI,e:Math.E,tau:Math.PI*2};class Et extends Error{source;position;constructor(e,n,s){super(`${e} at ${s+1} in "${n}"`),this.name="ExpressionError",this.source=n,this.position=s}}function da(t){const e=[];let n=0;for(;n<t.length;){const s=t[n];if(/\s/.test(s)){n++;continue}const i=/^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(t.slice(n));if(i){e.push({kind:"number",value:Number(i[0]),at:n}),n+=i[0].length;continue}const r=/^[A-Za-z_][A-Za-z_0-9]*/.exec(t.slice(n));if(r){e.push({kind:"name",value:r[0],at:n}),n+=r[0].length;continue}if("+-*/^(),".includes(s)){e.push({kind:"op",value:s,at:n}),n++;continue}throw new Et(`Unexpected "${s}"`,t,n)}return e.push({kind:"end",at:t.length}),e}function rt(t){if(typeof t!="string")throw new TypeError("parseExpression: expected a string");const e=da(t);let n=0;const s=()=>e[n],i=f=>{const y=s();return y.kind==="op"&&y.value===f},r=f=>{if(!i(f))throw new Et(`Expected "${f}"`,t,s().at);n++},o=()=>{let f=c();for(;i("+")||i("-");)f={type:"binary",operator:e[n++].value,left:f,right:c()};return f},c=()=>{let f=l();for(;;)if(i("*")||i("/"))f={type:"binary",operator:e[n++].value,left:f,right:l()};else if(s().kind==="name"||s().kind==="number"||i("("))f={type:"binary",operator:"*",left:f,right:u()};else return f},l=()=>i("-")||i("+")?{type:"unary",operator:e[n++].value,operand:l()}:u(),u=()=>{const f=h();return i("^")?(n++,{type:"binary",operator:"^",left:f,right:l()}):f},h=()=>{const f=s();if(f.kind==="number")return n++,{type:"number",value:f.value};if(f.kind==="name"){if(n++,!i("("))return{type:"name",name:f.value};const y=Object.prototype.hasOwnProperty.call(Ee,f.value)?Ee[f.value]:void 0;if(!y)throw new Et(`Unknown function "${f.value}"`,t,f.at);n++;const g=[];if(!i(")"))for(g.push(o());i(",");)n++,g.push(o());if(r(")"),g.length!==y.arity)throw new Et(`"${f.value}" takes ${y.arity} argument${y.arity===1?"":"s"}, got ${g.length}`,t,f.at);return{type:"call",name:f.value,args:g}}if(i("(")){n++;const y=o();return r(")"),y}throw new Et(f.kind==="end"?"Unexpected end":`Unexpected "${f.value}"`,t,f.at)},d=o();if(s().kind!=="end")throw new Et(`Unexpected "${s().value}"`,t,s().at);return d}function $n(t){const e=new Set,n=s=>{s.type==="name"&&!(s.name in ie)?e.add(s.name):s.type==="unary"?n(s.operand):s.type==="binary"?(n(s.left),n(s.right)):s.type==="call"&&s.args.forEach(n)};return n(t),[...e].sort()}const j=t=>({type:"number",value:t}),re=j(0),B=j(1),G=t=>t.type==="number",nt=(t,e)=>t.type==="number"&&t.value===e;function vt(t,e){return G(t)&&G(e)?j(t.value+e.value):nt(t,0)?e:nt(e,0)?t:{type:"binary",operator:"+",left:t,right:e}}function dt(t,e){return G(t)&&G(e)?j(t.value-e.value):nt(e,0)?t:nt(t,0)?Te(e):{type:"binary",operator:"-",left:t,right:e}}function X(t,e){return G(t)&&G(e)?j(t.value*e.value):nt(t,0)||nt(e,0)?re:nt(t,1)?e:nt(e,1)?t:G(e)?X(e,t):G(t)&&e.type==="binary"&&e.operator==="*"&&G(e.left)?X(j(t.value*e.left.value),e.right):{type:"binary",operator:"*",left:t,right:e}}function Q(t,e){return nt(t,0)?re:nt(e,1)?t:G(t)&&G(e)&&e.value!==0?j(t.value/e.value):{type:"binary",operator:"/",left:t,right:e}}function gt(t,e){return nt(e,0)?B:nt(e,1)?t:G(t)&&G(e)?j(t.value**e.value):{type:"binary",operator:"^",left:t,right:e}}function Te(t){return G(t)?j(-t.value):t.type==="unary"&&t.operator==="-"?t.operand:{type:"unary",operator:"-",operand:t}}const K=(t,...e)=>({type:"call",name:t,args:e});function Tt(t,e){switch(t.type){case"number":return!0;case"name":return t.name!==e;case"unary":return Tt(t.operand,e);case"binary":return Tt(t.left,e)&&Tt(t.right,e);case"call":return t.args.every(n=>Tt(n,e))}}function J(t,e="x"){if(Tt(t,e))return re;switch(t.type){case"number":return re;case"name":return t.name===e?B:re;case"unary":return t.operator==="-"?Te(J(t.operand,e)):J(t.operand,e);case"binary":{const{left:n,right:s}=t,i=()=>J(n,e),r=()=>J(s,e);switch(t.operator){case"+":return vt(i(),r());case"-":return dt(i(),r());case"*":return vt(X(i(),s),X(n,r()));case"/":return Q(dt(X(i(),s),X(n,r())),gt(s,j(2)));case"^":if(Tt(s,e)){const o=G(s)?j(s.value-1):dt(s,B);return X(X(s,gt(n,o)),i())}return Tt(n,e)?X(X(t,K("ln",n)),r()):X(t,vt(X(r(),K("ln",n)),Q(X(s,i()),n)))}break}case"call":{const[n,s]=t.args,i=()=>J(n,e),r=o=>X(o,i());switch(t.name){case"sin":return r(K("cos",n));case"cos":return r(Te(K("sin",n)));case"tan":return r(Q(B,gt(K("cos",n),j(2))));case"asin":return r(Q(B,K("sqrt",dt(B,gt(n,j(2))))));case"acos":return r(Te(Q(B,K("sqrt",dt(B,gt(n,j(2)))))));case"atan":return r(Q(B,vt(B,gt(n,j(2)))));case"sinh":return r(K("cosh",n));case"cosh":return r(K("sinh",n));case"tanh":return r(dt(B,gt(K("tanh",n),j(2))));case"exp":return r(t);case"ln":return r(Q(B,n));case"log":return r(Q(B,X(n,j(Math.LN10))));case"log2":return r(Q(B,X(n,j(Math.LN2))));case"sqrt":return r(Q(B,X(j(2),t)));case"abs":return r(K("sign",n));case"sigmoid":return r(X(t,dt(B,t)));case"relu":return r(Q(vt(K("sign",n),B),j(2)));case"atan2":{const o=J(s,e);return Q(dt(X(s,i()),X(n,o)),vt(gt(n,j(2)),gt(s,j(2))))}case"min":case"max":{const o=t.name==="max"?1:-1,c=J(s,e),l=Q(vt(B,X(j(o),K("sign",dt(n,s)))),j(2));return vt(X(l,i()),X(dt(B,l),c))}}throw new Error(`differentiate: "${t.name}" has no derivative rule`)}}throw new Error("differentiate: malformed expression")}function Bs(t,e,n="x"){let s=t;for(let i=0;i<e;i++)s=J(s,n);return s}function oe(t){switch(t.type){case"number":return t.value<0?`(${t.value})`:String(t.value);case"name":return t.name;case"unary":return`(${t.operator}${oe(t.operand)})`;case"binary":return`(${oe(t.left)} ${t.operator} ${oe(t.right)})`;case"call":return`${t.name}(${t.args.map(oe).join(", ")})`}}function st(t,e={}){switch(t.type){case"number":return t.value;case"name":{if(Object.prototype.hasOwnProperty.call(e,t.name))return e[t.name];if(Object.prototype.hasOwnProperty.call(ie,t.name))return ie[t.name];throw new Error(`evaluate: unknown name "${t.name}"`)}case"unary":{const n=st(t.operand,e);return t.operator==="-"?-n:n}case"binary":{const n=st(t.left,e),s=st(t.right,e);switch(t.operator){case"+":return n+s;case"-":return n-s;case"*":return n*s;case"/":return n/s;case"^":return n**s}break}case"call":return Ee[t.name].apply(...t.args.map(n=>st(n,e)))}throw new Error("evaluate: malformed expression")}const _e=new Map;function tt(t,e="x"){let n=_e.get(t);n||(n=rt(t),_e.size<256&&_e.set(t,n));const s=n;return(i,r={})=>st(s,{...r,[e]:i})}const Sn=new Map;function Pe(t,e,n="x"){if(!Number.isInteger(e)||e<0)throw new Error(`compileDerivative: order must be a whole number ≥ 0, got ${e}`);const s=`${n}|${e}|${t}`;let i=Sn.get(s);if(!i){let o=_e.get(t);o||(o=rt(t)),i=Bs(o,e,n),Sn.size<512&&Sn.set(s,i)}const r=i;return(o,c={})=>st(r,{...c,[n]:o})}const Oe=480;function Vs(t,e){const n=[];let s=[];return t.forEach((i,r)=>{const o=t[r-1];(!i||o&&Math.abs(i[1]-o[1])>e*1.5)&&(s.length>=2&&n.push(s),s=[]),i&&s.push(i)}),s.length>=2&&n.push(s),n}function Hs(t,e){const n=Math.max(e.plane.width,e.plane.height)*20;if(!(!Number.isFinite(t[0])||!Number.isFinite(t[1])))return[Math.max(-n,Math.min(n,t[0])),Math.max(-n,Math.min(n,t[1]))]}function Us(t,e,n,s,i,r){return H(e,i.draw).map((o,c)=>({type:"line",id:`${t}.${c}`,points:o,stroke:n,width:s,opacity:i.opacity,...r?{dash:r}:{}}))}function Ie(t,e,n,s,i,r,o,c){const l=Array.from({length:Oe+1},(u,h)=>{const d=n+(s-n)*h/Oe;return Hs(o.plane.toScreen([d,e(d)]),o)});return Us(t,Vs(l,o.plane.height),i,r,o,c)}function fa(t,e){const n=t.derivative?Pe(t.expr,t.derivative):tt(t.expr,"x"),[s,i]=t.domain??e.plane.x,r=C(e.theme,t.color,e.theme.colors.blue),o=t.dashed?[10*e.plane.scale,8*e.plane.scale]:void 0;return Ie(t.id,c=>n(c,e.scope),s,i,r,(t.width??3.5)*e.plane.scale,e,o)}function pa(t,e){const n=tt(t.x,"t"),s=tt(t.y,"t"),i=xt(e.values,t.transform),[r,o]=t.t??[0,Math.PI*2],c=Array.from({length:Oe+1},(u,h)=>{const d=r+(o-r)*h/Oe;return Hs(e.plane.toScreen(it(i,[n(d,e.scope),s(d,e.scope)])),e)}),l=C(e.theme,t.color,e.theme.colors.blue);return Us(t.id,Vs(c,e.plane.height),l,(t.width??3.5)*e.plane.scale,e)}const ga=[[0,0],[1,0],[1,1],[0,1]];function ya(t,e){const n=xt(e.values,t.transform),s=(t.points??ga).map(c=>it(n,c)),i=s.map(e.plane.toScreen),r=C(e.theme,t.color,e.theme.colors.yellow),o=[{type:"line",id:`${t.id}.fill`,points:i,closed:!0,fill:r,opacity:e.opacity*(t.fillOpacity??.3)*e.draw},...H([[...i,i[0]]],e.draw).map(c=>({type:"line",id:`${t.id}.outline`,points:c,stroke:r,width:2.5*e.plane.scale,opacity:e.opacity}))];if(t.label&&e.draw>=1){const c=s.reduce((h,d)=>[h[0]+d[0]/s.length,h[1]+d[1]/s.length],[0,0]),[l,u]=e.plane.toScreen(c);o.push(...Z(W(t.label,{values:e.scope,style:"inline"}),{x:l,y:u,size:24*e.plane.scale,color:e.theme.ink,opacity:e.opacity,idPrefix:`${t.id}.label.`}))}return o}function ma(t,e){const n=t.eigen?Es(xt(e.values,t.eigen)).map(o=>o.vector):t.along!==void 0?[Lt(e.values,t.along)]:[],s=Math.max(Math.abs(e.plane.x[0]),Math.abs(e.plane.x[1]),Math.abs(e.plane.y[0]),Math.abs(e.plane.y[1]))*1.5,i=C(e.theme,t.color,e.theme.colors.yellow),r=(t.width??2.5)*e.plane.scale;return n.flatMap((o,c)=>{const l=Math.hypot(o[0],o[1]);if(l===0)return[];const u=dn(o,s/l),h=[dn(u,-1),u].map(e.plane.toScreen);return H([h],e.draw).map(d=>({type:"line",id:`${t.id}.${c}`,points:d,stroke:i,width:r,opacity:e.opacity,...t.dashed?{dash:[10*e.plane.scale,8*e.plane.scale]}:{}}))})}const ot=(t,e,n)=>t+(e-t)*n;function Ws(t,e,n){return t.kind==="stroke"?{...t,points:t.points.map(([s,i])=>[s+e,i+n])}:{...t,x:t.x+e,y:t.y+n}}function ba(t,e,n){if(t.kind==="glyph"&&e.kind==="glyph"&&t.text===e.text)return{...e,x:ot(t.x,e.x,n),y:ot(t.y,e.y,n),width:ot(t.width,e.width,n),size:ot(t.size,e.size,n)};if(t.kind==="rule"&&e.kind==="rule")return{...e,x:ot(t.x,e.x,n),y:ot(t.y,e.y,n),width:ot(t.width,e.width,n),height:ot(t.height,e.height,n)};if(t.kind==="stroke"&&e.kind==="stroke"&&t.points.length===e.points.length)return{...e,width:ot(t.width,e.width,n),points:t.points.map(([s,i],r)=>[ot(s,e.points[r][0],n),ot(i,e.points[r][1],n)])}}const va=t=>t*t*(3-2*t);function Gs(t,e,n){const s=Math.min(1,Math.max(0,n)),i=t.layout.pieces.map(y=>Ws(y,t.x,t.y)),r=e.layout.pieces.map(y=>Ws(y,e.x,e.y));if(s===0)return i.map(y=>({...y,opacity:1}));if(s===1)return r.map(y=>({...y,opacity:1}));const o=y=>{const g=new Map;for(const p of y)g.set(p.id,[...g.get(p.id)??[],p]);return g},c=o(i),l=o(r),u=[],h=va(s),d=Math.max(0,1-s*2),f=Math.max(0,s*2-1);for(const y of new Set([...c.keys(),...l.keys()])){const g=c.get(y)??[],p=l.get(y)??[],a=Math.max(g.length,p.length);for(let m=0;m<a;m++){const b=g[m],S=p[m],w=b&&S?ba(b,S,h):void 0;if(w){u.push({...w,opacity:1});continue}b&&u.push({...b,opacity:d}),S&&u.push({...S,opacity:f})}}return u.filter(y=>y.opacity>0)}function xn(t,e,n,s){const i=n.size*.35;let r=1/0,o=1/0,c=-1/0,l=-1/0;for(const u of e){const[h,d]=gn(u,n);r=Math.min(r,h-i),c=Math.max(c,h+u.width*n.size+i),o=Math.min(o,d-u.height*n.size-i),l=Math.max(l,d+u.depth*n.size+i)}return[{type:"line",id:`${t}.backdrop`,points:[[r,o],[c,o],[c,l],[r,l]],closed:!0,fill:s.theme.background,opacity:(n.opacity??1)*.85}]}function Zs(t,e,n){const s=Lt(n.values,t);return e?s:n.plane.toScreen(s)}function wa(t,e){const[n,s]=Zs(t.at,t.screen,e),i=(t.size??28)*e.plane.scale,r=C(e.theme,t.color,e.theme.ink),o={x:n,y:s,size:i,color:r,align:t.align,opacity:e.opacity*e.draw,idPrefix:`${t.id}.`,palette:e.theme.colors},c=W(t.tex,{values:e.scope});return[...t.backdrop??t.screen??!1?xn(t.id,[c],o,e):[],...Z(c,o)]}function ka(t,e){const[n,s]=Zs(t.at,t.screen,e),i=(t.size??36)*e.plane.scale,r=C(e.theme,t.color,e.theme.ink),o=t.steps.length-1,c=Math.min(o,Math.max(0,e.prop("step")??t.step??0)),l=Math.floor(c),u=c-l,h={x:n,y:s,size:i,color:r,align:t.align,opacity:e.opacity*e.draw,idPrefix:`${t.id}.`,palette:e.theme.colors},d=a=>W(t.steps[a],{values:e.scope}),f=t.backdrop??t.screen??!1;if(u===0||l>=o){const a=d(l);return[...f?xn(t.id,[a],h,e):[],...Z(a,h)]}const y=a=>{const[m,b]=gn(a,h);return{layout:a,x:m/i,y:b/i}},g=d(l),p=d(l+1);return[...f?xn(t.id,[g,p],h,e):[],...Ls(Gs(y(g),y(p),u),[0,0],h)]}const ae=["normal","uniform","exponential","binomial","poisson","dice","mean"];function Qs(t){switch(t.kind){case"binomial":return[0,t.n];case"dice":return[t.count??2,(t.count??2)*(t.sides??6)];case"poisson":return[0,1/0];default:return[-1/0,1/0]}}function ce(t){return t.kind==="binomial"||t.kind==="poisson"||t.kind==="dice"}const Ce=(()=>{const t=[0];return e=>{for(let n=t.length;n<=e;n++)t[n]=t[n-1]+Math.log(n);return t[e]}})(),An=(t,e)=>Math.exp(Ce(t)-Ce(e)-Ce(t-e));function yt(t,e){switch(t.kind){case"normal":{const{mean:n=0,sd:s=1}=t;return Math.exp(-(((e-n)/s)**2)/2)/(s*Math.sqrt(2*Math.PI))}case"uniform":{const{min:n=0,max:s=1}=t;return e>=n&&e<=s?1/(s-n):0}case"exponential":{const{rate:n=1}=t;return e<0?0:n*Math.exp(-n*e)}case"binomial":return!Number.isInteger(e)||e<0||e>t.n?0:An(t.n,e)*t.p**e*(1-t.p)**(t.n-e);case"poisson":return!Number.isInteger(e)||e<0?0:Math.exp(e*Math.log(t.rate)-t.rate-Ce(e));case"dice":{const{count:n=2,sides:s=6}=t;if(!Number.isInteger(e)||e<n||e>n*s)return 0;let i=0;for(let r=0;r<=Math.floor((e-n)/s);r++)i+=(r%2?-1:1)*An(n,r)*An(e-s*r-1,n-1);return i/s**n}case"mean":return t.count===1?yt(t.of,e):yt({kind:"normal",mean:zt(t.of),sd:qt(t.of)/Math.sqrt(t.count)},e)}}function zt(t){switch(t.kind){case"normal":return t.mean??0;case"uniform":return((t.min??0)+(t.max??1))/2;case"exponential":return 1/(t.rate??1);case"binomial":return t.n*t.p;case"poisson":return t.rate;case"dice":return(t.count??2)*((t.sides??6)+1)/2;case"mean":return zt(t.of)}}function qt(t){switch(t.kind){case"normal":return t.sd??1;case"uniform":return((t.max??1)-(t.min??0))/Math.sqrt(12);case"exponential":return 1/(t.rate??1);case"binomial":return Math.sqrt(t.n*t.p*(1-t.p));case"poisson":return Math.sqrt(t.rate);case"dice":return Math.sqrt((t.count??2)*((t.sides??6)**2-1)/12);case"mean":return qt(t.of)/Math.sqrt(t.count)}}function En(t,e){switch(t.kind){case"normal":return St(e,t.mean??0,t.sd??1);case"uniform":return(t.min??0)+e.next()*((t.max??1)-(t.min??0));case"exponential":return-Math.log(1-e.next())/(t.rate??1);case"binomial":{let n=0;for(let s=0;s<t.n;s++)e.next()<t.p&&n++;return n}case"poisson":{const n=Math.exp(-t.rate);let s=0,i=e.next();for(;i>n;)s++,i*=e.next();return s}case"dice":{let n=0;for(let s=0;s<(t.count??2);s++)n+=1+Math.floor(e.next()*(t.sides??6));return n}case"mean":{let n=0;for(let s=0;s<t.count;s++)n+=En(t.of,e);return n/t.count}}}const Ne=new Map;function Tn(t,e,n){const s=`${JSON.stringify(t)}|${e}`;let i=Ne.get(s);if(i||(i=[],Ne.size>64&&Ne.clear(),Ne.set(s,i)),i.length<n){const r=Nt(typeof e=="number"?e:$t(e)),o=[];for(let c=0;c<n;c++)o.push(En(t,r));i.splice(0,i.length,...o)}return i.slice(0,n)}function _n(t){if(!t||typeof t!="object"||!ae.includes(t.kind))return`kind must be one of ${ae.join(", ")}`;const e=(n,s)=>n!==void 0&&!(n>0)?`${s} must be positive`:void 0;switch(t.kind){case"normal":return e(t.sd,"sd");case"uniform":return(t.max??1)>(t.min??0)?void 0:"max must be greater than min";case"exponential":return e(t.rate,"rate");case"binomial":return Number.isInteger(t.n)&&t.n>=0&&t.n<=1e3&&t.p>=0&&t.p<=1?void 0:"n must be a whole number 0..1000 and p in 0..1";case"poisson":return t.rate>0&&t.rate<=200?void 0:"rate must be in (0, 200]";case"dice":return Number.isInteger(t.count??2)&&(t.count??2)>=1&&(t.count??2)<=50&&Number.isInteger(t.sides??6)&&(t.sides??6)>=2?void 0:"count must be 1..50 and sides a whole number ≥ 2";case"mean":return Number.isInteger(t.count)&&t.count>=1&&t.count<=200?_n(t.of):"count must be a whole number 1..200"}}function Pn(t){const e=zt(t),n=qt(t);if(ce(t)){const[s,i]=Qs(t),r=Math.max(s,Math.floor(e-4*n)),o=Math.min(i,Math.ceil(e+4*n));return[r-.5,o+.5,o-r+1]}return[e-4*n,e+4*n,30]}function Ks(t,[e,n,s],i){const r=(n-e)/s,o=new Array(s).fill(0);for(const l of t){const u=Math.floor((l-e)/r);u>=0&&u<s?o[u]++:l===n&&o[s-1]++}const c=t.length||1;return o.map((l,u)=>({left:e+u*r,right:e+(u+1)*r,count:l,height:i==="density"?l/(c*r):l}))}function Js(t){if(t.length===0)return{mean:0,sd:0};const e=t.reduce((s,i)=>s+i,0)/t.length,n=t.reduce((s,i)=>s+(i-e)**2,0)/t.length;return{mean:e,sd:Math.sqrt(n)}}function On(t,e,n){const s=Nt(typeof e=="number"?e:$t(e));return Array.from({length:Math.max(0,Math.floor(n))},()=>{const i=s.next();if(t.kind==="uniform"){const o=s.next();return[t.x[0]+i*(t.x[1]-t.x[0]),t.y[0]+o*(t.y[1]-t.y[0])]}const r=t.x[0]+i*(t.x[1]-t.x[0]);return[r,t.slope*r+t.intercept+t.noise*St(s)]})}function In(t){const e=t.length;if(e<2)return;const n=t.reduce((l,u)=>l+u[0],0)/e,s=t.reduce((l,u)=>l+u[1],0)/e;let i=0,r=0,o=0;for(const[l,u]of t)i+=(l-n)*(u-s),r+=(l-n)**2,o+=(u-s)**2;if(r===0)return;const c=i/r;return{slope:c,intercept:s-c*n,r:o===0?0:i/Math.sqrt(r*o)}}function ti(t,e,n){const s=Math.min(1,Math.max(0,t)),i=s*Math.min(1,Math.max(0,e)),r=(1-s)*Math.min(1,Math.max(0,n)),o=i+r;return{truePositive:i,falsePositive:r,positive:o,posterior:o>0?i/o:0}}function Cn(t,e,n){const s=Nt($t(`${t}:${e}`));return Array.from({length:n},()=>s.next()<.5)}const Fe=t=>t.filter(Boolean).length;function ei(t,e){const n=t.length,s=Math.min(1,Math.max(0,e))*n,i=Math.min(n-1,Math.floor(s)),r=s-i,c=t.slice(0,i).filter(Boolean).length-i/2,l=c+(t[i]?.5:-.5),u=.18*Math.sin(Math.PI*r);return{x:c+(l-c)*r,depth:i+r-u}}const Nn=(t,e,n,s,i)=>[[e,n],[s,n],[s,i],[e,i]].map(t.plane.toScreen),Le=t=>Math.min(2e4,Math.max(0,Math.floor(t)));function Ma(t,e){const n=Rt(e.values,t.distribution),s=Tn(n,t.seed??t.id,Le(N(e.values,t.count))),i=Ks(s,t.bins??Pn(n),t.scale??"density"),r=C(e.theme,t.color,e.theme.colors.blue),o=e.opacity*e.draw,c=i.flatMap((l,u)=>l.height>0?[{type:"line",id:`${t.id}.${u}`,points:Nn(e,l.left,0,l.right,l.height),closed:!0,fill:r,stroke:e.theme.background,width:1*e.plane.scale,opacity:o*(t.fillOpacity??.75)}]:[]);if(t.curve&&(t.scale??"density")==="density"){const[l,u]=t.bins??Pn(n),h=C(e.theme,"yellow",e.theme.colors.yellow);c.push(...Ie(`${t.id}.curve`,d=>yt(ce(n)?{kind:"normal",mean:zt(n),sd:qt(n)}:n,d),l,u,h,3*e.plane.scale,{...e,draw:1}))}return c}function $a(t,e){const n=Rt(e.values,t.distribution),s=C(e.theme,t.color,e.theme.colors.blue),[i,r]=t.domain??e.plane.x,o=t.shade?[N(e.values,t.shade[0]),N(e.values,t.shade[1])].sort((u,h)=>u-h):void 0,c=C(e.theme,"yellow",e.theme.colors.yellow);if(ce(n)){const u=[],h=Math.max(0,Math.ceil(i)),d=Math.floor(r),f=h+Math.ceil((d-h+1)*e.draw);for(let y=h;y<f&&y<=d;y++){const g=yt(n,y);if(g<=0)continue;const p=o&&y>=o[0]&&y<=o[1];u.push({type:"line",id:`${t.id}.${y}`,points:Nn(e,y-.4,0,y+.4,g),closed:!0,fill:p?c:s,opacity:e.opacity*(t.fillOpacity??.8)})}return u}const l=[];if(o&&e.draw>=1){const[u,h]=[Math.max(o[0],i),Math.min(o[1],r)];if(h>u){const f=Array.from({length:121},(g,p)=>{const a=u+(h-u)*p/120;return[a,yt(n,a)]}),y=[[u,0],...f,[h,0]].map(e.plane.toScreen);l.push({type:"line",id:`${t.id}.shade`,points:y,closed:!0,fill:c,opacity:e.opacity*(t.fillOpacity??.4)})}}return l.push(...Ie(t.id,u=>yt(n,u),i,r,s,(t.width??3.5)*e.plane.scale,e)),l}function Sa(t,e){const n=t.rows??10,s=t.spacing??.5,i=t.top??e.plane.y[1]-s,r=s*.9,o=(v,k)=>[v*s,i-k*r],c=C(e.theme,"grey",e.theme.colors.grey),l=C(e.theme,t.color,e.theme.colors.yellow),u=s*.19*e.plane.unitX,h=[];for(let v=0;v<n;v++)for(let k=0;k<=v;k++){const[x,M]=e.plane.toScreen(o(k-v/2,v));h.push({type:"circle",id:`${t.id}.peg.${v}.${k}`,x,y:M,r:u*.45,fill:c,opacity:e.opacity*e.draw})}const d=n+.3,f=Math.max(n+2,(i-e.plane.y[0])/r-.2);for(let v=0;v<=n+1;v++){const k=v-(n+1)/2,x=H([[o(k,d),o(k,f)].map(e.plane.toScreen)],e.draw);for(const M of x)h.push({type:"line",id:`${t.id}.bin.${v}`,points:M,stroke:c,width:1.2*e.plane.scale,opacity:e.opacity*.6})}const y=H([[o(-(n+1)/2,f),o((n+1)/2,f)].map(e.plane.toScreen)],e.draw);for(const v of y)h.push({type:"line",id:`${t.id}.floor`,points:v,stroke:c,width:1.2*e.plane.scale,opacity:e.opacity*.6});const g=Math.max(0,N(e.values,t.balls)),p=Math.floor(g),a=t.seed??t.id,m=new Array(n+1).fill(0),b=2*u/e.plane.unitY/r,S=(v,k)=>({x:v-n/2+(k%2?.22:-.22),depth:f-b*(Math.floor(k/2)+.5)});for(let v=0;v<p;v++){const k=Fe(Cn(a,v,n)),x=S(k,m[k]),[M,A]=e.plane.toScreen(o(x.x,x.depth));m[k]++,h.push({type:"circle",id:`${t.id}.ball.${v}`,x:M,y:A,r:u,fill:l,opacity:e.opacity})}const w=g-p;if(w>0){const v=Cn(a,p,n),k=Math.min(1,w/.8);let{x,depth:M}=ei(v,k);if(M-=1,w>.8){const _=((w-.8)/.2)**2,T=Fe(v),F=S(T,m[T]),R={x:Fe(v)-n/2,depth:n-1};M=R.depth+(F.depth-R.depth)*_,x=R.x+(F.x-R.x)*_}const[A,E]=e.plane.toScreen(o(x,M));h.push({type:"circle",id:`${t.id}.falling`,x:A,y:E,r:u,fill:l,opacity:e.opacity})}return h}function xa(t,e){const n=ni(t,e),s=On(n,t.seed??t.id,Le(N(e.values,t.count))),i=C(e.theme,t.color,e.theme.colors.blue),r=C(e.theme,t.insideColor,e.theme.colors.yellow),o=t.inside?rt(t.inside):void 0,c=(t.radius??3)*e.plane.scale,l=s.map(([u,h],d)=>{const[f,y]=e.plane.toScreen([u,h]),g=o?st(o,{...e.scope,x:u,y:h})<=0:!1;return{type:"circle",id:`${t.id}.${d}`,x:f,y,r:c,fill:g?r:i,opacity:e.opacity*e.draw*.85}});if(t.fit){const u=In(s);if(u){const[h,d]=e.plane.x;l.push({type:"line",id:`${t.id}.fit`,points:[[h,u.slope*h+u.intercept],[d,u.slope*d+u.intercept]].map(e.plane.toScreen),stroke:C(e.theme,"red",e.theme.colors.red),width:3*e.plane.scale,opacity:e.opacity})}}return l}function ni(t,e){const n=t.points;return n.kind==="uniform"?n:{kind:"linear",slope:N(e.values,n.slope),intercept:N(e.values,n.intercept),noise:N(e.values,n.noise),x:n.x}}function Aa(t,e){const n=N(e.values,t.prior),s=N(e.values,t.truePositive),i=N(e.values,t.falsePositive),r=e.plane.x[1]-e.plane.x[0],o=e.plane.y[1]-e.plane.y[0],[c,l]=t.size??[r*.8,o*.7],[u,h]=t.at??[e.plane.x[0]+r*.1,e.plane.y[0]+o*.08],d=u+c*Math.min(1,Math.max(0,n)),f=C(e.theme,t.color,e.theme.colors.yellow),y=C(e.theme,"red",e.theme.colors.red),g=C(e.theme,"grey",e.theme.colors.grey),p=e.opacity*e.draw,a=(v,k,x,M,A,E,_)=>({type:"line",id:`${t.id}.${v}`,points:Nn(e,k,x,M,A),closed:!0,fill:E,stroke:e.theme.background,width:2*e.plane.scale,opacity:p*_}),m=h+l,b=m-l*Math.min(1,Math.max(0,s)),S=m-l*Math.min(1,Math.max(0,i)),w=[a("tp",u,b,d,m,f,.85),a("fn",u,h,d,b,g,.35),a("fp",d,S,u+c,m,y,.8),a("tn",d,h,u+c,S,g,.2)];if(t.labels!==!1&&e.draw>=1){const v=20*e.plane.scale,k=(x,M,A,E)=>{const[_,T]=e.plane.toScreen(A);w.push(...Z(W(M,{values:e.scope,style:"inline"}),{x:_,y:T,size:v,color:E,opacity:e.opacity,idPrefix:`${t.id}.label.${x}.`}))};k("prior",`\\text{has it: } \\val{${t.id}.prior:3}`,[u+c/2,h-o*.04],e.theme.ink),k("tp",`\\text{has it, tests positive: } \\val{${t.id}.truePositive:3}`,[u+c/2,h-o*.09],f),k("fp",`\\text{does not, tests positive: } \\val{${t.id}.falsePositive:3}`,[u+c/2,h-o*.14],y),k("posterior",`P(\\text{has it} \\mid +) = \\val{${t.id}.posterior:3}`,[u+c/2,h+l+o*.05],f)}return w}const Fn=["bfs","dfs","dijkstra"];function Re(t,e,n){const s=new Map(t.map((r,o)=>[r,o])),i=new Map(t.map(r=>[r,[]]));for(const r of e){const o=r.weight??1;i.get(r.from)?.push({to:r.to,weight:o}),n||i.get(r.to)?.push({to:r.from,weight:o})}for(const r of i.values())r.sort((o,c)=>(s.get(o.to)??0)-(s.get(c.to)??0));return i}function Ea(t,e){const n=[],s=new Set([t]),i=[{node:t}];for(;i.length>0;){const{node:r,parent:o}=i.shift();for(const{to:c}of e.get(r)??[])s.has(c)||(s.add(c),i.push({node:c,parent:r}));n.push({node:r,...o!==void 0?{parent:o}:{},frontier:i.map(c=>c.node)})}return n}function Ta(t,e){const n=[],s=new Set,i=[{node:t}];for(;i.length>0;){const{node:r,parent:o}=i.pop();if(s.has(r))continue;s.add(r);const c=(e.get(r)??[]).filter(({to:l})=>!s.has(l)).reverse();for(const{to:l}of c)i.push({node:l,parent:r});n.push({node:r,...o!==void 0?{parent:o}:{},frontier:[...new Set(i.map(l=>l.node).filter(l=>!s.has(l)))].reverse()})}return n}function _a(t,e,n){const s=[],i=Object.fromEntries(e.map(l=>[l,1/0])),r={},o=new Map(e.map((l,u)=>[l,u]));i[t]=0;const c=new Set;for(;;){let l;for(const h of e)c.has(h)||i[h]===1/0||(l===void 0||i[h]<i[l]||i[h]===i[l]&&o.get(h)<o.get(l))&&(l=h);if(l===void 0)break;c.add(l);for(const{to:h,weight:d}of n.get(l)??[])c.has(h)||i[l]+d<i[h]&&(i[h]=i[l]+d,r[h]=l);const u=e.filter(h=>!c.has(h)&&i[h]<1/0).sort((h,d)=>i[h]-i[d]);s.push({node:l,...r[l]!==void 0?{parent:r[l]}:{},frontier:u,distances:{...i}})}return s}const De=new Map;function si(t,e,n,s,i=!1){const r=JSON.stringify([t,e,n,s,i]),o=De.get(r);if(o)return o;if(!n.includes(e))throw new Error(`graph search: no node "${e}"`);const c=Re(n,s,i),l=t==="bfs"?Ea(e,c):t==="dfs"?Ta(e,c):_a(e,n,c);return De.size>64&&De.clear(),De.set(r,l),l}function ii(t,e,n){const s=Re(e,n,!0),i=Re(e,n,!1),r=new Map,o=new Set([t]),c=[t];for(;c.length;){const y=c.shift(),g=(s.get(y)?.length?s.get(y):i.get(y)??[]).map(p=>p.to).filter(p=>!o.has(p));g.forEach(p=>o.add(p)),r.set(y,g),c.push(...g)}const l=new Map;let u=0;const h=(y,g)=>{const p=r.get(y)??[],a=p.length===0?u++:p.map(m=>h(m,g+1)).reduce((m,b,S,w)=>m+b/w.length,0);return l.set(y,[a,g===0?0:-g]),a};h(t,0);const d=[...l.values()].map(([y])=>y),f=(Math.min(...d)+Math.max(...d))/2;for(const[y,[g,p]]of l)l.set(y,[g-f,p]);return l}const Pa={"∪":"|","∩":"&","∖":"-","△":"^","¬":"!","\\":"-"};function Ln(t){const e=[...t].map(u=>Pa[u]??u).join("");let n=0;const s=()=>{for(;/\s/.test(e[n]??"");)n++},i=u=>{throw new Error(`set expression: ${u} at ${n+1} in "${t}"`)},r=()=>{s();let u;if(e[n]==="!")n++,u={type:"not",operand:r()};else if(e[n]==="(")n++,u=c(),s(),e[n]!==")"&&i('expected ")"'),n++;else{const h=/^[A-Za-z]\w*/.exec(e.slice(n));h||i(n>=e.length?"unexpected end":`unexpected "${e[n]}"`),n+=h[0].length,u={type:"set",name:h[0]}}for(s();e[n]==="'";)n++,u={type:"not",operand:u},s();return u},o=()=>{let u=r();for(s();e[n]==="&";)n++,u={type:"op",operator:"&",left:u,right:r()},s();return u},c=()=>{let u=o();for(s();e[n]==="|"||e[n]==="-"||e[n]==="^";)u={type:"op",operator:e[n++],left:u,right:o()},s();return u},l=c();return s(),n<e.length&&i(`unexpected "${e[n]}"`),l}function le(t){return t.type==="set"?[t.name]:t.type==="not"?le(t.operand):[...new Set([...le(t.left),...le(t.right)])]}function ue(t,e){switch(t.type){case"set":return e.has(t.name);case"not":return!ue(t.operand,e);case"op":{const n=ue(t.left,e),s=ue(t.right,e);return t.operator==="&"?n&&s:t.operator==="|"?n||s:t.operator==="-"?n&&!s:n!==s}}}function ri(t,e){const n=[];for(let s=0;s<1<<e.length;s++){const i=e.filter((r,o)=>s&1<<o);ue(t,new Set(i))&&n.push(i)}return n}function oi(t,e,n,s,i=64){return Array.from({length:i},(r,o)=>{const c=o/i*2*Math.PI;return[t+n*Math.cos(c),e+s*Math.sin(c)]})}function ze(t){return t.edges.map(e=>Array.isArray(e)?{from:e[0],to:e[1],...e[2]!==void 0?{weight:e[2]}:{}}:e)}function ai(t){const e=new Map;if(t.tree){const[n,s]=t.tree.spacing??[1.2,1.2],[i,r]=t.tree.at??[0,0];for(const[o,[c,l]]of ii(t.tree.root,t.nodes.map(u=>u.id),ze(t)))e.set(o,[i+c*n,r+l*s])}for(const n of t.nodes)n.at&&e.set(n.id,n.at);return e}function ci(t,e){if(!t.search)return;const n=si(t.search.kind,t.search.start,t.nodes.map(r=>r.id),ze(t),t.directed),s=t.step===void 0?n.length:Math.min(n.length,Math.max(0,N(e,t.step))),i=Math.floor(s);return{events:n,done:i,partial:i<n.length?s-i:0}}const Oa={bfs:"queue",dfs:"stack",dijkstra:"open"};function Ia(t,e){const{plane:n,theme:s}=e,i=ai(t),r=ze(t),o=ci(t,e.values),c=(t.radius??18)*n.scale,l=C(s,t.color,s.ink),u=C(s,"grey",s.colors.grey),h=C(s,"yellow",s.colors.yellow),d=C(s,"blue",s.colors.blue),f=[],y=o?o.events.slice(0,o.done):[],g=new Set(y.map(M=>M.node)),p=new Set(y.filter(M=>M.parent!==void 0).map(M=>`${M.parent}>${M.node}`)),a=y.at(-1),m=new Set(a?.frontier??[]),b=o&&o.partial>0?o.events[o.done]:void 0,S=(M,A)=>p.has(`${M}>${A}`)||!t.directed&&p.has(`${A}>${M}`),w=M=>n.toScreen(i.get(M)??[0,0]),v=(M,A)=>{const E=w(M),_=w(A),[T,F]=ee([_[0]-E[0],_[1]-E[1]]);return[[E[0]+T*c,E[1]+F*c],[_[0]-T*c,_[1]-F*c]]},k=t.weights??t.search?.kind==="dijkstra";if(r.forEach((M,A)=>{const[E,_]=v(M.from,M.to),T=S(M.from,M.to),F=T?h:u,R=(T?4:2)*n.scale,[P]=H([[E,_]],e.draw);if(P&&(f.push(t.directed?{type:"arrow",id:`${t.id}.edge.${A}`,points:P,stroke:F,width:R,head:11*n.scale,opacity:e.opacity}:{type:"line",id:`${t.id}.edge.${A}`,points:P,stroke:F,width:R,opacity:e.opacity}),k&&e.draw>=1)){const O=[(E[0]+_[0])/2,(E[1]+_[1])/2],[I,L]=ee([-(_[1]-E[1]),_[0]-E[0]]),D=14*n.scale;f.push({type:"text",id:`${t.id}.weight.${A}`,text:String(M.weight??1),x:O[0]+I*D*.9,y:O[1]+L*D*.9+D*.35,size:D,font:At,color:T?h:u,align:"center",opacity:e.opacity})}}),b?.parent!==void 0){const[M,A]=v(b.parent,b.node),[E]=H([[M,A]],b.parent?o.partial:1);E&&f.push({type:"line",id:`${t.id}.reaching`,points:E,stroke:h,width:4*n.scale,opacity:e.opacity})}const x=a?.distances;for(const M of t.nodes){const[A,E]=w(M.id),_=g.has(M.id),T=b?.node===M.id&&o.partial>=.999,F=!_&&m.has(M.id),R=_||T?h:F?d:s.background;f.push({type:"circle",id:`${t.id}.node.${M.id}`,x:A,y:E,r:c,fill:R,stroke:_?h:F?d:l,width:2*n.scale,opacity:e.opacity*Math.min(1,e.draw*1.5)}),a?.node===M.id&&f.push({type:"circle",id:`${t.id}.current`,x:A,y:E,r:c*1.35,stroke:h,width:2*n.scale,opacity:e.opacity*.8});const P=_||F||T?s.background:l;if(f.push(...Z(W(M.label??M.id,{style:"inline"}),{x:A,y:E,size:c*.95,color:P,opacity:e.opacity*e.draw,idPrefix:`${t.id}.label.${M.id}.`})),x){const O=x[M.id],I=13*n.scale;f.push({type:"text",id:`${t.id}.distance.${M.id}`,text:O===1/0?"∞":String(Math.round(O*100)/100),x:A,y:E+c+I*1.15,size:I,font:At,color:d,align:"center",opacity:e.opacity})}}if(t.frontier&&t.search&&e.draw>=1){const[M,A]=t.frontier,E=16*n.scale,_=Oa[t.search.kind];f.push({type:"text",id:`${t.id}.frontier.name`,text:`${_}:`,x:M,y:A+E*.35,size:E,font:At,color:u,align:"left",opacity:e.opacity});const T=E*1.9;[...m].forEach((F,R)=>{const P=M+E*4+R*(T+E*.4),O=t.nodes.find(I=>I.id===F)?.label??F;f.push({type:"line",id:`${t.id}.frontier.box.${R}`,points:[[P,A-T/2],[P+T,A-T/2],[P+T,A+T/2],[P,A+T/2]],closed:!0,fill:d,opacity:e.opacity*.9}),f.push(...Z(W(O,{style:"inline"}),{x:P+T/2,y:A,size:E*1.05,color:s.background,opacity:e.opacity,idPrefix:`${t.id}.frontier.label.${R}.`}))})}return f}function Ca(t){return t===2?[[-.6,0],[.6,0]]:[0,1,2].map(e=>{const n=Math.PI/2+e*2*Math.PI/3;return[.62*Math.cos(n),.62*Math.sin(n)-.1]})}function Na(t,e){const{plane:n,theme:s}=e,i=t.radius??1.5,[r,o]=t.at??[0,0],c=Ca(t.sets.length).map(([a,m])=>[r+a*i,o+m*i]),l=c.map(([a,m])=>oi(a,m,i,i,96).map(n.toScreen)),u=c.map(([a])=>a),h=c.map(([,a])=>a),d=i*.35,f=[[Math.min(...u)-i-d,Math.min(...h)-i-d],[Math.max(...u)+i+d,Math.min(...h)-i-d],[Math.max(...u)+i+d,Math.max(...h)+i+d],[Math.min(...u)-i-d,Math.max(...h)+i+d]].map(n.toScreen),y=[],g=t.sets.map(a=>a.id);if(t.highlight){const a=C(s,t.highlightColor,s.colors.yellow);ri(Ln(t.highlight),g).forEach((m,b)=>{y.push({type:"line",id:`${t.id}.region.${b}`,points:f,closed:!0,fill:a,opacity:e.opacity*e.draw*.55,clip:g.map((S,w)=>({points:l[w],outside:!m.includes(S)}))})})}if(t.universe!==!1){y.push({type:"line",id:`${t.id}.universe`,points:f,closed:!0,stroke:C(s,"grey",s.colors.grey),width:2*n.scale,opacity:e.opacity});const[a,m]=f[3];y.push(...Z(W("U",{style:"inline"}),{x:a+16*n.scale,y:m+20*n.scale,size:22*n.scale,color:C(s,"grey",s.colors.grey),opacity:e.opacity,idPrefix:`${t.id}.universe.`}))}const p=["blue","red","green"];return t.sets.forEach((a,m)=>{const b=C(s,a.color??p[m],s.colors.blue);for(const x of H([[...l[m],l[m][0]]],e.draw))y.push({type:"line",id:`${t.id}.set.${a.id}`,points:x,stroke:b,width:3*n.scale,opacity:e.opacity});const[S,w]=ee([c[m][0]-r||(m===0?-1:1),c[m][1]-o]),[v,k]=n.toScreen([c[m][0]+S*i*.78,c[m][1]+w*i*.78+(t.sets.length===2?i*.85:0)]);y.push(...Z(W(a.label??a.id,{style:"inline"}),{x:v,y:k,size:26*n.scale,color:b,opacity:e.opacity*e.draw,idPrefix:`${t.id}.label.${a.id}.`}))}),y}const li=(t,e)=>(Math.round(t)%e+e)%e;function Fa(t,e){const{plane:n,theme:s}=e,i=t.modulus,[r,o]=t.at??[0,0],c=t.radius??2,l=N(e.values,t.value),u=C(s,t.color,s.ink),h=C(s,"yellow",s.colors.yellow),d=(g,p)=>{const a=Math.PI/2-g/i*2*Math.PI;return n.toScreen([r+Math.cos(a)*c*p,o+Math.sin(a)*c*p])},f=[];for(const g of H([oi(r,o,c,c,120).map(n.toScreen)],e.draw))f.push({type:"line",id:`${t.id}.face`,points:g,stroke:u,width:3*n.scale,opacity:e.opacity});const y=li(l,i);for(let g=0;g<i;g++){const[p,a]=d(g,.8),m=Math.min(26,220/i+8)*n.scale;f.push({type:"line",id:`${t.id}.tick.${g}`,points:[d(g,.95),d(g,1)],stroke:u,width:2*n.scale,opacity:e.opacity*e.draw}),f.push({type:"text",id:`${t.id}.hour.${g}`,text:String(g),x:p,y:a+m*.35,size:m,font:At,color:g===y?h:u,align:"center",opacity:e.opacity*e.draw})}if(e.draw>=1){const g=n.toScreen([r,o]);f.push({type:"arrow",id:`${t.id}.hand`,points:[g,d(l,.62)],stroke:h,width:5*n.scale,head:16*n.scale,opacity:e.opacity}),f.push({type:"circle",id:`${t.id}.pin`,x:g[0],y:g[1],r:6*n.scale,fill:h,opacity:e.opacity})}return f}const Rn=["sigmoid","tanh","relu"],ui=(t,e)=>t==="sigmoid"?1/(1+Math.exp(-e)):t==="tanh"?Math.tanh(e):Math.max(0,e);function hi(t,e){const n=Nt(typeof e=="number"?e:$t(e)),s=[],i=[];for(let r=0;r<t.length-1;r++){const o=1.6/Math.sqrt(t[r]);s.push(Array.from({length:t[r+1]},()=>Array.from({length:t[r]},()=>St(n)*o))),i.push(Array.from({length:t[r+1]},()=>St(n)*.3))}return{layers:t,weights:s,biases:i}}function di(t,e,n){const s=[e.slice(0,t.layers[0])];for(let i=0;i<t.weights.length;i++){const r=s[i];s.push(t.weights[i].map((o,c)=>ui(n,o.reduce((l,u,h)=>l+u*(r[h]??0),t.biases[i][c]))))}return s}const he=["viridis","heat","diverging"],La={viridis:[[68,1,84],[59,82,139],[33,145,140],[94,201,98],[253,231,37]],heat:[[20,12,30],[120,28,60],[214,70,40],[250,160,50],[252,240,180]],diverging:[[49,99,185],[140,180,225],[245,245,245],[235,140,120],[190,40,50]]};function de(t,e){const n=La[t],s=Math.min(1,Math.max(0,Number.isFinite(e)?e:0))*(n.length-1),i=Math.min(n.length-2,Math.floor(s)),r=s-i;return`#${n[i].map((o,c)=>Math.round(o+(n[i+1][c]-o)*r).toString(16).padStart(2,"0")).join("")}`}function fi(t){const e=/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(t.trim());if(e){const s=e[1].length===3?[...e[1]].map(i=>i+i).join(""):e[1];return[0,2,4].map(i=>parseInt(s.slice(i,i+2),16))}const n=/^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/i.exec(t.trim());return n?[Number(n[1]),Number(n[2]),Number(n[3])]:void 0}function Dn(t,e,n){const s=fi(t),i=fi(e);if(!s||!i)return t;const r=Math.min(1,Math.max(0,n)),[o,c,l]=s.map((u,h)=>Math.round(i[h]+(u-i[h])*r));return`rgb(${o}, ${c}, ${l})`}function pi(t,e,n,s,i,r){r+=1e-9*Math.max(1,Math.abs(r));const o=[],c=t.length,l=t[0]?.length??0,u=(d,f,y,g)=>{(f>g||f===g&&d>y)&&([d,f,y,g]=[y,g,d,f]);const p=t[f][d]-r,a=t[g][y]-r,m=p===a?.5:p/(p-a);return[e+(d+(y-d)*m)*s,n+(f+(g-f)*m)*i]};for(let d=0;d<c-1;d++)for(let f=0;f<l-1;f++){const y=[t[d][f],t[d][f+1],t[d+1][f+1],t[d+1][f]];if(y.some(a=>!Number.isFinite(a)))continue;const g=[],p=[[0,1,f,d,f+1,d],[1,2,f+1,d,f+1,d+1],[2,3,f+1,d+1,f,d+1],[3,0,f,d+1,f,d]];for(const[a,m,b,S,w,v]of p)y[a]>=r!=y[m]>=r&&g.push(u(b,S,w,v));if(g.length===2)o.push([g[0],g[1]]);else if(g.length===4){const a=(y[0]+y[1]+y[2]+y[3])/4>=r,m=y[0]>=r;a===m?o.push([g[0],g[1]],[g[2],g[3]]):o.push([g[0],g[3]],[g[1],g[2]])}}const h=1e-6*Math.min(Math.abs(s),Math.abs(i));return Ra(o.filter(([d,f])=>Math.hypot(f[0]-d[0],f[1]-d[1])>h))}function Ra(t){const e=([o,c])=>`${Math.round(o*1e6)},${Math.round(c*1e6)}`,n=new Map;t.forEach(([o,c],l)=>{for(const u of[o,c])n.set(e(u),[...n.get(e(u))??[],l])});const s=new Set,i=[],r=o=>{for(;;){const c=o[o.length-1],l=(n.get(e(c))??[]).find(d=>!s.has(d));if(l===void 0)return;s.add(l);const[u,h]=t[l];o.push(e(u)===e(c)?h:u)}};return t.forEach(([o,c],l)=>{if(s.has(l))return;s.add(l);const u=[o,c];r(u),u.reverse(),r(u),i.push(u)}),i}function gi(t,[e,n],[s,i],r){const o=(n-e)/r,c=(i-s)/r;return{values:Array.from({length:r+1},(u,h)=>Array.from({length:r+1},(d,f)=>t(e+f*o,s+h*c))),x0:e,y0:s,dx:o,dy:c}}function zn(t,e,n,s,i=0,r={}){const o=rt(t),c=J(o,"x"),l=J(o,"y"),u=(f,y)=>{const g={...r,x:f,y};return[st(c,g),st(l,g)]},h=[e];let d=[0,0];for(let f=0;f<s;f++){const[y,g]=h[h.length-1],[p,a]=u(y,g);d=[i*d[0]-n*p,i*d[1]-n*a];const m=[y+d[0],g+d[1]];if(!Number.isFinite(m[0])||!Number.isFinite(m[1])||Math.abs(m[0])>1e6||Math.abs(m[1])>1e6)break;h.push(m)}return h}function fe(t){const e=rt(t);return(n,s,i={})=>st(e,{...i,x:n,y:s})}function qn(t,e,n,s){const i=Nt(typeof s=="number"?s:$t(s)),r=[];for(let o=0;o<e;o++)t.forEach(([c,l],u)=>r.push({point:[c+St(i)*n,l+St(i)*n],label:u}));return r}const Da=t=>1/(1+Math.exp(-t)),pe=(t,[e,n])=>Da(t.w[0]*e+t.w[1]*n+t.b);function yi(t,e,n,s={w:[0,0],b:0}){const i=[s];for(let r=0;r<e;r++){const{w:o,b:c}=i[i.length-1];let l=0,u=0,h=0;for(const{point:f,label:y}of t){const g=pe({w:o,b:c},f)-y;l+=g*f[0],u+=g*f[1],h+=g}const d=t.length||1;i.push({w:[o[0]-n*l/d,o[1]-n*u/d],b:c-n*h/d})}return i}function mi(t,e){return e.length===0?0:e.filter(({point:n,label:s})=>(pe(t,n)>=.5?1:0)===s).length/e.length}function bi(t,e){if(e.length===0)return 0;const n=1e-12;return-e.reduce((s,{point:i,label:r})=>{const o=pe(t,i);return s+Math.log(r?o+n:1-o+n)},0)/e.length}const qe=(t,e)=>(t[0]-e[0])**2+(t[1]-e[1])**2;function je(t,e){return t.map(n=>{let s=0;for(let i=1;i<e.length;i++)qe(n,e[i])<qe(n,e[s])&&(s=i);return s})}function vi(t,e,n=20,s=t.slice(0,e)){const i=[s.map(r=>[r[0],r[1]])];for(let r=0;r<n;r++){const o=i[i.length-1],c=je(t,o),l=o.map((h,d)=>{const f=t.filter((y,g)=>c[g]===d);return f.length===0?h:[f.reduce((y,g)=>y+g[0],0)/f.length,f.reduce((y,g)=>y+g[1],0)/f.length]}),u=l.some((h,d)=>qe(h,o[d])>1e-12);if(i.push(l),!u)break}return i}function wi(t,e){const n=je(t,e);return t.reduce((s,i,r)=>s+qe(i,e[n[r]]),0)}const Xe=(t,e,n)=>{let s=t.get(e);return s===void 0&&(s=n(),t.size>32&&t.clear(),t.set(e,s)),s},Ye=t=>Number.isFinite(t)?t:0,ki=t=>({x:t.plane.x,y:t.plane.y,w:t.plane.x[1]-t.plane.x[0],h:t.plane.y[1]-t.plane.y[0]});function Mi(t,e){const n=hi(t.layers,t.seed??t.id),s=Array.from({length:t.layers[0]},(o,c)=>t.inputs?.[c]===void 0?.5:N(e,t.inputs[c])),i=di(n,s,t.activation??"sigmoid"),r=t.flow===void 0?t.layers.length-1:Math.min(t.layers.length-1,Math.max(0,Ye(N(e,t.flow))));return{network:n,activations:i,flow:r}}function za(t,e){const{plane:n,theme:s}=e,{network:i,activations:r,flow:o}=Mi(t,e.values),c=ki(e),[l,u]=t.size??[c.w*.75,c.h*.7],[h,d]=t.at??[(c.x[0]+c.x[1])/2,(c.y[0]+c.y[1])/2],f=(t.radius??16)*n.scale,y=t.layers,g=(w,v)=>{const k=h-l/2+(y.length===1?l/2:w/(y.length-1)*l),x=Math.min(u/Math.max(1,y[w]-1),u*.3),M=d+((y[w]-1)/2-v)*x;return n.toScreen([k,M])},p=C(s,"blue",s.colors.blue),a=C(s,"red",s.colors.red),m=[],b=Math.max(...i.weights.flat(2).map(Math.abs),1e-9);i.weights.forEach((w,v)=>{w.forEach((k,x)=>{k.forEach((M,A)=>{const E=g(v,A),_=g(v+1,x),T=Math.min(1,Math.max(0,o-v)),F=M>=0?p:a,R=(.6+3*(Math.abs(M)/b))*n.scale;for(const P of H([[E,_]],e.draw))m.push({type:"line",id:`${t.id}.w.${v}.${x}.${A}`,points:P,stroke:F,width:R,opacity:e.opacity*(.18+.5*T)});if(T>0&&T<1){const[P,O]=ne(E,_,T);m.push({type:"circle",id:`${t.id}.pulse.${v}.${x}.${A}`,x:P,y:O,r:f*.22,fill:C(s,"yellow",s.colors.yellow),opacity:e.opacity*(.5+.5*Math.abs(r[v][A]??0))})}})})}),y.forEach((w,v)=>{const k=Math.min(1,Math.max(0,o-v+1));for(let x=0;x<w;x++){const[M,A]=g(v,x),E=r[v][x]??0,_=t.activation==="relu"?Math.min(1,E/2):t.activation==="tanh"?(E+1)/2:E;m.push({type:"circle",id:`${t.id}.node.${v}.${x}`,x:M,y:A,r:f,fill:s.background,stroke:C(s,t.color,s.ink),width:2*n.scale,opacity:e.opacity*Math.min(1,e.draw*1.5)}),k>0&&m.push({type:"circle",id:`${t.id}.value.${v}.${x}`,x:M,y:A,r:f*.86,fill:de("viridis",_),opacity:e.opacity*k})}});const S=(w,v,k,x)=>m.push(...Z(W(w,{values:e.scope,style:"inline"}),{x:v[0],y:v[1],size:20*n.scale,color:s.ink,align:k,opacity:e.opacity*e.draw,idPrefix:`${t.id}.${x}.`}));return t.labels?.inputs?.forEach((w,v)=>{const[k,x]=g(0,v);S(w,[k-f*1.5,x],"right",`in${v}`)}),t.labels?.outputs?.forEach((w,v)=>{const[k,x]=g(y.length-1,v);S(w,[k+f*1.5,x],"left",`out${v}`)}),m}const qa=t=>{const e=Math.max(...t),n=t.map(i=>Math.exp(i-e)),s=n.reduce((i,r)=>i+r,0);return n.map(i=>i/s)};function ja(t,e){if(t.cells){const u=ki(e),[h,d]=t.size??[u.w*.7,u.h*.7],f=t.at??[(u.x[0]+u.x[1])/2-h/2,(u.y[0]+u.y[1])/2-d/2];return{cells:t.softmax?t.cells.map(qa):t.cells,box:[f,[f[0]+h,f[1]+d]]}}const[[n,s],[i,r]]=t.region??[e.plane.x,e.plane.y],o=t.resolution??48,c=fe(t.expr);return{cells:Array.from({length:o},(u,h)=>Array.from({length:o},(d,f)=>c(n+(f+.5)/o*(s-n),r-(h+.5)/o*(r-i),e.scope))),box:[[n,i],[s,r]]}}function Xa(t,e){const{plane:n,theme:s}=e,{cells:i,box:r}=ja(t,e),o=i.flat().filter(Number.isFinite),[c,l]=t.range??[Math.min(...o),Math.max(...o)],u=i.length,h=i[0]?.length??0,[[d,f],[y,g]]=r,p=(y-d)/h,a=(g-f)/u,m=[],b=t.colormap??"viridis",S=Math.ceil(u*e.draw);for(let v=0;v<S;v++)for(let k=0;k<h;k++){const x=i[v][k];if(!Number.isFinite(x))continue;const M=l===c?.5:(x-c)/(l-c),A=d+k*p,E=g-v*a,_=[[A,E-a],[A+p*1.01,E-a],[A+p*1.01,E+a*.01],[A,E+a*.01]].map(n.toScreen);if(m.push({type:"line",id:`${t.id}.${v}.${k}`,points:_,closed:!0,fill:Dn(de(b,M),s.background,e.opacity)}),t.values){const[T,F]=n.toScreen([A+p/2,E-a/2]),R=Math.min(16*n.scale,Math.abs(p*n.unitX)*.32);m.push({type:"text",id:`${t.id}.v.${v}.${k}`,text:x.toFixed(2).replace(/^0/,""),x:T,y:F+R*.35,size:R,font:At,color:M>.6?"#111":"#eee",align:"center",opacity:e.opacity})}}const w=Math.min(22*n.scale,Math.abs(a*n.unitY)*.6);return t.rowLabels?.forEach((v,k)=>{const[x,M]=n.toScreen([d,g-(k+.5)*a]);m.push(...Z(W(v,{style:"inline"}),{x:x-w*.5,y:M,size:w,color:s.ink,align:"right",opacity:e.opacity*e.draw,idPrefix:`${t.id}.row.${k}.`}))}),t.colLabels?.forEach((v,k)=>{const[x,M]=n.toScreen([d+(k+.5)*p,g]);m.push(...Z(W(v,{style:"inline"}),{x,y:M-w*.8,size:w,color:s.ink,opacity:e.opacity*e.draw,idPrefix:`${t.id}.col.${k}.`}))}),m}const Ya=new Map;function Ba(t,e){const n=t.region??[e.plane.x,e.plane.y],s=t.resolution??80,i=Object.entries(e.scope).filter(([l])=>!l.includes(".")),r=Xe(Ya,JSON.stringify([t.expr,t.levels,n,s,i]),()=>{const l=fe(t.expr),u=gi((p,a)=>l(p,a,e.scope),n[0],n[1],s),h=u.values.flat().filter(Number.isFinite),d=Math.min(...h),f=Math.max(...h),y=typeof t.levels=="number"?t.levels:10;return(Array.isArray(t.levels)?t.levels:Array.from({length:y},(p,a)=>d+(f-d)*(a+1)/(y+1))).map(p=>pi(u.values,u.x0,u.y0,u.dx,u.dy,p))}),o=[],c=t.colormap??"viridis";return r.forEach((l,u)=>{const h=t.color?C(e.theme,t.color,e.theme.ink):de(c,r.length===1?.6:.15+.85*u/(r.length-1));H(l.map(d=>d.map(e.plane.toScreen)),e.draw).forEach((d,f)=>{o.push({type:"line",id:`${t.id}.${u}.${f}`,points:d,stroke:h,width:(t.width??1.8)*e.plane.scale,opacity:e.opacity})})}),o}const Va=new Map;function $i(t,e,n){const s=Lt(e,t.start),i=N(e,t.rate),r=t.momentum===void 0?0:N(e,t.momentum),o=Math.min(500,Math.max(0,Ye(N(e,t.steps)))),c=Object.entries(n).filter(([f])=>!f.includes(".")),l=Xe(Va,JSON.stringify([t.expr,s,i,r,c]),()=>zn(t.expr,s,i,500,r,n)),u=Math.min(l.length-1,Math.floor(o)),h=u<l.length-1?o-u:0,d=h>0?ne(l[u],l[u+1],h):l[u];return{path:l.slice(0,u+1),here:d,step:u,diverged:l.length<501&&o>l.length-1}}function Ha(t,e){const{path:n,here:s}=$i(t,e.values,e.scope),i=C(e.theme,t.color,e.theme.colors.red),r=[...n,s].map(e.plane.toScreen),o=[];r.length>=2&&o.push({type:"line",id:`${t.id}.path`,points:r,stroke:i,width:(t.width??2.5)*e.plane.scale,opacity:e.opacity*.9}),n.forEach((u,h)=>{const[d,f]=e.plane.toScreen(u);o.push({type:"circle",id:`${t.id}.step.${h}`,x:d,y:f,r:3*e.plane.scale,fill:i,opacity:e.opacity*.8})});const[c,l]=e.plane.toScreen(s);return o.push({type:"circle",id:`${t.id}.ball`,x:c,y:l,r:8*e.plane.scale,fill:C(e.theme,"yellow",e.theme.colors.yellow),stroke:e.theme.background,width:2*e.plane.scale,opacity:e.opacity}),o}const Ua=new Map;function Si(t,e){const n=t.centres??[[-1.5,-1],[1.5,1]],s=Math.min(500,Math.max(0,Ye(N(e,t.epochs)))),[i,r,o]=t.start??[.9,-1.1,.8],{data:c,models:l}=Xe(Ua,JSON.stringify([n,t.count,t.spread,t.seed??t.id,t.rate,i,r,o]),()=>{const g=qn(n,t.count??40,t.spread??.9,t.seed??t.id);return{data:g,models:yi(g,500,t.rate??.5,{w:[i,r],b:o})}}),u=Math.floor(s),h=s-u,d=l[u],f=l[Math.min(l.length-1,u+1)],y={w:ne(d.w,f.w,h),b:d.b+(f.b-d.b)*h};return{data:c,model:y,epochs:s}}function Wa(t,e){const{plane:n,theme:s}=e,{data:i,model:r}=Si(t,e.values),o=[],c=[C(s,"blue",s.colors.blue),C(s,"orange",s.colors.orange)];if(t.probability!==!1){const[d,f]=n.x,[y,g]=n.y,p=(f-d)/32,a=(g-y)/32;for(let m=0;m<32;m++)for(let b=0;b<32;b++){const S=pe(r,[d+(b+.5)*p,y+(m+.5)*a]),w=[[d+b*p,y+m*a],[d+(b+1.02)*p,y+m*a],[d+(b+1.02)*p,y+(m+1.02)*a],[d+b*p,y+(m+1.02)*a]].map(n.toScreen);o.push({type:"line",id:`${t.id}.p.${m}.${b}`,points:w,closed:!0,fill:Dn(S>=.5?c[1]:c[0],s.background,e.opacity*Math.abs(S-.5)*.5)})}}i.forEach(({point:h,label:d},f)=>{const[y,g]=n.toScreen(h);o.push({type:"circle",id:`${t.id}.pt.${f}`,x:y,y:g,r:4.5*n.scale,fill:c[d],stroke:s.background,width:1*n.scale,opacity:e.opacity*e.draw})});const[l,u]=r.w;if(Math.hypot(l,u)>1e-6){const[h,d]=n.x,[f,y]=n.y,g=Math.abs(u)>Math.abs(l)?[[h,-(l*h+r.b)/u],[d,-(l*d+r.b)/u]]:[[-(u*f+r.b)/l,f],[-(u*y+r.b)/l,y]];o.push({type:"line",id:`${t.id}.boundary`,points:g.map(n.toScreen),stroke:s.ink,width:3*n.scale,opacity:e.opacity,dash:[12*n.scale,8*n.scale]})}return o}const Ga=new Map;function xi(t,e){const{points:n,history:s}=Xe(Ga,JSON.stringify([t.centres,t.count,t.spread,t.seed??t.id,t.k]),()=>{const l=qn(t.centres,t.count??30,t.spread??.7,t.seed??t.id).map(f=>f.point),u=t.k??t.centres.length,h=[l.reduce((f,y)=>f+y[0],0)/l.length,l.reduce((f,y)=>f+y[1],0)/l.length],d=[...l].sort((f,y)=>Math.hypot(f[0]-h[0],f[1]-h[1])-Math.hypot(y[0]-h[0],y[1]-h[1])).slice(0,u);return{points:l,history:vi(l,u,20,d)}}),i=Math.min(s.length-1,Math.max(0,Ye(N(e,t.iteration)))),r=Math.floor(i),o=i-r,c=s[r].map((l,u)=>ne(l,s[Math.min(s.length-1,r+1)][u],o));return{points:n,history:s,centroids:c,owners:je(n,s[r]),iteration:i,iterations:s.length-1}}function Za(t,e){const{plane:n,theme:s}=e,{points:i,centroids:r,owners:o,history:c,iteration:l}=xi(t,e.values),u=["blue","orange","green","pink","purple","teal"].map(d=>C(s,d,s.colors.blue)),h=[];return i.forEach((d,f)=>{const[y,g]=n.toScreen(d);h.push({type:"circle",id:`${t.id}.pt.${f}`,x:y,y:g,r:4.5*n.scale,fill:u[o[f]%u.length],opacity:e.opacity*e.draw*.85})}),r.forEach((d,f)=>{const y=c.slice(0,Math.floor(l)+1).map(m=>m[f]);y.push(d),y.length>=2&&h.push({type:"line",id:`${t.id}.trail.${f}`,points:y.map(n.toScreen),stroke:u[f%u.length],width:2*n.scale,opacity:e.opacity*.7,dash:[6*n.scale,5*n.scale]});const[g,p]=n.toScreen(d),a=11*n.scale;h.push({type:"line",id:`${t.id}.centroid.${f}`,points:[[g,p-a],[g+a,p],[g,p+a],[g-a,p]],closed:!0,fill:u[f%u.length],stroke:s.ink,width:2.5*n.scale,opacity:e.opacity})}),h}function Qa(t,e,n){switch(t.kind){case"network":{const{activations:s}=Mi(t,e);return Object.fromEntries(s[s.length-1].map((i,r)=>[`${t.id}.out${r}`,i]))}case"descent":{const{here:s,step:i}=$i(t,e,n);return{[`${t.id}.x`]:s[0],[`${t.id}.y`]:s[1],[`${t.id}.loss`]:fe(t.expr)(s[0],s[1],n),[`${t.id}.step`]:i}}case"classifier":{const{data:s,model:i,epochs:r}=Si(t,e);return{[`${t.id}.accuracy`]:mi(i,s),[`${t.id}.loss`]:bi(i,s),[`${t.id}.epoch`]:Math.floor(r)}}case"kmeans":{const{points:s,centroids:i,iteration:r,iterations:o}=xi(t,e);return{[`${t.id}.inertia`]:wi(s,i),[`${t.id}.iteration`]:Math.floor(r),[`${t.id}.iterations`]:o}}}}function Be(t,e,n,s=512){if(e===n)return 0;const i=(n-e)/s;let r=t(e)+t(n);for(let o=1;o<s;o++)r+=t(e+o*i)*(o%2?4:2);return r*i/3}function Ai(t,e,n,s,i){const r=(n-e)/s;return Array.from({length:s},(o,c)=>{const l=e+c*r,u=l+r;if(i==="trapezoid")return[l,u,t(l),t(u)];const h=t(i==="left"?l:i==="right"?u:(l+u)/2);return[l,u,h,h]})}const Ei=t=>Math.min(400,Math.max(1,Math.round(t)));function Ti(t,e,n){const s={},i={...n};for(const r of t)switch(r.kind){case"tangent":{const o=tt(r.expr),c=N(e,r.at),l=r.h===void 0?0:N(e,r.h),u=Math.abs(l)>1e-9?(o(c+l,i)-o(c,i))/l:Pe(r.expr,1)(c,i);Object.assign(s,{[`${r.id}.slope`]:u,[`${r.id}.x`]:c,[`${r.id}.y`]:o(c,i)});break}case"riemann":{const o=tt(r.expr),c=N(e,r.from),l=N(e,r.to),u=Ei(N(e,r.n)),d=Ai(f=>o(f,i),c,l,u,r.rule??"left").reduce((f,[y,g,p,a])=>f+(p+a)/2*(g-y),0);Object.assign(s,{[`${r.id}.sum`]:d,[`${r.id}.exact`]:Be(f=>o(f,i),c,l),[`${r.id}.n`]:u});break}case"area":{const o=tt(r.expr),c=r.lower?tt(r.lower):()=>0;s[`${r.id}.value`]=Be(l=>o(l,i)-c(l,i),N(e,r.from),N(e,r.to));break}case"point":if(r.on!==void 0&&r.x!==void 0){const o=N(e,r.x);Object.assign(s,{[`${r.id}.x`]:o,[`${r.id}.y`]:tt(r.on)(o,i)})}break;case"histogram":{const o=Tn(Rt(e,r.distribution),r.seed??r.id,Le(N(e,r.count))),{mean:c,sd:l}=Js(o);Object.assign(s,{[`${r.id}.count`]:o.length,[`${r.id}.mean`]:c,[`${r.id}.sd`]:l});break}case"distribution":{const o=Rt(e,r.distribution);let c=0;if(r.shade){const[l,u]=[N(e,r.shade[0]),N(e,r.shade[1])].sort((h,d)=>h-d);if(ce(o))for(let h=Math.max(0,Math.ceil(l));h<=Math.floor(u)&&h<=5e3;h++)c+=yt(o,h);else c=Be(h=>yt(o,h),l,u,2048)}Object.assign(s,{[`${r.id}.p`]:c,[`${r.id}.mean`]:zt(o),[`${r.id}.sd`]:qt(o)});break}case"galton":s[`${r.id}.landed`]=Math.max(0,Math.floor(N(e,r.balls)));break;case"scatter":{const o=On(ni(r,{values:e}),r.seed??r.id,Le(N(e,r.count))),c=r.inside?rt(r.inside):void 0,l=c?o.filter(([h,d])=>st(c,{...i,x:h,y:d})<=0).length:0,u=In(o);Object.assign(s,{[`${r.id}.count`]:o.length,[`${r.id}.inside`]:l,[`${r.id}.ratio`]:o.length?l/o.length:0,[`${r.id}.slope`]:u?.slope??0,[`${r.id}.intercept`]:u?.intercept??0,[`${r.id}.r`]:u?.r??0});break}case"bayes":{const o=N(e,r.prior),c=ti(o,N(e,r.truePositive),N(e,r.falsePositive));Object.assign(s,{[`${r.id}.prior`]:o,[`${r.id}.posterior`]:c.posterior,[`${r.id}.positive`]:c.positive,[`${r.id}.truePositive`]:c.truePositive,[`${r.id}.falsePositive`]:c.falsePositive});break}case"graph":{const o=ci(r,e);if(o&&(s[`${r.id}.visited`]=o.done,s[`${r.id}.steps`]=o.events.length,r.search?.kind==="dijkstra")){const c=o.events[o.done-1]?.distances??{};for(const l of r.nodes)s[`${r.id}.d.${l.id}`]=c[l.id]??1/0}break}case"clock":{const o=N(e,r.value);Object.assign(s,{[`${r.id}.hour`]:li(o,r.modulus),[`${r.id}.turns`]:Math.floor(Math.round(o)/r.modulus)});break}case"network":case"descent":case"classifier":case"kmeans":Object.assign(s,Qa(r,e,i));break;case"taylor":s[`${r.id}.order`]=Math.min(20,Math.max(0,N(e,r.order))),s[`${r.id}.degree`]=Math.floor(s[`${r.id}.order`]);break}return s}function Ka(t,e){const n=tt(t.expr),s=N(e.values,t.at),i=t.h===void 0?0:N(e.values,t.h),r=n(s,e.scope),o=e.scope[`${t.id}.slope`];if(!Number.isFinite(r)||!Number.isFinite(o))return[];const c=t.length!==void 0?t.length/2:Math.max(Math.abs(e.plane.x[0]-s),Math.abs(e.plane.x[1]-s)),l=[[s-c,r-o*c],[s+c,r+o*c]],u=C(e.theme,t.color,e.theme.colors.yellow),h=e.plane.toScreen([s,r]),d=l.map(e.plane.toScreen),f=[d[0],d[1]].flatMap((y,g)=>H([[h,y]],e.draw).map(p=>({type:"line",id:`${t.id}.${g}`,points:p,stroke:u,width:(t.width??3)*e.plane.scale,opacity:e.opacity})));if(t.points!==!1){const y=6*e.plane.scale;if(f.push({type:"circle",id:`${t.id}.point`,x:h[0],y:h[1],r:y,fill:u,opacity:e.opacity}),Math.abs(i)>1e-9){const[g,p]=e.plane.toScreen([s+i,n(s+i,e.scope)]);Number.isFinite(p)&&f.push({type:"circle",id:`${t.id}.secant`,x:g,y:p,r:y,fill:u,opacity:e.opacity})}}if(t.label&&e.draw>=1){const y=24*e.plane.scale,g=W(t.label,{values:e.scope,style:"inline"});f.push(...Z(g,{x:h[0],y:h[1]-y*1.6,size:y,color:u,opacity:e.opacity,idPrefix:`${t.id}.label.`}))}return f}function Ja(t,e){const n=tt(t.expr),s=N(e.values,t.from),i=N(e.values,t.to),r=Ei(N(e.values,t.n)),o=Ai(h=>n(h,e.scope),s,i,r,t.rule??"left"),c=C(e.theme,t.color,e.theme.colors.blue),l=Math.ceil(o.length*e.draw),u=Math.max(.5,Math.min(1.5,60/r))*e.plane.scale;return o.slice(0,l).flatMap(([h,d,f,y],g)=>{if(!Number.isFinite(f)||!Number.isFinite(y))return[];const p=[[h,0],[d,0],[d,y],[h,f]].map(e.plane.toScreen),m=(f+y)/2<0?C(e.theme,"red",e.theme.colors.red):c;return[{type:"line",id:`${t.id}.${g}`,points:p,closed:!0,fill:m,stroke:m,width:u,opacity:e.opacity*(t.fillOpacity??.35)}]})}function tc(t,e){const n=tt(t.expr),s=t.lower?tt(t.lower):()=>0,i=N(e.values,t.from),r=i+(N(e.values,t.to)-i)*e.draw;if(i===r)return[];const o=240,c=C(e.theme,t.color,e.theme.colors.blue),l=C(e.theme,t.negativeColor,e.theme.colors.red),u=e.opacity*(t.fillOpacity??.4),h=[];let d=[],f=[],y;const g=()=>{d.length>=2&&h.push({type:"line",id:`${t.id}.${h.length}`,points:[...d,...f.reverse()].map(e.plane.toScreen),closed:!0,fill:y?c:l,opacity:u}),d=[],f=[]};let p;for(let a=0;a<=o;a++){const m=i+(r-i)*a/o,b=n(m,e.scope),S=s(m,e.scope);if(!Number.isFinite(b)||!Number.isFinite(S)){g(),p=void 0;continue}const w=b-S>=0;if(p&&y!==void 0&&w!==y){const v=p.fy-p.gy,k=b-S,x=v/(v-k),M=p.x+(m-p.x)*x,A=p.gy+(S-p.gy)*x;d.push([M,A]),f.push([M,A]),g(),d.push([M,A]),f.push([M,A])}y=w,d.push([m,b]),f.push([m,S]),p={x:m,fy:b,gy:S}}return g(),h}const ec=Array.from({length:22},(t,e)=>e).map(t=>t===0?1:Array.from({length:t},(e,n)=>n+1).reduce((e,n)=>e*n,1));function nc(t,e){const n=N(e.values,t.at),s=e.scope[`${t.id}.order`],i=Math.floor(s),r=s-i,o=Array.from({length:Math.min(20,i+1)+1},(d,f)=>Pe(t.expr,f)(n,e.scope)/ec[f]),c=d=>{let f=0,y=1;for(let g=0;g<=i;g++)f+=o[g]*y,y*=d-n;return r>0&&i<20?f+r*o[i+1]*y:f},l=C(e.theme,t.color,e.theme.colors.yellow),[u,h]=t.domain??e.plane.x;return Ie(t.id,d=>c(d),u,h,l,(t.width??3.5)*e.plane.scale,e)}function sc(t,e){switch(t.kind){case"grid":return Qo(t,e);case"axes":return Ko(t,e);case"vector":return la(t,e);case"basis":return ua(t,e);case"point":return ha(t,e);case"function":return fa(t,e);case"parametric":return pa(t,e);case"polygon":return ya(t,e);case"line":return ma(t,e);case"label":return wa(t,e);case"equation":return ka(t,e);case"tangent":return Ka(t,e);case"riemann":return Ja(t,e);case"area":return tc(t,e);case"taylor":return nc(t,e);case"histogram":return Ma(t,e);case"distribution":return $a(t,e);case"galton":return Sa(t,e);case"scatter":return xa(t,e);case"bayes":return Aa(t,e);case"graph":return Ia(t,e);case"venn":return Na(t,e);case"clock":return Fa(t,e);case"network":return za(t,e);case"heatmap":return Xa(t,e);case"contours":return Ba(t,e);case"descent":return Ha(t,e);case"classifier":return Wa(t,e);case"kmeans":return Za(t,e)}}const _i=t=>Math.min(1,Math.max(0,t));function jt(t,e={}){const n=Se[t.theme??"dark"],s=fn(t),i={...t.values},r=new Map;for(const[h,d]of Object.entries(e))h.indexOf(".")<0?typeof d!="string"&&(i[h]=d):typeof d=="number"&&r.set(h,d);const o=_s(i),c={...o,...Ti(t.items,i,o)},l=[];for(const h of t.items){const d=g=>r.get(`${h.id}.${g}`),f=_i(d("draw")??h.draw??1),y=_i(d("opacity")??h.opacity??1);f<=0||y<=0||l.push(...sc(h,{plane:s,theme:n,values:i,scope:c,draw:f,opacity:y,prop:d}))}const u=t.background==="none"?void 0:t.background??n.background;return{width:t.width,height:t.height,...u?{background:u}:{},shapes:l}}const ic=new Set(["x","y","z","t","opacity","rotate","rotateX","rotateY","scale","scaleX","scaleY","skewX","skewY","originX","originY","perspective","width","height","fill","stroke","fillStyle","strokeStyle","lineWidth","strokeWidth","filter","blur","visible","clipTop","clipRight","clipBottom","clipLeft","quaternion"]);function _t(t){const e=a=>{throw new Error(`math figure: ${a}`)};(!t||typeof t!="object")&&e("expected a figure object"),(!(t.width>0)||!(t.height>0))&&e("width and height must be positive numbers (px)");for(const a of["x","y"]){const m=t[a];m!==void 0&&!(Array.isArray(m)&&m.length===2&&m.every(Number.isFinite)&&m[0]<m[1])&&e(`${a} must be [min, max] with min < max`)}t.theme!==void 0&&!(t.theme in Se)&&e(Y("theme",t.theme,Object.keys(Se))),Array.isArray(t.items)||e("items must be an array");const n=t.values??{};for(const[a,m]of Object.entries(n))/^[A-Za-z_]\w*$/.test(a)||e(`value name "${a}" must be letters, digits and _ (starting with a letter)`),ic.has(a)&&e(`"${a}" cannot name a value: it is ${a==="x"||a==="t"?"the variable of functions and curves":"a property of the figure itself (its place, size or look)"}`),typeof m=="number"&&Number.isFinite(m)||lt(m)||Ft(m)||e(`value "${a}" must be a number, an [x, y] vector or an [a, b, c, d] matrix`);const s=_s(n),i=Object.keys(n).filter(a=>typeof n[a]=="number"),r=(a,m,b)=>{b!==void 0&&(typeof b=="string"?(b in n||e(`${a.id}.${m}: ${Y("value",b,Object.keys(n))}`),lt(n[b])||e(`${a.id}.${m}: value "${b}" is not an [x, y] vector`)):lt(b)||e(`${a.id}.${m} must be [x, y] or the name of a vector value`))},o=(a,m,b)=>{b!==void 0&&(b in n||e(`${a.id}.${m}: ${Y("value",b,Object.keys(n))}`),Ft(n[b])||e(`${a.id}.${m}: value "${b}" is not an [a, b, c, d] matrix`))},c=(a,m,b,S)=>{let w=[];try{w=$n(rt(b))}catch(v){e(`${a.id}.${m}: ${v.message}`)}for(const v of w)v!==S&&!(v in ie)&&!i.includes(v)&&e(`${a.id}.${m}: "${v}" is neither ${S} nor a number value (${Y("value",v,[S,...i])})`)},l=[],u=(a,m,b)=>{l.push([a,m,b])},h=(a,m,b)=>{b!==void 0&&(typeof b=="string"?(b in n||e(`${a.id}.${m}: ${Y("value",b,i)}`),typeof n[b]!="number"&&e(`${a.id}.${m}: value "${b}" is not a number`)):Number.isFinite(b)||e(`${a.id}.${m} must be a number or the name of a number value`))},d=(a,m,b)=>{(!b||typeof b!="object"||!ae.includes(b.kind))&&e(`${a.id}.${m}: ${Y("distribution",b?.kind,ae)}`);for(const[w,v]of Object.entries(b))w!=="kind"&&(w==="of"?d(a,`${m}.of`,v):h(a,`${m}.${w}`,v));const S=_n(Rt(n,b));S&&e(`${a.id}.${m}: ${S}`)},f=(a,m,b)=>{let S=[];try{S=$n(rt(b))}catch(w){e(`${a.id}.${m}: ${w.message}`)}for(const w of S)w!=="x"&&w!=="y"&&!i.includes(w)&&e(`${a.id}.${m}: "${w}" is neither x, y nor a number value`)},y=(a,m,b,S)=>{try{let w=rt(b);for(let v=0;v<S;v++)w=J(w)}catch(w){e(`${a.id}.${m}: ${w.message} (calculus needs functions with derivatives)`)}},g=new Set;for(const a of t.items)switch((!a||typeof a!="object")&&e("every item must be an object"),un.includes(a.kind)||e(Y("item kind",a.kind,un)),(typeof a.id!="string"||!/^[A-Za-z_][\w-]*$/.test(a.id))&&e(`a ${a.kind} needs an id (letters, digits, _ and -)`),g.has(a.id)&&e(`two items have the id "${a.id}"`),a.id in n&&e(`"${a.id}" is both an item id and a value name`),g.add(a.id),a.kind){case"grid":a.step!==void 0&&!(a.step>0)&&e(`${a.id}.step must be positive`),o(a,"transform",a.transform);break;case"vector":r(a,"to",a.to),r(a,"from",a.from),o(a,"transform",a.transform),a.label&&u(a,"label",a.label);break;case"basis":o(a,"transform",a.transform);break;case"point":a.at===void 0==(a.on===void 0)&&e(`${a.id} needs at, or on with x (a point on a curve)`),a.on!==void 0&&(a.x===void 0&&e(`${a.id}: a point on a curve needs x`),c(a,"on",a.on,"x"),h(a,"x",a.x)),r(a,"at",a.at),o(a,"transform",a.transform),a.label&&u(a,"label",a.label);break;case"function":c(a,"expr",a.expr,"x"),a.derivative!==void 0&&((!Number.isInteger(a.derivative)||a.derivative<0||a.derivative>8)&&e(`${a.id}.derivative must be a whole number from 0 to 8`),y(a,"expr",a.expr,a.derivative));break;case"tangent":c(a,"expr",a.expr,"x"),y(a,"expr",a.expr,1),h(a,"at",a.at),h(a,"h",a.h),a.label&&u(a,"label",a.label);break;case"riemann":c(a,"expr",a.expr,"x"),h(a,"from",a.from),h(a,"to",a.to),h(a,"n",a.n),a.rule!==void 0&&!["left","right","midpoint","trapezoid"].includes(a.rule)&&e(`${a.id}.rule: ${Y("rule",a.rule,["left","right","midpoint","trapezoid"])}`);break;case"area":c(a,"expr",a.expr,"x"),a.lower!==void 0&&c(a,"lower",a.lower,"x"),h(a,"from",a.from),h(a,"to",a.to);break;case"histogram":d(a,"distribution",a.distribution),h(a,"count",a.count),a.bins!==void 0&&!(Array.isArray(a.bins)&&a.bins.length===3&&a.bins[1]>a.bins[0]&&Number.isInteger(a.bins[2])&&a.bins[2]>=1&&a.bins[2]<=500)&&e(`${a.id}.bins must be [from, to, count] with from < to and a whole count 1..500`);break;case"distribution":d(a,"distribution",a.distribution),a.shade&&a.shade.forEach((m,b)=>h(a,`shade[${b}]`,m));break;case"galton":a.rows!==void 0&&!(Number.isInteger(a.rows)&&a.rows>=1&&a.rows<=30)&&e(`${a.id}.rows must be a whole number 1..30`),h(a,"balls",a.balls);break;case"scatter":(!a.points||!["uniform","linear"].includes(a.points.kind))&&e(`${a.id}.points: ${Y("points kind",a.points?.kind,["uniform","linear"])}`),a.points.kind==="linear"&&(h(a,"points.slope",a.points.slope),h(a,"points.intercept",a.points.intercept),h(a,"points.noise",a.points.noise)),h(a,"count",a.count),a.inside&&f(a,"inside",a.inside);break;case"bayes":h(a,"prior",a.prior),h(a,"truePositive",a.truePositive),h(a,"falsePositive",a.falsePositive);break;case"graph":{(!Array.isArray(a.nodes)||a.nodes.length===0)&&e(`${a.id}.nodes needs at least one node`);const m=a.nodes.map(v=>v.id);new Set(m).size!==m.length&&e(`${a.id}: two nodes share an id`);const b=(v,k)=>{m.includes(k)||e(`${a.id}.${v}: ${Y("node",k,m)}`)};Array.isArray(a.edges)||e(`${a.id}.edges must be an array`),ze(a).forEach((v,k)=>{b(`edges[${k}]`,v.from),b(`edges[${k}]`,v.to),v.weight!==void 0&&!(v.weight>=0)&&e(`${a.id}.edges[${k}]: weights must be ≥ 0 (shortest paths need them)`)}),a.tree&&b("tree.root",a.tree.root);const S=ai(a),w=m.filter(v=>!S.has(v));w.length&&e(`${a.id}: nodes ${w.join(", ")} have no "at" and are not reached from the tree root`),a.search&&(Fn.includes(a.search.kind)||e(`${a.id}.search: ${Y("search",a.search.kind,Fn)}`),b("search.start",a.search.start)),h(a,"step",a.step),a.nodes.forEach(v=>v.label!==void 0&&u(a,`nodes.${v.id}.label`,v.label));break}case"venn":{(!Array.isArray(a.sets)||a.sets.length<2||a.sets.length>3)&&e(`${a.id}.sets: give two or three sets`);const m=a.sets.map(b=>b.id);if(m.every(b=>/^[A-Za-z]\w*$/.test(b))||e(`${a.id}.sets: ids must be names like A, B, Evens`),a.highlight)try{for(const b of le(Ln(a.highlight)))m.includes(b)||e(`${a.id}.highlight: ${Y("set",b,m)}`)}catch(b){e(`${a.id}.highlight: ${b.message}`)}a.sets.forEach(b=>b.label!==void 0&&u(a,`sets.${b.id}.label`,b.label));break}case"network":(!Array.isArray(a.layers)||a.layers.length<2||a.layers.length>8||!a.layers.every(m=>Number.isInteger(m)&&m>=1&&m<=12))&&e(`${a.id}.layers: give 2 to 8 layers of 1 to 12 nodes, like [3, 4, 2]`),a.activation!==void 0&&!Rn.includes(a.activation)&&e(`${a.id}.activation: ${Y("activation",a.activation,Rn)}`),a.inputs&&a.inputs.length>a.layers[0]&&e(`${a.id}.inputs: more inputs than the ${a.layers[0]} input nodes`),a.inputs?.forEach((m,b)=>h(a,`inputs[${b}]`,m)),h(a,"flow",a.flow),a.labels?.inputs?.forEach((m,b)=>u(a,`labels.inputs[${b}]`,m)),a.labels?.outputs?.forEach((m,b)=>u(a,`labels.outputs[${b}]`,m));break;case"heatmap":a.cells===void 0==(a.expr===void 0)&&e(`${a.id} needs exactly one of cells or expr`),a.cells&&!(Array.isArray(a.cells)&&a.cells.length>=1&&a.cells.length<=64&&a.cells.every(m=>Array.isArray(m)&&m.length===a.cells[0].length&&m.length<=64&&m.every(Number.isFinite)))&&e(`${a.id}.cells must be up to 64 equal rows of up to 64 numbers`),a.expr&&f(a,"expr",a.expr),a.resolution!==void 0&&!(Number.isInteger(a.resolution)&&a.resolution>=4&&a.resolution<=120)&&e(`${a.id}.resolution must be 4..120`),a.colormap!==void 0&&!he.includes(a.colormap)&&e(`${a.id}.colormap: ${Y("colormap",a.colormap,he)}`),a.rowLabels?.forEach((m,b)=>u(a,`rowLabels[${b}]`,m)),a.colLabels?.forEach((m,b)=>u(a,`colLabels[${b}]`,m));break;case"contours":f(a,"expr",a.expr),a.colormap!==void 0&&!he.includes(a.colormap)&&e(`${a.id}.colormap: ${Y("colormap",a.colormap,he)}`),a.resolution!==void 0&&!(Number.isInteger(a.resolution)&&a.resolution>=8&&a.resolution<=200)&&e(`${a.id}.resolution must be 8..200`);break;case"descent":f(a,"expr",a.expr);for(const m of["x","y"])try{J(rt(a.expr),m)}catch(b){e(`${a.id}.expr: ${b.message} (descent needs a gradient)`)}r(a,"start",a.start),h(a,"rate",a.rate),h(a,"steps",a.steps),h(a,"momentum",a.momentum);break;case"classifier":h(a,"epochs",a.epochs),a.count!==void 0&&!(Number.isInteger(a.count)&&a.count>=1&&a.count<=500)&&e(`${a.id}.count must be 1..500 points per cluster`),a.centres!==void 0&&!(a.centres.length===2&&a.centres.every(lt))&&e(`${a.id}.centres must be two [x, y] points`);break;case"kmeans":(!Array.isArray(a.centres)||a.centres.length<1||a.centres.length>6||!a.centres.every(lt))&&e(`${a.id}.centres: give 1 to 6 [x, y] cluster centres`),a.k!==void 0&&!(Number.isInteger(a.k)&&a.k>=1&&a.k<=6)&&e(`${a.id}.k must be 1..6`),h(a,"iteration",a.iteration);break;case"clock":(!Number.isInteger(a.modulus)||a.modulus<2||a.modulus>60)&&e(`${a.id}.modulus must be a whole number 2..60`),h(a,"value",a.value);break;case"taylor":c(a,"expr",a.expr,"x"),y(a,"expr",a.expr,3),h(a,"at",a.at),h(a,"order",a.order);break;case"parametric":c(a,"x",a.x,"t"),c(a,"y",a.y,"t"),o(a,"transform",a.transform);break;case"polygon":a.points!==void 0&&!(Array.isArray(a.points)&&a.points.length>=3&&a.points.every(lt))&&e(`${a.id}.points must be three or more [x, y] points`),o(a,"transform",a.transform),a.label&&u(a,"label",a.label);break;case"line":a.along===void 0==(a.eigen===void 0)&&e(`${a.id} needs exactly one of along or eigen`),r(a,"along",a.along),o(a,"eigen",a.eigen);break;case"label":r(a,"at",a.at),u(a,"tex",a.tex);break;case"equation":r(a,"at",a.at),(!Array.isArray(a.steps)||a.steps.length===0)&&e(`${a.id}.steps needs at least one TeX step`),a.steps.forEach((m,b)=>u(a,`steps[${b}]`,m));break}const p={...s,...Ti(t.items,n,s)};for(const[a,m,b]of l)try{W(b,{values:p})}catch(S){e(`${a.id}.${m}: ${S.message}`)}return t}function Pi(t,e){if(t.length<2)return{shaft:t,head:void 0};const n=t[t.length-1],s=t[t.length-2],i=n[0]-s[0],r=n[1]-s[1],o=Math.hypot(i,r);if(o===0||e<=0)return{shaft:t,head:void 0};const c=i/o,l=r/o,u=Math.min(e,o),h=[n[0]-c*u,n[1]-l*u],d=u*.55;return{shaft:[...t.slice(0,-1),h],head:[n,[h[0]-l*d,h[1]+c*d],[h[0]+l*d,h[1]-c*d]]}}const V=t=>String(Math.round(t*100)/100),at=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),ge=(t,e=!1)=>t.map(([n,s],i)=>`${i?"L":"M"}${V(n)} ${V(s)}`).join("")+(e?"Z":""),Ve=t=>t.opacity!==void 0&&t.opacity<1?` opacity="${V(t.opacity)}"`:"";function Oi(t){switch(t.type){case"line":{if(t.points.length<2)return"";if(t.clip?.length){const i=t.clip.map(({points:o,outside:c})=>{const l=c?`M-1000000 -1000000H1000000V1000000H-1000000Z${ge(o,!0)}`:ge(o,!0),u=`tfclip${$t(`${c?"o":"i"}${l}`).toString(36)}`;return{id:u,def:`<clipPath id="${u}"><path d="${l}"${c?' clip-rule="evenodd"':""}/></clipPath>`}}),r=Oi({...t,clip:void 0});return`<defs>${i.map(o=>o.def).join("")}</defs>`+i.reduceRight((o,c)=>`<g clip-path="url(#${c.id})">${o}</g>`,r)}const e=t.fill?` fill="${at(t.fill)}"`:' fill="none"',n=t.stroke&&(t.width??1)>0?` stroke="${at(t.stroke)}" stroke-width="${V(t.width??1)}"`:"",s=t.dash?.length?` stroke-dasharray="${t.dash.map(V).join(" ")}"`:"";return`<path d="${ge(t.points,t.closed)}"${e}${n}${s}${Ve(t)}/>`}case"arrow":{const{shaft:e,head:n}=Pi(t.points,t.head),s=at(t.stroke),i=e.length>=2?`<path d="${ge(e)}" fill="none" stroke="${s}" stroke-width="${V(t.width)}"/>`:"",r=n?`<path d="${ge(n,!0)}" fill="${s}"/>`:"";return`<g${Ve(t)}>${i}${r}</g>`}case"circle":{const e=t.fill?` fill="${at(t.fill)}"`:' fill="none"',n=t.stroke?` stroke="${at(t.stroke)}" stroke-width="${V(t.width??1)}"`:"";return`<circle cx="${V(t.x)}" cy="${V(t.y)}" r="${V(t.r)}"${e}${n}${Ve(t)}/>`}case"text":{const e=t.align==="center"?"middle":t.align==="right"?"end":"start",n=t.italic?' font-style="italic"':"";return`<text x="${V(t.x)}" y="${V(t.y)}" font-size="${V(t.size)}" font-family="${at(t.font)}"${n} text-anchor="${e}" fill="${at(t.color)}"${Ve(t)}>${at(t.text)}</text>`}}}function He(t){return`${t.background?`<rect width="${V(t.width)}" height="${V(t.height)}" fill="${at(t.background)}"/>`:""}<g stroke-linecap="round" stroke-linejoin="round">${t.shapes.map(Oi).join("")}</g>`}function Ii(t,e={}){const n=e.title?`<title>${at(e.title)}</title>`:"",s=e.title?` role="img" aria-label="${at(e.title)}"`:"";return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${V(t.width)} ${V(t.height)}" width="${V(t.width)}" height="${V(t.height)}"${s}>${n}${He(t)}</svg>`}const rc="http://www.w3.org/2000/svg",jn=new WeakMap;function oc(t,e){const n=t?.values.get(e);return n?Object.fromEntries(n):{}}async function Ci(t,e={}){const n=jn.get(t);if(n)return n;const s=t.querySelector("script[data-tinyfly-figure]");let i;try{i=_t(JSON.parse(s?.textContent??"null"))}catch(f){console.warn("tinyfly: math figure is missing or invalid",t,f);return}const r=t.getAttribute("data-target")??"fig";let o=t.querySelector("svg[data-tinyfly-math-svg]");o||(o=t.ownerDocument.createElementNS(rc,"svg"),o.setAttribute("data-tinyfly-math-svg",""),o.setAttribute("viewBox",`0 0 ${i.width} ${i.height}`),o.setAttribute("style","display:block;width:100%;height:auto"),t.insertBefore(o,t.querySelector("figcaption")));const c=f=>{o.innerHTML=He(jt(i,f))};if(c({}),!(t.querySelector("script[data-tinyfly-timeline]")||t.hasAttribute("data-src"))){const f={element:t,figure:i,redraw:()=>c({})};return jn.set(t,f),f}const u=await Lo(t,e);if(!u)return;const h=()=>c(oc(u.player.state,r));u.player.subscribe(h),h();const d={...u,figure:i,redraw:h};return jn.set(t,d),d}async function Ni(t=document,e={}){const n=Array.from(t.querySelectorAll("[data-tinyfly-math]"));return(await Promise.all(n.map(i=>Ci(i,e)))).filter(i=>i!==void 0)}function ac(){if(!(typeof document<"u"?document.currentScript:null)?.hasAttribute("data-tinyfly-auto"))return;const e=()=>{Ni()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}function cc(t){const e=t.id??"loss",[[n,s],[i,r]]=t.region??[[-3,3],[-3,3]],o=Math.max(4,Math.min(120,Math.round(t.resolution??36))),c=5,l=fe(t.expr),u=t.scope??{},h=(O,I)=>l(O,I,u),d=Array.from({length:o+1},(O,I)=>Array.from({length:o+1},(L,D)=>h(n+(s-n)*D/o,i+(r-i)*I/o))),f=d.flat().filter(Number.isFinite),y=Math.min(...f),g=Math.max(...f),p=t.height??1.6,a=O=>g===y?0:(Math.min(g,Math.max(y,O))-y)/(g-y),m=(O,I,L,D=0)=>[((O-n)/(s-n)-.5)*c,a(L)*p+D,-((I-i)/(r-i)-.5)*c],b=[],S=[];for(let O=0;O<=o;O++)for(let I=0;I<=o;I++){const L=d[O][I];b.push(...m(n+(s-n)*I/o,i+(r-i)*O/o,Number.isFinite(L)?L:g)),S.push(de(t.colormap??"viridis",a(L)))}const w=[];for(let O=0;O<o;O++)for(let I=0;I<o;I++){const L=O*(o+1)+I,D=L+1,z=L+o+1,q=z+1;w.push(L,D,z,D,q,z)}const v=Math.max(1,Math.round(t.steps??40)),k=zn(t.expr,t.start,t.rate,v,t.momentum??0,u),x=k.map(([O,I])=>h(O,I)),M=.09,A=k.map(([O,I],L)=>m(O,I,x[L],.06)),E=t.stepDuration??250,_=600,T=_+(k.length-1)*E+800,F=[{id:"rig",kind:"group",rotation:[0,0,0]},{id:"cam",kind:"camera",parent:"rig",projection:"perspective",fov:40,near:.1,far:60,position:[0,p+3.6,6.4],lookAt:[0,p*.25,0]},{id:"sky",kind:"light",light:"ambient",color:"#ffffff",intensity:.45},{id:"sun",kind:"light",light:"directional",color:"#ffffff",intensity:.85,position:[3,6,4]},{id:"surface",kind:"mesh",material:"surface",geometry:{type:"mesh",positions:b,indices:w,colors:S}},...k.slice(1).map(([O,I],L)=>{const[D,z]=k[L],q=Array.from({length:10},(U,ct)=>{const wt=ct/9,mt=D+(O-D)*wt,ft=z+(I-z)*wt;return m(mt,ft,h(mt,ft),.06)});return{id:`path${L}`,kind:"line",points:q,color:"#fc6255",width:.05,visible:!1}}),{id:"ball",kind:"mesh",material:"ball",position:[A[0][0],A[0][1]+M,A[0][2]],geometry:{type:"sphere",radius:M,segments:16}}],R=[{id:`${e}-ball`,target:`${e}/ball`,property:"position",keyframes:k.flatMap(([O,I],L)=>{if(L===0)return[{time:_,value:[A[0][0],A[0][1]+M,A[0][2]]}];const[D,z]=k[L-1];return[1,2,3,4].map(q=>{const U=D+(O-D)*q/4,ct=z+(I-z)*q/4,[wt,mt,ft]=m(U,ct,h(U,ct),.06);return{time:_+(L-1+q/4)*E,value:[wt,mt+M,ft]}})})},...A.slice(1).map((O,I)=>({id:`${e}-path${I}`,target:`${e}/path${I}`,property:"visible",keyframes:[{time:0,value:0},{time:_+(I+1)*E-1,value:0},{time:_+(I+1)*E,value:1}]}))],P=t.orbit??50;return P!==0&&R.push({id:`${e}-orbit`,target:`${e}/rig`,property:"rotateY",keyframes:[{time:0,value:-P/2},{time:T,value:P/2,easing:"ease-in-out"}]}),{scene:{id:e,camera:"cam",background:t.background??"#0f1117",materials:{surface:{color:"#ffffff",shading:"lambert",doubleSided:!0,creases:!1},ball:{color:"#ffd75e",shading:"toon",outline:{width:2,color:"#0f1117"}}},objects:F},tracks:R,duration:T,path:k,losses:x}}function Ue(t,e,n=!1){t.beginPath(),e.forEach(([s,i],r)=>r===0?t.moveTo(s,i):t.lineTo(s,i)),n&&t.closePath()}function Fi(t,e){switch(t.globalAlpha=e.opacity??1,e.type){case"line":if(e.points.length<2)return;if(e.clip?.length){t.save();for(const{points:n,outside:s}of e.clip)Ue(t,n,!0),s?(t.rect(-1e6,-1e6,2e6,2e6),t.clip("evenodd")):t.clip();Fi(t,{...e,clip:void 0}),t.restore();return}Ue(t,e.points,e.closed),e.fill&&(t.fillStyle=e.fill,t.fill()),e.stroke&&(e.width??1)>0&&(t.strokeStyle=e.stroke,t.lineWidth=e.width??1,t.setLineDash(e.dash??[]),t.stroke(),t.setLineDash([]));return;case"arrow":{const{shaft:n,head:s}=Pi(e.points,e.head);t.strokeStyle=e.stroke,t.fillStyle=e.stroke,t.lineWidth=e.width,n.length>=2&&(Ue(t,n),t.stroke()),s&&(Ue(t,s,!0),t.fill());return}case"circle":t.beginPath(),t.arc(e.x,e.y,e.r,0,Math.PI*2),e.fill&&(t.fillStyle=e.fill,t.fill()),e.stroke&&(t.strokeStyle=e.stroke,t.lineWidth=e.width??1,t.stroke());return;case"text":t.font=`${e.italic?"italic ":""}${e.size}px ${e.font}`,t.textAlign=e.align,t.textBaseline="alphabetic",t.fillStyle=e.color,t.fillText(e.text,e.x,e.y)}}function Li(t,e){t.save(),t.beginPath(),t.rect(0,0,e.width,e.height),t.clip(),e.background&&(t.fillStyle=e.background,t.fillRect(0,0,e.width,e.height)),t.lineCap="round",t.lineJoin="round";for(const n of e.shapes)Fi(t,n);t.restore()}function Ri(t){const e={};for(const[n,s]of Object.entries(t.values??{})){const i=typeof s=="number"?"number":s.length===2?"[x, y] vector":"[a, b, c, d] matrix";e[n]={description:`The value ${n} (a ${i})`,kind:typeof s=="number"?"number":"list"}}for(const n of t.items)e[`${n.id}.draw`]={description:`How much of the ${n.kind} "${n.id}" is drawn`,unit:"0..1",min:0,max:1},e[`${n.id}.opacity`]={description:`Opacity of the ${n.kind} "${n.id}"`,unit:"0..1",min:0,max:1},n.kind==="equation"&&(e[`${n.id}.step`]={description:`Which step of "${n.id}" shows; in between, terms glide`,unit:"step",min:0,max:n.steps.length-1});return e}function Di(t,e={}){_t(t);const n=Ri(t),s={...t.values??{}};return{type:"custom",x:e.x??0,y:e.y??0,width:t.width,height:t.height,props:s,acceptsProp:i=>Object.prototype.hasOwnProperty.call(n,i),draw(i,r){Li(i,jt(t,r.props??{}))},about:{kind:"math figure",summary:`A ${t.width}×${t.height} maths figure with ${t.items.map(i=>`${i.kind} "${i.id}"`).join(", ")}. Animate its values by name and each item's draw / opacity (an equation's step).`,props:n}}}function lc(t,e,n,s={}){const i=new Set(n.items.map(l=>l.id)),r=l=>{if(!i.has(l))throw new Error(`mathSteps: no item "${l}" (items: ${[...i].join(", ")})`)},o={...n.values??{}};for(const l of n.items)o[`${l.id}.draw`]=l.draw??1,o[`${l.id}.opacity`]=l.opacity??1,l.kind==="equation"&&(o[`${l.id}.step`]=l.step??0);for(const l of s.hidden??[])r(l),o[`${l}.draw`]=0;t.initial(e,o);const c={toValue(l,u,h){if(!(l in o))throw new Error(`mathSteps: no value "${l}" (values: ${Object.keys(n.values??{}).join(", ")})`);return t.to(e,{[l]:u},{duration:1200,...h}),c},applyMatrix(l,u={}){const{name:h="M",...d}=u;if(l.length!==4||!l.every(Number.isFinite))throw new Error("mathSteps.applyMatrix: expected [a, b, c, d]");return c.toValue(h,l,{duration:1600,...d})},drawOn(l,u){return r(l),t.to(e,{[`${l}.draw`]:1},{duration:900,...u}),c},fadeIn(l,u){return r(l),t.set(e,{[`${l}.draw`]:1,[`${l}.opacity`]:0}),t.to(e,{[`${l}.opacity`]:1},{duration:500,...u}),c},fadeOut(l,u){return r(l),t.to(e,{[`${l}.opacity`]:0},{duration:500,...u}),c},showStep(l,u,h){return r(l),t.to(e,{[`${l}.step`]:u},{duration:900,...h}),c}};return c}const Xt={kind:"math",create:"mathSurface(figure, { x, y })",anchors:{box:"the whole figure","item:ID":"everything an item draws","tip:ID":"the tip of a vector (tip:basis.i, tip:basis.j for î and ĵ)","point:ID":"a point (also a point riding a curve)","node:GRAPH:NODE":"a node of a graph item","term:ID:TEXT":"glyphs of an equation or label, matched by their text (term:eq:2x, term:eq#2:x for the second)","value:NAME":"a value of the figure (for the set edit; the box is the whole figure)"},edits:{drawOn:"item:ID — draws the item on (default 900 ms)",erase:"item:ID — undraws it (default 600 ms)",show:"item:ID — fades it in (default 500 ms)",hide:"item:ID — fades it out (default 500 ms)",step:"item:ID of an equation, { to } — moves to that step, terms gliding (default 900 ms)",set:"value:NAME, { value } — tweens a value: a number, [x, y] or [a, b, c, d] (default 1200 ms)"}},uc=(t,e,n)=>typeof t=="number"&&typeof e=="number"?t+(e-t)*n:Array.isArray(t)&&Array.isArray(e)?t.map((s,i)=>s+((e[i]??s)-s)*n):n<1?t:e;function hc(t,e){const n=[...t].sort((s,i)=>s.time-i.time);if(e<=n[0].time)return n[0].value;for(let s=1;s<n.length;s++)if(e<=n[s].time){const i=n[s-1],r=n[s];return r.time===i.time?r.value:uc(i.value,r.value,(e-i.time)/(r.time-i.time))}return n[n.length-1].value}function dc(t){let e=1/0,n=1/0,s=-1/0,i=-1/0;const r=(o,c)=>{e=Math.min(e,o),s=Math.max(s,o),n=Math.min(n,c),i=Math.max(i,c)};for(const o of t)if(o.type==="line"||o.type==="arrow")o.points.forEach(([c,l])=>r(c,l));else if(o.type==="circle")r(o.x-o.r,o.y-o.r),r(o.x+o.r,o.y+o.r);else{const c=o.size*.55*o.text.length,l=o.align==="center"?o.x-c/2:o.align==="right"?o.x-c:o.x;r(l,o.y-o.size*.75),r(l+c,o.y+o.size*.25)}return Number.isFinite(e)?{left:e,top:n,right:s,bottom:i}:void 0}const Xn=t=>t.replace(/\s+/g,"").replace(/-/g,"−").replace(/\*/g,"∗");function fc(t,e={}){_t(t);const n=e.x??0,s=e.y??0,i=Di(t,{x:n,y:s}),r=new Map,o=t.items.map(p=>p.id),c=p=>({left:n+p.left,top:s+p.top,right:n+p.right,bottom:s+p.bottom,width:p.right-p.left,height:p.bottom-p.top,x:n+(p.left+p.right)/2,y:s+(p.top+p.bottom)/2}),l=c({left:0,top:0,right:t.width,bottom:t.height}),u=p=>{if(!p.includes(".")){const S=t.values?.[p];if(S===void 0)throw new Error(`mathSurface: ${Y("value",p,Object.keys(t.values??{}))}`);return S}const[a,m]=p.split("."),b=t.items.find(S=>S.id===a);return m==="step"?b.kind==="equation"?b.step??0:0:b[m]??1},h=(p,a)=>{const m=r.get(p);return m?.length?hc(m,a):u(p)},d=(p,a,m,b)=>{const S=h(p,m.at);r.set(p,[...r.get(p)??[],{time:m.at,value:S},{time:m.at+(m.duration??b),value:a,...m.easing?{easing:m.easing}:{}}])},f=p=>{const a={};for(const m of r.keys())a[m]=h(m,p);return a},y=(p,a)=>{const m=a.split(":")[0].split("#")[0].split(".")[0];if(!o.includes(m))throw new Error(`mathSurface: ${p}: ${Y("item",m,o)}`);return m},g={kind:"math",target:i,box:l,about:Xt,anchor(p,a=1/0){const m=p.indexOf(":"),b=m<0?p:p.slice(0,m),S=m<0?"":p.slice(m+1);if(b==="box"||b==="value")return l;if(!["item","tip","point","node","term"].includes(b))throw new Error(`mathSurface: ${Y("anchor",b,Object.keys(Xt.anchors).map(M=>M.split(":")[0]))}`);const w=jt(t,f(a)).shapes,v=M=>w.filter(A=>A.id===M||A.id.startsWith(`${M}.`));let k=[];if(b==="item")k=v(y(p,S));else if(b==="tip"){y(p,S);const M=w.find(T=>T.type==="arrow"&&(T.id===S||T.id===`${S}.0`));if(!M||M.type!=="arrow")throw new Error(`mathSurface: no vector at "${p}" (a vector item id, or basis.i / basis.j)`);const[A,E]=M.points[M.points.length-1],_=M.width*2.5;return c({left:A-_,top:E-_,right:A+_,bottom:E+_})}else if(b==="point")k=w.filter(M=>M.id===y(p,S)&&M.type==="circle");else if(b==="node"){const[M,A]=S.split(":");y(p,M),k=w.filter(E=>E.id===`${M}.node.${A}`)}else{const M=/^([^:#]+)(?:#(\d+))?:(.+)$/.exec(S);if(!M)throw new Error(`mathSurface: "${p}" should be term:ID:TEXT`);const[,A,E,_]=M;y(p,A);const T=v(A).filter(I=>I.type==="text"&&!I.id.includes(".backdrop")),F=Xn(_),R=T.map(I=>Xn(I.text)).join("");let P=-1;for(let I=0,L=0;I<Number(E??1)&&(P=R.indexOf(F,L),!(P<0));I++,L=P+1);if(P<0)throw new Error(`mathSurface: no "${_}" in ${A} (it reads "${R}")`);let O=0;k=T.filter(I=>{const L=Xn(I.text).length,D=O<P+F.length&&O+L>P;return O+=L,D})}const x=dc(k);if(!x)throw new Error(`mathSurface: "${p}" is not drawn at ${a===1/0?"the end":`${a} ms`}`);return c(x)},edit(p,a,m){if(!(p in Xt.edits))throw new Error(`mathSurface.edit: ${Y("edit",p,Object.keys(Xt.edits))}`);for(const b of Array.isArray(a)?a:[a]){const[S,w=""]=[b.slice(0,b.indexOf(":")),b.slice(b.indexOf(":")+1)];if(p==="set"){if(S!=="value")throw new Error(`mathSurface.edit: set takes value:NAME, not "${b}"`);if(m.value===void 0)throw new Error("mathSurface.edit: set needs `value`");u(w),d(w,m.value,m,1200);continue}if(S!=="item")throw new Error(`mathSurface.edit: ${p} takes item:ID, not "${b}"`);const v=y(b,w);if(p==="drawOn")d(`${v}.draw`,1,m,900);else if(p==="erase")d(`${v}.draw`,0,m,600);else if(p==="show")d(`${v}.opacity`,1,m,500);else if(p==="hide")d(`${v}.opacity`,0,m,500);else{if(typeof m.to!="number")throw new Error("mathSurface.edit: step needs `to`, the step number");d(`${v}.step`,m.to,m,900)}}return g},piece(p){throw new Error(`mathSurface: parts of a figure do not come loose ("${p}"); change it with edits (${Object.keys(Xt.edits).join(", ")})`)},follow(){throw new Error("mathSurface: parts of a figure do not come loose; use edits instead")},fling(){throw new Error("mathSurface: parts of a figure do not come loose; use edits instead")},move(){throw new Error("mathSurface: parts of a figure do not come loose; use edits instead")},ride:p=>p,tracks(p){return[...r].map(([a,m])=>({id:`${p}-${a}`,target:p,property:a,keyframes:[...m].sort((b,S)=>b.time-S.time).map(b=>({time:b.time,value:b.value,...b.easing?{easing:b.easing}:{}}))}))}};return g}const pc="http://www.w3.org/2000/svg";function gc(t,e,n={}){_t(e);const s={...e.values??{}};for(const w of n.sliders??[])if(typeof s[w.value]!="number")throw new Error(`mathExplorable: slider value "${w.value}" is not a number value of the figure`);for(const w of n.drag??[]){if("vector"in w&&!lt(s[w.vector]))throw new Error(`mathExplorable: "${w.vector}" is not a vector value of the figure`);if("matrix"in w&&!Ft(s[w.matrix]))throw new Error(`mathExplorable: "${w.matrix}" is not a matrix value of the figure`)}const i=fn(e),r=t.ownerDocument,o=r.createElementNS(pc,"svg");o.setAttribute("viewBox",`0 0 ${e.width} ${e.height}`),o.setAttribute("style","display:block;width:100%;height:auto;touch-action:none"),o.setAttribute("role","img"),t.appendChild(o);const c=n.drag??[],l=w=>{if("vector"in w)return s[w.vector];const[v,k,x,M]=s[w.matrix];return w.column===0?[v,x]:[k,M]},u=()=>{const w=c.map(v=>{const[k,x]=i.toScreen(l(v));return`<circle cx="${k}" cy="${x}" r="${14*i.scale}" fill="rgba(255,255,255,0.08)" stroke="rgba(255,255,255,0.55)" stroke-width="${1.5*i.scale}" style="cursor:grab"/>`});o.innerHTML=He(jt(e,s))+w.join(""),n.onChange?.({...s})},h=(w,v)=>{if(!(w in s))throw new Error(`mathExplorable: no value "${w}"`);s[w]=v;const k=d.get(w);k&&typeof v=="number"&&(k.value=String(v),f.get(w).textContent=String(v)),u()},d=new Map,f=new Map;let y;if(n.sliders?.length){y=r.createElement("div"),y.setAttribute("style","display:flex;flex-wrap:wrap;gap:8px 18px;align-items:center;padding:8px 0;font:14px system-ui,sans-serif");for(const w of n.sliders){const v=r.createElement("label");v.setAttribute("style","display:flex;align-items:center;gap:6px");const k=r.createElement("input");k.type="range",k.min=String(w.min),k.max=String(w.max),k.step=String(w.step??(w.max-w.min)/100),k.value=String(s[w.value]),k.setAttribute("aria-label",w.label??w.value);const x=r.createElement("output");x.textContent=String(s[w.value]),k.addEventListener("input",()=>h(w.value,Number(k.value))),v.append(w.label??w.value,k,x),y.appendChild(v),d.set(w.value,k),f.set(w.value,x)}t.appendChild(y)}const g=n.snap??.1,p=w=>{const v=o.getBoundingClientRect(),k=(w.clientX-v.left)/(v.width||e.width)*e.width,x=(w.clientY-v.top)/(v.height||e.height)*e.height,[M,A]=i.toWorld([k,x]),E=_=>g>0?Math.round(_/g)*g:_;return[Number(E(M).toFixed(6)),Number(E(A).toFixed(6))]};let a;const m=w=>{const v=o.getBoundingClientRect(),k=e.width/(v.width||e.width),x=[(w.clientX-v.left)*k,(w.clientY-v.top)*k];let M;for(const A of c){const[E,_]=i.toScreen(l(A)),T=Math.hypot(E-x[0],_-x[1]);T<30*i.scale*Math.max(1,k)&&(!M||T<M.distance)&&(M={handle:A,distance:T})}M&&(a=M.handle,o.setPointerCapture?.(w.pointerId),w.preventDefault())},b=w=>{if(!a)return;const[v,k]=p(w);if("vector"in a)h(a.vector,[v,k]);else{const[x,M,A,E]=s[a.matrix];h(a.matrix,a.column===0?[v,M,k,E]:[x,v,A,k])}},S=()=>{a=void 0};return o.addEventListener("pointerdown",m),o.addEventListener("pointermove",b),o.addEventListener("pointerup",S),o.addEventListener("pointercancel",S),u(),{get values(){return{...s}},set:h,destroy(){o.removeEventListener("pointerdown",m),o.removeEventListener("pointermove",b),o.removeEventListener("pointerup",S),o.removeEventListener("pointercancel",S),y?.remove()}}}const ye=(t,e,n)=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{},...t.x?{x:t.x}:{},values:e,items:n}),We="\\begin{bmatrix} \\val{M.a} & \\val{M.b} \\\\ \\val{M.c} & \\val{M.d} \\end{bmatrix}",Yn=t=>[(t.width??600)*.05,(t.height??600)*.1];function yc(t={}){return ye(t,{M:t.matrix??Jt},[{id:"grid",kind:"grid",transform:"M",ghost:!0},{id:"square",kind:"polygon",transform:"M",color:"yellow",fillOpacity:.25},{id:"basis",kind:"basis",transform:"M"},{id:"matrix",kind:"label",tex:We,at:Yn(t),screen:!0,align:"left"}])}function mc(t={}){return ye(t,{M:t.matrix??Jt},[{id:"grid",kind:"grid",transform:"M",ghost:!0},{id:"square",kind:"polygon",transform:"M",color:"yellow",fillOpacity:.35,label:"\\det = \\val{M.det}"},{id:"basis",kind:"basis",transform:"M"},{id:"matrix",kind:"label",tex:We,at:Yn(t),screen:!0,align:"left"}])}function bc(t){return ye(t,{M:Jt,A:t.matrix},[{id:"grid",kind:"grid",transform:"M",ghost:!0},{id:"eigen",kind:"line",eigen:"A",color:"yellow",width:3},{id:"basis",kind:"basis",transform:"M"},{id:"matrix",kind:"label",tex:We,at:Yn(t),screen:!0,align:"left"}])}function vc(t){const e=[t.u[0]+t.v[0],t.u[1]+t.v[1]];return ye(t,{u:t.u,v:t.v,s:e},[{id:"grid",kind:"grid",ghost:!1,color:"grey",opacity:.5},{id:"axes",kind:"axes"},{id:"arrowU",kind:"vector",to:"u",color:"green",label:"\\vec{u}",labelAt:"middle"},{id:"arrowV",kind:"vector",from:"u",to:"s",color:"red",label:"\\vec{v}",labelAt:"middle"},{id:"sum",kind:"vector",to:"s",color:"yellow",label:"\\vec{u} + \\vec{v}"}])}function wc(t){const e=[{id:"axes",kind:"axes"},{id:"spanU",kind:"line",along:"u",color:"green",dashed:!0},{id:"arrowU",kind:"vector",to:"u",color:"green",label:"\\vec{u}"}],n={u:t.u};return t.v&&(n.v=t.v,e.splice(2,0,{id:"spanV",kind:"line",along:"v",color:"red",dashed:!0}),e.push({id:"arrowV",kind:"vector",to:"v",color:"red",label:"\\vec{v}"})),ye(t,n,e)}const Yt=(t,e,n)=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{},...t.x?{x:t.x}:{},...t.y?{y:t.y}:{},values:e,items:[{id:"axes",kind:"axes"},{id:"f",kind:"function",expr:t.expr,color:"blue"},...n]});function kc(t){return Yt(t,{a:t.at??1},[{id:"tangent",kind:"tangent",expr:t.expr,at:"a",color:"yellow",label:"\\text{slope} = \\val{tangent.slope}"}])}function Mc(t){return Yt(t,{a:t.at??1,h:t.h??2},[{id:"secant",kind:"tangent",expr:t.expr,at:"a",h:"h",color:"yellow",label:"\\frac{\\Delta y}{\\Delta x} = \\val{secant.slope}"}])}function $c(t){const e=Yt(t,{n:t.n??4},[{id:"sum",kind:"riemann",expr:t.expr,from:t.from,to:t.to,n:"n",rule:t.rule??"left",color:"teal"}]);return e.items.push(e.items.splice(1,1)[0]),e.items.push({id:"readout",kind:"label",screen:!0,align:"left",size:24,at:[(t.width??600)*.05,(t.height??600)*.08],tex:"n = \\val{sum.n:0} \\quad \\text{sum} = \\val{sum.sum:3} \\quad \\int = \\val{sum.exact:3}"}),e}function Sc(t){const e=Yt(t,{b:t.to},[{id:"area",kind:"area",expr:t.expr,from:t.from,to:"b",color:"teal"}]);return e.items.push(e.items.splice(1,1)[0]),e.items.push({id:"readout",kind:"label",screen:!0,align:"left",size:26,at:[(t.width??600)*.05,(t.height??600)*.09],tex:`\\int_{${t.from}}^{\\val{b:2}} f(x)\\,dx = \\val{area.value:3}`}),e}function xc(t){const e=Yt(t,{order:t.order??1},[{id:"taylor",kind:"taylor",expr:t.expr,at:t.at??0,order:"order",color:"yellow"},{id:"centre",kind:"point",on:t.expr,x:t.at??0,color:"yellow"}]);return e.items.push({id:"readout",kind:"label",screen:!0,align:"left",size:26,at:[(t.width??600)*.05,(t.height??600)*.09],tex:"\\text{degree } \\val{taylor.degree:0}"}),e}function Ac(t){const e=Yt(t,{p:t.from??t.at-2},[{id:"hole",kind:"point",at:[t.at,t.limit],hollow:!0,color:"blue",radius:7},{id:"moving",kind:"point",on:t.expr,x:"p",color:"yellow"}]);return e.items.push({id:"readout",kind:"label",screen:!0,align:"left",size:26,at:[(t.width??600)*.05,(t.height??600)*.09],tex:"f(\\val{moving.x:3}) = \\val{moving.y:4}"}),e}const Pt=(t,e,n,s)=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{},x:t.x??e.x,y:t.y??e.y,values:n,items:s}),Bt=(t,e)=>({id:"readout",kind:"label",screen:!0,align:"left",size:24,at:[(t.width??600)*.05,(t.height??600)*.08],tex:e});function Ec(t={}){const[e,n]=t.shade??[-1,1];return Pt(t,{x:[-4,4],y:[-.08,.55]},{mu:t.mean??0,sigma:t.sd??1,a:e,b:n},[{id:"axes",kind:"axes",ticks:1,labels:!0},{id:"dist",kind:"distribution",distribution:{kind:"normal",mean:"mu",sd:"sigma"},shade:["a","b"]},Bt(t,"P(\\val{a:2} \\le X \\le \\val{b:2}) = \\val{dist.p:3}")])}function Tc(t={}){const e=t.n??10;return Pt(t,{x:[-1,e+1],y:[-.04,.4]},{n:e,p:t.p??.5},[{id:"axes",kind:"axes",ticks:Math.max(1,Math.round(e/10))},{id:"dist",kind:"distribution",distribution:{kind:"binomial",n:"n",p:"p"}},Bt(t,"n = \\val{n:0} \\quad p = \\val{p:2} \\quad \\mu = \\val{dist.mean:2}")])}function _c(t={}){return Pt(t,{x:[-.2,3.2],y:[-.2,3]},{k:t.k??1,samples:t.samples??2e3},[{id:"axes",kind:"axes",ticks:1},{id:"hist",kind:"histogram",distribution:{kind:"mean",of:t.of??{kind:"exponential",rate:1},count:"k"},count:"samples",bins:[0,3,45],curve:!0,color:"teal"},Bt(t,"k = \\val{k:0} \\text{ draws averaged} \\quad \\bar{x} = \\val{hist.mean:3} \\quad s = \\val{hist.sd:3}")])}function Pc(t={}){const e=t.rows??10;return Pt(t,{x:[-(e+2)*.25,(e+2)*.25],y:[-12,1]},{balls:t.balls??0},[{id:"board",kind:"galton",rows:e,balls:"balls",spacing:.5,top:0},Bt(t,"\\val{board.landed:0} \\text{ balls}")])}function Oc(t={}){return Pt(t,{x:[-1.3,1.3],y:[-1.3,1.3]},{count:t.count??0},[{id:"square",kind:"polygon",points:[[-1,-1],[1,-1],[1,1],[-1,1]],color:"grey",fillOpacity:0},{id:"circle",kind:"parametric",x:"cos(t)",y:"sin(t)",color:"yellow",width:2.5},{id:"pts",kind:"scatter",points:{kind:"uniform",x:[-1,1],y:[-1,1]},count:"count",inside:"x^2 + y^2 - 1",color:"blue",radius:2.2},Bt(t,"\\frac{\\text{inside}}{\\text{all}} = \\frac{\\val{pts.inside:0}}{\\val{pts.count:0}} = \\val{pts.ratio:4} \\approx \\frac{\\pi}{4}")])}function Ic(t={}){return Pt(t,{x:[-1,11],y:[-2,10]},{slope:t.slope??.6,intercept:t.intercept??1,noise:t.noise??1,count:t.count??60},[{id:"axes",kind:"axes",ticks:2},{id:"pts",kind:"scatter",points:{kind:"linear",slope:"slope",intercept:"intercept",noise:"noise",x:[0,10]},count:"count",fit:!0,radius:3.5},Bt(t,"y = \\val{pts.slope:2}\\,x + \\val{pts.intercept:2} \\quad r = \\val{pts.r:2}")])}function Cc(t={}){return Pt(t,{x:[0,1],y:[0,1]},{prior:t.prior??.1,sensitivity:t.sensitivity??.9,falsePositive:t.falsePositive??.1},[{id:"test",kind:"bayes",prior:"prior",truePositive:"sensitivity",falsePositive:"falsePositive",at:[.08,.2],size:[.84,.66]}])}const Ot=t=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{}}),me=(t,e)=>({id:"readout",kind:"label",screen:!0,align:"left",size:22,at:[(t.width??600)*.05,(t.height??600)*.07],tex:e}),be={nodes:[{id:"A",at:[-3,1.5]},{id:"B",at:[-1,2.5]},{id:"C",at:[-1,.5]},{id:"D",at:[1,2.5]},{id:"E",at:[1,.5]},{id:"F",at:[-1,-1.5]},{id:"G",at:[3,1.5]},{id:"H",at:[1.5,-1.5]}],edges:[["A","B",4],["A","C",2],["B","D",5],["C","B",1],["C","E",8],["C","F",3],["D","G",3],["E","G",2],["E","D",2],["F","H",6],["H","E",1]]};function Nc(t={}){const{width:e,height:n}=Ot(t);return{...Ot(t),x:[-4.2,4.2],y:[-3.6,3.6],values:{step:0},items:[{id:"g",kind:"graph",nodes:t.nodes??be.nodes,edges:t.edges??be.edges.map(([s,i])=>[s,i]),search:{kind:t.search??"bfs",start:t.start??"A"},step:"step",frontier:[e*.06,n*.92]},me(t,"\\text{visited } \\val{g.visited:0} \\text{ of } \\val{g.steps:0}")]}}function Fc(t={}){const{width:e,height:n}=Ot(t),s=t.target??"G";return{...Ot(t),x:[-4.2,4.2],y:[-3.6,3.6],values:{step:0},items:[{id:"g",kind:"graph",nodes:t.nodes??be.nodes,edges:t.edges??be.edges,search:{kind:"dijkstra",start:t.start??"A"},step:"step",frontier:[e*.06,n*.92]},me(t,`d(${s}) = \\val{g.d.${s}:0}`)]}}function Lc(t={}){const e=Math.min(6,Math.max(1,t.n??5)),n=[],s=[],i=c=>{const l=`c${n.length}`;return n.push({id:l,label:`F_{${c}}`}),c>=2&&(s.push([l,i(c-1)]),s.push([l,i(c-2)])),l};i(e);const r=n.filter(c=>!s.some(([l])=>l===c.id)).length,o=Math.max(r*.75,4);return{...Ot(t),x:[-o,o],y:[-(e+.2)*1.05,1.2],values:{step:0},items:[{id:"calls",kind:"graph",nodes:n,edges:s,directed:!0,tree:{root:"c0",spacing:[1.3,1.05],at:[0,0]},search:{kind:"dfs",start:"c0"},step:"step",radius:17},me(t,"\\text{calls made: } \\val{calls.visited:0} \\text{ of } \\val{calls.steps:0}")]}}function Rc(t={}){const n=[{id:"venn",kind:"venn",sets:(t.sets??["A","B"]).map(s=>({id:s})),highlight:t.highlight??"A & B",radius:1.6,at:[0,-.3]}];return t.label!==void 0&&n.push(me(t,t.label)),{...Ot(t),x:[-4,4],y:[-4,4],items:n}}function Dc(t={}){const e=t.modulus??12;return{...Ot(t),x:[-3,3],y:[-3,3],values:{value:t.value??0},items:[{id:"clock",kind:"clock",modulus:e,value:"value",radius:2.2,at:[0,-.2]},me(t,`\\val{value:0} \\equiv \\val{clock.hour:0} \\pmod{${e}}`.replace("\\pmod","\\;(\\text{mod } ").replace(`{${e}}`,`${e})`))]}}const Vt=t=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{}}),ve=(t,e)=>({id:"readout",kind:"label",screen:!0,align:"left",size:22,at:[(t.width??600)*.05,(t.height??600)*.07],tex:e});function zc(t={}){const e=t.layers??[3,5,4,2],n=Array.from({length:e[0]},(s,i)=>t.inputs?.[i]??[.9,.2,.6,.4,.8][i%5]);return{...Vt(t),x:[-5,5],y:[-5,5],values:{flow:e.length-1,...Object.fromEntries(n.map((s,i)=>[`in${i}`,s]))},items:[{id:"net",kind:"network",layers:e,activation:t.activation??"sigmoid",seed:t.seed??"net",flow:"flow",at:[0,-.3],size:[7,6.5],inputs:n.map((s,i)=>`in${i}`),labels:{inputs:n.map((s,i)=>`x_{${i+1}}`),outputs:Array.from({length:e[e.length-1]},(s,i)=>`y_{${i+1}}`)}},ve(t,e[e.length-1]>=2?"y_1 = \\val{net.out0:2} \\quad y_2 = \\val{net.out1:2}":"y = \\val{net.out0:2}")]}}function qc(t={}){const e=t.expr??"(x^2 + 8 y^2) / 4";return{...Vt(t),x:[-4,4],y:[-4,4],values:{steps:0,rate:t.rate??.2,momentum:t.momentum??0,sx:t.start?.[0]??-3.5,sy:t.start?.[1]??2},items:[{id:"field",kind:"heatmap",expr:e,resolution:40,colormap:"viridis",opacity:.35},{id:"levels",kind:"contours",expr:e,levels:9,colormap:"viridis"},{id:"gd",kind:"descent",expr:e,start:[t.start?.[0]??-3.5,t.start?.[1]??2],rate:"rate",steps:"steps",momentum:"momentum"},ve(t,"\\text{step } \\val{gd.step:0} \\quad f = \\val{gd.loss:3}")]}}function jc(t={}){const e=t.tokens??["The","cat","sat","on","the","mat"],n=Nt($t(t.seed??"attention")),s=t.scores??e.map((r,o)=>e.map((c,l)=>(o===l?2.2:0)+(l===o-1?1.4:0)+St(n)*.8)),i=e.map(r=>`\\text{${r}}`);return{...Vt(t),x:[-5,5],y:[-5,5],items:[{id:"attn",kind:"heatmap",cells:s,softmax:!0,range:[0,1],colormap:"heat",at:[-3,-4],size:[7,7],rowLabels:i,colLabels:i,values:!0}]}}function Xc(t={}){return{...Vt(t),x:[-4,4],y:[-4,4],values:{epochs:0},items:[{id:"clf",kind:"classifier",epochs:"epochs",centres:[[-1.1,-.7],[1.1,.9]],rate:t.rate??.3,spread:t.spread??1.15},ve(t,"\\text{epoch } \\val{clf.epoch:0} \\quad \\text{accuracy } \\val{clf.accuracy:2} \\quad \\text{loss } \\val{clf.loss:3}")]}}function Yc(t={}){return{...Vt(t),x:[-4.5,4.5],y:[-4.5,4.5],values:{iteration:0},items:[{id:"km",kind:"kmeans",centres:t.centres??[[-2.2,1.6],[2,2],[.4,-2.2]],k:t.k,iteration:"iteration",spread:.75},ve(t,"\\text{iteration } \\val{km.iteration:0} \\quad \\text{inertia } \\val{km.inertia:1}")]}}function Bc(t={}){return{...Vt(t),x:[-4,4],y:[-2,3],items:[{id:"axes",kind:"axes"},{id:"sigmoid",kind:"function",expr:"sigmoid(x)",color:"blue"},{id:"tanh",kind:"function",expr:"tanh(x)",color:"yellow"},{id:"relu",kind:"function",expr:"relu(x)",color:"red"},ve(t,"\\color{blue}{\\sigma(x)} \\quad \\color{yellow}{\\tanh x} \\quad \\color{red}{\\text{ReLU}(x)}")]}}function Vc(t){return _t(t)}function Hc(t,e={},n={}){return Ii(jt(_t(t),e),n)}const Uc={opacity:1,scale:1,scaleX:1,scaleY:1};function Wc(t){const e=new Map,n=new Map,s=[],i={};let r=0,o=0,c;const l=(y,g)=>`${y}\0${g}`,u=(y,g)=>{const p=l(y,g);let a=e.get(p);if(!a){const m=n.get(p)??Uc[g]??(g==="text"?"":0);a={id:`${y}-${g}`,target:y,property:g,keyframes:[{time:0,value:m}]},e.set(p,a)}return a},h=(y,g)=>{const p=y.keyframes[y.keyframes.length-1];p.time<g&&y.keyframes.push({time:g,value:p.value})},d=(y,g,p,a,m)=>{for(const[S,w]of Object.entries(g)){const v=u(y,S);if(typeof w=="string"&&!/^#|^rgb/.test(w)){h(v,p),v.keyframes.push({time:p+1,value:w});continue}h(v,p),v.keyframes.push({time:p+Math.max(a,1),value:w,...m&&{easing:m}})}const b=p+Math.max(a,1);return o=Math.max(o,b),b},f={get time(){return r},at(y){return r=Math.max(0,y),f},wait(y){return r+=y,o=Math.max(o,r),f},initial(y,g){for(const[p,a]of Object.entries(g)){const m=l(y,p);n.set(m,a);const b=e.get(m);b&&(b.keyframes[0].value=a)}return f},set(y,g){const p=c?c.start:r;return d(y,g,p,1,{type:"steps",count:1,position:"start"}),f},to(y,g,p={}){const a=(c?c.start:r)+(p.delay??0),m=d(y,g,a,p.duration??400,p.easing??"ease-in-out");return c?c.end=Math.max(c.end,m):r=m,f},together(y){const g=c;c={start:g?g.start:r,end:g?g.start:r},y();const p=c.end;return c=g,g?g.end=Math.max(g.end,p):r=p,f},marker(y,g={}){const{captions:p,...a}=g;s.push({id:y,time:r,...a});for(const[m,b]of Object.entries(p??{}))(i[m]??={})[y]=b;return o=Math.max(o,r),f},definition(){return{formatVersion:Ge,id:t.id,...t.name&&{name:t.name},config:{duration:o,...s.length>0&&{markers:[...s].sort((y,g)=>y.time-g.time)}},tracks:[...e.values()].map(y=>({...y,keyframes:y.keyframes.map(g=>({...g}))})),...Object.keys(i).length>0&&{captions:i}}}};return f}ac(),$.ACTIVATIONS=Rn,$.COLORMAPS=he,$.CONSTANTS=ie,$.DISTRIBUTION_KINDS=ae,$.ExpressionError=Et,$.FUNCTIONS=Ee,$.ITEM_KINDS=un,$.MATH_FONT=Ps,$.MATH_SURFACE=Xt,$.MATH_SYMBOL_FONT=Os,$.MATH_THEMES=Se,$.MATRIX_TEX=We,$.SAMPLE_GRAPH=be,$.SEARCH_KINDS=Fn,$.SYMBOLS=xe,$.TEX_COMMANDS=qs,$.TexError=zs,$.accuracy=mi,$.activate=ui,$.activationFigure=Bc,$.adjacency=Re,$.areaFigure=Sc,$.assign=je,$.attentionFigure=jc,$.ballAt=ei,$.ballPath=Cn,$.bayesAreas=ti,$.bayesFigure=Cc,$.binOf=Fe,$.binSamples=Ks,$.binomialFigure=Tc,$.blendOver=Dn,$.blobs=qn,$.clockFigure=Dc,$.cltFigure=_c,$.colorAt=de,$.compile=tt,$.compileDerivative=Pe,$.contourLines=pi,$.decisionBoundaryFigure=Xc,$.defaultBins=Pn,$.density=yt,$.descentPath=zn,$.determinantFigure=mc,$.differentiate=J,$.displayListToSvg=Ii,$.displayListToSvgContent=He,$.distributionProblem=_n,$.drawDisplayList=Li,$.eigenFigure=bc,$.evaluate=st,$.expressionNames=$n,$.expressionToString=oe,$.forward=di,$.galtonFigure=Pc,$.gradientDescentFigure=qc,$.graphSearchFigure=Nc,$.inRegion=ue,$.inertia=wi,$.integrate=Be,$.isDiscrete=ce,$.kmeansFigure=Yc,$.kmeansHistory=vi,$.layoutFigure=jt,$.layoutTex=W,$.leastSquares=In,$.lesson=Wc,$.limitFigure=Ac,$.linearMapFigure=yc,$.logLoss=bi,$.lossSurface3D=cc,$.mat2=Bo,$.mathExplorable=gc,$.mathFigure=Vc,$.mathFigureProps=Ri,$.mathFigureToSvg=Hc,$.mathSteps=lc,$.mathSurface=fc,$.mathTarget=Di,$.meanOf=zt,$.monteCarloPiFigure=Oc,$.morphEquation=Gs,$.mountAllMath=Ni,$.mountMath=Ci,$.neuralNetworkFigure=zc,$.normalFigure=Ec,$.nthDerivative=Bs,$.parseExpression=rt,$.parseSetExpression=Ln,$.parseTex=js,$.planeOf=fn,$.predict=pe,$.recursionTreeFigure=Lc,$.regionCells=ri,$.regressionFigure=Ic,$.riemannFigure=$c,$.sample=En,$.sampleGrid=gi,$.samples=Tn,$.scatterPoints=On,$.sdOf=qt,$.searchEvents=si,$.secantFigure=Mc,$.seededNetwork=hi,$.setNames=le,$.shortestPathFigure=Fc,$.spanFigure=wc,$.summary=Js,$.supportOf=Qs,$.surface=fe,$.tangentFigure=kc,$.taylorFigure=xc,$.texToShapes=Z,$.trainLogistic=yi,$.treeLayout=ii,$.trimPolylines=H,$.validateMathFigure=_t,$.vec2=Wo,$.vectorSumFigure=vc,$.vennFigure=Rc,Object.defineProperty($,Symbol.toStringTag,{value:"Module"})})(this.tinyfly=this.tinyfly||{});