@algorisys/tinyfly 0.117.0 → 0.119.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/docs/editor-guide.md +1 -1
- package/docs/examples.md +1 -1
- package/docs/getting-started.md +1 -1
- package/docs/gsap-compat.md +1 -1
- package/docs/llm-guide.md +5 -1
- package/docs/maps.md +2 -2
- package/docs/math.md +74 -9
- package/docs/teaching.md +1 -1
- package/lib/addons/characters.js +2311 -2299
- package/lib/addons/math.js +2120 -1166
- package/lib/browser/tinyfly-math.iife.js +4 -4
- package/lib/browser/tinyfly.iife.js +1 -1
- package/lib/browser/tinyfly.js +13 -1
- package/lib/browser/tinyfly.umd.js +1 -1
- package/lib/types/math/discrete/graph-search.d.ts +38 -0
- package/lib/types/math/discrete/set-expression.d.ts +33 -0
- package/lib/types/math/figure/display-list.d.ts +10 -0
- package/lib/types/math/figure/figure-spec.d.ts +168 -1
- package/lib/types/math/figure/items/discrete.d.ts +23 -0
- package/lib/types/math/figure/items/ml.d.ts +47 -0
- package/lib/types/math/figure/items/shapes.d.ts +3 -0
- package/lib/types/math/index.d.ts +11 -1
- package/lib/types/math/ml/classify.d.ts +30 -0
- package/lib/types/math/ml/colormap.d.ts +14 -0
- package/lib/types/math/ml/contours.d.ts +15 -0
- package/lib/types/math/ml/descent.d.ts +11 -0
- package/lib/types/math/ml/kmeans.d.ts +11 -0
- package/lib/types/math/ml/network.d.ts +19 -0
- package/lib/types/math/presets/discrete.d.ts +49 -0
- package/lib/types/math/presets/ml.d.ts +50 -0
- package/lib/types/math/tex/glyph-metrics.d.ts +8 -0
- package/lib/types/math/tex/tex-parser.d.ts +2 -1
- package/llms-full.txt +99 -18
- package/llms.txt +31 -31
- package/package.json +1 -1
- package/skills/tinyfly/SKILL.md +3 -1
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
(function(S){"use strict";function qi(t){return typeof t=="object"&&t!==null&&t.type==="cubic-bezier"}function ji(t){return typeof t=="object"&&t!==null&&t.type!=="cubic-bezier"}const ke=2;function zi(t){return t.some(e=>e.interpolation!==void 0)?2:1}function pn(t){return t.property==="text"&&"textConfig"in t}function Me(t){return t.kind==="inertia"&&"inertia"in t}function $e(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 mn(t,e,n="start"){if(e<=1)return 0;if(typeof n=="number"){const i=Math.max(0,Math.min(e-1,n));return Math.abs(t-i)}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 i=0;i<t;i++)n=Math.max(n,mn(i,t,e));return n}function gn(t,e,n){if(n.offsets)return n.offsets[t]??0;const i=n.from??"start",r=mn(t,e,i);if(n.amount!==void 0){const s=Bi(e,i);return s===0?0:n.amount*r/s}return n.each!==void 0?n.each*r:0}function Vi(t,e){return Array.from({length:t},(n,i)=>gn(i,t,e))}function Se(t,e){return t<=1?0:Math.max(...Vi(t,e))}const Rt=1,yn=6e4,Jt=yn/Rt,$t={stiffness:180,damping:12,mass:1,velocity:0,restDelta:.01,restSpeed:.1};class Wi{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??$t.stiffness,this.damping=e.damping??$t.damping,this.mass=e.mass??$t.mass,this.restDelta=e.restDelta??$t.restDelta,this.restSpeed=e.restSpeed??$t.restSpeed,this.distance=Math.abs(this.to-this.from)||1,this.samples=[this.from],this.velocity=e.velocity??$t.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/Rt);if(this.simulateTo(n+1),this.settledStep!==null&&n>=this.settledStep)return this.to;const i=this.samples[Math.min(n,this.samples.length-1)],r=this.samples[Math.min(n+1,this.samples.length-1)],s=e/Rt-n;return i+(r-i)*s}settleTime(){return this.simulateTo(Jt+1),this.settledStep!==null?this.settledStep*Rt:yn}simulateTo(e){if(this.settledStep!==null)return;const n=Math.min(e,Jt+1),i=Rt/1e3;for(;this.samples.length<n;){const r=this.samples[this.samples.length-1],s=r-this.to,o=-this.stiffness*s,a=-this.damping*this.velocity,l=(o+a)/this.mass;this.velocity+=l*i;const h=r+this.velocity*i;if(this.samples.push(h),this.isAtRest(h)){this.settledStep=this.samples.length-1;return}}this.samples.length>Jt&&(this.settledStep=Jt)}}const bn=4,Ui=.002,Hi=1e-4,Gi=6e4;function xe(t){const e=t.friction??bn;return e>0?e:bn}function Zi(t){return t.from+t.velocity/xe(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 i of e)Math.abs(i-t)<Math.abs(n-t)&&(n=i);return n}function vn(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 wn(t){const e=Math.abs(vn(t)-t.from);if(e===0)return 0;const n=t.restDelta??Math.max(Hi,e*Ui);if(n>=e)return 0;const i=Math.log(e/n)/xe(t);return Math.min(Gi,i*1e3)}function kn(t,e){if(e<=0)return t.from;const n=vn(t);if(e>=wn(t))return n;const i=xe(t);return t.from+(n-t.from)*(1-Math.exp(-i*e/1e3))}const Te=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,Mn=t=>t*t*t,$n=t=>1-Math.pow(1-t,3),Sn=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,er={linear:Te,"ease-in":Mn,"ease-out":$n,"ease-in-out":Sn,"ease-in-quad":Ki,"ease-out-quad":Ji,"ease-in-out-quad":tr,"ease-in-cubic":Mn,"ease-out-cubic":$n,"ease-in-out-cubic":Sn};function nr(t){const[e,n,i,r]=t,s=3*e,o=3*(i-e)-s,a=1-s-o,l=3*n,h=3*(r-n)-l,u=1-l-h,d=m=>((a*m+o)*m+s)*m,f=m=>((u*m+h)*m+l)*m,g=m=>(3*a*m+2*o)*m+s,p=m=>{let c=m;for(let $=0;$<8;$++){const w=d(c)-m;if(Math.abs(w)<1e-7)return c;const b=g(c);if(Math.abs(b)<1e-7)break;c-=w/b}let y=0,v=1;for(c=m;y<v;){const $=d(c);if(Math.abs($-m)<1e-7)return c;m>$?y=c:v=c,c=(y+v)/2}return c};return m=>{if(m<=0)return 0;if(m>=1)return 1;const c=p(m);return f(c)}}function Ae(t,e="out"){if(e==="out")return t;const n=i=>1-t(1-i);return e==="in"?n:i=>i<.5?n(i*2)/2:t(i*2-1)/2+.5}function ir(t=1,e=.3){const n=Math.max(1,t),i=e/(2*Math.PI)*Math.asin(1/n);return r=>r<=0?0:r>=1?1:n*Math.pow(2,-10*r)*Math.sin((r-i)*(2*Math.PI)/e)+1}const rr=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 r=t-.5454545454545454;return 7.5625*r*r+.75}if(t<2.5/2.75){const r=t-.8181818181818182;return 7.5625*r*r+.9375}const i=t-2.625/2.75;return 7.5625*i*i+.984375};function sr(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 i=>{if(i>=1)return 1;if(i<=0)return e==="start"||e==="both"?e==="start"?1/n:1/(n+1):0;const r=Math.floor(i*n);switch(e){case"start":return Math.min(1,(r+1)/n);case"both":return(r+1)/(n+1);case"none":return n===1?0:Math.min(1,r/(n-1));default:return r/n}}}function ar(t){switch(t.type){case"steps":return or(t.count,t.position);case"elastic":return Ae(ir(t.amplitude,t.period),t.mode);case"bounce":return Ae(rr,t.mode);case"back":return Ae(sr(t.overshoot),t.mode)}}function cr(t){return t===void 0?Te:qi(t)?nr(t.points):ji(t)?ar(t):er[t]??Te}const xn=32,lr=256,Lt=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,i=null;const r=()=>{for(;n<t.length&&/[\s,]/.test(t[n]);)n++};for(;n<t.length&&(r(),!(n>=t.length));){const s=t[n];if(ur.test(s)){i={type:s,args:[]},e.push(i),n++;continue}if(!i)break;const o=i.type==="A"||i.type==="a",a=i.args.length%7;if(o&&(a===3||a===4)){if(s!=="0"&&s!=="1")break;i.args.push(s==="1"?1:0),n++;continue}const l=hr.exec(t.slice(n));if(!l)break;i.args.push(parseFloat(l[0])),n+=l[0].length}return e}function pr(t,e,n,i,r,s,o,a,l){if(t===a&&e===l)return[];let h=Math.abs(n),u=Math.abs(i);if(h===0||u===0)return[[t,e,a,l,a,l]];const d=r*Math.PI/180,f=Math.cos(d),g=Math.sin(d),p=(t-a)/2,m=(e-l)/2,c=f*p+g*m,y=-g*p+f*m,v=c*c/(h*h)+y*y/(u*u);if(v>1){const L=Math.sqrt(v);h*=L,u*=L}const $=s===o?-1:1,w=h*h*u*u-h*h*y*y-u*u*c*c,b=h*h*y*y+u*u*c*c,k=$*Math.sqrt(Math.max(0,w/b)),M=k*h*y/u,x=-k*u*c/h,P=f*M-g*x+(t+a)/2,A=g*M+f*x+(e+l)/2,O=(L,z,U,Ct)=>{const fn=L*U+z*Ct,we=Math.sqrt((L*L+z*z)*(U*U+Ct*Ct)),Kt=Math.acos(Math.max(-1,Math.min(1,fn/we)));return L*Ct-z*U<0?-Kt:Kt},_=O(1,0,(c-M)/h,(y-x)/u);let F=O((c-M)/h,(y-x)/u,(-c-M)/h,(-y-x)/u);!o&&F>0&&(F-=2*Math.PI),o&&F<0&&(F+=2*Math.PI);const j=Math.max(1,Math.ceil(Math.abs(F)/(Math.PI/2))),E=F/j,q=4/3*Math.tan(E/4),st=L=>{const z=h*Math.cos(L),U=u*Math.sin(L);return[f*z-g*U+P,g*z+f*U+A]},tt=L=>{const z=-h*Math.sin(L),U=u*Math.cos(L);return[f*z-g*U,g*z+f*U]},W=[];for(let L=0;L<j;L++){const z=_+L*E,U=z+E,[Ct,fn]=st(z),[we,Kt]=L===j-1?[a,l]:st(U),[ha,da]=tt(z),[fa,pa]=tt(U);W.push([Ct+q*ha,fn+q*da,we-q*fa,Kt-q*pa,we,Kt])}return W}function ht(t,e,n,i,r){const s=1-r;return s*s*s*t+3*s*s*r*e+3*s*r*r*n+r*r*r*i}function Tn(t,e,n,i,r){const s=1-r;return 3*s*s*(e-t)+6*s*r*(n-e)+3*r*r*(i-n)}function Ft(t,e,n,i){return{subpath:0,type:"L",points:[n,i],startX:t,startY:e,endX:n,endY:i,length:Math.hypot(n-t,i-e)}}function te(t,e,n){const[i,r,s,o,a,l]=n,h=[0];let u=t,d=e,f=0;for(let g=1;g<=xn;g++){const p=g/xn,m=ht(t,i,s,a,p),c=ht(e,r,o,l,p);f+=Math.hypot(m-u,c-d),h.push(f),u=m,d=c}return{subpath:0,type:"C",points:[i,r,s,o,a,l],startX:t,startY:e,endX:a,endY:l,length:f,lengths:h}}function ee(t){const e=Lt.get(t);if(e)return e;const n=[];let i=0,r=0,s=0,o=0,a=null,l=null,h=-1;const u=new Set,d=m=>{h<0&&(h=0),m.subpath=h,n.push(m)};for(const{type:m,args:c}of fr(t)){const y=m.toUpperCase(),v=m!==y,$=dr[y];if(y==="Z"){(i!==s||r!==o)&&d(Ft(i,r,s,o)),h>=0&&u.add(h),i=s,r=o,a=l=null;continue}for(let w=0;w+$<=c.length;w+=$){const b=c.slice(w,w+$),k=v?i:0,M=v?r:0;let x=null,P=null;switch(y){case"M":w===0?(i=b[0]+k,r=b[1]+M,s=i,o=r,(h<0||n[n.length-1]?.subpath===h)&&h++):(d(Ft(i,r,b[0]+k,b[1]+M)),i=b[0]+k,r=b[1]+M);break;case"L":d(Ft(i,r,b[0]+k,b[1]+M)),i=b[0]+k,r=b[1]+M;break;case"H":d(Ft(i,r,b[0]+k,r)),i=b[0]+k;break;case"V":d(Ft(i,r,i,b[0]+M)),r=b[0]+M;break;case"C":{const A=[b[0]+k,b[1]+M,b[2]+k,b[3]+M,b[4]+k,b[5]+M];d(te(i,r,A)),x=[A[2],A[3]],i=A[4],r=A[5];break}case"S":{const[A,O]=a?[2*i-a[0],2*r-a[1]]:[i,r],_=[A,O,b[0]+k,b[1]+M,b[2]+k,b[3]+M];d(te(i,r,_)),x=[_[2],_[3]],i=_[4],r=_[5];break}case"Q":case"T":{let A=i,O=r;y==="Q"?(A=b[0]+k,O=b[1]+M):l&&(A=2*i-l[0],O=2*r-l[1]);const _=y==="Q"?b[2]+k:b[0]+k,F=y==="Q"?b[3]+M:b[1]+M;d(te(i,r,[i+2/3*(A-i),r+2/3*(O-r),_+2/3*(A-_),F+2/3*(O-F),_,F])),P=[A,O],i=_,r=F;break}case"A":{const A=b[5]+k,O=b[6]+M;let _=i,F=r;for(const j of pr(i,r,b[0],b[1],b[2],b[3],b[4],A,O))d(te(_,F,j)),_=j[4],F=j[5];i=A,r=O;break}}a=x,l=P}}const f=n.reduce((m,c)=>m+c.length,0),g=[];for(let m=0;m<n.length;){const c=n[m].subpath;let y=m,v=0;for(;y<n.length&&n[y].subpath===c;)v+=n[y++].length;const $=n[m],w=n[y-1],b=u.has(c)||Math.abs(w.endX-$.startX)<1e-9&&Math.abs(w.endY-$.startY)<1e-9;g.push({start:m,end:y,length:v,closed:b}),m=y}const p={segments:n,totalLength:f,subpaths:g};return Lt.size>=lr&&Lt.delete(Lt.keys().next().value),Lt.set(t,p),p}function mr(t,e){const n=t.lengths;if(e<=0)return 0;if(e>=t.length)return 1;let i=0,r=n.length-1;for(;i<r-1;){const a=i+r>>1;n[a]<e?i=a:r=a}const s=n[r]-n[i],o=s>0?(e-n[i])/s:0;return(i+o)/(n.length-1)}function gr(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,i,r,s,o,a]=t.points,l=mr(t,e);let h=Tn(t.startX,n,r,o,l),u=Tn(t.startY,i,s,a,l);if(Math.hypot(h,u)<1e-9){const d=l<.5?Math.min(1,l+.001):Math.max(0,l-.001),f=ht(t.startX,n,r,o,d),g=ht(t.startY,i,s,a,d),p=ht(t.startX,n,r,o,l),m=ht(t.startY,i,s,a,l);h=l<.5?f-p:p-f,u=l<.5?g-m:m-g}return{x:ht(t.startX,n,r,o,l),y:ht(t.startY,i,s,a,l),angle:Math.atan2(u,h)*180/Math.PI}}function An(t,e,n=0,i=t.length){if(i<=n)return{x:0,y:0,angle:0};let r=0;for(let s=n;s<i;s++){const o=t[s];if(r+o.length>=e||s===i-1)return gr(o,e-r);r+=o.length}return{x:0,y:0,angle:0}}function yr(t,e){const{segments:n,totalLength:i}=ee(t);return An(n,Math.max(0,Math.min(1,e))*i)}const br=24,vr=320,wr=2.5,Nt=72,kr=.2,Mr=128,ne=new Map;let _e=0,gt;const _n=t=>Math.round(t*100)/100;function En(t,e){const{segments:n,subpaths:i,totalLength:r}=ee(t);if(n.length===0)return[];if(e){const s=i.every(o=>o.closed);return[{segments:n,start:0,end:n.length,length:r,closed:s}]}return i.filter(s=>s.length>0).map(s=>({segments:n,start:s.start,end:s.end,length:s.length,closed:s.closed}))}function Ee(t,e){const n=t.closed?(e%1+1)%1:Math.max(0,Math.min(1,e)),i=An(t.segments,n*t.length,t.start,t.end);return[i.x,i.y]}function Pn(t){const e=[];let n=0;for(let i=t.start;i<t.end;i++)n+=t.segments[i].length,t.length>0&&e.push(n/t.length);return e}function On(t,e){const n=[];for(let i=0;i<e;i++)n.push(Ee(t,t.closed?i/e:i/(e-1)));return n}function In(t){let e=0,n=0;for(const[i,r]of t)e+=i,n+=r;return e/=t.length,n/=t.length,t.map(([i,r])=>[i-e,r-n])}function $r(t,e,n){const i=t.closed&&e.closed;if(n!==void 0)return{offset:i?Math.abs(n)%Nt/Nt:0,reversed:n<0};const r=In(On(t,Nt)),s=In(On(e,Nt)),o=Nt;let a={offset:0,reversed:!1},l=1/0;for(const h of[!1,!0]){const u=i?o:1;for(let d=0;d<u;d++){let f=0;for(let g=0;g<o&&f<l;g++){const p=i?h?(d-g+o)%o:(g+d)%o:h?o-1-g:g,m=r[g][0]-s[p][0],c=r[g][1]-s[p][1];f+=m*m+c*c}f<l&&(l=f,a={offset:i?d/o:0,reversed:h})}}return a}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 Tr(t,e,n){const i=t.closed&&e.closed,r=$r(t,e,n.shapeIndex),s=Math.max(br,Math.min(vr,Math.ceil(Math.max(t.length,e.length)/wr))),o=new Set,a=d=>o.add(Math.round(d*1e7)/1e7);for(let d=0;d<=s;d++)a(d/s);for(const d of Pn(t))a(d);for(const d of Pn(e))a(xr(d,r,i));let l=[...o].sort((d,f)=>d-f);i&&(l=l.filter(d=>d<1));const h=[],u=[];for(const d of l)h.push(...Ee(t,d)),u.push(...Ee(e,Sr(d,r,i)));return Ar({from:h,to:u,closed:i})}function Ar(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 i=[[0,e-1]];for(;i.length>0;){const[o,a]=i.pop();let l=-1,h=kr;for(let u=o+1;u<a;u++){const d=Math.max(Cn(t.from,o,a,u),Cn(t.to,o,a,u));d>h&&(h=d,l=u)}l!==-1&&(n[l]=1,i.push([o,l],[l,a]))}const r=[],s=[];for(let o=0;o<e;o++)n[o]&&(r.push(t.from[o*2],t.from[o*2+1]),s.push(t.to[o*2],t.to[o*2+1]));return{from:r,to:s,closed:t.closed}}function Cn(t,e,n,i){const r=t[e*2],s=t[e*2+1],o=t[n*2]-r,a=t[n*2+1]-s,l=t[i*2]-r,h=t[i*2+1]-s,u=o*o+a*a,d=u===0?0:Math.max(0,Math.min(1,(l*o+h*a)/u));return Math.hypot(l-d*o,h-d*a)}function _r(t,e,n){const i=n.shapeIndex;if(gt&>.from===t&>.to===e&>.shapeIndex===i)return gt.plan;const s=ne.get(String(i??"auto"))?.get(t)?.get(e);if(s)return gt={from:t,to:e,shapeIndex:i,plan:s},s;const o=ee(t).subpaths.filter(g=>g.length>0).length===ee(e).subpaths.filter(g=>g.length>0).length,a=En(t,!o),l=En(e,!o),h={pairs:a.map((g,p)=>Tr(g,l[p],n))};_e>=Mr&&(ne.clear(),_e=0);const u=String(i??"auto"),d=ne.get(u)??new Map;ne.set(u,d);const f=d.get(t)??new Map;return d.set(t,f),f.set(e,h),_e++,gt={from:t,to:e,shapeIndex:i,plan:h},h}function Er(t,e,n,i={}){if(!t)return e;if(!e)return t;const r=Math.max(0,Math.min(1,n));if(r===0)return t;if(r===1)return e;const s=_r(t,e,i);if(s.pairs.length===0)return r<.5?t:e;let o="";for(const a of s.pairs){for(let l=0;l<a.from.length;l+=2){const h=_n(a.from[l]+(a.to[l]-a.from[l])*r),u=_n(a.from[l+1]+(a.to[l+1]-a.from[l+1])*r);o+=`${l===0?o?" M":"M":" L"}${h} ${u}`}a.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 Rr(t){return Math.hypot(t[0],t[1],t[2],t[3])}function Dt(t){const e=Rr(t);return e===0?Ir():[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function Lr(t,e,n){const i=Dt(t);let r=Dt(e),s=Cr(i,r);if(s<0&&(r=[-r[0],-r[1],-r[2],-r[3]],s=-s),s>Or)return Dt([i[0]+(r[0]-i[0])*n,i[1]+(r[1]-i[1])*n,i[2]+(r[2]-i[2])*n,i[3]+(r[3]-i[3])*n]);const o=Math.acos(s),a=Math.sin(o),l=Math.sin((1-n)*o)/a,h=Math.sin(n*o)/a;return Dt([i[0]*l+r[0]*h,i[1]*l+r[1]*h,i[2]*l+r[2]*h,i[3]*l+r[3]*h])}const ot=(t,e,n)=>t+(e-t)*n,Rn=512,Pe=new Map,Oe=new Map;function Ln(t){const e=Pe.get(t);if(e)return e;const n=t.replace("#",""),i=[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16)];return Pe.size<Rn&&Pe.set(t,i),i}const Fn=t=>t.charCodeAt(0)===35,Nn=t=>t.startsWith("rgb"),Dn=t=>t.startsWith("rgba"),Fr=/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/,Ie=t=>Math.round(t).toString(16).padStart(2,"0");function Nr(t,e,n){return`#${Ie(t)}${Ie(e)}${Ie(n)}`}function qn(t){const e=Oe.get(t);if(e)return e;const n=t.match(Fr);if(!n)throw new Error(`Invalid rgb color: ${t}`);const i=parseInt(n[1],10),r=parseInt(n[2],10),s=parseInt(n[3],10),o=n[4]!==void 0?[i,r,s,parseFloat(n[4])]:[i,r,s];return Oe.size<Rn&&Oe.set(t,o),o}const Dr=(t,e,n)=>{if(Fn(t)&&Fn(e)){const[i,r,s]=Ln(t),[o,a,l]=Ln(e),h=ot(i,o,n),u=ot(r,a,n),d=ot(s,l,n);return Nr(h,u,d)}if((Nn(t)||Dn(t))&&(Nn(e)||Dn(e))){const i=qn(t),r=qn(e),s=Math.round(ot(i[0],r[0],n)),o=Math.round(ot(i[1],r[1],n)),a=Math.round(ot(i[2],r[2],n));if(i.length===4||r.length===4){const l=i[3]??1,h=r[3]??1,u=ot(l,h,n);return`rgba(${s}, ${o}, ${a}, ${u})`}return`rgb(${s}, ${o}, ${a})`}return n<1?t:e},qr=(t,e,n)=>{const i=Math.min(t.length,e.length),r=[];for(let s=0;s<i;s++)r.push(ot(t[s],e[s],n));return r},jr=(t,e,n)=>Lr(t,e,n),jn=(t,e,n)=>n<1?t:e,zr=(t,e,n)=>Er(t,e,n);function Xr(t,e){return e==="slerp"?jr:typeof t=="number"?ot:Array.isArray(t)?qr:typeof t=="string"?t.startsWith("#")||t.startsWith("rgb")?Dr:Pr(t)?zr:jn:jn}function Yr(t){const e=[...t.keyframes].sort((n,i)=>n.time-i.time);return{...t,keyframes:e}}function yt(t){return t.targets&&t.targets.length>0?t.targets:[t.target]}function St(t,e,n,i){const r=n??0;return!i||e<=1?r:r+gn(t,e,i)}class Ce{track;targets;constructor(e){this.track=e,this.targets=yt(e)}getValueAtTime(e){return this.valueForOffset(e-St(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,i=[];for(let r=0;r<n;r++){const s=St(r,n,this.track.delay,this.track.stagger),o=this.valueForOffset(e-s);o!==void 0&&i.push({target:this.targets[r],value:o,start:s+this.track.keyframes[0].time})}return i}getDuration(){const{keyframes:e}=this.track;if(e.length===0)return 0;const n=e[e.length-1].time,i=this.track.stagger?Se(this.targets.length,this.track.stagger):0;return n+(this.track.delay??0)+i+(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:i,to:r}=this.findSurroundingKeyframes(e);if(!i||!r)return;if(i.time===e)return i.value;const s=r.time-i.time,o=(e-i.time)/s,l=cr(r.easing)(o);return Xr(i.value,this.track.interpolation)(i.value,r.value,l)}findSurroundingKeyframes(e){const{keyframes:n}=this.track;for(let i=0;i<n.length-1;i++)if(e>=n[i].time&&e<=n[i+1].time)return{from:n[i],to:n[i+1]};return{from:null,to:null}}}class Br{track;targets;sampler;constructor(e){this.track=e,this.targets=yt(e),this.sampler=new Wi(e.spring)}getValueAtTime(e){return this.sampler.valueAt(e-St(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,i=[];for(let r=0;r<n;r++){const s=St(r,n,this.track.delay,this.track.stagger);i.push({target:this.targets[r],value:this.sampler.valueAt(e-s),start:s})}return i}getDuration(){const e=this.track.stagger?Se(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=yt(e),this.duration=wn(e.inertia)}getValueAtTime(e){return kn(this.track.inertia,e-St(0,this.targets.length,this.track.delay,this.track.stagger))}getTargetValues(e){const n=this.targets.length,i=[];for(let r=0;r<n;r++){const s=St(r,n,this.track.delay,this.track.stagger);i.push({target:this.targets[r],value:kn(this.track.inertia,e-s),start:s})}return i}getDuration(){const e=this.track.stagger?Se(this.targets.length,this.track.stagger):0;return this.duration+(this.track.delay??0)+e}getTrack(){return this.track}}function Wr(t,e){const n={...yr(t.pathData,e)};if(t.matrix){const[i,r,s,o,a,l]=t.matrix,{x:h,y:u}=n;n.x=i*h+s*u+a,n.y=r*h+o*u+l;const d=n.angle*Math.PI/180,f=Math.cos(d),g=Math.sin(d);n.angle=Math.atan2(r*f+o*g,i*f+s*g)*180/Math.PI}return t.autoRotate&&t.rotateOffset&&(n.angle+=t.rotateOffset),n}const Re={upperCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",lowerCase:"abcdefghijklmnopqrstuvwxyz",upperAndLowerCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",numbers:"0123456789"},Ur=20;function Hr(t){const e=Re[t??"upperCase"]??t??Re.upperCase,n=Array.from(e);return n.length>0?n:Array.from(Re.upperCase)}function Gr(t,e,n){let i=(t|0)^Math.imul(e+1,2654435761)^Math.imul(n+1,2246822507);return i=Math.imul(i^i>>>16,2146121005),i=Math.imul(i^i>>>15,2221713035),(i^i>>>16)>>>0}function Zr(t,e,n=0){const i=t.from??"",r=t.to,s=Math.max(0,Math.min(1,e));if(s<=0)return i;if(s>=1)return r;const o=Array.from(i),a=Array.from(r),l=t.rightToLeft??!1;if(t.mode==="type"){const v=Math.round(s*Math.max(o.length,a.length));return l?o.slice(0,Math.max(0,o.length-v)).join("")+a.slice(Math.max(0,a.length-v)).join(""):a.slice(0,v).join("")+o.slice(v).join("")}const h=Math.max(0,Math.min(.999,t.revealDelay??0)),u=Math.max(0,(s-h)/(1-h)),d=Math.floor(u*a.length),f=t.tweenLength===!1?a.length:Math.round(o.length+(a.length-o.length)*s),g=Hr(t.chars),p=t.refreshRate??Ur,m=p>0?Math.floor(n*p/1e3):0,c=t.seed??1;let y="";for(let v=0;v<f;v++){const $=l?v>=f-d:v<d,w=l?a[a.length-(f-v)]:a[v];$&&w!==void 0||w===" "||w===`
|
|
2
|
-
`?y+=w:y+=g[Gr(c,v,m)%g.length]}return y}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 r=e*this.speed;if(this._repeatDelayRemaining>0){const a=Math.min(this._repeatDelayRemaining,r);if(this._repeatDelayRemaining-=a,r-=a,this._repeatDelayRemaining>0){this.onUpdate?.(this.getStateAtTime(this._currentTime));return}this._wrapAfterDelay&&(this._wrapAfterDelay=!1,this._currentTime=0)}const s=1e3;for(let a=0;a<s&&r>0&&this._playbackState==="playing";a++)if(this._direction==="forward"){const l=n-this._currentTime;if(r>=l){if(r-=l,this._currentTime=n,!this._handleEndReached())break}else this._currentTime+=r,r=0}else{const l=this._currentTime;if(r>=l){if(r-=l,this._currentTime=0,!this._handleStartReached())break}else this._currentTime-=r,r=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[i,r]of this._trackPlayers){const s=r.getTrack().property;for(const{target:o,value:a,start:l}of r.getTargetValues(e))this._write(n,i,o,s,a,e-l)}return{values:n,currentTime:this._currentTime,playbackState:this._playbackState,direction:this._direction,loopIteration:this._loopIteration}}_resolveShared(e,n){const i=new Map;for(const[r,s]of this._trackPlayers){const o=s.getTrack().property;for(const{target:a,value:l,start:h}of s.getTargetValues(e)){const u=`${a}\0${o}`,d=h<=e,f=i.get(u);(!f||(d!==f.started?d:d?h>=f.start:h<=f.start))&&i.set(u,{trackId:r,target:a,property:o,value:l,start:h,started:d})}}for(const{trackId:r,target:s,property:o,value:a,start:l}of i.values())this._write(n,r,s,o,a,e-l)}_write(e,n,i,r,s,o){if(s===void 0)return;let a=e.get(i);a||(a=new Map,e.set(i,a));const l=this._textTracks.get(n);if(l&&typeof s=="number"){a.set("text",Zr(l.textConfig,s,Math.max(0,o)));return}const h=this._motionPathTracks.get(n);if(h&&typeof s=="number"){const u=Wr(h.motionPathConfig,s);a.set("motionPathX",u.x),a.set("motionPathY",u.y),h.motionPathConfig.autoRotate&&a.set("motionPathRotate",u.angle)}else a.set(r,s)}_sharedWrites=null;_hasSharedWrites(){if(this._sharedWrites===null){const e=new Set;this._sharedWrites=!1;t:for(const n of this._tracks)for(const i of yt(n)){const r=`${i}\0${n.property}`;if(e.has(r)){this._sharedWrites=!0;break t}e.add(r)}}return this._sharedWrites}addTrack(e){if(this._tracks.push(e),this._sharedWrites=null,Me(e)){this._trackPlayers.set(e.id,new Vr(e));return}if($e(e)){this._trackPlayers.set(e.id,new Br(e)),this._springTracks.set(e.id,e);return}if(pn(e))this._trackPlayers.set(e.id,new Ce(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 Ce(n)),this._motionPathTracks.set(e.id,e)}else this._trackPlayers.set(e.id,new Ce(e))}replaceTrack(e,n){const i=this._tracks.findIndex(s=>s.id===e);if(i<0)return;const r=this._tracks.slice(i+1);this.removeTrack(e);for(const s of r)this.removeTrack(s.id);this.addTrack(n);for(const s of r)this.addTrack(s)}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(i=>i.id);for(const i of n)this.removeTrack(i);return n}getTrackSpan(e){const n=this._trackPlayers.get(e);if(!n)return;const i=n.getTrack(),r=i.delay??0;if($e(i)||Me(i))return{from:r,to:n.getDuration()};const s=i.keyframes;if(!(!s||s.length===0))return{from:s[0].time+r,to:n.getDuration()}}findConflicts(){const e=[];for(let n=0;n<this._tracks.length;n++){const i=this._tracks[n],r=this.getTrackSpan(i.id);if(r)for(let s=0;s<n;s++){const o=this._tracks[s];if(o.property!==i.property)continue;const a=yt(o).filter(d=>yt(i).includes(d));if(a.length===0)continue;const l=this.getTrackSpan(o.id);if(!l||!(l.from<=r.to&&r.from<=l.to))continue;const u=r.from>=l.from;for(const d of a)e.push({target:d,property:i.property,losingTrackId:u?o.id:i.id,winningTrackId:u?i.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&&!yt(e).includes(n.target))return!1;if(n.timeRange){const i=this.getTrackSpan(e.id);if(!i||i.to<n.timeRange.from||i.from>n.timeRange.to)return!1}return!0}toDefinition(){return{formatVersion:zi(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((r,s)=>r.time-s.time).map(r=>({...r})):void 0,i={...this._config};n?i.markers=n:delete i.markers,this._config=i}get captions(){return this._captions}setCaptions(e){const n={};for(const[i,r]of Object.entries(e??{}))n[i]={...r};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,i){const r=[],s=[],{duration:o,alternate:a}=i,l=(g,p,m,c)=>{s.push([g,p]);const y=[];t.forEach((v,$)=>{(m==="forward"?(c?v>=g:v>g)&&v<=p:(c?v<=g:v<g)&&v>=p)&&y.push($)}),y.sort((v,$)=>(m==="forward"?t[v]-t[$]:t[$]-t[v])||v-$);for(const v of y)r.push({kind:"event",index:v,direction:m})};let h=e.time,u=e.direction,d=e.fresh===!0;const f=Math.min(Kr,Math.max(0,n.iteration-e.iteration));for(let g=0;g<f;g++){const p=u==="forward"?o:0;l(h,p,u,d),r.push({kind:"repeat"}),a?(u=u==="forward"?"reverse":"forward",h=p,d=!1):(h=u==="forward"?0:o,d=!0)}return f>0&&i.holding&&!a?{crossings:r,passes:s}:(l(h,n.time,u,d),{crossings:r,passes:s})}function ts(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 es(t){if(Me(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"inertia",inertia:ts(e.inertia),...qt(e)}}if($e(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"spring",spring:{...e.spring},...qt(e)}}if(pn(t)){const e=t;return{id:e.id,target:e.target,property:"text",textConfig:{...e.textConfig},keyframes:[...e.keyframes].sort((n,i)=>n.time-i.time),...qt(e)}}if(t.property==="motionPath"&&"motionPathConfig"in t){const e=t,n=[...e.keyframes].sort((i,r)=>i.time-r.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 zn(t){const e=t.formatVersion??1;if(e>ke)throw new Error(`tinyfly: this animation uses format version ${e}, but this tinyfly reads up to version ${ke}. Update tinyfly to play it.`);return new Qr({id:t.id,name:t.name,config:t.config,tracks:t.tracks.map(es),captions:t.captions})}function Le(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 Fe(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 Xn(t,e=0,n=1){const i=1-t.next(),r=t.next();return e+n*Math.sqrt(-2*Math.log(i))*Math.cos(2*Math.PI*r)}function ns(t,e){const n=t.toLowerCase(),i=e.toLowerCase();let r=Array.from({length:i.length+1},(s,o)=>o);for(let s=1;s<=n.length;s++){const o=[s];for(let a=1;a<=i.length;a++)o[a]=Math.min(r[a]+1,o[a-1]+1,r[a-1]+(n[s-1]===i[a-1]?0:1));r=o}return r[i.length]}function Yn(t,e){const n=t.toLowerCase(),i=e.find(o=>o.toLowerCase().includes(n)||n.includes(o.toLowerCase()));if(i&&Math.min(t.length,i.length)>=3)return i;let r,s=1/0;for(const o of e){const a=ns(t,o);a<s&&(s=a,r=o)}return r!==void 0&&s<=Math.max(2,Math.floor(t.length/3))?r:void 0}function at(t,e,n,i){const r=typeof e=="string"?Yn(e,n):void 0;return`Unknown ${t} ${JSON.stringify(e)}${r?`: did you mean "${r}"?`:"."} Known: ${n.join(", ")}`}function is(t){const[e,n,i,r]=t;return[1-2*(n*n+i*i),2*(e*n+i*r),2*(e*i-n*r),0,2*(e*n-i*r),1-2*(e*e+i*i),2*(n*i+e*r),0,2*(e*i+n*r),2*(n*i-e*r),1-2*(e*e+n*n),0,0,0,0,1]}function rs(t){return!Array.isArray(t)||t.length!==4?null:`matrix3d(${is(Dt(t)).map(n=>Math.round(n*1e6)/1e6+0).join(", ")})`}const ss=new Set(["blur","brightness","glow","glowColor","shadowX","shadowY","shadowBlur","shadowColor"]),os="#ffffff",as="rgba(0, 0, 0, 0.5)";function cs(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??os})`),t.shadowX!==void 0||t.shadowY!==void 0||t.shadowBlur!==void 0){const n=t.shadowX??0,i=t.shadowY??0,r=Math.max(0,t.shadowBlur??0);e.push(`drop-shadow(${n}px ${i}px ${r}px ${t.shadowColor??as})`)}return e.length>0?e.join(" "):null}function ls(t,e){const n=t.childNodes.length===1?t.firstChild:null;if(n&&n.nodeType===3){const i=n;i.data!==e&&(i.data=e);return}t.textContent!==e&&(t.textContent=e)}function us(t){if(!("ownerSVGElement"in t))return;const e=t.style;!e||e.transformBox||(e.transformBox="fill-box",e.transformOrigin||(e.transformOrigin="50% 50%"))}const Bn=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"]),hs=new Set(["x","y","z","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skewX","skewY","quaternion","motionPathX","motionPathY","motionPathRotate"]),ds=["x","motionPathX","y","motionPathY","z","rotate","rotateZ","motionPathRotate","rotateX","rotateY","quaternion","scale","scaleX","scaleY","scaleZ","skewX","skewY"],fs=new Set(["childPerspective","perspectiveOriginX","perspectiveOriginY"]),ps=new Set(["originX","originY"]),ms=new Set(["clipTop","clipRight","clipBottom","clipLeft"]),gs=new Set(["drawOn"]),ys={fill:"backgroundColor",stroke:"borderColor",strokeWidth:"borderWidth",color:"color",backgroundColor:"backgroundColor",borderColor:"borderColor"},Vn={fill:"fill",stroke:"stroke",strokeWidth:"strokeWidth",strokeDasharray:"strokeDasharray",strokeDashoffset:"strokeDashoffset",fillOpacity:"fillOpacity",strokeOpacity:"strokeOpacity"},bs="http://www.w3.org/2000/svg";class Wn{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,i]of e.values){const r=this.targets.get(n);r&&this.applyProperties(r,i)}}applyProperties(e,n){let i=null,r=null,s=null,o=null,a=null;const l=n.has("motionPathX"),h=n.has("motionPathY"),u=n.has("motionPathRotate");for(const[p,m]of n)if(!(p==="x"&&l)&&!(p==="y"&&h)&&!((p==="rotate"||p==="rotateZ")&&u)&&!gs.has(p)){if(hs.has(p))(i??={})[p]=m;else if(fs.has(p))typeof m=="number"&&((r??={})[p]=m);else if(ps.has(p))typeof m=="number"&&((s??={})[p]=m);else if(ms.has(p))typeof m=="number"&&((o??={})[p]=m);else if(ss.has(p))(a??={})[p]=m;else if(p!=="perspective"){if(p!=="shine")if(p==="text"&&typeof m=="string")ls(e,m);else if(p==="d"&&typeof m=="string"){const c=e;(c.tagName?.toLowerCase()==="path"?c:c.querySelector?.("path"))?.setAttribute?.("d",m)}else this.applyStyleProperty(e,p,m)}}const d=n.get("shine");typeof d=="number"&&this.applyShine(e,d);const f=[],g=n.get("perspective");if(typeof g=="number"&&g>0&&f.push(`perspective(${g}px)`),i)for(const p of ds){const m=i[p];if(m===void 0)continue;const c=this.buildTransformPart(p,m);c&&f.push(c)}if(f.length>0&&(e.style.transform=f.join(" "),us(e)),r&&(r.childPerspective!==void 0&&(e.style.perspective=`${r.childPerspective}px`),(r.perspectiveOriginX!==void 0||r.perspectiveOriginY!==void 0)&&(e.style.perspectiveOrigin=`${r.perspectiveOriginX??50}% ${r.perspectiveOriginY??50}%`)),s){const p=s.originX??50,m=s.originY??50;e.style.transformOrigin=`${p}% ${m}%`}if(o){const p=o.clipTop??0,m=o.clipRight??0,c=o.clipBottom??0,y=o.clipLeft??0;e.style.clipPath=`inset(${p}% ${m}% ${c}% ${y}%)`}if(a){const p=cs(a);p&&(e.style.filter=p)}}buildTransformPart(e,n){if(e==="quaternion")return rs(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 i=e.dataset.shineBase,r=-20+n*140,s=e.style;s.color="transparent",s.backgroundImage=`linear-gradient(105deg, transparent 40%, rgba(255, 255, 255, 0.9) 50%, transparent 60%), linear-gradient(${i}, ${i})`,s.backgroundSize="250% 100%, 100% 100%",s.backgroundPosition=`${r}% 0, 0 0`,s.backgroundRepeat="no-repeat",s.webkitBackgroundClip="text",s.backgroundClip="text"}applyStyleProperty(e,n,i){let r;if(e.namespaceURI===bs&&n in Vn){const a=Array.isArray(i)?i.join(", "):String(i);e.style[Vn[n]]=a;return}else n==="fill"&&e.dataset?.elementType==="text"?r="color":r=ys[n]??n;let o;typeof i=="number"?Bn.has(n)||Bn.has(r)?o=`${i}px`:o=String(i):Array.isArray(i)?o=i.join(", "):o=i,e.style[r]=o}}class Un{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 i=this.targetTime(e);n?(this.media.paused&&this.safePlay(),Math.abs(this.media.currentTime-i)>this.driftTolerance&&(this.media.currentTime=i)):(this.media.paused||this.media.pause(),this.media.currentTime!==i&&(this.media.currentTime=i))}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 vs(t,e,n,i,r){const s=n-r;if(s<0){e.paused||e.pause(),e.currentTime=0;return}t.update(s,i)}class ws{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 i=document.querySelector(e);if(!i)throw new Error(`Container not found: ${e}`);this.container=i}else this.container=e;this.options=n,this.adapter=new Wn}async load(e){this.scenarioList=[],this.scenarioId=void 0,await this.loadSource(e)}async loadSource(e){let n;if(typeof e=="string"){const i=await fetch(e);if(!i.ok)throw new Error(`Failed to load animation: ${i.statusText}`);n=await i.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=zn({...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 i=new Set;for(const s of e){if(i.has(s.id))throw new Error(`tinyfly: scenario id "${s.id}" is used more than once`);i.add(s.id)}const r=n.initial===void 0?e[0]:e.find(s=>s.id===n.initial);if(!r)throw new Error(`tinyfly: there is no scenario "${n.initial}"`);this.scenarioList=[...e],this.scenarioId=r.id,await this.loadSource(r.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(a=>a.id===e);if(!n||!this.timeline)return!1;if(e===this.scenarioId)return!0;const i=this.isPlaying,r=this.currentTime>=this.duration-.5,s=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||r?o=this.duration:s!==void 0&&(o=this.markers.find(a=>a.id===s)?.time??0),this.seek(o),i&&!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 i=e.tagName.toLowerCase()==="path"?e:e.querySelector("path");i&&(n.path={element:i,d:i.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 i=e.dataset;i&&delete i.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 i of this.markers)if(i.time<=e+.5)n=i;else break;return n}caption(e,n){const i=e?this.markers.find(o=>o.id===e):this.currentMarker;if(!i)return;const r=n??this.language(),s=o=>o?.[r]?.[i.id]??o?.[r.split("-")[0]]?.[i.id];return s(this.options.captions)??s(this.timeline?.captions)??i.label}next(){if(!this.timeline)return;const e=this.currentTime,n=this.markers.find(i=>i.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(i=>i.time<e-.5);this.pause(),this.seek(n?n.time:0)}goToMarker(e){const n=this.markers.find(i=>i.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 i of n)this.onScreen=i.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 i=n,r=Number(i.getAttribute("data-tinyfly-start")??"0")||0,s=i.getAttribute("data-volume");s!==null&&(i.volume=Math.max(0,Math.min(1,Number(s)||0))),this.mediaTargets.push({el:i,startTime:r,sync:new Un(i)})})}syncAllMedia(e,n){for(const i of this.mediaTargets)vs(i.sync,i.el,e,n,i.startTime)}loadFromString(e){const n=JSON.parse(e);this.load(n)}registerTarget(e,n){if(typeof n=="string"){const i=this.container.querySelector(n);i&&(this.rememberAuthored(i),this.targets[e]=i,this.adapter.registerTarget(e,i))}else this.rememberAuthored(n),this.targets[e]=n,this.adapter.registerTarget(e,n)}autoRegisterTargets(){this.container.querySelectorAll("[data-tinyfly]").forEach(n=>{const i=n.closest("[data-tinyfly-symbol]");if(i&&i!==n)return;const r=n.getAttribute("data-tinyfly");r&&this.registerTarget(r,n)}),this.timeline&&new Set(this.timeline.tracks.map(i=>i.target)).forEach(i=>{if(!this.targets[i]){const r=this.container.querySelector(`[data-tinyfly="${i}"]`)||this.container.querySelector(`.${i}`)||this.container.querySelector(`#${i}`);r&&this.registerTarget(i,r)}})}setupSymbolInstances(){this.symbolInstances=[];const e=this.options.symbols;if(!e||e.length===0)return;const n=new Map(e.map(i=>[i.id,i]));this.container.querySelectorAll("[data-tinyfly-symbol]").forEach(i=>{const r=i.getAttribute("data-tinyfly-symbol");if(!r)return;const s=n.get(r);if(!s||!s.timeline.tracks?.length)return;const o=new Wn;i.querySelectorAll("[data-tinyfly]").forEach(a=>{const l=a.getAttribute("data-tinyfly");l&&o.registerTarget(l,a)}),this.symbolInstances.push({adapter:o,timeline:zn(s.timeline)})})}attachMedia(e,n){this.mediaSync=new Un(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 i=n-(this.lastTime??n);this.lastTime=n;const r=this.playhead;this.timeline.tick(i),this.stopAtMarker(r),this.applyState();const s=this.timeline.playbackState==="playing";this.mediaSync?.update(this.timeline.currentTime,s),this.syncAllMedia(this.timeline.currentTime,s),this.timeline.playbackState==="playing"?this.animationFrameId=requestAnimationFrame(e):(this.animationFrameId=void 0,this.notify())};this.animationFrameId=requestAnimationFrame(e)}stopAtMarker(e){const n=this.timeline,i={time:n.currentTime,iteration:n.loopIteration,direction:n.direction};this.playhead=i;const r=this.markers;if(r.length===0)return;const{crossings:s}=Jr(r.map(o=>o.time),e,i,{duration:n.duration,alternate:n.config.alternate===!0,holding:n.repeatDelayRemaining>0});for(const o of s){if(o.kind!=="event")continue;const a=r[o.index];if(this.stepping||a.pause){this.stepping=!1,n.pause(),n.seek(a.time),this.playhead={time:a.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 i=n.timeline.duration;n.adapter.applyState(n.timeline.getStateAtTime(i>0?e%i:e))}}}const ks={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"},Hn="tinyfly-controls-style",Ms=`
|
|
1
|
+
(function(M){"use strict";function Li(t){return typeof t=="object"&&t!==null&&t.type==="cubic-bezier"}function Ri(t){return typeof t=="object"&&t!==null&&t.type!=="cubic-bezier"}const Ue=2;function Di(t){return t.some(e=>e.interpolation!==void 0)?2:1}function jn(t){return t.property==="text"&&"textConfig"in t}function We(t){return t.kind==="inertia"&&"inertia"in t}function Ge(t){return t.kind==="spring"&&"spring"in t}function qi(t){return t.property==="motionPath"&&"motionPathConfig"in t}function zi(t,e){if(!(e>0))return t;const n=1e3/e;return Math.floor(t/n+1e-9)*n}function Xn(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 ji(t,e="start"){if(t<=1)return 0;let n=0;for(let s=0;s<t;s++)n=Math.max(n,Xn(s,t,e));return n}function Yn(t,e,n){if(n.offsets)return n.offsets[t]??0;const s=n.from??"start",i=Xn(t,e,s);if(n.amount!==void 0){const r=ji(e,s);return r===0?0:n.amount*i/r}return n.each!==void 0?n.each*i:0}function Xi(t,e){return Array.from({length:t},(n,s)=>Yn(s,t,e))}function Ze(t,e){return t<=1?0:Math.max(...Xi(t,e))}const jt=1,Bn=6e4,ge=Bn/jt,Tt={stiffness:180,damping:12,mass:1,velocity:0,restDelta:.01,restSpeed:.1};class Yi{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/jt);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/jt-n;return s+(i-s)*r}settleTime(){return this.simulateTo(ge+1),this.settledStep!==null?this.settledStep*jt:Bn}simulateTo(e){if(this.settledStep!==null)return;const n=Math.min(e,ge+1),s=jt/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>ge&&(this.settledStep=ge)}}const Vn=4,Bi=.002,Vi=1e-4,Hi=6e4;function Qe(t){const e=t.friction??Vn;return e>0?e:Vn}function Ui(t){return t.from+t.velocity/Qe(t)}function Wi(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 Hn(t){let e=Wi(Ui(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 Un(t){const e=Math.abs(Hn(t)-t.from);if(e===0)return 0;const n=t.restDelta??Math.max(Vi,e*Bi);if(n>=e)return 0;const s=Math.log(e/n)/Qe(t);return Math.min(Hi,s*1e3)}function Wn(t,e){if(e<=0)return t.from;const n=Hn(t);if(e>=Un(t))return n;const s=Qe(t);return t.from+(n-t.from)*(1-Math.exp(-s*e/1e3))}const Ke=t=>t,Gi=t=>t*t,Zi=t=>1-(1-t)*(1-t),Qi=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2,Gn=t=>t*t*t,Zn=t=>1-Math.pow(1-t,3),Qn=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,Ki={linear:Ke,"ease-in":Gn,"ease-out":Zn,"ease-in-out":Qn,"ease-in-quad":Gi,"ease-out-quad":Zi,"ease-in-out-quad":Qi,"ease-in-cubic":Gn,"ease-out-cubic":Zn,"ease-in-out-cubic":Qn};function Ji(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=y=>((c*y+o)*y+r)*y,f=y=>((h*y+u)*y+l)*y,g=y=>(3*c*y+2*o)*y+r,p=y=>{let a=y;for(let x=0;x<8;x++){const w=d(a)-y;if(Math.abs(w)<1e-7)return a;const b=g(a);if(Math.abs(b)<1e-7)break;a-=w/b}let m=0,v=1;for(a=y;m<v;){const x=d(a);if(Math.abs(x-y)<1e-7)return a;y>x?m=a:v=a,a=(m+v)/2}return a};return y=>{if(y<=0)return 0;if(y>=1)return 1;const a=p(y);return f(a)}}function Je(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 tr(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 er=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 nr(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 sr(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 ir(t){switch(t.type){case"steps":return sr(t.count,t.position);case"elastic":return Je(tr(t.amplitude,t.period),t.mode);case"bounce":return Je(er,t.mode);case"back":return Je(nr(t.overshoot),t.mode)}}function rr(t){return t===void 0?Ke:Li(t)?Ji(t.points):Ri(t)?ir(t):Ki[t]??Ke}const Kn=32,or=256,Xt=new Map,ar=/[MmLlHhVvCcSsQqTtAaZz]/,cr=/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/,lr={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0};function ur(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(ar.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=cr.exec(t.slice(n));if(!l)break;s.args.push(parseFloat(l[0])),n+=l[0].length}return e}function hr(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),g=Math.sin(d),p=(t-c)/2,y=(e-l)/2,a=f*p+g*y,m=-g*p+f*y,v=a*a/(u*u)+m*m/(h*h);if(v>1){const D=Math.sqrt(v);u*=D,h*=D}const x=r===o?-1:1,w=u*u*h*h-u*u*m*m-h*h*a*a,b=u*u*m*m+h*h*a*a,k=x*Math.sqrt(Math.max(0,w/b)),$=k*u*m/h,S=-k*h*a/u,T=f*$-g*S+(t+c)/2,A=g*$+f*S+(e+l)/2,_=(D,B,tt,zt)=>{const zn=D*tt+B*zt,He=Math.sqrt((D*D+B*B)*(tt*tt+zt*zt)),pe=Math.acos(Math.max(-1,Math.min(1,zn/He)));return D*zt-B*tt<0?-pe:pe},E=_(1,0,(a-$)/u,(m-S)/h);let C=_((a-$)/u,(m-S)/h,(-a-$)/u,(-m-S)/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),Y=D=>{const B=u*Math.cos(D),tt=h*Math.sin(D);return[f*B-g*tt+T,g*B+f*tt+A]},J=D=>{const B=-u*Math.sin(D),tt=h*Math.cos(D);return[f*B-g*tt,g*B+f*tt]},j=[];for(let D=0;D<N;D++){const B=E+D*P,tt=B+P,[zt,zn]=Y(B),[He,pe]=D===N-1?[c,l]:Y(tt),[Xc,Yc]=J(B),[Bc,Vc]=J(tt);j.push([zt+F*Xc,zn+F*Yc,He-F*Bc,pe-F*Vc,He,pe])}return j}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 Jn(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 Yt(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 ye(t,e,n){const[s,i,r,o,c,l]=n,u=[0];let h=t,d=e,f=0;for(let g=1;g<=Kn;g++){const p=g/Kn,y=gt(t,s,r,c,p),a=gt(e,i,o,l,p);f+=Math.hypot(y-h,a-d),u.push(f),h=y,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=Xt.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=y=>{u<0&&(u=0),y.subpath=u,n.push(y)};for(const{type:y,args:a}of ur(t)){const m=y.toUpperCase(),v=y!==m,x=lr[m];if(m==="Z"){(s!==r||i!==o)&&d(Yt(s,i,r,o)),u>=0&&h.add(u),s=r,i=o,c=l=null;continue}for(let w=0;w+x<=a.length;w+=x){const b=a.slice(w,w+x),k=v?s:0,$=v?i:0;let S=null,T=null;switch(m){case"M":w===0?(s=b[0]+k,i=b[1]+$,r=s,o=i,(u<0||n[n.length-1]?.subpath===u)&&u++):(d(Yt(s,i,b[0]+k,b[1]+$)),s=b[0]+k,i=b[1]+$);break;case"L":d(Yt(s,i,b[0]+k,b[1]+$)),s=b[0]+k,i=b[1]+$;break;case"H":d(Yt(s,i,b[0]+k,i)),s=b[0]+k;break;case"V":d(Yt(s,i,s,b[0]+$)),i=b[0]+$;break;case"C":{const A=[b[0]+k,b[1]+$,b[2]+k,b[3]+$,b[4]+k,b[5]+$];d(ye(s,i,A)),S=[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],E=[A,_,b[0]+k,b[1]+$,b[2]+k,b[3]+$];d(ye(s,i,E)),S=[E[2],E[3]],s=E[4],i=E[5];break}case"Q":case"T":{let A=s,_=i;m==="Q"?(A=b[0]+k,_=b[1]+$):l&&(A=2*s-l[0],_=2*i-l[1]);const E=m==="Q"?b[2]+k:b[0]+k,C=m==="Q"?b[3]+$:b[1]+$;d(ye(s,i,[s+2/3*(A-s),i+2/3*(_-i),E+2/3*(A-E),C+2/3*(_-C),E,C])),T=[A,_],s=E,i=C;break}case"A":{const A=b[5]+k,_=b[6]+$;let E=s,C=i;for(const N of hr(s,i,b[0],b[1],b[2],b[3],b[4],A,_))d(ye(E,C,N)),E=N[4],C=N[5];s=A,i=_;break}}c=S,l=T}}const f=n.reduce((y,a)=>y+a.length,0),g=[];for(let y=0;y<n.length;){const a=n[y].subpath;let m=y,v=0;for(;m<n.length&&n[m].subpath===a;)v+=n[m++].length;const x=n[y],w=n[m-1],b=h.has(a)||Math.abs(w.endX-x.startX)<1e-9&&Math.abs(w.endY-x.startY)<1e-9;g.push({start:y,end:m,length:v,closed:b}),y=m}const p={segments:n,totalLength:f,subpaths:g};return Xt.size>=or&&Xt.delete(Xt.keys().next().value),Xt.set(t,p),p}function dr(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 fr(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=dr(t,e);let u=Jn(t.startX,n,i,o,l),h=Jn(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),g=gt(t.startY,s,r,c,d),p=gt(t.startX,n,i,o,l),y=gt(t.startY,s,r,c,l);u=l<.5?f-p:p-f,h=l<.5?g-y:y-g}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 ts(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 fr(o,e-i);i+=o.length}return{x:0,y:0,angle:0}}function pr(t,e){const{segments:n,totalLength:s}=me(t);return ts(n,Math.max(0,Math.min(1,e))*s)}const gr=24,yr=320,mr=2.5,Bt=72,br=.2,vr=128,be=new Map;let tn=0,mt;const es=t=>Math.round(t*100)/100;function ns(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 en(t,e){const n=t.closed?(e%1+1)%1:Math.max(0,Math.min(1,e)),s=ts(t.segments,n*t.length,t.start,t.end);return[s.x,s.y]}function ss(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 is(t,e){const n=[];for(let s=0;s<e;s++)n.push(en(t,t.closed?s/e:s/(e-1)));return n}function rs(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 wr(t,e,n){const s=t.closed&&e.closed;if(n!==void 0)return{offset:s?Math.abs(n)%Bt/Bt:0,reversed:n<0};const i=rs(is(t,Bt)),r=rs(is(e,Bt)),o=Bt;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 g=0;g<o&&f<l;g++){const p=s?u?(d-g+o)%o:(g+d)%o:u?o-1-g:g,y=i[g][0]-r[p][0],a=i[g][1]-r[p][1];f+=y*y+a*a}f<l&&(l=f,c={offset:s?d/o:0,reversed:u})}}return c}function kr(t,e,n){return n?((e.reversed?e.offset-t:t+e.offset)%1+1)%1:e.reversed?1-t:t}function Mr(t,e,n){return n?((e.reversed?e.offset-t:t-e.offset)%1+1)%1:e.reversed?1-t:t}function $r(t,e,n){const s=t.closed&&e.closed,i=wr(t,e,n.shapeIndex),r=Math.max(gr,Math.min(yr,Math.ceil(Math.max(t.length,e.length)/mr))),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 ss(t))c(d);for(const d of ss(e))c(Mr(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(...en(t,d)),h.push(...en(e,kr(d,i,s)));return Sr({from:u,to:h,closed:s})}function Sr(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=br;for(let h=o+1;h<c;h++){const d=Math.max(os(t.from,o,c,h),os(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 os(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 xr(t,e,n){const s=n.shapeIndex;if(mt&&mt.from===t&&mt.to===e&&mt.shapeIndex===s)return mt.plan;const r=be.get(String(s??"auto"))?.get(t)?.get(e);if(r)return mt={from:t,to:e,shapeIndex:s,plan:r},r;const o=me(t).subpaths.filter(g=>g.length>0).length===me(e).subpaths.filter(g=>g.length>0).length,c=ns(t,!o),l=ns(e,!o),u={pairs:c.map((g,p)=>$r(g,l[p],n))};tn>=vr&&(be.clear(),tn=0);const h=String(s??"auto"),d=be.get(h)??new Map;be.set(h,d);const f=d.get(t)??new Map;return d.set(t,f),f.set(e,u),tn++,mt={from:t,to:e,shapeIndex:s,plan:u},u}function Ar(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=xr(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=es(c.from[l]+(c.to[l]-c.from[l])*i),h=es(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 Tr(t){return/^\s*[Mm]\s*[-+]?(?:\d|\.\d)/.test(t)}const Er=.9995;function _r(){return[0,0,0,1]}function Pr(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]+t[3]*e[3]}function Or(t){return Math.hypot(t[0],t[1],t[2],t[3])}function Vt(t){const e=Or(t);return e===0?_r():[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function Ir(t,e,n){const s=Vt(t);let i=Vt(e),r=Pr(s,i);if(r<0&&(i=[-i[0],-i[1],-i[2],-i[3]],r=-r),r>Er)return Vt([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 Vt([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,as=512,nn=new Map,sn=new Map;function cs(t){const e=nn.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 nn.size<as&&nn.set(t,s),s}const ls=t=>t.charCodeAt(0)===35,us=t=>t.startsWith("rgb"),hs=t=>t.startsWith("rgba"),Cr=/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/,rn=t=>Math.round(t).toString(16).padStart(2,"0");function Nr(t,e,n){return`#${rn(t)}${rn(e)}${rn(n)}`}function ds(t){const e=sn.get(t);if(e)return e;const n=t.match(Cr);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 sn.size<as&&sn.set(t,o),o}const Fr=(t,e,n)=>{if(ls(t)&&ls(e)){const[s,i,r]=cs(t),[o,c,l]=cs(e),u=dt(s,o,n),h=dt(i,c,n),d=dt(r,l,n);return Nr(u,h,d)}if((us(t)||hs(t))&&(us(e)||hs(e))){const s=ds(t),i=ds(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},Lr=(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},Rr=(t,e,n)=>Ir(t,e,n),fs=(t,e,n)=>n<1?t:e,Dr=(t,e,n)=>Ar(t,e,n);function qr(t,e){return e==="slerp"?Rr:typeof t=="number"?dt:Array.isArray(t)?Lr:typeof t=="string"?t.startsWith("#")||t.startsWith("rgb")?Fr:Tr(t)?Dr:fs:fs}function zr(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 Et(t,e,n,s){const i=n??0;return!s||e<=1?i:i+Yn(t,e,s)}class on{track;targets;constructor(e){this.track=e,this.targets=bt(e)}getValueAtTime(e){return this.valueForOffset(e-Et(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=Et(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?Ze(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=rr(i.easing)(o);return qr(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 jr{track;targets;sampler;constructor(e){this.track=e,this.targets=bt(e),this.sampler=new Yi(e.spring)}getValueAtTime(e){return this.sampler.valueAt(e-Et(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=Et(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?Ze(this.targets.length,this.track.stagger):0;return this.sampler.settleTime()+(this.track.delay??0)+e}getTrack(){return this.track}}class Xr{track;targets;duration;constructor(e){this.track=e,this.targets=bt(e),this.duration=Un(e.inertia)}getValueAtTime(e){return Wn(this.track.inertia,e-Et(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=Et(i,n,this.track.delay,this.track.stagger);s.push({target:this.targets[i],value:Wn(this.track.inertia,e-r),start:r})}return s}getDuration(){const e=this.track.stagger?Ze(this.targets.length,this.track.stagger):0;return this.duration+(this.track.delay??0)+e}getTrack(){return this.track}}function Yr(t,e){const n={...pr(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),g=Math.sin(d);n.angle=Math.atan2(i*f+o*g,s*f+r*g)*180/Math.PI}return t.autoRotate&&t.rotateOffset&&(n.angle+=t.rotateOffset),n}const an={upperCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",lowerCase:"abcdefghijklmnopqrstuvwxyz",upperAndLowerCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",numbers:"0123456789"},Br=20;function Vr(t){const e=an[t??"upperCase"]??t??an.upperCase,n=Array.from(e);return n.length>0?n:Array.from(an.upperCase)}function Hr(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 Ur(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 v=Math.round(r*Math.max(o.length,c.length));return l?o.slice(0,Math.max(0,o.length-v)).join("")+c.slice(Math.max(0,c.length-v)).join(""):c.slice(0,v).join("")+o.slice(v).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),g=Vr(t.chars),p=t.refreshRate??Br,y=p>0?Math.floor(n*p/1e3):0,a=t.seed??1;let m="";for(let v=0;v<f;v++){const x=l?v>=f-d:v<d,w=l?c[c.length-(f-v)]:c[v];x&&w!==void 0||w===" "||w===`
|
|
2
|
+
`?m+=w:m+=g[Hr(a,v,y)%g.length]}return m}class Wr{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=zi(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",Ur(l.textConfig,r,Math.max(0,o)));return}const u=this._motionPathTracks.get(n);if(u&&typeof r=="number"){const h=Yr(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,We(e)){this._trackPlayers.set(e.id,new Xr(e));return}if(Ge(e)){this._trackPlayers.set(e.id,new jr(e)),this._springTracks.set(e.id,e);return}if(jn(e))this._trackPlayers.set(e.id,new on(e)),this._textTracks.set(e.id,e);else if(qi(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 on(n)),this._motionPathTracks.set(e.id,e)}else this._trackPlayers.set(e.id,new on(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(Ge(s)||We(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:Di(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 Gr=100;function Zr(t,e,n,s){const i=[],r=[],{duration:o,alternate:c}=s,l=(g,p,y,a)=>{r.push([g,p]);const m=[];t.forEach((v,x)=>{(y==="forward"?(a?v>=g:v>g)&&v<=p:(a?v<=g:v<g)&&v>=p)&&m.push(x)}),m.sort((v,x)=>(y==="forward"?t[v]-t[x]:t[x]-t[v])||v-x);for(const v of m)i.push({kind:"event",index:v,direction:y})};let u=e.time,h=e.direction,d=e.fresh===!0;const f=Math.min(Gr,Math.max(0,n.iteration-e.iteration));for(let g=0;g<f;g++){const p=h==="forward"?o:0;l(u,p,h,d),i.push({kind:"repeat"}),c?(h=h==="forward"?"reverse":"forward",u=p,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 Qr(t){return{...t,...Array.isArray(t.end)&&{end:[...t.end]}}}function Ht(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 Kr(t){if(We(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"inertia",inertia:Qr(e.inertia),...Ht(e)}}if(Ge(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"spring",spring:{...e.spring},...Ht(e)}}if(jn(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),...Ht(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,...Ht(e)}}return zr({id:t.id,target:t.target,property:t.property,keyframes:t.keyframes,...t.interpolation!==void 0&&{interpolation:t.interpolation},...Ht(t)})}function ps(t){const e=t.formatVersion??1;if(e>Ue)throw new Error(`tinyfly: this animation uses format version ${e}, but this tinyfly reads up to version ${Ue}. Update tinyfly to play it.`);return new Wr({id:t.id,name:t.name,config:t.config,tracks:t.tracks.map(Kr),captions:t.captions})}function vt(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 _t(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 wt(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 Jr(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 gs(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=Jr(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 V(t,e,n,s){const i=typeof e=="string"?gs(e,n):void 0;return`Unknown ${t} ${JSON.stringify(e)}${i?`: did you mean "${i}"?`:"."} Known: ${n.join(", ")}`}function to(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 eo(t){return!Array.isArray(t)||t.length!==4?null:`matrix3d(${to(Vt(t)).map(n=>Math.round(n*1e6)/1e6+0).join(", ")})`}const no=new Set(["blur","brightness","glow","glowColor","shadowX","shadowY","shadowBlur","shadowColor"]),so="#ffffff",io="rgba(0, 0, 0, 0.5)";function ro(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??so})`),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??io})`)}return e.length>0?e.join(" "):null}function oo(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 ao(t){if(!("ownerSVGElement"in t))return;const e=t.style;!e||e.transformBox||(e.transformBox="fill-box",e.transformOrigin||(e.transformOrigin="50% 50%"))}const ys=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"]),co=new Set(["x","y","z","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skewX","skewY","quaternion","motionPathX","motionPathY","motionPathRotate"]),lo=["x","motionPathX","y","motionPathY","z","rotate","rotateZ","motionPathRotate","rotateX","rotateY","quaternion","scale","scaleX","scaleY","scaleZ","skewX","skewY"],uo=new Set(["childPerspective","perspectiveOriginX","perspectiveOriginY"]),ho=new Set(["originX","originY"]),fo=new Set(["clipTop","clipRight","clipBottom","clipLeft"]),po=new Set(["drawOn"]),go={fill:"backgroundColor",stroke:"borderColor",strokeWidth:"borderWidth",color:"color",backgroundColor:"backgroundColor",borderColor:"borderColor"},ms={fill:"fill",stroke:"stroke",strokeWidth:"strokeWidth",strokeDasharray:"strokeDasharray",strokeDashoffset:"strokeDashoffset",fillOpacity:"fillOpacity",strokeOpacity:"strokeOpacity"},yo="http://www.w3.org/2000/svg";class bs{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[p,y]of n)if(!(p==="x"&&l)&&!(p==="y"&&u)&&!((p==="rotate"||p==="rotateZ")&&h)&&!po.has(p)){if(co.has(p))(s??={})[p]=y;else if(uo.has(p))typeof y=="number"&&((i??={})[p]=y);else if(ho.has(p))typeof y=="number"&&((r??={})[p]=y);else if(fo.has(p))typeof y=="number"&&((o??={})[p]=y);else if(no.has(p))(c??={})[p]=y;else if(p!=="perspective"){if(p!=="shine")if(p==="text"&&typeof y=="string")oo(e,y);else if(p==="d"&&typeof y=="string"){const a=e;(a.tagName?.toLowerCase()==="path"?a:a.querySelector?.("path"))?.setAttribute?.("d",y)}else this.applyStyleProperty(e,p,y)}}const d=n.get("shine");typeof d=="number"&&this.applyShine(e,d);const f=[],g=n.get("perspective");if(typeof g=="number"&&g>0&&f.push(`perspective(${g}px)`),s)for(const p of lo){const y=s[p];if(y===void 0)continue;const a=this.buildTransformPart(p,y);a&&f.push(a)}if(f.length>0&&(e.style.transform=f.join(" "),ao(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 p=r.originX??50,y=r.originY??50;e.style.transformOrigin=`${p}% ${y}%`}if(o){const p=o.clipTop??0,y=o.clipRight??0,a=o.clipBottom??0,m=o.clipLeft??0;e.style.clipPath=`inset(${p}% ${y}% ${a}% ${m}%)`}if(c){const p=ro(c);p&&(e.style.filter=p)}}buildTransformPart(e,n){if(e==="quaternion")return eo(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===yo&&n in ms){const c=Array.isArray(s)?s.join(", "):String(s);e.style[ms[n]]=c;return}else n==="fill"&&e.dataset?.elementType==="text"?i="color":i=go[n]??n;let o;typeof s=="number"?ys.has(n)||ys.has(i)?o=`${s}px`:o=String(s):Array.isArray(s)?o=s.join(", "):o=s,e.style[i]=o}}class vs{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 mo(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 bo{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 bs}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=ps({...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 vs(s)})})}syncAllMedia(e,n){for(const s of this.mediaTargets)mo(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 bs;s.querySelectorAll("[data-tinyfly]").forEach(c=>{const l=c.getAttribute("data-tinyfly");l&&o.registerTarget(l,c)}),this.symbolInstances.push({adapter:o,timeline:ps(r.timeline)})})}attachMedia(e,n){this.mediaSync=new vs(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}=Zr(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 vo={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"},ws="tinyfly-controls-style",wo=`
|
|
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
|
|
50
|
+
`;let ko=0;function Mo(t){if(t.getElementById(ws))return;const e=t.createElement("style");e.id=ws,e.textContent=wo,t.head.appendChild(e)}function $o(t,e,n={}){const s=e.ownerDocument;Mo(s);const i={...vo,...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,Y,J="")=>{const j=s.createElement("button");return j.type="button",j.className=`tf-ctl-btn ${J}`.trim(),j.setAttribute("aria-label",P),j.title=P,j.textContent=F,j.addEventListener("click",Y),j},d=h(i.restart,"⟲",()=>{t.pause(),t.seek(0)}),f=h(i.prev,"|◀",()=>t.prev()),g=h(i.play,"▶",()=>t.isPlaying?t.pause():y(),"tf-ctl-primary"),p=h(i.next,"▶|",()=>t.next()),y=()=>{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 v=s.createElement("select");v.className="tf-ctl-speed",v.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),v.appendChild(F)}v.addEventListener("change",()=>t.setSpeed(Number(v.value))),u.append(d,f,g,p,a,m),r.length>0&&u.append(v),l.append(u);const x=n.fullscreen?To(e,s,i):void 0;x&&u.append(x.button);const w=s.createElement("p");w.className="tf-ctl-caption",w.setAttribute("aria-live","polite"),n.captions!==!1&&l.append(w);const b=s.createElement("div");b.className="tf-ctl-question",b.hidden=!0;const k=s.createElement("span"),$=h(i.reveal,i.reveal,()=>t.play(),"tf-ctl-primary");b.append(k,$),l.append(b);const S=So(t,s,i.scenario,n.scenarioControl??"buttons");S&&l.append(S.element);const T=n.mount;T?T.appendChild(l):e.insertAdjacentElement("afterend",l);const A=()=>{const P=t.isPlaying;g.textContent=P?"❚❚":"▶",g.setAttribute("aria-label",P?i.pause:i.play),g.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 Y=t.markers;if(f.hidden=p.hidden=m.hidden=Y.length===0,Y.length>0){const J=t.currentMarker,j=J?Y.indexOf(J)+1:0;m.textContent=i.stepFormat.replace("{index}",String(j)).replace("{total}",String(Y.length)),m.setAttribute("aria-label",`${i.step} ${j} ${i.of} ${Y.length}`),f.disabled=t.currentTime<=.5,p.disabled=t.currentTime>=F-.5;const D=t.caption()??"";w.textContent!==D&&(w.textContent=D),w.hidden=!c();const B=!P&&J?.question!==void 0&&Math.abs(t.currentTime-J.time)<1;b.hidden=!B,B&&k.textContent!==J.question&&(k.textContent=J.question)}else b.hidden=!0,w.hidden=!0;S?.update()},_=t.subscribe(A);A();const E=n.keyboardScope??e;!E.hasAttribute("tabindex")&&E.tabIndex<0&&(E.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():y();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(!x)return;P.preventDefault(),x.active?x.exit():x.enter();break}};return E.addEventListener("keydown",N),l.addEventListener("keydown",N),{element:l,fullscreen:x&&{get active(){return x.active},enter:x.enter,exit:x.exit},destroy(){x?.destroy(),_(),E.removeEventListener("keydown",N),l.removeEventListener("keydown",N),l.remove()}}}function So(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 g=e.createElement("output");return g.setAttribute("aria-hidden","true"),f.addEventListener("input",()=>{const y=i[Number(f.value)];y&&t.setScenario(y.id)}),h.append(d,f,g),{element:h,update:()=>{const y=Math.max(0,i.findIndex(m=>m.id===t.scenario));e.activeElement!==f&&(f.value=String(y));const a=i[y].label;g.textContent!==a&&(g.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-${++ko}`,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 g=e.createElement("span");return g.textContent=h.label,d.append(f,g),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 xo='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>',Ao='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>';function To(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 y=o!==void 0;r.innerHTML=y?Ao:xo;const a=y?n.exitFullscreen:n.fullscreen;r.setAttribute("aria-label",a),r.title=a,r.setAttribute("aria-pressed",String(y)),t.classList.toggle("tf-fullscreen",y),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=y=>{y.key==="Escape"&&p()},f=()=>{o="overlay",c=e.documentElement.style.overflow,e.documentElement.style.overflow="hidden",e.addEventListener("keydown",d),l()};async function g(){if(o)return;const y=i.requestFullscreen?.bind(i)??i.webkitRequestFullscreen?.bind(i),a=s.fullscreenEnabled??s.webkitFullscreenEnabled??!1;if(y&&a)try{if(await y(),u()===t){o="native",l();return}}catch{}f()}async function p(){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 y=s.exitFullscreen?.bind(s)??s.webkitExitFullscreen?.bind(s);u()===t&&y&&await y()}}return r.addEventListener("click",()=>{o?p():g()}),e.addEventListener("fullscreenchange",h),e.addEventListener("webkitfullscreenchange",h),l(),{button:r,get active(){return o!==void 0},enter:g,exit:p,destroy(){p(),e.removeEventListener("fullscreenchange",h),e.removeEventListener("webkitfullscreenchange",h),r.remove()}}}const ks="tinyfly-choices-style",Eo=`
|
|
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 Os(t){if(t.getElementById(Gn))return;const e=t.createElement("style");e.id=Gn,e.textContent=Ps,t.head.appendChild(e)}function Is(t,e){const n=Array.from(e.querySelectorAll("[data-tinyfly-choose]"));if(n.length===0)return()=>{};Os(e.ownerDocument);const i=[],r=[];for(const a of n){const l=a.getAttribute("data-tinyfly-choose")??"",h=[],u=(p,m)=>{a.hasAttribute(p)||(a.setAttribute(p,m),h.push(p))};u("role","button"),u("tabindex","0");const d=t.scenarios.find(p=>p.id===l)?.label;d!==void 0&&u("aria-label",d),a.setAttribute("aria-pressed","false"),h.push("aria-pressed"),i.push({element:a,attributes:h});const f=()=>t.setScenario(l),g=p=>{const m=p.key;m!=="Enter"&&m!==" "||(p.preventDefault(),f())};a.addEventListener("click",f),a.addEventListener("keydown",g),r.push(()=>{a.removeEventListener("click",f),a.removeEventListener("keydown",g)})}const s=()=>{for(const{element:a}of i)a.setAttribute("aria-pressed",String(a.getAttribute("data-tinyfly-choose")===t.scenario))},o=t.subscribe(s);return s(),()=>{o();for(const a of r)a();for(const{element:a,attributes:l}of i)for(const h of l)a.removeAttribute(h)}}const Zn=new WeakMap,Cs=new WeakMap;let Rs=0;function jt(t,e,n){if(t)try{return JSON.parse(t)}catch(i){console.warn(`tinyfly: invalid ${e} JSON on`,n,i);return}}async function Ls(t,e={}){const n=Zn.get(t);if(n)return n;const i=Array.from(t.querySelectorAll("script[data-tinyfly-timeline]")),r=i[0],s=t.getAttribute("data-src"),o=Ns(t.getAttribute("data-markers")),a=i.length>1||r?.hasAttribute("data-scenario")?Fs(i,o,t):void 0;if(a&&a.length===0)return;let l=r&&!a?jt(r.textContent,"timeline",t):void 0;if(!l&&s&&o){const g=await fetch(s);g.ok&&(l=await g.json())}if(l&&o&&(l=Qn(l,o)),!l&&!s&&!a){console.warn('tinyfly: embed has no timeline (a <script type="application/json" data-tinyfly-timeline> or data-src)',t);return}const h=jt(t.querySelector("script[data-tinyfly-captions]")?.textContent,"captions",t),u={playWhenVisible:!0,...e.player,...h&&{captions:h},...jt(t.getAttribute("data-options"),"data-options",t)};Ds(t);const d=new ws(t,u),f={element:t,player:d};if(Zn.set(t,f),t.setAttribute("data-tinyfly-mounted",""),a){const g=t.getAttribute("data-scenario")??void 0;await d.loadScenarios(a,{initial:a.some(p=>p.id===g)?g:void 0}),Cs.set(t,Is(d,t))}else await d.load(l??s);if(t.getAttribute("data-controls")!=="false"){const g=jt(t.getAttribute("data-labels"),"data-labels",t),p=t.querySelector("figcaption"),m=t.getAttribute("data-scenario-legend"),c=t.getAttribute("data-scenario-control");f.controls=xs(d,t,{...e.controls,...t.getAttribute("data-fullscreen")==="true"?{fullscreen:!0}:{},...c==="slider"||c==="buttons"?{scenarioControl:c}:{},labels:{...e.controls?.labels,...g,...m?{scenario:m}:{}},mount:void 0}),p?t.insertBefore(f.controls.element,p):t.appendChild(f.controls.element)}return f}function Fs(t,e,n){const i=[];return t.forEach((r,s)=>{const o=jt(r.textContent,"timeline",n);if(!o)return;const a=r.getAttribute("data-scenario")||`scenario-${s+1}`;if(i.some(h=>h.id===a)){console.warn(`tinyfly: scenario id "${a}" is used more than once; the later one is skipped`,n);return}const l=r.getAttribute("data-scenario-label")??void 0;i.push({id:a,label:l,timeline:e?Qn(o,e):o})}),i}function Qn(t,e){return t.config.markers?.length?t:{...t,config:{...t.config,markers:e.map((n,i)=>({id:`step-${i+1}`,time:n}))}}}function Ns(t){if(!t)return;const e=t.split(/[\s,]+/).filter(Boolean).map(Number).filter(n=>Number.isFinite(n)&&n>=0).sort((n,i)=>n-i);return e.length>0?e:void 0}function Ds(t){const e=t.querySelector("svg");if(!e||e.hasAttribute("role")||e.hasAttribute("aria-hidden"))return;const n=t.getAttribute("data-alt"),i=t.querySelector("figcaption");e.setAttribute("role","img"),n?e.setAttribute("aria-label",n):i&&(i.id||=`tinyfly-caption-${++Rs}`,e.setAttribute("aria-labelledby",i.id))}const Ne=["grid","axes","vector","basis","point","function","parametric","polygon","line","label","equation","tangent","riemann","area","taylor","histogram","distribution","galton","scatter","bayes"],ie={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],Z=([t,e,n,i],[r,s])=>[t*r+e*s,n*r+i*s];function qs(t,e){const[n,i,r,s]=t,[o,a,l,h]=e;return[n*o+i*l,n*a+i*h,r*o+s*l,r*a+s*h]}const Xt=([t,e,n,i])=>t*i-e*n;function js(t){const e=Xt(t);if(Math.abs(e)<1e-12)return;const[n,i,r,s]=t;return[s/e,-i/e,-r/e,n/e]}const zs=(t,e,n)=>t.map((i,r)=>i+(e[r]-i)*n),Xs=t=>[Math.cos(t),-Math.sin(t),Math.sin(t),Math.cos(t)];function Kn(t){const[e,n,i,r]=t,s=e+r,o=Xt(t),a=s*s-4*o,l=1e-9;if(a<-l)return[];const h=Math.sqrt(Math.max(0,a)),u=h<l?[s/2]:[(s+h)/2,(s-h)/2],d=[];for(const f of u){const p=[[e-f,n],[i,r-f]].reduce((v,$)=>Math.hypot(...$)>Math.hypot(...v)?$:v);if(Math.hypot(...p)<l){d.push({value:f,vector:[1,0]},{value:f,vector:[0,1]});continue}const m=[-p[1],p[0]],c=Math.hypot(...m),y=m[0]<-l||Math.abs(m[0])<=l&&m[1]<0?-1:1;d.push({value:f,vector:[y*m[0]/c+0,y*m[1]/c+0]})}return d}function xt(t){return Array.isArray(t)&&t.length===4&&t.every(Number.isFinite)}const Ys=Object.freeze(Object.defineProperty({__proto__:null,IDENTITY:zt,apply:Z,determinant:Xt,eigen:Kn,inverse:js,isMat2:xt,lerp:zs,multiply:qs,rotation:Xs},Symbol.toStringTag,{value:"Module"})),Bs=(t,e)=>[t[0]+e[0],t[1]+e[1]],De=(t,e)=>[t[0]-e[0],t[1]-e[1]],qe=(t,e)=>[t[0]*e,t[1]*e],Vs=(t,e)=>t[0]*e[0]+t[1]*e[1],Ws=(t,e)=>t[0]*e[1]-t[1]*e[0],Jn=t=>Math.hypot(t[0],t[1]);function ti(t){const e=Jn(t);return e===0?[0,0]:[t[0]/e,t[1]/e]}const Us=(t,e,n)=>[t[0]+(e[0]-t[0])*n,t[1]+(e[1]-t[1])*n];function dt(t){return Array.isArray(t)&&t.length===2&&t.every(Number.isFinite)}const Hs=Object.freeze(Object.defineProperty({__proto__:null,add:Bs,cross:Ws,dot:Vs,isVec2:dt,length:Jn,lerp:Us,normalize:ti,scale:qe,sub:De},Symbol.toStringTag,{value:"Module"}));function ei(t){const e={};for(const[n,i]of Object.entries(t))if(typeof i=="number")e[n]=i;else if(xt(i)){const[r,s,o,a]=i;Object.assign(e,{[`${n}.a`]:r,[`${n}.b`]:s,[`${n}.c`]:o,[`${n}.d`]:a,[`${n}.det`]:Xt(i)})}else dt(i)&&Object.assign(e,{[`${n}.x`]:i[0],[`${n}.y`]:i[1],[`${n}.length`]:Math.hypot(i[0],i[1])});return e}function I(t,e,n){return e?Object.prototype.hasOwnProperty.call(t.colors,e)?t.colors[e]:e:n}function Yt(t,e){if(typeof e!="string")return e;const n=t[e];if(!dt(n))throw new Error(`math figure: value "${e}" is not an [x, y] vector`);return n}function bt(t,e){if(e===void 0)return zt;const n=t[e];if(!xt(n))throw new Error(`math figure: value "${e}" is not a [a, b, c, d] matrix`);return n}function T(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 Tt(t,e){const n=r=>r===void 0?void 0:T(t,r),i=r=>r===void 0?void 0:Math.round(T(t,r));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:i(e.n),p:n(e.p)};case"poisson":return{kind:"poisson",rate:n(e.rate)};case"dice":return{kind:"dice",count:i(e.count),sides:i(e.sides)};case"mean":return{kind:"mean",of:Tt(t,e.of),count:i(e.count)}}}function je(t){const{width:e,height:n}=t,i=t.x??[-5,5],r=e/(i[1]-i[0]),s=t.y??[-(n/r)/2,n/r/2],o=n/(s[1]-s[0]);return{width:e,height:n,x:i,y:s,unitX:r,unitY:o,scale:Math.min(e,n)/600,toScreen:([a,l])=>[(a-i[0])*r,(s[1]-l)*o],toWorld:([a,l])=>[i[0]+a/r,s[1]-l/o]}}const ni='"Latin Modern Math", "STIX Two Math", "Cambria Math", "Times New Roman", "Liberation Serif", "Noto Serif", Times, serif',ii=.25,Bt=.05,ri={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 ze(t){return t.length!==1?t.length*.5:/[0-9]/.test(t)?.5:Object.prototype.hasOwnProperty.call(ri,t)?ri[t]+.04:"()[]".includes(t)?.39:"{}".includes(t)?.5:"|".includes(t)||",.;:!".includes(t)?.28:"+−=<>±×÷≤≥≠≈∼≡∝→←↔⇒⇔∈∉⊂⊃⊆⊇∪∩∧∨".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 si(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 oi='system-ui, -apple-system, "Segoe UI", sans-serif',ai=(t,e)=>Math.hypot(e[0]-t[0],e[1]-t[1]);function Q(t,e){if(e>=1)return t;if(e<=0)return[];const n=t.map(s=>s.slice(1).reduce((o,a,l)=>o+ai(s[l],a),0));let i=n.reduce((s,o)=>s+o,0)*e;const r=[];for(const[s,o]of t.entries()){if(i<=0)break;if(n[s]<=i){r.push(o),i-=n[s];continue}const a=[o[0]];for(let l=1;l<o.length;l++){const h=ai(o[l-1],o[l]);if(h>=i){const u=h===0?0:i/h;a.push([o[l-1][0]+(o[l][0]-o[l-1][0])*u,o[l-1][1]+(o[l][1]-o[l-1][1])*u]);break}a.push(o[l]),i-=h}r.push(a),i=0}return r}function Xe(t,e){const n=e.align??"center",i=n==="left"?0:n==="right"?-t.width:-t.width/2,r=e.baseline==="baseline"?0:(t.height-t.depth)/2;return[e.x+i*e.size,e.y+r*e.size]}function ci(t,e,n){const[i,r]=e,s=n.size,o=n.opacity??1;return t.map(a=>{const l=a.color??n.color,h=o*(a.opacity??1),u=`${n.idPrefix}${a.id}`;if(a.kind==="glyph")return{type:"text",id:u,text:a.text,x:i+(a.x+a.width/2)*s,y:r+a.y*s,size:a.size*s,font:ni,italic:a.italic,color:l,align:"center",opacity:h};if(a.kind==="rule"){const d=i+a.x*s,f=r+a.y*s,g=a.width*s,p=Math.max(1,a.height*s);return{type:"line",id:u,points:[[d,f],[d+g,f],[d+g,f+p],[d,f+p]],closed:!0,fill:l,opacity:h}}return{type:"line",id:u,points:a.points.map(([d,f])=>[i+d*s,r+f*s]),stroke:l,width:Math.max(1,a.width*s),opacity:h}})}function vt(t,e){return ci(t.pieces,Xe(t,e),e)}function Gs(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])),[i,r,s,o]=e,a=Math.hypot(i,r,s,o),l=a===0?0:Math.abs(Xt(e))/a;return Math.min(n*12,n/Math.max(l,.08))+1}function li(t,e,n){const i=Gs(t,e),r=Math.min(120,Math.ceil(i/n)),s=[];for(let o=-r;o<=r;o++){const a=o*n;s.push({line:[Z(e,[a,-i]),Z(e,[a,i])].map(t.toScreen),axis:o===0}),s.push({line:[Z(e,[-i,a]),Z(e,[i,a])].map(t.toScreen),axis:o===0})}return s}function Zs(t,e){const{plane:n,theme:i}=e,r=t.step??1,s=[],o=1.4*n.scale;if(t.ghost)for(const[l,{line:h}]of li(n,[1,0,0,1],r).entries())s.push({type:"line",id:`${t.id}.ghost.${l}`,points:h,stroke:i.ghost,width:o,opacity:e.opacity});const a=I(i,t.color,i.grid);for(const[l,{line:h,axis:u}]of li(n,bt(e.values,t.transform),r).entries()){const[d]=Q([h],e.draw);d&&s.push({type:"line",id:`${t.id}.${l}`,points:d,stroke:u?i.ink:a,width:u?o*1.6:o,opacity:e.opacity})}return s}function Qs(t,e){const{plane:n,theme:i}=e,r=I(i,t.color,i.axes),s=2*n.scale,o=e.opacity,a=Q([[n.toScreen([n.x[0],0]),n.toScreen([n.x[1],0])]],e.draw),l=Q([[n.toScreen([0,n.y[0]]),n.toScreen([0,n.y[1]])]],e.draw),h=[...a,...l].map((m,c)=>({type:"line",id:`${t.id}.${c?"y":"x"}`,points:m,stroke:r,width:s,opacity:o})),u=t.ticks??1;if(u<=0||e.draw<1)return h;const d=5*n.scale,f=13*n.scale,g=(m,c)=>{const y=[];for(let v=Math.ceil(m/u)*u;v<=c+1e-9;v+=u)Math.abs(v)>1e-9&&y.push(Number(v.toFixed(6)));return y},p=m=>String(m).replace("-","−");for(const m of g(n.x[0],n.x[1])){const[c,y]=n.toScreen([m,0]);h.push({type:"line",id:`${t.id}.tick.x${m}`,points:[[c,y-d],[c,y+d]],stroke:r,width:s*.8,opacity:o}),t.labels!==!1&&h.push({type:"text",id:`${t.id}.label.x${m}`,text:p(m),x:c,y:y+d+f*1.1,size:f,font:oi,color:r,align:"center",opacity:o*.8})}for(const m of g(n.y[0],n.y[1])){const[c,y]=n.toScreen([0,m]);h.push({type:"line",id:`${t.id}.tick.y${m}`,points:[[c-d,y],[c+d,y]],stroke:r,width:s*.8,opacity:o}),t.labels!==!1&&h.push({type:"text",id:`${t.id}.label.y${m}`,text:p(m),x:c-d-f*.4,y:y+f*.35,size:f,font:oi,color:r,align:"right",opacity:o*.8})}return h}const Ye={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:"Ω"},re={cdot:["·","bin"],times:["×","bin"],div:["÷","bin"],pm:["±","bin"],mp:["∓","bin"],circ:["∘","bin"],cup:["∪","bin"],cap:["∩","bin"],land:["∧","bin"],lor:["∨","bin"],setminus:["∖","bin"],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"]},Be={sum:["∑",!0],prod:["∏",!0],int:["∫",!1],oint:["∮",!1]},Ve={sin:!1,cos:!1,tan:!1,log:!1,ln:!1,exp:!1,det:!1,tr:!1,rank:!1,lim:!0,max:!0,min:!0,argmax:!0,argmin:!0,arg:!1,sup:!0,inf:!0,Pr:!1,E:!1,Var:!1},We={",":3/18,":":4/18,";":5/18,"!":-3/18,quad:1,qquad:2},ui=new Set(["pmatrix","bmatrix","vmatrix","matrix"]);class hi extends Error{source;position;constructor(e,n,i){super(`${e} at ${i+1} in "${n}"`),this.name="TexError",this.source=n,this.position=i}}const di=[...Object.keys(Ye),...Object.keys(re),...Object.keys(Be),...Object.keys(Ve),...Object.keys(We).filter(t=>t.length>1),"frac","sqrt","vec","hat","bar","text","color","id","val","begin","end","left","right"].sort();function fi(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++},i=(u,d=e)=>{throw new hi(u,t,d)},r=()=>{const u=e;if(/[A-Za-z]/.test(t[e]??""))for(;/[A-Za-z]/.test(t[e]??"");)e++;else e<t.length?e++:i("A backslash with no command");return t.slice(u,e)},s=u=>{n(),t[e]!=="{"&&i(`Expected "{" for ${u}`);const d=t.indexOf("}",e);d<0&&i(`Missing "}" for ${u}`);const f=t.slice(e+1,d);return e=d+1,f},o=u=>{if(n(),e>=t.length&&i(`Missing ${u}`),t[e]==="{"){e++;const f=a("}");return e++,{type:"group",body:f}}const d=l();return d||i(`Missing ${u}`),d},a=u=>{const d=[];for(;;){if(n(),e>=t.length)return u==="}"&&i('Missing "}"'),u==="cell"&&i("Missing \\end"),d;if(u==="}"&&t[e]==="}"||(t[e]==="}"&&i('Unexpected "}"'),u==="cell"&&(t[e]==="&"||t.startsWith("\\\\",e)||t.startsWith("\\end",e))))return d;if(t[e]==="^"||t[e]==="_"){const g=e,p=t[e]==="^";e++;const m=o(p?"superscript":"subscript");let c=d.pop()??{type:"group",body:[]};c.type!=="scripts"&&(c={type:"scripts",base:c}),c.type==="scripts"&&((p&&c.sup||!p&&c.sub)&&i(`Double ${p?"superscript":"subscript"}`,g),p?c.sup=m:c.sub=m),d.push(c);continue}if(t[e]==="'"){e++;const g={type:"symbol",text:"′",cls:"ord",italic:!1},p=d.pop()??{type:"group",body:[]};d.push(p.type==="scripts"&&!p.sup?{...p,sup:g}:{type:"scripts",base:p,sup:g});continue}const f=l();f&&d.push(f)}},l=()=>{const u=t[e];if(u==="{"){e++;const d=a("}");return e++,{type:"group",body:d}}if(u==="&"&&i('"&" outside a matrix'),u==="\\"){const d=e;e++;const f=r();if(f==="\\"&&i('"\\\\" outside a matrix',d),f in We)return{type:"space",width:We[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(Ye,f))return{type:"symbol",text:Ye[f],cls:"ord",italic:f[0]===f[0].toLowerCase()};if(Object.prototype.hasOwnProperty.call(re,f)){const[p,m]=re[f];return{type:"symbol",text:p,cls:m,italic:!1}}if(Object.prototype.hasOwnProperty.call(Be,f)){const[p,m]=Be[f];return{type:"bigop",text:p,limits:m}}if(Object.prototype.hasOwnProperty.call(Ve,f))return{type:"opname",text:f,limits:Ve[f]};switch(f){case"frac":return{type:"frac",num:o("numerator"),den:o("denominator")};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:s("\\text")};case"color":{const p=s("\\color").trim();return/^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)$/.test(p)||i(`"${p}" is not a colour name or #hex`,d),{type:"color",color:p,body:o("\\color's body")}}case"id":{const p=s("\\id").trim();return/^[\w.-]+$/.test(p)||i(`"${p}" is not a term id (letters, digits, _ . -)`,d),{type:"id",id:p,body:o("\\id's body")}}case"val":{const p=s("\\val").trim(),m=/^([A-Za-z_][\w.]*)(?::(\d))?$/.exec(p);return m||i(`"${p}" is not a value name (name or name:digits)`,d),{type:"value",name:m[1],digits:m[2]===void 0?2:Number(m[2])}}case"left":case"right":{n();const p=t[e]==="\\"?(e++,r()):t[e++];if(p===".")return{type:"space",width:0};const c={"(":"(",")":")","[":"[","]":"]","|":"|","{":"{","}":"}",langle:"⟨",rangle:"⟩","|.":"‖"}[p];return c||i(`"${p}" is not a delimiter`,d),{type:"symbol",text:c,cls:f==="left"?"open":"close",italic:!1}}case"begin":{const p=s("\\begin").trim();ui.has(p)||i(`Unknown environment "${p}" (use ${[...ui].join(", ")})`,d);const m=[[]];for(;;){const c=a("cell");if(m[m.length-1].push({type:"group",body:c}),t[e]==="&")e++;else if(t.startsWith("\\\\",e))e+=2,m.push([]);else{e+=4;const y=s("\\end").trim();y!==p&&i(`\\begin{${p}} ended by \\end{${y}}`);break}}return m.length>1&&m[m.length-1].every(c=>c.type==="group"&&c.body.length===0)&&m.pop(),{type:"matrix",delimiters:p,rows:m}}case"end":return i("\\end without \\begin",d)}const g=Yn(f,di);return i(`Unknown command "\\${f}"${g?` (did you mean "\\${g}"?)`:""}`,d)}return e++,/[A-Za-z]/.test(u)?{type:"symbol",text:u,cls:"ord",italic:!0}:/[0-9.]/.test(u)?{type:"symbol",text:u,cls:"ord",italic:!1}:u==="+"?{type:"symbol",text:"+",cls:"bin",italic:!1}:u==="-"?{type:"symbol",text:"−",cls:"bin",italic:!1}:u==="*"?{type:"symbol",text:"∗",cls:"bin",italic:!1}:"=<>".includes(u)?{type:"symbol",text:u,cls:"rel",italic:!1}:"([".includes(u)?{type:"symbol",text:u,cls:"open",italic:!1}:")]".includes(u)?{type:"symbol",text:u,cls:"close",italic:!1}:",;".includes(u)?{type:"symbol",text:u,cls:"punct",italic:!1}:"|/!:".includes(u)?{type:"symbol",text:u,cls:u===":"?"rel":"ord",italic:!1}:i(`Unexpected "${u}"`,e-1)};return{type:"group",body:a("")}}const et=[1,1,.7,.5],Ks=t=>t<=1?2:3,Js=t=>Math.min(3,t+1),Ue=()=>({width:0,height:0,depth:0,pieces:[]});function nt(t,e,n){return t.pieces.map(i=>i.kind==="stroke"?{...i,points:i.points.map(([r,s])=>[r+e,s+n])}:{...i,x:i.x+e,y:i.y+n})}function At(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 pi(t,e,n,i=1,r=t){const s=et[n.level]*i,o=ze(t)*s,{height:a,depth:l}=si(t);return{width:o,height:a*s,depth:l*s,pieces:[{kind:"glyph",text:t,x:0,y:0,width:o,size:s,italic:e,...n.color?{color:n.color}:{},id:At(n,r)}]}}function He(t,e,n){const i=Ue(),r=At(e,n),s=et[e.level];for(const o of t){const a=(o===" "?.28:/[A-Za-z]/.test(o)?ze(o)-.04:ze(o))*s;if(o!==" "){const{height:l,depth:h}=si(o);i.pieces.push({kind:"glyph",text:o,x:i.width,y:0,width:a,size:s,italic:!1,...e.color?{color:e.color}:{},id:r}),i.height=Math.max(i.height,l*s),i.depth=Math.max(i.depth,h*s)}i.width+=a}return i}function Ge(t){switch(t.type){case"symbol":return t.cls;case"bigop":case"opname":return"op";case"scripts":return Ge(t.base);case"id":case"color":return Ge(t.body);default:return"ord"}}function to(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 eo(t,e){const n=Ue();let i;return t.forEach(r=>{if(r.type==="space"){n.width+=r.width*et[e.level];return}let s=Ge(r);s==="bin"&&(i===void 0||i==="bin"||i==="rel"||i==="open"||i==="punct"||i==="op")&&(s="ord"),i!==void 0&&e.level<=1&&(n.width+=to(i,s)/18*et[e.level]);const o=H(r,e);n.pieces.push(...nt(o,n.width,0)),n.width+=o.width,n.height=Math.max(n.height,o.height),n.depth=Math.max(n.depth,o.depth),i=s}),n}function no(t,e){if(!Number.isFinite(t))return t>0?"∞":t<0?"−∞":"?";const n=t.toFixed(e),i=n.includes(".")?n.replace(/\.?0+$/,""):n;return(i==="-0"?"0":i).replace("-","−")}function H(t,e){const n=et[e.level];switch(t.type){case"symbol":return pi(t.text,t.italic,e);case"group":return eo(t.body,e);case"space":return{...Ue(),width:t.width*n};case"text":return He(t.text,e,`text:${t.text}`);case"opname":return He(t.text,e,t.text);case"value":{const i=e.values[t.name];if(i===void 0)throw new Error(`\\val{${t.name}}: no value named "${t.name}"`);return He(no(i,t.digits),{...e,id:e.id??`val:${t.name}`},`val:${t.name}`)}case"bigop":return pi(t.text,!1,e,e.level===0?1.4:1.1);case"color":return H(t.body,{...e,color:t.color});case"id":return H(t.body,{...e,id:t.id});case"scripts":return io(t,e);case"frac":return ro(t,e);case"sqrt":return so(t,e);case"accent":return oo(t,e);case"matrix":return ao(t,e)}}function io(t,e){const n=H(t.base,e),i={...e,level:Ks(e.level)},r=t.sup?H(t.sup,i):void 0,s=t.sub?H(t.sub,i):void 0,o=et[e.level],a=e.level===0&&(t.base.type==="bigop"&&t.base.limits||t.base.type==="opname"&&t.base.limits),l={...n,pieces:[...n.pieces]};if(a){const g=Math.max(n.width,r?.width??0,s?.width??0),p=nt(n,(g-n.width)/2,0);let m=n.height,c=n.depth;const y=.12*o;if(r){const v=-(n.height+y+r.depth);p.push(...nt(r,(g-r.width)/2,v)),m=-v+r.height}if(s){const v=n.depth+y+s.height;p.push(...nt(s,(g-s.width)/2,v)),c=v+s.depth}return{width:g,height:m,depth:c,pieces:p}}let h=r?Math.max(.42*o,n.height-.3*o,r.depth+.25*o):0,u=s?Math.max(.2*o,n.depth+.12*o,s.height-.4*o):0;if(r&&s){const g=h-r.depth-(s.height-u);g<.2*o&&(u+=.2*o-g)}const d=n.width+.03*o;let f=n.width;return r?(l.pieces.push(...nt(r,d,-h)),l.height=Math.max(l.height,h+r.height),f=Math.max(f,d+r.width)):h=0,s&&(l.pieces.push(...nt(s,d,u)),l.depth=Math.max(l.depth,u+s.depth),f=Math.max(f,d+s.width)),l.width=f+.04*o,l}function ro(t,e){const n={...e,level:Js(e.level)},i=H(t.num,n),r=H(t.den,n),s=et[e.level],o=Bt*s,a=ii*s,l=(e.level===0?.16:.1)*s,h=.1*s,u=Math.max(i.width,r.width)+h*2,d=-(a+o/2+l+i.depth),f=-a+o/2+l+r.height;return{width:u,height:-d+i.height,depth:f+r.depth,pieces:[...nt(i,(u-i.width)/2,d),{kind:"rule",x:0,y:-a-o/2,width:u,height:o,...e.color?{color:e.color}:{},id:At(e,"frac")},...nt(r,(u-r.width)/2,f)]}}function so(t,e){const n=H(t.body,e),i=et[e.level],r=Math.max(n.height,.7*i)+.14*i,s=Math.max(n.depth,.05*i)+.05*i,o=.56*i,a=o+n.width+.08*i,l=[[.02*i,-.36*i],[.13*i,-.44*i],[.3*i,s],[o-.04*i,-r],[a,-r]];return{width:a,height:r+Bt*i,depth:s,pieces:[{kind:"stroke",points:l,width:Bt*i,...e.color?{color:e.color}:{},id:At(e,"sqrt")},...nt(n,o,0)]}}function oo(t,e){const n=H(t.body,e),i=et[e.level],r=-(n.height+.12*i),s=.04*i,o=Math.max(n.width-.02*i,s+.3*i),a=e.color?{color:e.color}:{},l=At(e,t.accent);let h;if(t.accent==="vec"){const u=.12*i;h=[[[s,r],[o,r]],[[o-u,r-u*.7],[o,r],[o-u,r+u*.7]]]}else if(t.accent==="hat"){const u=(s+o)/2;h=[[[u-.16*i,r+.02*i],[u,r-.12*i],[u+.16*i,r+.02*i]]]}else h=[[[s,r],[o,r]]];return{width:Math.max(n.width,o+.02*i),height:-r+.14*i,depth:n.depth,pieces:[...n.pieces,...h.map(u=>({kind:"stroke",points:u,width:Bt*i*.9,...a,id:l}))]}}function ao(t,e){const n={...e,level:Math.max(e.level,1)},i=et[n.level],r=t.rows.map(k=>k.map(M=>H(M,n))),s=Math.max(...r.map(k=>k.length)),o=Array.from({length:s},(k,M)=>Math.max(0,...r.map(x=>x[M]?.width??0))),a=r.map(k=>Math.max(.7*i,...k.map(M=>M.height))),l=r.map(k=>Math.max(.2*i,...k.map(M=>M.depth))),h=.9*i,u=.25*i,d=t.delimiters==="matrix"?0:.55*i,f=o.reduce((k,M)=>k+M,0)+h*(s-1),g=a.reduce((k,M,x)=>k+M+l[x],0)+u*(r.length-1),p=-ii*i-g/2,m=[];let c=p;r.forEach((k,M)=>{c+=a[M];let x=d;k.forEach((P,A)=>{m.push(...nt(P,x+(o[A]-P.width)/2,c)),x+=o[A]+h}),c+=l[M]+u});const y=f+d*2,v=p+g,$=e.color?{color:e.color}:{},w=(k,M)=>({kind:"stroke",points:k,width:Bt*i*1.1,...$,id:At(e,M)}),b=.08*i;if(t.delimiters==="pmatrix"){const k=M=>{const x=M===1?d*.75:y-d*.75,P=M*d*.5;return Array.from({length:17},(A,O)=>{const _=O/16;return[x-P*Math.sin(Math.PI*_),p-b+(g+b*2)*_]})};m.push(w(k(1),"("),w(k(-1),")"))}else if(t.delimiters==="bmatrix"){const k=d*.35,M=d*.2,x=y-d*.2;m.push(w([[M+k,p-b],[M,p-b],[M,v+b],[M+k,v+b]],"["),w([[x-k,p-b],[x,p-b],[x,v+b],[x-k,v+b]],"]"))}else t.delimiters==="vmatrix"&&m.push(w([[d*.4,p-b],[d*.4,v+b]],"|"),w([[y-d*.4,p-b],[y-d*.4,v+b]],"|"));return{width:y,height:-p+b,depth:v+b,pieces:m}}function ft(t,e={}){const n=typeof t=="string"?fi(t):t,i={level:e.style==="inline"?1:0,values:e.values??{},counts:new Map},r=H(n,i);return{width:r.width,height:r.height,depth:r.depth,pieces:r.pieces}}function se(t,e,n,i,r,s){const o=26*s.plane.scale,[a,l]=ti(n),h=ft(t,{values:s.scope,style:"inline"}),u=o*(.55+Math.abs(a)*h.width*.5);return vt(h,{x:e[0]+a*u,y:e[1]+l*u,size:o,color:i,opacity:s.opacity,idPrefix:`${r}.label.`})}function mi(t,e,n,i,r,s){const o=s.plane.toScreen(e),a=s.plane.toScreen(n),[l]=Q([[o,a]],s.draw);if(!l)return[];const h=Math.hypot(a[0]-o[0],a[1]-o[1]),u=Math.min(r*3.6,h*.45);return[{type:"arrow",id:t,points:l,stroke:i,width:r,head:u,opacity:s.opacity}]}function co(t,e){const n=bt(e.values,t.transform),i=Z(n,t.from===void 0?[0,0]:Yt(e.values,t.from)),r=Z(n,Yt(e.values,t.to)),s=I(e.theme,t.color,e.theme.colors.yellow),o=mi(t.id,i,r,s,(t.width??4)*e.plane.scale,e);if(t.label&&e.draw>=1){const a=e.plane.toScreen(r),l=e.plane.toScreen(i),h=De(a,l);if(t.labelAt==="middle"){const u=[(a[0]+l[0])/2,(a[1]+l[1])/2];o.push(...se(t.label,u,[h[1],-h[0]],s,t.id,e))}else o.push(...se(t.label,a,h,s,t.id,e))}return o}function lo(t,e){const n=bt(e.values,t.transform),i=4.5*e.plane.scale,r=e.plane.toScreen([0,0]),s=[],o=[["i",[1,0],e.theme.colors.green,"\\hat{i}"],["j",[0,1],e.theme.colors.red,"\\hat{j}"]];for(const[a,l,h,u]of o){const d=Z(n,l);if(s.push(...mi(`${t.id}.${a}`,[0,0],d,h,i,e)),t.labels!==!1&&e.draw>=1){const f=e.plane.toScreen(d);s.push(...se(u,f,De(f,r),h,`${t.id}.${a}`,e))}}return s}function uo(t,e){const n=t.on!==void 0?[e.scope[`${t.id}.x`],e.scope[`${t.id}.y`]]:Yt(e.values,t.at);if(!Number.isFinite(n[0])||!Number.isFinite(n[1]))return[];const i=Z(bt(e.values,t.transform),n),[r,s]=e.plane.toScreen(i),o=I(e.theme,t.color,e.theme.colors.yellow),a=(t.radius??6)*e.plane.scale*Math.min(1,e.draw*2),l=t.hollow?{type:"circle",id:t.id,x:r,y:s,r:a,fill:e.theme.background,stroke:o,width:2.5*e.plane.scale,opacity:e.opacity}:{type:"circle",id:t.id,x:r,y:s,r:a,fill:o,opacity:e.opacity},h=a>0?[l]:[];return t.label&&e.draw>=1&&h.push(...se(t.label,[r,s],[.7,-.7],o,t.id,e)),h}const oe={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)}},Vt={pi:Math.PI,e:Math.E,tau:Math.PI*2};class wt extends Error{source;position;constructor(e,n,i){super(`${e} at ${i+1} in "${n}"`),this.name="ExpressionError",this.source=n,this.position=i}}function ho(t){const e=[];let n=0;for(;n<t.length;){const i=t[n];if(/\s/.test(i)){n++;continue}const r=/^(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?/.exec(t.slice(n));if(r){e.push({kind:"number",value:Number(r[0]),at:n}),n+=r[0].length;continue}const s=/^[A-Za-z_][A-Za-z_0-9]*/.exec(t.slice(n));if(s){e.push({kind:"name",value:s[0],at:n}),n+=s[0].length;continue}if("+-*/^(),".includes(i)){e.push({kind:"op",value:i,at:n}),n++;continue}throw new wt(`Unexpected "${i}"`,t,n)}return e.push({kind:"end",at:t.length}),e}function pt(t){if(typeof t!="string")throw new TypeError("parseExpression: expected a string");const e=ho(t);let n=0;const i=()=>e[n],r=f=>{const g=i();return g.kind==="op"&&g.value===f},s=f=>{if(!r(f))throw new wt(`Expected "${f}"`,t,i().at);n++},o=()=>{let f=a();for(;r("+")||r("-");)f={type:"binary",operator:e[n++].value,left:f,right:a()};return f},a=()=>{let f=l();for(;;)if(r("*")||r("/"))f={type:"binary",operator:e[n++].value,left:f,right:l()};else if(i().kind==="name"||i().kind==="number"||r("("))f={type:"binary",operator:"*",left:f,right:h()};else return f},l=()=>r("-")||r("+")?{type:"unary",operator:e[n++].value,operand:l()}:h(),h=()=>{const f=u();return r("^")?(n++,{type:"binary",operator:"^",left:f,right:l()}):f},u=()=>{const f=i();if(f.kind==="number")return n++,{type:"number",value:f.value};if(f.kind==="name"){if(n++,!r("("))return{type:"name",name:f.value};const g=Object.prototype.hasOwnProperty.call(oe,f.value)?oe[f.value]:void 0;if(!g)throw new wt(`Unknown function "${f.value}"`,t,f.at);n++;const p=[];if(!r(")"))for(p.push(o());r(",");)n++,p.push(o());if(s(")"),p.length!==g.arity)throw new wt(`"${f.value}" takes ${g.arity} argument${g.arity===1?"":"s"}, got ${p.length}`,t,f.at);return{type:"call",name:f.value,args:p}}if(r("(")){n++;const g=o();return s(")"),g}throw new wt(f.kind==="end"?"Unexpected end":`Unexpected "${f.value}"`,t,f.at)},d=o();if(i().kind!=="end")throw new wt(`Unexpected "${i().value}"`,t,i().at);return d}function Ze(t){const e=new Set,n=i=>{i.type==="name"&&!(i.name in Vt)?e.add(i.name):i.type==="unary"?n(i.operand):i.type==="binary"?(n(i.left),n(i.right)):i.type==="call"&&i.args.forEach(n)};return n(t),[...e].sort()}const C=t=>({type:"number",value:t}),Wt=C(0),N=C(1),X=t=>t.type==="number",G=(t,e)=>t.type==="number"&&t.value===e;function mt(t,e){return X(t)&&X(e)?C(t.value+e.value):G(t,0)?e:G(e,0)?t:{type:"binary",operator:"+",left:t,right:e}}function it(t,e){return X(t)&&X(e)?C(t.value-e.value):G(e,0)?t:G(t,0)?ae(e):{type:"binary",operator:"-",left:t,right:e}}function R(t,e){return X(t)&&X(e)?C(t.value*e.value):G(t,0)||G(e,0)?Wt:G(t,1)?e:G(e,1)?t:X(e)?R(e,t):X(t)&&e.type==="binary"&&e.operator==="*"&&X(e.left)?R(C(t.value*e.left.value),e.right):{type:"binary",operator:"*",left:t,right:e}}function Y(t,e){return G(t,0)?Wt:G(e,1)?t:X(t)&&X(e)&&e.value!==0?C(t.value/e.value):{type:"binary",operator:"/",left:t,right:e}}function ct(t,e){return G(e,0)?N:G(e,1)?t:X(t)&&X(e)?C(t.value**e.value):{type:"binary",operator:"^",left:t,right:e}}function ae(t){return X(t)?C(-t.value):t.type==="unary"&&t.operator==="-"?t.operand:{type:"unary",operator:"-",operand:t}}const B=(t,...e)=>({type:"call",name:t,args:e});function kt(t,e){switch(t.type){case"number":return!0;case"name":return t.name!==e;case"unary":return kt(t.operand,e);case"binary":return kt(t.left,e)&&kt(t.right,e);case"call":return t.args.every(n=>kt(n,e))}}function rt(t,e="x"){if(kt(t,e))return Wt;switch(t.type){case"number":return Wt;case"name":return t.name===e?N:Wt;case"unary":return t.operator==="-"?ae(rt(t.operand,e)):rt(t.operand,e);case"binary":{const{left:n,right:i}=t,r=()=>rt(n,e),s=()=>rt(i,e);switch(t.operator){case"+":return mt(r(),s());case"-":return it(r(),s());case"*":return mt(R(r(),i),R(n,s()));case"/":return Y(it(R(r(),i),R(n,s())),ct(i,C(2)));case"^":if(kt(i,e)){const o=X(i)?C(i.value-1):it(i,N);return R(R(i,ct(n,o)),r())}return kt(n,e)?R(R(t,B("ln",n)),s()):R(t,mt(R(s(),B("ln",n)),Y(R(i,r()),n)))}break}case"call":{const[n,i]=t.args,r=()=>rt(n,e),s=o=>R(o,r());switch(t.name){case"sin":return s(B("cos",n));case"cos":return s(ae(B("sin",n)));case"tan":return s(Y(N,ct(B("cos",n),C(2))));case"asin":return s(Y(N,B("sqrt",it(N,ct(n,C(2))))));case"acos":return s(ae(Y(N,B("sqrt",it(N,ct(n,C(2)))))));case"atan":return s(Y(N,mt(N,ct(n,C(2)))));case"sinh":return s(B("cosh",n));case"cosh":return s(B("sinh",n));case"tanh":return s(it(N,ct(B("tanh",n),C(2))));case"exp":return s(t);case"ln":return s(Y(N,n));case"log":return s(Y(N,R(n,C(Math.LN10))));case"log2":return s(Y(N,R(n,C(Math.LN2))));case"sqrt":return s(Y(N,R(C(2),t)));case"abs":return s(B("sign",n));case"sigmoid":return s(R(t,it(N,t)));case"relu":return s(Y(mt(B("sign",n),N),C(2)));case"atan2":{const o=rt(i,e);return Y(it(R(i,r()),R(n,o)),mt(ct(n,C(2)),ct(i,C(2))))}case"min":case"max":{const o=t.name==="max"?1:-1,a=rt(i,e),l=Y(mt(N,R(C(o),B("sign",it(n,i)))),C(2));return mt(R(l,r()),R(it(N,l),a))}}throw new Error(`differentiate: "${t.name}" has no derivative rule`)}}throw new Error("differentiate: malformed expression")}function gi(t,e,n="x"){let i=t;for(let r=0;r<e;r++)i=rt(i,n);return i}function Ut(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}${Ut(t.operand)})`;case"binary":return`(${Ut(t.left)} ${t.operator} ${Ut(t.right)})`;case"call":return`${t.name}(${t.args.map(Ut).join(", ")})`}}function lt(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(Vt,t.name))return Vt[t.name];throw new Error(`evaluate: unknown name "${t.name}"`)}case"unary":{const n=lt(t.operand,e);return t.operator==="-"?-n:n}case"binary":{const n=lt(t.left,e),i=lt(t.right,e);switch(t.operator){case"+":return n+i;case"-":return n-i;case"*":return n*i;case"/":return n/i;case"^":return n**i}break}case"call":return oe[t.name].apply(...t.args.map(n=>lt(n,e)))}throw new Error("evaluate: malformed expression")}const ce=new Map;function V(t,e="x"){let n=ce.get(t);n||(n=pt(t),ce.size<256&&ce.set(t,n));const i=n;return(r,s={})=>lt(i,{...s,[e]:r})}const Qe=new Map;function le(t,e,n="x"){if(!Number.isInteger(e)||e<0)throw new Error(`compileDerivative: order must be a whole number ≥ 0, got ${e}`);const i=`${n}|${e}|${t}`;let r=Qe.get(i);if(!r){let o=ce.get(t);o||(o=pt(t)),r=gi(o,e,n),Qe.size<512&&Qe.set(i,r)}const s=r;return(o,a={})=>lt(s,{...a,[n]:o})}const ue=480;function yi(t,e){const n=[];let i=[];return t.forEach((r,s)=>{const o=t[s-1];(!r||o&&Math.abs(r[1]-o[1])>e*1.5)&&(i.length>=2&&n.push(i),i=[]),r&&i.push(r)}),i.length>=2&&n.push(i),n}function bi(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 vi(t,e,n,i,r,s){return Q(e,r.draw).map((o,a)=>({type:"line",id:`${t}.${a}`,points:o,stroke:n,width:i,opacity:r.opacity,...s?{dash:s}:{}}))}function he(t,e,n,i,r,s,o,a){const l=Array.from({length:ue+1},(h,u)=>{const d=n+(i-n)*u/ue;return bi(o.plane.toScreen([d,e(d)]),o)});return vi(t,yi(l,o.plane.height),r,s,o,a)}function fo(t,e){const n=t.derivative?le(t.expr,t.derivative):V(t.expr,"x"),[i,r]=t.domain??e.plane.x,s=I(e.theme,t.color,e.theme.colors.blue),o=t.dashed?[10*e.plane.scale,8*e.plane.scale]:void 0;return he(t.id,a=>n(a,e.scope),i,r,s,(t.width??3.5)*e.plane.scale,e,o)}function po(t,e){const n=V(t.x,"t"),i=V(t.y,"t"),r=bt(e.values,t.transform),[s,o]=t.t??[0,Math.PI*2],a=Array.from({length:ue+1},(h,u)=>{const d=s+(o-s)*u/ue;return bi(e.plane.toScreen(Z(r,[n(d,e.scope),i(d,e.scope)])),e)}),l=I(e.theme,t.color,e.theme.colors.blue);return vi(t.id,yi(a,e.plane.height),l,(t.width??3.5)*e.plane.scale,e)}const mo=[[0,0],[1,0],[1,1],[0,1]];function go(t,e){const n=bt(e.values,t.transform),i=(t.points??mo).map(a=>Z(n,a)),r=i.map(e.plane.toScreen),s=I(e.theme,t.color,e.theme.colors.yellow),o=[{type:"line",id:`${t.id}.fill`,points:r,closed:!0,fill:s,opacity:e.opacity*(t.fillOpacity??.3)*e.draw},...Q([[...r,r[0]]],e.draw).map(a=>({type:"line",id:`${t.id}.outline`,points:a,stroke:s,width:2.5*e.plane.scale,opacity:e.opacity}))];if(t.label&&e.draw>=1){const a=i.reduce((u,d)=>[u[0]+d[0]/i.length,u[1]+d[1]/i.length],[0,0]),[l,h]=e.plane.toScreen(a);o.push(...vt(ft(t.label,{values:e.scope,style:"inline"}),{x:l,y:h,size:24*e.plane.scale,color:e.theme.ink,opacity:e.opacity,idPrefix:`${t.id}.label.`}))}return o}function yo(t,e){const n=t.eigen?Kn(bt(e.values,t.eigen)).map(o=>o.vector):t.along!==void 0?[Yt(e.values,t.along)]:[],i=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,r=I(e.theme,t.color,e.theme.colors.yellow),s=(t.width??2.5)*e.plane.scale;return n.flatMap((o,a)=>{const l=Math.hypot(o[0],o[1]);if(l===0)return[];const h=qe(o,i/l),u=[qe(h,-1),h].map(e.plane.toScreen);return Q([u],e.draw).map(d=>({type:"line",id:`${t.id}.${a}`,points:d,stroke:r,width:s,opacity:e.opacity,...t.dashed?{dash:[10*e.plane.scale,8*e.plane.scale]}:{}}))})}const K=(t,e,n)=>t+(e-t)*n;function wi(t,e,n){return t.kind==="stroke"?{...t,points:t.points.map(([i,r])=>[i+e,r+n])}:{...t,x:t.x+e,y:t.y+n}}function bo(t,e,n){if(t.kind==="glyph"&&e.kind==="glyph"&&t.text===e.text)return{...e,x:K(t.x,e.x,n),y:K(t.y,e.y,n),width:K(t.width,e.width,n),size:K(t.size,e.size,n)};if(t.kind==="rule"&&e.kind==="rule")return{...e,x:K(t.x,e.x,n),y:K(t.y,e.y,n),width:K(t.width,e.width,n),height:K(t.height,e.height,n)};if(t.kind==="stroke"&&e.kind==="stroke"&&t.points.length===e.points.length)return{...e,width:K(t.width,e.width,n),points:t.points.map(([i,r],s)=>[K(i,e.points[s][0],n),K(r,e.points[s][1],n)])}}const vo=t=>t*t*(3-2*t);function ki(t,e,n){const i=Math.min(1,Math.max(0,n)),r=t.layout.pieces.map(g=>wi(g,t.x,t.y)),s=e.layout.pieces.map(g=>wi(g,e.x,e.y));if(i===0)return r.map(g=>({...g,opacity:1}));if(i===1)return s.map(g=>({...g,opacity:1}));const o=g=>{const p=new Map;for(const m of g)p.set(m.id,[...p.get(m.id)??[],m]);return p},a=o(r),l=o(s),h=[],u=vo(i),d=Math.max(0,1-i*2),f=Math.max(0,i*2-1);for(const g of new Set([...a.keys(),...l.keys()])){const p=a.get(g)??[],m=l.get(g)??[],c=Math.max(p.length,m.length);for(let y=0;y<c;y++){const v=p[y],$=m[y],w=v&&$?bo(v,$,u):void 0;if(w){h.push({...w,opacity:1});continue}v&&h.push({...v,opacity:d}),$&&h.push({...$,opacity:f})}}return h.filter(g=>g.opacity>0)}function Ke(t,e,n,i){const r=n.size*.35;let s=1/0,o=1/0,a=-1/0,l=-1/0;for(const h of e){const[u,d]=Xe(h,n);s=Math.min(s,u-r),a=Math.max(a,u+h.width*n.size+r),o=Math.min(o,d-h.height*n.size-r),l=Math.max(l,d+h.depth*n.size+r)}return[{type:"line",id:`${t}.backdrop`,points:[[s,o],[a,o],[a,l],[s,l]],closed:!0,fill:i.theme.background,opacity:(n.opacity??1)*.85}]}function Mi(t,e,n){const i=Yt(n.values,t);return e?i:n.plane.toScreen(i)}function wo(t,e){const[n,i]=Mi(t.at,t.screen,e),r=(t.size??28)*e.plane.scale,s=I(e.theme,t.color,e.theme.ink),o={x:n,y:i,size:r,color:s,align:t.align,opacity:e.opacity*e.draw,idPrefix:`${t.id}.`},a=ft(t.tex,{values:e.scope});return[...t.backdrop??t.screen??!1?Ke(t.id,[a],o,e):[],...vt(a,o)]}function ko(t,e){const[n,i]=Mi(t.at,t.screen,e),r=(t.size??36)*e.plane.scale,s=I(e.theme,t.color,e.theme.ink),o=t.steps.length-1,a=Math.min(o,Math.max(0,e.prop("step")??t.step??0)),l=Math.floor(a),h=a-l,u={x:n,y:i,size:r,color:s,align:t.align,opacity:e.opacity*e.draw,idPrefix:`${t.id}.`},d=c=>ft(t.steps[c],{values:e.scope}),f=t.backdrop??t.screen??!1;if(h===0||l>=o){const c=d(l);return[...f?Ke(t.id,[c],u,e):[],...vt(c,u)]}const g=c=>{const[y,v]=Xe(c,u);return{layout:c,x:y/r,y:v/r}},p=d(l),m=d(l+1);return[...f?Ke(t.id,[p,m],u,e):[],...ci(ki(g(p),g(m),h),[0,0],u)]}const Ht=["normal","uniform","exponential","binomial","poisson","dice","mean"];function $i(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 Gt(t){return t.kind==="binomial"||t.kind==="poisson"||t.kind==="dice"}const de=(()=>{const t=[0];return e=>{for(let n=t.length;n<=e;n++)t[n]=t[n-1]+Math.log(n);return t[e]}})(),Je=(t,e)=>Math.exp(de(t)-de(e)-de(t-e));function ut(t,e){switch(t.kind){case"normal":{const{mean:n=0,sd:i=1}=t;return Math.exp(-(((e-n)/i)**2)/2)/(i*Math.sqrt(2*Math.PI))}case"uniform":{const{min:n=0,max:i=1}=t;return e>=n&&e<=i?1/(i-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:Je(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-de(e));case"dice":{const{count:n=2,sides:i=6}=t;if(!Number.isInteger(e)||e<n||e>n*i)return 0;let r=0;for(let s=0;s<=Math.floor((e-n)/i);s++)r+=(s%2?-1:1)*Je(n,s)*Je(e-i*s-1,n-1);return r/i**n}case"mean":return t.count===1?ut(t.of,e):ut({kind:"normal",mean:_t(t.of),sd:Et(t.of)/Math.sqrt(t.count)},e)}}function _t(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 _t(t.of)}}function Et(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 Et(t.of)/Math.sqrt(t.count)}}function tn(t,e){switch(t.kind){case"normal":return Xn(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 i=0;i<t.n;i++)e.next()<t.p&&n++;return n}case"poisson":{const n=Math.exp(-t.rate);let i=0,r=e.next();for(;r>n;)i++,r*=e.next();return i}case"dice":{let n=0;for(let i=0;i<(t.count??2);i++)n+=1+Math.floor(e.next()*(t.sides??6));return n}case"mean":{let n=0;for(let i=0;i<t.count;i++)n+=tn(t.of,e);return n/t.count}}}const fe=new Map;function en(t,e,n){const i=`${JSON.stringify(t)}|${e}`;let r=fe.get(i);if(r||(r=[],fe.size>64&&fe.clear(),fe.set(i,r)),r.length<n){const s=Fe(typeof e=="number"?e:Le(e)),o=[];for(let a=0;a<n;a++)o.push(tn(t,s));r.splice(0,r.length,...o)}return r.slice(0,n)}function nn(t){if(!t||typeof t!="object"||!Ht.includes(t.kind))return`kind must be one of ${Ht.join(", ")}`;const e=(n,i)=>n!==void 0&&!(n>0)?`${i} 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?nn(t.of):"count must be a whole number 1..200"}}function rn(t){const e=_t(t),n=Et(t);if(Gt(t)){const[i,r]=$i(t),s=Math.max(i,Math.floor(e-4*n)),o=Math.min(r,Math.ceil(e+4*n));return[s-.5,o+.5,o-s+1]}return[e-4*n,e+4*n,30]}function Si(t,[e,n,i],r){const s=(n-e)/i,o=new Array(i).fill(0);for(const l of t){const h=Math.floor((l-e)/s);h>=0&&h<i?o[h]++:l===n&&o[i-1]++}const a=t.length||1;return o.map((l,h)=>({left:e+h*s,right:e+(h+1)*s,count:l,height:r==="density"?l/(a*s):l}))}function xi(t){if(t.length===0)return{mean:0,sd:0};const e=t.reduce((i,r)=>i+r,0)/t.length,n=t.reduce((i,r)=>i+(r-e)**2,0)/t.length;return{mean:e,sd:Math.sqrt(n)}}function sn(t,e,n){const i=Fe(typeof e=="number"?e:Le(e));return Array.from({length:Math.max(0,Math.floor(n))},()=>{const r=i.next();if(t.kind==="uniform"){const o=i.next();return[t.x[0]+r*(t.x[1]-t.x[0]),t.y[0]+o*(t.y[1]-t.y[0])]}const s=t.x[0]+r*(t.x[1]-t.x[0]);return[s,t.slope*s+t.intercept+t.noise*Xn(i)]})}function on(t){const e=t.length;if(e<2)return;const n=t.reduce((l,h)=>l+h[0],0)/e,i=t.reduce((l,h)=>l+h[1],0)/e;let r=0,s=0,o=0;for(const[l,h]of t)r+=(l-n)*(h-i),s+=(l-n)**2,o+=(h-i)**2;if(s===0)return;const a=r/s;return{slope:a,intercept:i-a*n,r:o===0?0:r/Math.sqrt(s*o)}}function Ti(t,e,n){const i=Math.min(1,Math.max(0,t)),r=i*Math.min(1,Math.max(0,e)),s=(1-i)*Math.min(1,Math.max(0,n)),o=r+s;return{truePositive:r,falsePositive:s,positive:o,posterior:o>0?r/o:0}}function an(t,e,n){const i=Fe(Le(`${t}:${e}`));return Array.from({length:n},()=>i.next()<.5)}const pe=t=>t.filter(Boolean).length;function Ai(t,e){const n=t.length,i=Math.min(1,Math.max(0,e))*n,r=Math.min(n-1,Math.floor(i)),s=i-r,a=t.slice(0,r).filter(Boolean).length-r/2,l=a+(t[r]?.5:-.5),h=.18*Math.sin(Math.PI*s);return{x:a+(l-a)*s,depth:r+s-h}}const cn=(t,e,n,i,r)=>[[e,n],[i,n],[i,r],[e,r]].map(t.plane.toScreen),me=t=>Math.min(2e4,Math.max(0,Math.floor(t)));function Mo(t,e){const n=Tt(e.values,t.distribution),i=en(n,t.seed??t.id,me(T(e.values,t.count))),r=Si(i,t.bins??rn(n),t.scale??"density"),s=I(e.theme,t.color,e.theme.colors.blue),o=e.opacity*e.draw,a=r.flatMap((l,h)=>l.height>0?[{type:"line",id:`${t.id}.${h}`,points:cn(e,l.left,0,l.right,l.height),closed:!0,fill:s,stroke:e.theme.background,width:1*e.plane.scale,opacity:o*(t.fillOpacity??.75)}]:[]);if(t.curve&&(t.scale??"density")==="density"){const[l,h]=t.bins??rn(n),u=I(e.theme,"yellow",e.theme.colors.yellow);a.push(...he(`${t.id}.curve`,d=>ut(Gt(n)?{kind:"normal",mean:_t(n),sd:Et(n)}:n,d),l,h,u,3*e.plane.scale,{...e,draw:1}))}return a}function $o(t,e){const n=Tt(e.values,t.distribution),i=I(e.theme,t.color,e.theme.colors.blue),[r,s]=t.domain??e.plane.x,o=t.shade?[T(e.values,t.shade[0]),T(e.values,t.shade[1])].sort((h,u)=>h-u):void 0,a=I(e.theme,"yellow",e.theme.colors.yellow);if(Gt(n)){const h=[],u=Math.max(0,Math.ceil(r)),d=Math.floor(s),f=u+Math.ceil((d-u+1)*e.draw);for(let g=u;g<f&&g<=d;g++){const p=ut(n,g);if(p<=0)continue;const m=o&&g>=o[0]&&g<=o[1];h.push({type:"line",id:`${t.id}.${g}`,points:cn(e,g-.4,0,g+.4,p),closed:!0,fill:m?a:i,opacity:e.opacity*(t.fillOpacity??.8)})}return h}const l=[];if(o&&e.draw>=1){const[h,u]=[Math.max(o[0],r),Math.min(o[1],s)];if(u>h){const f=Array.from({length:121},(p,m)=>{const c=h+(u-h)*m/120;return[c,ut(n,c)]}),g=[[h,0],...f,[u,0]].map(e.plane.toScreen);l.push({type:"line",id:`${t.id}.shade`,points:g,closed:!0,fill:a,opacity:e.opacity*(t.fillOpacity??.4)})}}return l.push(...he(t.id,h=>ut(n,h),r,s,i,(t.width??3.5)*e.plane.scale,e)),l}function So(t,e){const n=t.rows??10,i=t.spacing??.5,r=t.top??e.plane.y[1]-i,s=i*.9,o=(b,k)=>[b*i,r-k*s],a=I(e.theme,"grey",e.theme.colors.grey),l=I(e.theme,t.color,e.theme.colors.yellow),h=i*.19*e.plane.unitX,u=[];for(let b=0;b<n;b++)for(let k=0;k<=b;k++){const[M,x]=e.plane.toScreen(o(k-b/2,b));u.push({type:"circle",id:`${t.id}.peg.${b}.${k}`,x:M,y:x,r:h*.45,fill:a,opacity:e.opacity*e.draw})}const d=n+.3,f=Math.max(n+2,(r-e.plane.y[0])/s-.2);for(let b=0;b<=n+1;b++){const k=b-(n+1)/2,M=Q([[o(k,d),o(k,f)].map(e.plane.toScreen)],e.draw);for(const x of M)u.push({type:"line",id:`${t.id}.bin.${b}`,points:x,stroke:a,width:1.2*e.plane.scale,opacity:e.opacity*.6})}const g=Q([[o(-(n+1)/2,f),o((n+1)/2,f)].map(e.plane.toScreen)],e.draw);for(const b of g)u.push({type:"line",id:`${t.id}.floor`,points:b,stroke:a,width:1.2*e.plane.scale,opacity:e.opacity*.6});const p=Math.max(0,T(e.values,t.balls)),m=Math.floor(p),c=t.seed??t.id,y=new Array(n+1).fill(0),v=2*h/e.plane.unitY/s,$=(b,k)=>({x:b-n/2+(k%2?.22:-.22),depth:f-v*(Math.floor(k/2)+.5)});for(let b=0;b<m;b++){const k=pe(an(c,b,n)),M=$(k,y[k]),[x,P]=e.plane.toScreen(o(M.x,M.depth));y[k]++,u.push({type:"circle",id:`${t.id}.ball.${b}`,x,y:P,r:h,fill:l,opacity:e.opacity})}const w=p-m;if(w>0){const b=an(c,m,n),k=Math.min(1,w/.8);let{x:M,depth:x}=Ai(b,k);if(x-=1,w>.8){const O=((w-.8)/.2)**2,_=pe(b),F=$(_,y[_]),j={x:pe(b)-n/2,depth:n-1};x=j.depth+(F.depth-j.depth)*O,M=j.x+(F.x-j.x)*O}const[P,A]=e.plane.toScreen(o(M,x));u.push({type:"circle",id:`${t.id}.falling`,x:P,y:A,r:h,fill:l,opacity:e.opacity})}return u}function xo(t,e){const n=_i(t,e),i=sn(n,t.seed??t.id,me(T(e.values,t.count))),r=I(e.theme,t.color,e.theme.colors.blue),s=I(e.theme,t.insideColor,e.theme.colors.yellow),o=t.inside?pt(t.inside):void 0,a=(t.radius??3)*e.plane.scale,l=i.map(([h,u],d)=>{const[f,g]=e.plane.toScreen([h,u]),p=o?lt(o,{...e.scope,x:h,y:u})<=0:!1;return{type:"circle",id:`${t.id}.${d}`,x:f,y:g,r:a,fill:p?s:r,opacity:e.opacity*e.draw*.85}});if(t.fit){const h=on(i);if(h){const[u,d]=e.plane.x;l.push({type:"line",id:`${t.id}.fit`,points:[[u,h.slope*u+h.intercept],[d,h.slope*d+h.intercept]].map(e.plane.toScreen),stroke:I(e.theme,"red",e.theme.colors.red),width:3*e.plane.scale,opacity:e.opacity})}}return l}function _i(t,e){const n=t.points;return n.kind==="uniform"?n:{kind:"linear",slope:T(e.values,n.slope),intercept:T(e.values,n.intercept),noise:T(e.values,n.noise),x:n.x}}function To(t,e){const n=T(e.values,t.prior),i=T(e.values,t.truePositive),r=T(e.values,t.falsePositive),s=e.plane.x[1]-e.plane.x[0],o=e.plane.y[1]-e.plane.y[0],[a,l]=t.size??[s*.8,o*.7],[h,u]=t.at??[e.plane.x[0]+s*.1,e.plane.y[0]+o*.08],d=h+a*Math.min(1,Math.max(0,n)),f=I(e.theme,t.color,e.theme.colors.yellow),g=I(e.theme,"red",e.theme.colors.red),p=I(e.theme,"grey",e.theme.colors.grey),m=e.opacity*e.draw,c=(b,k,M,x,P,A,O)=>({type:"line",id:`${t.id}.${b}`,points:cn(e,k,M,x,P),closed:!0,fill:A,stroke:e.theme.background,width:2*e.plane.scale,opacity:m*O}),y=u+l,v=y-l*Math.min(1,Math.max(0,i)),$=y-l*Math.min(1,Math.max(0,r)),w=[c("tp",h,v,d,y,f,.85),c("fn",h,u,d,v,p,.35),c("fp",d,$,h+a,y,g,.8),c("tn",d,u,h+a,$,p,.2)];if(t.labels!==!1&&e.draw>=1){const b=20*e.plane.scale,k=(M,x,P,A)=>{const[O,_]=e.plane.toScreen(P);w.push(...vt(ft(x,{values:e.scope,style:"inline"}),{x:O,y:_,size:b,color:A,opacity:e.opacity,idPrefix:`${t.id}.label.${M}.`}))};k("prior",`\\text{has it: } \\val{${t.id}.prior:3}`,[h+a/2,u-o*.04],e.theme.ink),k("tp",`\\text{has it, tests positive: } \\val{${t.id}.truePositive:3}`,[h+a/2,u-o*.09],f),k("fp",`\\text{does not, tests positive: } \\val{${t.id}.falsePositive:3}`,[h+a/2,u-o*.14],g),k("posterior",`P(\\text{has it} \\mid +) = \\val{${t.id}.posterior:3}`,[h+a/2,u+l+o*.05],f)}return w}function ge(t,e,n,i=512){if(e===n)return 0;const r=(n-e)/i;let s=t(e)+t(n);for(let o=1;o<i;o++)s+=t(e+o*r)*(o%2?4:2);return s*r/3}function Ei(t,e,n,i,r){const s=(n-e)/i;return Array.from({length:i},(o,a)=>{const l=e+a*s,h=l+s;if(r==="trapezoid")return[l,h,t(l),t(h)];const u=t(r==="left"?l:r==="right"?h:(l+h)/2);return[l,h,u,u]})}const Pi=t=>Math.min(400,Math.max(1,Math.round(t)));function Oi(t,e,n){const i={},r={...n};for(const s of t)switch(s.kind){case"tangent":{const o=V(s.expr),a=T(e,s.at),l=s.h===void 0?0:T(e,s.h),h=Math.abs(l)>1e-9?(o(a+l,r)-o(a,r))/l:le(s.expr,1)(a,r);Object.assign(i,{[`${s.id}.slope`]:h,[`${s.id}.x`]:a,[`${s.id}.y`]:o(a,r)});break}case"riemann":{const o=V(s.expr),a=T(e,s.from),l=T(e,s.to),h=Pi(T(e,s.n)),d=Ei(f=>o(f,r),a,l,h,s.rule??"left").reduce((f,[g,p,m,c])=>f+(m+c)/2*(p-g),0);Object.assign(i,{[`${s.id}.sum`]:d,[`${s.id}.exact`]:ge(f=>o(f,r),a,l),[`${s.id}.n`]:h});break}case"area":{const o=V(s.expr),a=s.lower?V(s.lower):()=>0;i[`${s.id}.value`]=ge(l=>o(l,r)-a(l,r),T(e,s.from),T(e,s.to));break}case"point":if(s.on!==void 0&&s.x!==void 0){const o=T(e,s.x);Object.assign(i,{[`${s.id}.x`]:o,[`${s.id}.y`]:V(s.on)(o,r)})}break;case"histogram":{const o=en(Tt(e,s.distribution),s.seed??s.id,me(T(e,s.count))),{mean:a,sd:l}=xi(o);Object.assign(i,{[`${s.id}.count`]:o.length,[`${s.id}.mean`]:a,[`${s.id}.sd`]:l});break}case"distribution":{const o=Tt(e,s.distribution);let a=0;if(s.shade){const[l,h]=[T(e,s.shade[0]),T(e,s.shade[1])].sort((u,d)=>u-d);if(Gt(o))for(let u=Math.max(0,Math.ceil(l));u<=Math.floor(h)&&u<=5e3;u++)a+=ut(o,u);else a=ge(u=>ut(o,u),l,h,2048)}Object.assign(i,{[`${s.id}.p`]:a,[`${s.id}.mean`]:_t(o),[`${s.id}.sd`]:Et(o)});break}case"galton":i[`${s.id}.landed`]=Math.max(0,Math.floor(T(e,s.balls)));break;case"scatter":{const o=sn(_i(s,{values:e}),s.seed??s.id,me(T(e,s.count))),a=s.inside?pt(s.inside):void 0,l=a?o.filter(([u,d])=>lt(a,{...r,x:u,y:d})<=0).length:0,h=on(o);Object.assign(i,{[`${s.id}.count`]:o.length,[`${s.id}.inside`]:l,[`${s.id}.ratio`]:o.length?l/o.length:0,[`${s.id}.slope`]:h?.slope??0,[`${s.id}.intercept`]:h?.intercept??0,[`${s.id}.r`]:h?.r??0});break}case"bayes":{const o=T(e,s.prior),a=Ti(o,T(e,s.truePositive),T(e,s.falsePositive));Object.assign(i,{[`${s.id}.prior`]:o,[`${s.id}.posterior`]:a.posterior,[`${s.id}.positive`]:a.positive,[`${s.id}.truePositive`]:a.truePositive,[`${s.id}.falsePositive`]:a.falsePositive});break}case"taylor":i[`${s.id}.order`]=Math.min(20,Math.max(0,T(e,s.order))),i[`${s.id}.degree`]=Math.floor(i[`${s.id}.order`]);break}return i}function Ao(t,e){const n=V(t.expr),i=T(e.values,t.at),r=t.h===void 0?0:T(e.values,t.h),s=n(i,e.scope),o=e.scope[`${t.id}.slope`];if(!Number.isFinite(s)||!Number.isFinite(o))return[];const a=t.length!==void 0?t.length/2:Math.max(Math.abs(e.plane.x[0]-i),Math.abs(e.plane.x[1]-i)),l=[[i-a,s-o*a],[i+a,s+o*a]],h=I(e.theme,t.color,e.theme.colors.yellow),u=e.plane.toScreen([i,s]),d=l.map(e.plane.toScreen),f=[d[0],d[1]].flatMap((g,p)=>Q([[u,g]],e.draw).map(m=>({type:"line",id:`${t.id}.${p}`,points:m,stroke:h,width:(t.width??3)*e.plane.scale,opacity:e.opacity})));if(t.points!==!1){const g=6*e.plane.scale;if(f.push({type:"circle",id:`${t.id}.point`,x:u[0],y:u[1],r:g,fill:h,opacity:e.opacity}),Math.abs(r)>1e-9){const[p,m]=e.plane.toScreen([i+r,n(i+r,e.scope)]);Number.isFinite(m)&&f.push({type:"circle",id:`${t.id}.secant`,x:p,y:m,r:g,fill:h,opacity:e.opacity})}}if(t.label&&e.draw>=1){const g=24*e.plane.scale,p=ft(t.label,{values:e.scope,style:"inline"});f.push(...vt(p,{x:u[0],y:u[1]-g*1.6,size:g,color:h,opacity:e.opacity,idPrefix:`${t.id}.label.`}))}return f}function _o(t,e){const n=V(t.expr),i=T(e.values,t.from),r=T(e.values,t.to),s=Pi(T(e.values,t.n)),o=Ei(u=>n(u,e.scope),i,r,s,t.rule??"left"),a=I(e.theme,t.color,e.theme.colors.blue),l=Math.ceil(o.length*e.draw),h=Math.max(.5,Math.min(1.5,60/s))*e.plane.scale;return o.slice(0,l).flatMap(([u,d,f,g],p)=>{if(!Number.isFinite(f)||!Number.isFinite(g))return[];const m=[[u,0],[d,0],[d,g],[u,f]].map(e.plane.toScreen),y=(f+g)/2<0?I(e.theme,"red",e.theme.colors.red):a;return[{type:"line",id:`${t.id}.${p}`,points:m,closed:!0,fill:y,stroke:y,width:h,opacity:e.opacity*(t.fillOpacity??.35)}]})}function Eo(t,e){const n=V(t.expr),i=t.lower?V(t.lower):()=>0,r=T(e.values,t.from),s=r+(T(e.values,t.to)-r)*e.draw;if(r===s)return[];const o=240,a=I(e.theme,t.color,e.theme.colors.blue),l=I(e.theme,t.negativeColor,e.theme.colors.red),h=e.opacity*(t.fillOpacity??.4),u=[];let d=[],f=[],g;const p=()=>{d.length>=2&&u.push({type:"line",id:`${t.id}.${u.length}`,points:[...d,...f.reverse()].map(e.plane.toScreen),closed:!0,fill:g?a:l,opacity:h}),d=[],f=[]};let m;for(let c=0;c<=o;c++){const y=r+(s-r)*c/o,v=n(y,e.scope),$=i(y,e.scope);if(!Number.isFinite(v)||!Number.isFinite($)){p(),m=void 0;continue}const w=v-$>=0;if(m&&g!==void 0&&w!==g){const b=m.fy-m.gy,k=v-$,M=b/(b-k),x=m.x+(y-m.x)*M,P=m.gy+($-m.gy)*M;d.push([x,P]),f.push([x,P]),p(),d.push([x,P]),f.push([x,P])}g=w,d.push([y,v]),f.push([y,$]),m={x:y,fy:v,gy:$}}return p(),u}const Po=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 Oo(t,e){const n=T(e.values,t.at),i=e.scope[`${t.id}.order`],r=Math.floor(i),s=i-r,o=Array.from({length:Math.min(20,r+1)+1},(d,f)=>le(t.expr,f)(n,e.scope)/Po[f]),a=d=>{let f=0,g=1;for(let p=0;p<=r;p++)f+=o[p]*g,g*=d-n;return s>0&&r<20?f+s*o[r+1]*g:f},l=I(e.theme,t.color,e.theme.colors.yellow),[h,u]=t.domain??e.plane.x;return he(t.id,d=>a(d),h,u,l,(t.width??3.5)*e.plane.scale,e)}function Io(t,e){switch(t.kind){case"grid":return Zs(t,e);case"axes":return Qs(t,e);case"vector":return co(t,e);case"basis":return lo(t,e);case"point":return uo(t,e);case"function":return fo(t,e);case"parametric":return po(t,e);case"polygon":return go(t,e);case"line":return yo(t,e);case"label":return wo(t,e);case"equation":return ko(t,e);case"tangent":return Ao(t,e);case"riemann":return _o(t,e);case"area":return Eo(t,e);case"taylor":return Oo(t,e);case"histogram":return Mo(t,e);case"distribution":return $o(t,e);case"galton":return So(t,e);case"scatter":return xo(t,e);case"bayes":return To(t,e)}}const Ii=t=>Math.min(1,Math.max(0,t));function Zt(t,e={}){const n=ie[t.theme??"dark"],i=je(t),r={...t.values},s=new Map;for(const[u,d]of Object.entries(e))u.indexOf(".")<0?typeof d!="string"&&(r[u]=d):typeof d=="number"&&s.set(u,d);const o=ei(r),a={...o,...Oi(t.items,r,o)},l=[];for(const u of t.items){const d=p=>s.get(`${u.id}.${p}`),f=Ii(d("draw")??u.draw??1),g=Ii(d("opacity")??u.opacity??1);f<=0||g<=0||l.push(...Io(u,{plane:i,theme:n,values:r,scope:a,draw:f,opacity:g,prop:d}))}const h=t.background==="none"?void 0:t.background??n.background;return{width:t.width,height:t.height,...h?{background:h}:{},shapes:l}}const Co=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 Pt(t){const e=c=>{throw new Error(`math figure: ${c}`)};(!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 c of["x","y"]){const y=t[c];y!==void 0&&!(Array.isArray(y)&&y.length===2&&y.every(Number.isFinite)&&y[0]<y[1])&&e(`${c} must be [min, max] with min < max`)}t.theme!==void 0&&!(t.theme in ie)&&e(at("theme",t.theme,Object.keys(ie))),Array.isArray(t.items)||e("items must be an array");const n=t.values??{};for(const[c,y]of Object.entries(n))/^[A-Za-z_]\w*$/.test(c)||e(`value name "${c}" must be letters, digits and _ (starting with a letter)`),Co.has(c)&&e(`"${c}" cannot name a value: it is ${c==="x"||c==="t"?"the variable of functions and curves":"a property of the figure itself (its place, size or look)"}`),typeof y=="number"&&Number.isFinite(y)||dt(y)||xt(y)||e(`value "${c}" must be a number, an [x, y] vector or an [a, b, c, d] matrix`);const i=ei(n),r=Object.keys(n).filter(c=>typeof n[c]=="number"),s=(c,y,v)=>{v!==void 0&&(typeof v=="string"?(v in n||e(`${c.id}.${y}: ${at("value",v,Object.keys(n))}`),dt(n[v])||e(`${c.id}.${y}: value "${v}" is not an [x, y] vector`)):dt(v)||e(`${c.id}.${y} must be [x, y] or the name of a vector value`))},o=(c,y,v)=>{v!==void 0&&(v in n||e(`${c.id}.${y}: ${at("value",v,Object.keys(n))}`),xt(n[v])||e(`${c.id}.${y}: value "${v}" is not an [a, b, c, d] matrix`))},a=(c,y,v,$)=>{let w=[];try{w=Ze(pt(v))}catch(b){e(`${c.id}.${y}: ${b.message}`)}for(const b of w)b!==$&&!(b in Vt)&&!r.includes(b)&&e(`${c.id}.${y}: "${b}" is neither ${$} nor a number value (${at("value",b,[$,...r])})`)},l=[],h=(c,y,v)=>{l.push([c,y,v])},u=(c,y,v)=>{v!==void 0&&(typeof v=="string"?(v in n||e(`${c.id}.${y}: ${at("value",v,r)}`),typeof n[v]!="number"&&e(`${c.id}.${y}: value "${v}" is not a number`)):Number.isFinite(v)||e(`${c.id}.${y} must be a number or the name of a number value`))},d=(c,y,v)=>{(!v||typeof v!="object"||!Ht.includes(v.kind))&&e(`${c.id}.${y}: ${at("distribution",v?.kind,Ht)}`);for(const[w,b]of Object.entries(v))w!=="kind"&&(w==="of"?d(c,`${y}.of`,b):u(c,`${y}.${w}`,b));const $=nn(Tt(n,v));$&&e(`${c.id}.${y}: ${$}`)},f=(c,y,v)=>{let $=[];try{$=Ze(pt(v))}catch(w){e(`${c.id}.${y}: ${w.message}`)}for(const w of $)w!=="x"&&w!=="y"&&!r.includes(w)&&e(`${c.id}.${y}: "${w}" is neither x, y nor a number value`)},g=(c,y,v,$)=>{try{let w=pt(v);for(let b=0;b<$;b++)w=rt(w)}catch(w){e(`${c.id}.${y}: ${w.message} (calculus needs functions with derivatives)`)}},p=new Set;for(const c of t.items)switch((!c||typeof c!="object")&&e("every item must be an object"),Ne.includes(c.kind)||e(at("item kind",c.kind,Ne)),(typeof c.id!="string"||!/^[A-Za-z_][\w-]*$/.test(c.id))&&e(`a ${c.kind} needs an id (letters, digits, _ and -)`),p.has(c.id)&&e(`two items have the id "${c.id}"`),c.id in n&&e(`"${c.id}" is both an item id and a value name`),p.add(c.id),c.kind){case"grid":c.step!==void 0&&!(c.step>0)&&e(`${c.id}.step must be positive`),o(c,"transform",c.transform);break;case"vector":s(c,"to",c.to),s(c,"from",c.from),o(c,"transform",c.transform),c.label&&h(c,"label",c.label);break;case"basis":o(c,"transform",c.transform);break;case"point":c.at===void 0==(c.on===void 0)&&e(`${c.id} needs at, or on with x (a point on a curve)`),c.on!==void 0&&(c.x===void 0&&e(`${c.id}: a point on a curve needs x`),a(c,"on",c.on,"x"),u(c,"x",c.x)),s(c,"at",c.at),o(c,"transform",c.transform),c.label&&h(c,"label",c.label);break;case"function":a(c,"expr",c.expr,"x"),c.derivative!==void 0&&((!Number.isInteger(c.derivative)||c.derivative<0||c.derivative>8)&&e(`${c.id}.derivative must be a whole number from 0 to 8`),g(c,"expr",c.expr,c.derivative));break;case"tangent":a(c,"expr",c.expr,"x"),g(c,"expr",c.expr,1),u(c,"at",c.at),u(c,"h",c.h),c.label&&h(c,"label",c.label);break;case"riemann":a(c,"expr",c.expr,"x"),u(c,"from",c.from),u(c,"to",c.to),u(c,"n",c.n),c.rule!==void 0&&!["left","right","midpoint","trapezoid"].includes(c.rule)&&e(`${c.id}.rule: ${at("rule",c.rule,["left","right","midpoint","trapezoid"])}`);break;case"area":a(c,"expr",c.expr,"x"),c.lower!==void 0&&a(c,"lower",c.lower,"x"),u(c,"from",c.from),u(c,"to",c.to);break;case"histogram":d(c,"distribution",c.distribution),u(c,"count",c.count),c.bins!==void 0&&!(Array.isArray(c.bins)&&c.bins.length===3&&c.bins[1]>c.bins[0]&&Number.isInteger(c.bins[2])&&c.bins[2]>=1&&c.bins[2]<=500)&&e(`${c.id}.bins must be [from, to, count] with from < to and a whole count 1..500`);break;case"distribution":d(c,"distribution",c.distribution),c.shade&&c.shade.forEach((y,v)=>u(c,`shade[${v}]`,y));break;case"galton":c.rows!==void 0&&!(Number.isInteger(c.rows)&&c.rows>=1&&c.rows<=30)&&e(`${c.id}.rows must be a whole number 1..30`),u(c,"balls",c.balls);break;case"scatter":(!c.points||!["uniform","linear"].includes(c.points.kind))&&e(`${c.id}.points: ${at("points kind",c.points?.kind,["uniform","linear"])}`),c.points.kind==="linear"&&(u(c,"points.slope",c.points.slope),u(c,"points.intercept",c.points.intercept),u(c,"points.noise",c.points.noise)),u(c,"count",c.count),c.inside&&f(c,"inside",c.inside);break;case"bayes":u(c,"prior",c.prior),u(c,"truePositive",c.truePositive),u(c,"falsePositive",c.falsePositive);break;case"taylor":a(c,"expr",c.expr,"x"),g(c,"expr",c.expr,3),u(c,"at",c.at),u(c,"order",c.order);break;case"parametric":a(c,"x",c.x,"t"),a(c,"y",c.y,"t"),o(c,"transform",c.transform);break;case"polygon":c.points!==void 0&&!(Array.isArray(c.points)&&c.points.length>=3&&c.points.every(dt))&&e(`${c.id}.points must be three or more [x, y] points`),o(c,"transform",c.transform),c.label&&h(c,"label",c.label);break;case"line":c.along===void 0==(c.eigen===void 0)&&e(`${c.id} needs exactly one of along or eigen`),s(c,"along",c.along),o(c,"eigen",c.eigen);break;case"label":s(c,"at",c.at),h(c,"tex",c.tex);break;case"equation":s(c,"at",c.at),(!Array.isArray(c.steps)||c.steps.length===0)&&e(`${c.id}.steps needs at least one TeX step`),c.steps.forEach((y,v)=>h(c,`steps[${v}]`,y));break}const m={...i,...Oi(t.items,n,i)};for(const[c,y,v]of l)try{ft(v,{values:m})}catch($){e(`${c.id}.${y}: ${$.message}`)}return t}function Ci(t,e){if(t.length<2)return{shaft:t,head:void 0};const n=t[t.length-1],i=t[t.length-2],r=n[0]-i[0],s=n[1]-i[1],o=Math.hypot(r,s);if(o===0||e<=0)return{shaft:t,head:void 0};const a=r/o,l=s/o,h=Math.min(e,o),u=[n[0]-a*h,n[1]-l*h],d=h*.55;return{shaft:[...t.slice(0,-1),u],head:[n,[u[0]-l*d,u[1]+a*d],[u[0]+l*d,u[1]-a*d]]}}const D=t=>String(Math.round(t*100)/100),J=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),ln=(t,e=!1)=>t.map(([n,i],r)=>`${r?"L":"M"}${D(n)} ${D(i)}`).join("")+(e?"Z":""),ye=t=>t.opacity!==void 0&&t.opacity<1?` opacity="${D(t.opacity)}"`:"";function Ro(t){switch(t.type){case"line":{if(t.points.length<2)return"";const e=t.fill?` fill="${J(t.fill)}"`:' fill="none"',n=t.stroke&&(t.width??1)>0?` stroke="${J(t.stroke)}" stroke-width="${D(t.width??1)}"`:"",i=t.dash?.length?` stroke-dasharray="${t.dash.map(D).join(" ")}"`:"";return`<path d="${ln(t.points,t.closed)}"${e}${n}${i}${ye(t)}/>`}case"arrow":{const{shaft:e,head:n}=Ci(t.points,t.head),i=J(t.stroke),r=e.length>=2?`<path d="${ln(e)}" fill="none" stroke="${i}" stroke-width="${D(t.width)}"/>`:"",s=n?`<path d="${ln(n,!0)}" fill="${i}"/>`:"";return`<g${ye(t)}>${r}${s}</g>`}case"circle":{const e=t.fill?` fill="${J(t.fill)}"`:' fill="none"',n=t.stroke?` stroke="${J(t.stroke)}" stroke-width="${D(t.width??1)}"`:"";return`<circle cx="${D(t.x)}" cy="${D(t.y)}" r="${D(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="${D(t.x)}" y="${D(t.y)}" font-size="${D(t.size)}" font-family="${J(t.font)}"${n} text-anchor="${e}" fill="${J(t.color)}"${ye(t)}>${J(t.text)}</text>`}}}function be(t){return`${t.background?`<rect width="${D(t.width)}" height="${D(t.height)}" fill="${J(t.background)}"/>`:""}<g stroke-linecap="round" stroke-linejoin="round">${t.shapes.map(Ro).join("")}</g>`}function Ri(t,e={}){const n=e.title?`<title>${J(e.title)}</title>`:"",i=e.title?` role="img" aria-label="${J(e.title)}"`:"";return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${D(t.width)} ${D(t.height)}" width="${D(t.width)}" height="${D(t.height)}"${i}>${n}${be(t)}</svg>`}const Lo="http://www.w3.org/2000/svg",un=new WeakMap;function Fo(t,e){const n=t?.values.get(e);return n?Object.fromEntries(n):{}}async function Li(t,e={}){const n=un.get(t);if(n)return n;const i=t.querySelector("script[data-tinyfly-figure]");let r;try{r=Pt(JSON.parse(i?.textContent??"null"))}catch(f){console.warn("tinyfly: math figure is missing or invalid",t,f);return}const s=t.getAttribute("data-target")??"fig";let o=t.querySelector("svg[data-tinyfly-math-svg]");o||(o=t.ownerDocument.createElementNS(Lo,"svg"),o.setAttribute("data-tinyfly-math-svg",""),o.setAttribute("viewBox",`0 0 ${r.width} ${r.height}`),o.setAttribute("style","display:block;width:100%;height:auto"),t.insertBefore(o,t.querySelector("figcaption")));const a=f=>{o.innerHTML=be(Zt(r,f))};if(a({}),!(t.querySelector("script[data-tinyfly-timeline]")||t.hasAttribute("data-src"))){const f={element:t,figure:r,redraw:()=>a({})};return un.set(t,f),f}const h=await Ls(t,e);if(!h)return;const u=()=>a(Fo(h.player.state,s));h.player.subscribe(u),u();const d={...h,figure:r,redraw:u};return un.set(t,d),d}async function Fi(t=document,e={}){const n=Array.from(t.querySelectorAll("[data-tinyfly-math]"));return(await Promise.all(n.map(r=>Li(r,e)))).filter(r=>r!==void 0)}function No(){if(!(typeof document<"u"?document.currentScript:null)?.hasAttribute("data-tinyfly-auto"))return;const e=()=>{Fi()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}function hn(t,e,n=!1){t.beginPath(),e.forEach(([i,r],s)=>s===0?t.moveTo(i,r):t.lineTo(i,r)),n&&t.closePath()}function Do(t,e){switch(t.globalAlpha=e.opacity??1,e.type){case"line":if(e.points.length<2)return;hn(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:i}=Ci(e.points,e.head);t.strokeStyle=e.stroke,t.fillStyle=e.stroke,t.lineWidth=e.width,n.length>=2&&(hn(t,n),t.stroke()),i&&(hn(t,i,!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 Ni(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)Do(t,n);t.restore()}function Di(t){const e={};for(const[n,i]of Object.entries(t.values??{})){const r=typeof i=="number"?"number":i.length===2?"[x, y] vector":"[a, b, c, d] matrix";e[n]={description:`The value ${n} (a ${r})`,kind:typeof i=="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 qo(t,e={}){Pt(t);const n=Di(t),i={...t.values??{}};return{type:"custom",x:e.x??0,y:e.y??0,width:t.width,height:t.height,props:i,acceptsProp:r=>Object.prototype.hasOwnProperty.call(n,r),draw(r,s){Ni(r,Zt(t,s.props??{}))},about:{kind:"math figure",summary:`A ${t.width}×${t.height} maths figure with ${t.items.map(r=>`${r.kind} "${r.id}"`).join(", ")}. Animate its values by name and each item's draw / opacity (an equation's step).`,props:n}}}function jo(t,e,n,i={}){const r=new Set(n.items.map(l=>l.id)),s=l=>{if(!r.has(l))throw new Error(`mathSteps: no item "${l}" (items: ${[...r].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 i.hidden??[])s(l),o[`${l}.draw`]=0;t.initial(e,o);const a={toValue(l,h,u){if(!(l in o))throw new Error(`mathSteps: no value "${l}" (values: ${Object.keys(n.values??{}).join(", ")})`);return t.to(e,{[l]:h},{duration:1200,...u}),a},applyMatrix(l,h={}){const{name:u="M",...d}=h;if(l.length!==4||!l.every(Number.isFinite))throw new Error("mathSteps.applyMatrix: expected [a, b, c, d]");return a.toValue(u,l,{duration:1600,...d})},drawOn(l,h){return s(l),t.to(e,{[`${l}.draw`]:1},{duration:900,...h}),a},fadeIn(l,h){return s(l),t.set(e,{[`${l}.draw`]:1,[`${l}.opacity`]:0}),t.to(e,{[`${l}.opacity`]:1},{duration:500,...h}),a},fadeOut(l,h){return s(l),t.to(e,{[`${l}.opacity`]:0},{duration:500,...h}),a},showStep(l,h,u){return s(l),t.to(e,{[`${l}.step`]:h},{duration:900,...u}),a}};return a}const zo="http://www.w3.org/2000/svg";function Xo(t,e,n={}){Pt(e);const i={...e.values??{}};for(const w of n.sliders??[])if(typeof i[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&&!dt(i[w.vector]))throw new Error(`mathExplorable: "${w.vector}" is not a vector value of the figure`);if("matrix"in w&&!xt(i[w.matrix]))throw new Error(`mathExplorable: "${w.matrix}" is not a matrix value of the figure`)}const r=je(e),s=t.ownerDocument,o=s.createElementNS(zo,"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 a=n.drag??[],l=w=>{if("vector"in w)return i[w.vector];const[b,k,M,x]=i[w.matrix];return w.column===0?[b,M]:[k,x]},h=()=>{const w=a.map(b=>{const[k,M]=r.toScreen(l(b));return`<circle cx="${k}" cy="${M}" r="${14*r.scale}" fill="rgba(255,255,255,0.08)" stroke="rgba(255,255,255,0.55)" stroke-width="${1.5*r.scale}" style="cursor:grab"/>`});o.innerHTML=be(Zt(e,i))+w.join(""),n.onChange?.({...i})},u=(w,b)=>{if(!(w in i))throw new Error(`mathExplorable: no value "${w}"`);i[w]=b;const k=d.get(w);k&&typeof b=="number"&&(k.value=String(b),f.get(w).textContent=String(b)),h()},d=new Map,f=new Map;let g;if(n.sliders?.length){g=s.createElement("div"),g.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 b=s.createElement("label");b.setAttribute("style","display:flex;align-items:center;gap:6px");const k=s.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(i[w.value]),k.setAttribute("aria-label",w.label??w.value);const M=s.createElement("output");M.textContent=String(i[w.value]),k.addEventListener("input",()=>u(w.value,Number(k.value))),b.append(w.label??w.value,k,M),g.appendChild(b),d.set(w.value,k),f.set(w.value,M)}t.appendChild(g)}const p=n.snap??.1,m=w=>{const b=o.getBoundingClientRect(),k=(w.clientX-b.left)/(b.width||e.width)*e.width,M=(w.clientY-b.top)/(b.height||e.height)*e.height,[x,P]=r.toWorld([k,M]),A=O=>p>0?Math.round(O/p)*p:O;return[Number(A(x).toFixed(6)),Number(A(P).toFixed(6))]};let c;const y=w=>{const b=o.getBoundingClientRect(),k=e.width/(b.width||e.width),M=[(w.clientX-b.left)*k,(w.clientY-b.top)*k];let x;for(const P of a){const[A,O]=r.toScreen(l(P)),_=Math.hypot(A-M[0],O-M[1]);_<30*r.scale*Math.max(1,k)&&(!x||_<x.distance)&&(x={handle:P,distance:_})}x&&(c=x.handle,o.setPointerCapture?.(w.pointerId),w.preventDefault())},v=w=>{if(!c)return;const[b,k]=m(w);if("vector"in c)u(c.vector,[b,k]);else{const[M,x,P,A]=i[c.matrix];u(c.matrix,c.column===0?[b,x,k,A]:[M,b,P,k])}},$=()=>{c=void 0};return o.addEventListener("pointerdown",y),o.addEventListener("pointermove",v),o.addEventListener("pointerup",$),o.addEventListener("pointercancel",$),h(),{get values(){return{...i}},set:u,destroy(){o.removeEventListener("pointerdown",y),o.removeEventListener("pointermove",v),o.removeEventListener("pointerup",$),o.removeEventListener("pointercancel",$),g?.remove()}}}const Qt=(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}),ve="\\begin{bmatrix} \\val{M.a} & \\val{M.b} \\\\ \\val{M.c} & \\val{M.d} \\end{bmatrix}",dn=t=>[(t.width??600)*.05,(t.height??600)*.1];function Yo(t={}){return Qt(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:ve,at:dn(t),screen:!0,align:"left"}])}function Bo(t={}){return Qt(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:ve,at:dn(t),screen:!0,align:"left"}])}function Vo(t){return Qt(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:ve,at:dn(t),screen:!0,align:"left"}])}function Wo(t){const e=[t.u[0]+t.v[0],t.u[1]+t.v[1]];return Qt(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 Uo(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}"})),Qt(t,n,e)}const Ot=(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 Ho(t){return Ot(t,{a:t.at??1},[{id:"tangent",kind:"tangent",expr:t.expr,at:"a",color:"yellow",label:"\\text{slope} = \\val{tangent.slope}"}])}function Go(t){return Ot(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 Zo(t){const e=Ot(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 Qo(t){const e=Ot(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 Ko(t){const e=Ot(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 Jo(t){const e=Ot(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 Mt=(t,e,n,i)=>({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:i}),It=(t,e)=>({id:"readout",kind:"label",screen:!0,align:"left",size:24,at:[(t.width??600)*.05,(t.height??600)*.08],tex:e});function ta(t={}){const[e,n]=t.shade??[-1,1];return Mt(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"]},It(t,"P(\\val{a:2} \\le X \\le \\val{b:2}) = \\val{dist.p:3}")])}function ea(t={}){const e=t.n??10;return Mt(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"}},It(t,"n = \\val{n:0} \\quad p = \\val{p:2} \\quad \\mu = \\val{dist.mean:2}")])}function na(t={}){return Mt(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"},It(t,"k = \\val{k:0} \\text{ draws averaged} \\quad \\bar{x} = \\val{hist.mean:3} \\quad s = \\val{hist.sd:3}")])}function ia(t={}){const e=t.rows??10;return Mt(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},It(t,"\\val{board.landed:0} \\text{ balls}")])}function ra(t={}){return Mt(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},It(t,"\\frac{\\text{inside}}{\\text{all}} = \\frac{\\val{pts.inside:0}}{\\val{pts.count:0}} = \\val{pts.ratio:4} \\approx \\frac{\\pi}{4}")])}function sa(t={}){return Mt(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},It(t,"y = \\val{pts.slope:2}\\,x + \\val{pts.intercept:2} \\quad r = \\val{pts.r:2}")])}function oa(t={}){return Mt(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]}])}function aa(t){return Pt(t)}function ca(t,e={},n={}){return Ri(Zt(Pt(t),e),n)}const la={opacity:1,scale:1,scaleX:1,scaleY:1};function ua(t){const e=new Map,n=new Map,i=[],r={};let s=0,o=0,a;const l=(g,p)=>`${g}\0${p}`,h=(g,p)=>{const m=l(g,p);let c=e.get(m);if(!c){const y=n.get(m)??la[p]??(p==="text"?"":0);c={id:`${g}-${p}`,target:g,property:p,keyframes:[{time:0,value:y}]},e.set(m,c)}return c},u=(g,p)=>{const m=g.keyframes[g.keyframes.length-1];m.time<p&&g.keyframes.push({time:p,value:m.value})},d=(g,p,m,c,y)=>{for(const[$,w]of Object.entries(p)){const b=h(g,$);if(typeof w=="string"&&!/^#|^rgb/.test(w)){u(b,m),b.keyframes.push({time:m+1,value:w});continue}u(b,m),b.keyframes.push({time:m+Math.max(c,1),value:w,...y&&{easing:y}})}const v=m+Math.max(c,1);return o=Math.max(o,v),v},f={get time(){return s},at(g){return s=Math.max(0,g),f},wait(g){return s+=g,o=Math.max(o,s),f},initial(g,p){for(const[m,c]of Object.entries(p)){const y=l(g,m);n.set(y,c);const v=e.get(y);v&&(v.keyframes[0].value=c)}return f},set(g,p){const m=a?a.start:s;return d(g,p,m,1,{type:"steps",count:1,position:"start"}),f},to(g,p,m={}){const c=(a?a.start:s)+(m.delay??0),y=d(g,p,c,m.duration??400,m.easing??"ease-in-out");return a?a.end=Math.max(a.end,y):s=y,f},together(g){const p=a;a={start:p?p.start:s,end:p?p.start:s},g();const m=a.end;return a=p,p?p.end=Math.max(p.end,m):s=m,f},marker(g,p={}){const{captions:m,...c}=p;i.push({id:g,time:s,...c});for(const[y,v]of Object.entries(m??{}))(r[y]??={})[g]=v;return o=Math.max(o,s),f},definition(){return{formatVersion:ke,id:t.id,...t.name&&{name:t.name},config:{duration:o,...i.length>0&&{markers:[...i].sort((g,p)=>g.time-p.time)}},tracks:[...e.values()].map(g=>({...g,keyframes:g.keyframes.map(p=>({...p}))})),...Object.keys(r).length>0&&{captions:r}}}};return f}No(),S.CONSTANTS=Vt,S.DISTRIBUTION_KINDS=Ht,S.ExpressionError=wt,S.FUNCTIONS=oe,S.ITEM_KINDS=Ne,S.MATH_FONT=ni,S.MATH_THEMES=ie,S.MATRIX_TEX=ve,S.SYMBOLS=re,S.TEX_COMMANDS=di,S.TexError=hi,S.areaFigure=Qo,S.ballAt=Ai,S.ballPath=an,S.bayesAreas=Ti,S.bayesFigure=oa,S.binOf=pe,S.binSamples=Si,S.binomialFigure=ea,S.cltFigure=na,S.compile=V,S.compileDerivative=le,S.defaultBins=rn,S.density=ut,S.determinantFigure=Bo,S.differentiate=rt,S.displayListToSvg=Ri,S.displayListToSvgContent=be,S.distributionProblem=nn,S.drawDisplayList=Ni,S.eigenFigure=Vo,S.evaluate=lt,S.expressionNames=Ze,S.expressionToString=Ut,S.galtonFigure=ia,S.integrate=ge,S.isDiscrete=Gt,S.layoutFigure=Zt,S.layoutTex=ft,S.leastSquares=on,S.lesson=ua,S.limitFigure=Jo,S.linearMapFigure=Yo,S.mat2=Ys,S.mathExplorable=Xo,S.mathFigure=aa,S.mathFigureProps=Di,S.mathFigureToSvg=ca,S.mathSteps=jo,S.mathTarget=qo,S.meanOf=_t,S.monteCarloPiFigure=ra,S.morphEquation=ki,S.mountAllMath=Fi,S.mountMath=Li,S.normalFigure=ta,S.nthDerivative=gi,S.parseExpression=pt,S.parseTex=fi,S.planeOf=je,S.regressionFigure=sa,S.riemannFigure=Zo,S.sample=tn,S.samples=en,S.scatterPoints=sn,S.sdOf=Et,S.secantFigure=Go,S.spanFigure=Uo,S.summary=xi,S.supportOf=$i,S.tangentFigure=Ho,S.taylorFigure=Ko,S.texToShapes=vt,S.trimPolylines=Q,S.validateMathFigure=Pt,S.vec2=Hs,S.vectorSumFigure=Wo,Object.defineProperty(S,Symbol.toStringTag,{value:"Module"})})(this.tinyfly=this.tinyfly||{});
|
|
53
|
+
`;function _o(t){if(t.getElementById(ks))return;const e=t.createElement("style");e.id=ks,e.textContent=Eo,t.head.appendChild(e)}function Po(t,e){const n=Array.from(e.querySelectorAll("[data-tinyfly-choose]"));if(n.length===0)return()=>{};_o(e.ownerDocument);const s=[],i=[];for(const c of n){const l=c.getAttribute("data-tinyfly-choose")??"",u=[],h=(p,y)=>{c.hasAttribute(p)||(c.setAttribute(p,y),u.push(p))};h("role","button"),h("tabindex","0");const d=t.scenarios.find(p=>p.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),g=p=>{const y=p.key;y!=="Enter"&&y!==" "||(p.preventDefault(),f())};c.addEventListener("click",f),c.addEventListener("keydown",g),i.push(()=>{c.removeEventListener("click",f),c.removeEventListener("keydown",g)})}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 Ms=new WeakMap,Oo=new WeakMap;let Io=0;function Ut(t,e,n){if(t)try{return JSON.parse(t)}catch(s){console.warn(`tinyfly: invalid ${e} JSON on`,n,s);return}}async function Co(t,e={}){const n=Ms.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=Fo(t.getAttribute("data-markers")),c=s.length>1||i?.hasAttribute("data-scenario")?No(s,o,t):void 0;if(c&&c.length===0)return;let l=i&&!c?Ut(i.textContent,"timeline",t):void 0;if(!l&&r&&o){const g=await fetch(r);g.ok&&(l=await g.json())}if(l&&o&&(l=$s(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=Ut(t.querySelector("script[data-tinyfly-captions]")?.textContent,"captions",t),h={playWhenVisible:!0,...e.player,...u&&{captions:u},...Ut(t.getAttribute("data-options"),"data-options",t)};Lo(t);const d=new bo(t,h),f={element:t,player:d};if(Ms.set(t,f),t.setAttribute("data-tinyfly-mounted",""),c){const g=t.getAttribute("data-scenario")??void 0;await d.loadScenarios(c,{initial:c.some(p=>p.id===g)?g:void 0}),Oo.set(t,Po(d,t))}else await d.load(l??r);if(t.getAttribute("data-controls")!=="false"){const g=Ut(t.getAttribute("data-labels"),"data-labels",t),p=t.querySelector("figcaption"),y=t.getAttribute("data-scenario-legend"),a=t.getAttribute("data-scenario-control");f.controls=$o(d,t,{...e.controls,...t.getAttribute("data-fullscreen")==="true"?{fullscreen:!0}:{},...a==="slider"||a==="buttons"?{scenarioControl:a}:{},labels:{...e.controls?.labels,...g,...y?{scenario:y}:{}},mount:void 0}),p?t.insertBefore(f.controls.element,p):t.appendChild(f.controls.element)}return f}function No(t,e,n){const s=[];return t.forEach((i,r)=>{const o=Ut(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?$s(o,e):o})}),s}function $s(t,e){return t.config.markers?.length?t:{...t,config:{...t.config,markers:e.map((n,s)=>({id:`step-${s+1}`,time:n}))}}}function Fo(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 Lo(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-${++Io}`,e.setAttribute("aria-labelledby",s.id))}const cn=["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"}}},Wt=[1,0,0,1],it=([t,e,n,s],[i,r])=>[t*i+e*r,n*i+s*r];function Ro(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 Gt=([t,e,n,s])=>t*s-e*n;function Do(t){const e=Gt(t);if(Math.abs(e)<1e-12)return;const[n,s,i,r]=t;return[r/e,-s/e,-i/e,n/e]}const qo=(t,e,n)=>t.map((s,i)=>s+(e[i]-s)*n),zo=t=>[Math.cos(t),-Math.sin(t),Math.sin(t),Math.cos(t)];function Ss(t){const[e,n,s,i]=t,r=e+i,o=Gt(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 p=[[e-f,n],[s,i-f]].reduce((v,x)=>Math.hypot(...x)>Math.hypot(...v)?x:v);if(Math.hypot(...p)<l){d.push({value:f,vector:[1,0]},{value:f,vector:[0,1]});continue}const y=[-p[1],p[0]],a=Math.hypot(...y),m=y[0]<-l||Math.abs(y[0])<=l&&y[1]<0?-1:1;d.push({value:f,vector:[m*y[0]/a+0,m*y[1]/a+0]})}return d}function Pt(t){return Array.isArray(t)&&t.length===4&&t.every(Number.isFinite)}const jo=Object.freeze(Object.defineProperty({__proto__:null,IDENTITY:Wt,apply:it,determinant:Gt,eigen:Ss,inverse:Do,isMat2:Pt,lerp:qo,multiply:Ro,rotation:zo},Symbol.toStringTag,{value:"Module"})),Xo=(t,e)=>[t[0]+e[0],t[1]+e[1]],ln=(t,e)=>[t[0]-e[0],t[1]-e[1]],un=(t,e)=>[t[0]*e,t[1]*e],Yo=(t,e)=>t[0]*e[0]+t[1]*e[1],Bo=(t,e)=>t[0]*e[1]-t[1]*e[0],xs=t=>Math.hypot(t[0],t[1]);function Zt(t){const e=xs(t);return e===0?[0,0]:[t[0]/e,t[1]/e]}const Qt=(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 Vo=Object.freeze(Object.defineProperty({__proto__:null,add:Xo,cross:Bo,dot:Yo,isVec2:ct,length:xs,lerp:Qt,normalize:Zt,scale:un,sub:ln},Symbol.toStringTag,{value:"Module"}));function As(t){const e={};for(const[n,s]of Object.entries(t))if(typeof s=="number")e[n]=s;else if(Pt(s)){const[i,r,o,c]=s;Object.assign(e,{[`${n}.a`]:i,[`${n}.b`]:r,[`${n}.c`]:o,[`${n}.d`]:c,[`${n}.det`]:Gt(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 Ot(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 Wt;const n=t[e];if(!Pt(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 It(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:It(t,e.of),count:s(e.count)}}}function hn(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 Ts='"Latin Modern Math", "STIX Two Math", "Cambria Math", "Times New Roman", "Liberation Serif", "Noto Serif", Times, serif',Es='"Latin Modern Math", "STIX Two Math", "Cambria Math", "DejaVu Math TeX Gyre", "DejaVu Serif", serif',Ho=t=>/^[A-Za-z0-9\u0370-\u03ff.,;:!?()[\]'"/ ]+$/.test(t)?Ts:Es,_s=.25,Kt=.05,Ps={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 dn(t){return t.length!==1?t.length*.5:/[0-9]/.test(t)?.5:Object.prototype.hasOwnProperty.call(Ps,t)?Ps[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 Os(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',Is=(t,e)=>Math.hypot(e[0]-t[0],e[1]-t[1]);function X(t,e){if(e>=1)return t;if(e<=0)return[];const n=t.map(r=>r.slice(1).reduce((o,c,l)=>o+Is(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=Is(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 fn(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 Cs(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:Ho(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,g=c.width*r,p=Math.max(1,c.height*r);return{type:"line",id:h,points:[[d,f],[d+g,f],[d+g,f+p],[d,f+p]],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 W(t,e){return Cs(t.pieces,fn(t,e),e)}function Uo(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(Gt(e))/c;return Math.min(n*12,n/Math.max(l,.08))+1}function Ns(t,e,n){const s=Uo(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 Wo(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 Ns(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 Ns(n,kt(e.values,t.transform),i).entries()){const[d]=X([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 Go(t,e){const{plane:n,theme:s}=e,i=O(s,t.color,s.axes),r=2*n.scale,o=e.opacity,c=X([[n.toScreen([n.x[0],0]),n.toScreen([n.x[1],0])]],e.draw),l=X([[n.toScreen([0,n.y[0]]),n.toScreen([0,n.y[1]])]],e.draw),u=[...c,...l].map((y,a)=>({type:"line",id:`${t.id}.${a?"y":"x"}`,points:y,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,g=(y,a)=>{const m=[];for(let v=Math.ceil(y/h)*h;v<=a+1e-9;v+=h)Math.abs(v)>1e-9&&m.push(Number(v.toFixed(6)));return m},p=y=>String(y).replace("-","−");for(const y of g(n.x[0],n.x[1])){const[a,m]=n.toScreen([y,0]);u.push({type:"line",id:`${t.id}.tick.x${y}`,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${y}`,text:p(y),x:a,y:m+d+f*1.1,size:f,font:Mt,color:i,align:"center",opacity:o*.8})}for(const y of g(n.y[0],n.y[1])){const[a,m]=n.toScreen([0,y]);u.push({type:"line",id:`${t.id}.tick.y${y}`,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${y}`,text:p(y),x:a-d-f*.4,y:m+f*.35,size:f,font:Mt,color:i,align:"right",opacity:o*.8})}return u}const pn={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:"Ω"},we={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"]},gn={sum:["∑",!0],prod:["∏",!0],int:["∫",!1],oint:["∮",!1]},yn={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},mn={",":3/18,":":4/18,";":5/18,"!":-3/18,quad:1,qquad:2},Fs=new Set(["pmatrix","bmatrix","vmatrix","matrix"]);class Ls 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 Rs=[...Object.keys(pn),...Object.keys(we),...Object.keys(gn),...Object.keys(yn),...Object.keys(mn).filter(t=>t.length>1),"frac","binom","sqrt","vec","hat","bar","text","color","id","val","begin","end","left","right"].sort();function Ds(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 Ls(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 g=e,p=t[e]==="^";e++;const y=o(p?"superscript":"subscript");let a=d.pop()??{type:"group",body:[]};a.type!=="scripts"&&(a={type:"scripts",base:a}),a.type==="scripts"&&((p&&a.sup||!p&&a.sub)&&s(`Double ${p?"superscript":"subscript"}`,g),p?a.sup=y:a.sub=y),d.push(a);continue}if(t[e]==="'"){e++;const g={type:"symbol",text:"′",cls:"ord",italic:!1},p=d.pop()??{type:"group",body:[]};d.push(p.type==="scripts"&&!p.sup?{...p,sup:g}:{type:"scripts",base:p,sup:g});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 mn)return{type:"space",width:mn[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(pn,f))return{type:"symbol",text:pn[f],cls:"ord",italic:f[0]===f[0].toLowerCase()};if(Object.prototype.hasOwnProperty.call(we,f)){const[p,y]=we[f];return{type:"symbol",text:p,cls:y,italic:!1}}if(Object.prototype.hasOwnProperty.call(gn,f)){const[p,y]=gn[f];return{type:"bigop",text:p,limits:y}}if(Object.prototype.hasOwnProperty.call(yn,f))return{type:"opname",text:f,limits:yn[f]};switch(f){case"frac":return{type:"frac",num:o("numerator"),den:o("denominator")};case"binom":{const p=o("\\binom's top"),y=o("\\binom's bottom");return{type:"group",body:[{type:"symbol",text:"(",cls:"open",italic:!1},{type:"frac",num:p,den:y,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 p=r("\\color").trim();return/^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)$/.test(p)||s(`"${p}" is not a colour name or #hex`,d),{type:"color",color:p,body:o("\\color's body")}}case"id":{const p=r("\\id").trim();return/^[\w.-]+$/.test(p)||s(`"${p}" is not a term id (letters, digits, _ . -)`,d),{type:"id",id:p,body:o("\\id's body")}}case"val":{const p=r("\\val").trim(),y=/^([A-Za-z_][\w.]*)(?::(\d))?$/.exec(p);return y||s(`"${p}" is not a value name (name or name:digits)`,d),{type:"value",name:y[1],digits:y[2]===void 0?2:Number(y[2])}}case"left":case"right":{n();const p=t[e]==="\\"?(e++,i()):t[e++];if(p===".")return{type:"space",width:0};const a={"(":"(",")":")","[":"[","]":"]","|":"|","{":"{","}":"}",langle:"⟨",rangle:"⟩","|.":"‖"}[p];return a||s(`"${p}" is not a delimiter`,d),{type:"symbol",text:a,cls:f==="left"?"open":"close",italic:!1}}case"begin":{const p=r("\\begin").trim();Fs.has(p)||s(`Unknown environment "${p}" (use ${[...Fs].join(", ")})`,d);const y=[[]];for(;;){const a=c("cell");if(y[y.length-1].push({type:"group",body:a}),t[e]==="&")e++;else if(t.startsWith("\\\\",e))e+=2,y.push([]);else{e+=4;const m=r("\\end").trim();m!==p&&s(`\\begin{${p}} ended by \\end{${m}}`);break}}return y.length>1&&y[y.length-1].every(a=>a.type==="group"&&a.body.length===0)&&y.pop(),{type:"matrix",delimiters:p,rows:y}}case"end":return s("\\end without \\begin",d)}const g=gs(f,Rs);return s(`Unknown command "\\${f}"${g?` (did you mean "\\${g}"?)`:""}`,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],Zo=t=>t<=1?2:3,Qo=t=>Math.min(3,t+1),bn=()=>({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 Ct(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 qs(t,e,n,s=1,i=t){const r=lt[n.level]*s,o=dn(t)*r,{height:c,depth:l}=Os(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:Ct(n,i)}]}}function vn(t,e,n){const s=bn(),i=Ct(e,n),r=lt[e.level];for(const o of t){const c=(o===" "?.28:/[A-Za-z]/.test(o)?dn(o)-.04:dn(o))*r;if(o!==" "){const{height:l,depth:u}=Os(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 wn(t){switch(t.type){case"symbol":return t.cls;case"bigop":case"opname":return"op";case"scripts":return wn(t.base);case"id":case"color":return wn(t.body);default:return"ord"}}function Ko(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 Jo(t,e){const n=bn();let s;return t.forEach(i=>{if(i.type==="space"){n.width+=i.width*lt[e.level];return}let r=wn(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+=Ko(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 ta(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 qs(t.text,t.italic,e);case"group":return Jo(t.body,e);case"space":return{...bn(),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(ta(s,t.digits),{...e,id:e.id??`val:${t.name}`},`val:${t.name}`)}case"bigop":return qs(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 ea(t,e);case"frac":return na(t,e);case"sqrt":return sa(t,e);case"accent":return ia(t,e);case"matrix":return ra(t,e)}}function ea(t,e){const n=et(t.base,e),s={...e,level:Zo(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 g=Math.max(n.width,i?.width??0,r?.width??0),p=ut(n,(g-n.width)/2,0);let y=n.height,a=n.depth;const m=.12*o;if(i){const v=-(n.height+m+i.depth);p.push(...ut(i,(g-i.width)/2,v)),y=-v+i.height}if(r){const v=n.depth+m+r.height;p.push(...ut(r,(g-r.width)/2,v)),a=v+r.depth}return{width:g,height:y,depth:a,pieces:p}}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 g=u-i.depth-(r.height-h);g<.2*o&&(h+=.2*o-g)}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 na(t,e){const n={...e,level:Qo(e.level)},s=et(t.num,n),i=et(t.den,n),r=lt[e.level],o=Kt*r,c=_s*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:Ct(e,"frac")}],...ut(i,(h-i.width)/2,f)]}}function sa(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+Kt*s,depth:r,pieces:[{kind:"stroke",points:l,width:Kt*s,...e.color?{color:e.color}:{},id:Ct(e,"sqrt")},...ut(n,o,0)]}}function ia(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=Ct(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:Kt*s*.9,...c,id:l}))]}}function ra(t,e){const n={...e,level:Math.max(e.level,1)},s=lt[n.level],i=t.rows.map(k=>k.map($=>et($,n))),r=Math.max(...i.map(k=>k.length)),o=Array.from({length:r},(k,$)=>Math.max(0,...i.map(S=>S[$]?.width??0))),c=i.map(k=>Math.max(.7*s,...k.map($=>$.height))),l=i.map(k=>Math.max(.2*s,...k.map($=>$.depth))),u=.9*s,h=.25*s,d=t.delimiters==="matrix"?0:.55*s,f=o.reduce((k,$)=>k+$,0)+u*(r-1),g=c.reduce((k,$,S)=>k+$+l[S],0)+h*(i.length-1),p=-_s*s-g/2,y=[];let a=p;i.forEach((k,$)=>{a+=c[$];let S=d;k.forEach((T,A)=>{y.push(...ut(T,S+(o[A]-T.width)/2,a)),S+=o[A]+u}),a+=l[$]+h});const m=f+d*2,v=p+g,x=e.color?{color:e.color}:{},w=(k,$)=>({kind:"stroke",points:k,width:Kt*s*1.1,...x,id:Ct(e,$)}),b=.08*s;if(t.delimiters==="pmatrix"){const k=$=>{const S=$===1?d*.75:m-d*.75,T=$*d*.5;return Array.from({length:17},(A,_)=>{const E=_/16;return[S-T*Math.sin(Math.PI*E),p-b+(g+b*2)*E]})};y.push(w(k(1),"("),w(k(-1),")"))}else if(t.delimiters==="bmatrix"){const k=d*.35,$=d*.2,S=m-d*.2;y.push(w([[$+k,p-b],[$,p-b],[$,v+b],[$+k,v+b]],"["),w([[S-k,p-b],[S,p-b],[S,v+b],[S-k,v+b]],"]"))}else t.delimiters==="vmatrix"&&y.push(w([[d*.4,p-b],[d*.4,v+b]],"|"),w([[m-d*.4,p-b],[m-d*.4,v+b]],"|"));return{width:m,height:-p+b,depth:v+b,pieces:y}}function H(t,e={}){const n=typeof t=="string"?Ds(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 ke(t,e,n,s,i,r){const o=26*r.plane.scale,[c,l]=Zt(n),u=H(t,{values:r.scope,style:"inline"}),h=o*(.55+Math.abs(c)*u.width*.5);return W(u,{x:e[0]+c*h,y:e[1]+l*h,size:o,color:s,opacity:r.opacity,idPrefix:`${i}.label.`})}function zs(t,e,n,s,i,r){const o=r.plane.toScreen(e),c=r.plane.toScreen(n),[l]=X([[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 oa(t,e){const n=kt(e.values,t.transform),s=it(n,t.from===void 0?[0,0]:Ot(e.values,t.from)),i=it(n,Ot(e.values,t.to)),r=O(e.theme,t.color,e.theme.colors.yellow),o=zs(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=ln(c,l);if(t.labelAt==="middle"){const h=[(c[0]+l[0])/2,(c[1]+l[1])/2];o.push(...ke(t.label,h,[u[1],-u[0]],r,t.id,e))}else o.push(...ke(t.label,c,u,r,t.id,e))}return o}function aa(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(...zs(`${t.id}.${c}`,[0,0],d,u,s,e)),t.labels!==!1&&e.draw>=1){const f=e.plane.toScreen(d);r.push(...ke(h,f,ln(f,i),u,`${t.id}.${c}`,e))}}return r}function ca(t,e){const n=t.on!==void 0?[e.scope[`${t.id}.x`],e.scope[`${t.id}.y`]]:Ot(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(...ke(t.label,[i,r],[.7,-.7],o,t.id,e)),u}const Me={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)}},Jt={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 la(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=la(t);let n=0;const s=()=>e[n],i=f=>{const g=s();return g.kind==="op"&&g.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 g=Object.prototype.hasOwnProperty.call(Me,f.value)?Me[f.value]:void 0;if(!g)throw new $t(`Unknown function "${f.value}"`,t,f.at);n++;const p=[];if(!i(")"))for(p.push(o());i(",");)n++,p.push(o());if(r(")"),p.length!==g.arity)throw new $t(`"${f.value}" takes ${g.arity} argument${g.arity===1?"":"s"}, got ${p.length}`,t,f.at);return{type:"call",name:f.value,args:p}}if(i("(")){n++;const g=o();return r(")"),g}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 kn(t){const e=new Set,n=s=>{s.type==="name"&&!(s.name in Jt)?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 L=t=>({type:"number",value:t}),te=L(0),q=L(1),U=t=>t.type==="number",nt=(t,e)=>t.type==="number"&&t.value===e;function yt(t,e){return U(t)&&U(e)?L(t.value+e.value):nt(t,0)?e:nt(e,0)?t:{type:"binary",operator:"+",left:t,right:e}}function ht(t,e){return U(t)&&U(e)?L(t.value-e.value):nt(e,0)?t:nt(t,0)?$e(e):{type:"binary",operator:"-",left:t,right:e}}function R(t,e){return U(t)&&U(e)?L(t.value*e.value):nt(t,0)||nt(e,0)?te:nt(t,1)?e:nt(e,1)?t:U(e)?R(e,t):U(t)&&e.type==="binary"&&e.operator==="*"&&U(e.left)?R(L(t.value*e.left.value),e.right):{type:"binary",operator:"*",left:t,right:e}}function G(t,e){return nt(t,0)?te:nt(e,1)?t:U(t)&&U(e)&&e.value!==0?L(t.value/e.value):{type:"binary",operator:"/",left:t,right:e}}function ft(t,e){return nt(e,0)?q:nt(e,1)?t:U(t)&&U(e)?L(t.value**e.value):{type:"binary",operator:"^",left:t,right:e}}function $e(t){return U(t)?L(-t.value):t.type==="unary"&&t.operator==="-"?t.operand:{type:"unary",operator:"-",operand:t}}const Z=(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 Q(t,e="x"){if(St(t,e))return te;switch(t.type){case"number":return te;case"name":return t.name===e?q:te;case"unary":return t.operator==="-"?$e(Q(t.operand,e)):Q(t.operand,e);case"binary":{const{left:n,right:s}=t,i=()=>Q(n,e),r=()=>Q(s,e);switch(t.operator){case"+":return yt(i(),r());case"-":return ht(i(),r());case"*":return yt(R(i(),s),R(n,r()));case"/":return G(ht(R(i(),s),R(n,r())),ft(s,L(2)));case"^":if(St(s,e)){const o=U(s)?L(s.value-1):ht(s,q);return R(R(s,ft(n,o)),i())}return St(n,e)?R(R(t,Z("ln",n)),r()):R(t,yt(R(r(),Z("ln",n)),G(R(s,i()),n)))}break}case"call":{const[n,s]=t.args,i=()=>Q(n,e),r=o=>R(o,i());switch(t.name){case"sin":return r(Z("cos",n));case"cos":return r($e(Z("sin",n)));case"tan":return r(G(q,ft(Z("cos",n),L(2))));case"asin":return r(G(q,Z("sqrt",ht(q,ft(n,L(2))))));case"acos":return r($e(G(q,Z("sqrt",ht(q,ft(n,L(2)))))));case"atan":return r(G(q,yt(q,ft(n,L(2)))));case"sinh":return r(Z("cosh",n));case"cosh":return r(Z("sinh",n));case"tanh":return r(ht(q,ft(Z("tanh",n),L(2))));case"exp":return r(t);case"ln":return r(G(q,n));case"log":return r(G(q,R(n,L(Math.LN10))));case"log2":return r(G(q,R(n,L(Math.LN2))));case"sqrt":return r(G(q,R(L(2),t)));case"abs":return r(Z("sign",n));case"sigmoid":return r(R(t,ht(q,t)));case"relu":return r(G(yt(Z("sign",n),q),L(2)));case"atan2":{const o=Q(s,e);return G(ht(R(s,i()),R(n,o)),yt(ft(n,L(2)),ft(s,L(2))))}case"min":case"max":{const o=t.name==="max"?1:-1,c=Q(s,e),l=G(yt(q,R(L(o),Z("sign",ht(n,s)))),L(2));return yt(R(l,i()),R(ht(q,l),c))}}throw new Error(`differentiate: "${t.name}" has no derivative rule`)}}throw new Error("differentiate: malformed expression")}function js(t,e,n="x"){let s=t;for(let i=0;i<e;i++)s=Q(s,n);return s}function ee(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}${ee(t.operand)})`;case"binary":return`(${ee(t.left)} ${t.operator} ${ee(t.right)})`;case"call":return`${t.name}(${t.args.map(ee).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(Jt,t.name))return Jt[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 Me[t.name].apply(...t.args.map(n=>st(n,e)))}throw new Error("evaluate: malformed expression")}const Se=new Map;function K(t,e="x"){let n=Se.get(t);n||(n=rt(t),Se.size<256&&Se.set(t,n));const s=n;return(i,r={})=>st(s,{...r,[e]:i})}const Mn=new Map;function xe(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=Mn.get(s);if(!i){let o=Se.get(t);o||(o=rt(t)),i=js(o,e,n),Mn.size<512&&Mn.set(s,i)}const r=i;return(o,c={})=>st(r,{...c,[n]:o})}const Ae=480;function Xs(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 Ys(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 Bs(t,e,n,s,i,r){return X(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:Ae+1},(u,h)=>{const d=n+(s-n)*h/Ae;return Ys(o.plane.toScreen([d,e(d)]),o)});return Bs(t,Xs(l,o.plane.height),i,r,o,c)}function ua(t,e){const n=t.derivative?xe(t.expr,t.derivative):K(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 ha(t,e){const n=K(t.x,"t"),s=K(t.y,"t"),i=kt(e.values,t.transform),[r,o]=t.t??[0,Math.PI*2],c=Array.from({length:Ae+1},(u,h)=>{const d=r+(o-r)*h/Ae;return Ys(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 Bs(t.id,Xs(c,e.plane.height),l,(t.width??3.5)*e.plane.scale,e)}const da=[[0,0],[1,0],[1,1],[0,1]];function fa(t,e){const n=kt(e.values,t.transform),s=(t.points??da).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},...X([[...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(...W(H(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 pa(t,e){const n=t.eigen?Ss(kt(e.values,t.eigen)).map(o=>o.vector):t.along!==void 0?[Ot(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=un(o,s/l),h=[un(u,-1),u].map(e.plane.toScreen);return X([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 Vs(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 ga(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 ya=t=>t*t*(3-2*t);function Hs(t,e,n){const s=Math.min(1,Math.max(0,n)),i=t.layout.pieces.map(g=>Vs(g,t.x,t.y)),r=e.layout.pieces.map(g=>Vs(g,e.x,e.y));if(s===0)return i.map(g=>({...g,opacity:1}));if(s===1)return r.map(g=>({...g,opacity:1}));const o=g=>{const p=new Map;for(const y of g)p.set(y.id,[...p.get(y.id)??[],y]);return p},c=o(i),l=o(r),u=[],h=ya(s),d=Math.max(0,1-s*2),f=Math.max(0,s*2-1);for(const g of new Set([...c.keys(),...l.keys()])){const p=c.get(g)??[],y=l.get(g)??[],a=Math.max(p.length,y.length);for(let m=0;m<a;m++){const v=p[m],x=y[m],w=v&&x?ga(v,x,h):void 0;if(w){u.push({...w,opacity:1});continue}v&&u.push({...v,opacity:d}),x&&u.push({...x,opacity:f})}}return u.filter(g=>g.opacity>0)}function $n(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]=fn(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 Us(t,e,n){const s=Ot(n.values,t);return e?s:n.plane.toScreen(s)}function ma(t,e){const[n,s]=Us(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=H(t.tex,{values:e.scope});return[...t.backdrop??t.screen??!1?$n(t.id,[c],o,e):[],...W(c,o)]}function ba(t,e){const[n,s]=Us(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=>H(t.steps[a],{values:e.scope}),f=t.backdrop??t.screen??!1;if(u===0||l>=o){const a=d(l);return[...f?$n(t.id,[a],h,e):[],...W(a,h)]}const g=a=>{const[m,v]=fn(a,h);return{layout:a,x:m/i,y:v/i}},p=d(l),y=d(l+1);return[...f?$n(t.id,[p,y],h,e):[],...Cs(Hs(g(p),g(y),u),[0,0],h)]}const ne=["normal","uniform","exponential","binomial","poisson","dice","mean"];function Ws(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 se(t){return t.kind==="binomial"||t.kind==="poisson"||t.kind==="dice"}const Ee=(()=>{const t=[0];return e=>{for(let n=t.length;n<=e;n++)t[n]=t[n-1]+Math.log(n);return t[e]}})(),Sn=(t,e)=>Math.exp(Ee(t)-Ee(e)-Ee(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:Sn(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-Ee(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)*Sn(n,r)*Sn(e-s*r-1,n-1);return i/s**n}case"mean":return t.count===1?pt(t.of,e):pt({kind:"normal",mean:Nt(t.of),sd:Ft(t.of)/Math.sqrt(t.count)},e)}}function Nt(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 Nt(t.of)}}function Ft(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 Ft(t.of)/Math.sqrt(t.count)}}function xn(t,e){switch(t.kind){case"normal":return wt(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+=xn(t.of,e);return n/t.count}}}const _e=new Map;function An(t,e,n){const s=`${JSON.stringify(t)}|${e}`;let i=_e.get(s);if(i||(i=[],_e.size>64&&_e.clear(),_e.set(s,i)),i.length<n){const r=_t(typeof e=="number"?e:vt(e)),o=[];for(let c=0;c<n;c++)o.push(xn(t,r));i.splice(0,i.length,...o)}return i.slice(0,n)}function Tn(t){if(!t||typeof t!="object"||!ne.includes(t.kind))return`kind must be one of ${ne.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 En(t){const e=Nt(t),n=Ft(t);if(se(t)){const[s,i]=Ws(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 Gs(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 Zs(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 _n(t,e,n){const s=_t(typeof e=="number"?e:vt(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*wt(s)]})}function Pn(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 Qs(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 On(t,e,n){const s=_t(vt(`${t}:${e}`));return Array.from({length:n},()=>s.next()<.5)}const Pe=t=>t.filter(Boolean).length;function Ks(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 In=(t,e,n,s,i)=>[[e,n],[s,n],[s,i],[e,i]].map(t.plane.toScreen),Oe=t=>Math.min(2e4,Math.max(0,Math.floor(t)));function va(t,e){const n=It(e.values,t.distribution),s=An(n,t.seed??t.id,Oe(I(e.values,t.count))),i=Gs(s,t.bins??En(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:In(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??En(n),h=O(e.theme,"yellow",e.theme.colors.yellow);c.push(...Te(`${t.id}.curve`,d=>pt(se(n)?{kind:"normal",mean:Nt(n),sd:Ft(n)}:n,d),l,u,h,3*e.plane.scale,{...e,draw:1}))}return c}function wa(t,e){const n=It(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(se(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 g=h;g<f&&g<=d;g++){const p=pt(n,g);if(p<=0)continue;const y=o&&g>=o[0]&&g<=o[1];u.push({type:"line",id:`${t.id}.${g}`,points:In(e,g-.4,0,g+.4,p),closed:!0,fill:y?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},(p,y)=>{const a=u+(h-u)*y/120;return[a,pt(n,a)]}),g=[[u,0],...f,[h,0]].map(e.plane.toScreen);l.push({type:"line",id:`${t.id}.shade`,points:g,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 ka(t,e){const n=t.rows??10,s=t.spacing??.5,i=t.top??e.plane.y[1]-s,r=s*.9,o=(b,k)=>[b*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 b=0;b<n;b++)for(let k=0;k<=b;k++){const[$,S]=e.plane.toScreen(o(k-b/2,b));h.push({type:"circle",id:`${t.id}.peg.${b}.${k}`,x:$,y:S,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 b=0;b<=n+1;b++){const k=b-(n+1)/2,$=X([[o(k,d),o(k,f)].map(e.plane.toScreen)],e.draw);for(const S of $)h.push({type:"line",id:`${t.id}.bin.${b}`,points:S,stroke:c,width:1.2*e.plane.scale,opacity:e.opacity*.6})}const g=X([[o(-(n+1)/2,f),o((n+1)/2,f)].map(e.plane.toScreen)],e.draw);for(const b of g)h.push({type:"line",id:`${t.id}.floor`,points:b,stroke:c,width:1.2*e.plane.scale,opacity:e.opacity*.6});const p=Math.max(0,I(e.values,t.balls)),y=Math.floor(p),a=t.seed??t.id,m=new Array(n+1).fill(0),v=2*u/e.plane.unitY/r,x=(b,k)=>({x:b-n/2+(k%2?.22:-.22),depth:f-v*(Math.floor(k/2)+.5)});for(let b=0;b<y;b++){const k=Pe(On(a,b,n)),$=x(k,m[k]),[S,T]=e.plane.toScreen(o($.x,$.depth));m[k]++,h.push({type:"circle",id:`${t.id}.ball.${b}`,x:S,y:T,r:u,fill:l,opacity:e.opacity})}const w=p-y;if(w>0){const b=On(a,y,n),k=Math.min(1,w/.8);let{x:$,depth:S}=Ks(b,k);if(S-=1,w>.8){const _=((w-.8)/.2)**2,E=Pe(b),C=x(E,m[E]),N={x:Pe(b)-n/2,depth:n-1};S=N.depth+(C.depth-N.depth)*_,$=N.x+(C.x-N.x)*_}const[T,A]=e.plane.toScreen(o($,S));h.push({type:"circle",id:`${t.id}.falling`,x:T,y:A,r:u,fill:l,opacity:e.opacity})}return h}function Ma(t,e){const n=Js(t,e),s=_n(n,t.seed??t.id,Oe(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,g]=e.plane.toScreen([u,h]),p=o?st(o,{...e.scope,x:u,y:h})<=0:!1;return{type:"circle",id:`${t.id}.${d}`,x:f,y:g,r:c,fill:p?r:i,opacity:e.opacity*e.draw*.85}});if(t.fit){const u=Pn(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 Js(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 $a(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),g=O(e.theme,"red",e.theme.colors.red),p=O(e.theme,"grey",e.theme.colors.grey),y=e.opacity*e.draw,a=(b,k,$,S,T,A,_)=>({type:"line",id:`${t.id}.${b}`,points:In(e,k,$,S,T),closed:!0,fill:A,stroke:e.theme.background,width:2*e.plane.scale,opacity:y*_}),m=h+l,v=m-l*Math.min(1,Math.max(0,s)),x=m-l*Math.min(1,Math.max(0,i)),w=[a("tp",u,v,d,m,f,.85),a("fn",u,h,d,v,p,.35),a("fp",d,x,u+c,m,g,.8),a("tn",d,h,u+c,x,p,.2)];if(t.labels!==!1&&e.draw>=1){const b=20*e.plane.scale,k=($,S,T,A)=>{const[_,E]=e.plane.toScreen(T);w.push(...W(H(S,{values:e.scope,style:"inline"}),{x:_,y:E,size:b,color:A,opacity:e.opacity,idPrefix:`${t.id}.label.${$}.`}))};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],g),k("posterior",`P(\\text{has it} \\mid +) = \\val{${t.id}.posterior:3}`,[u+c/2,h+l+o*.05],f)}return w}const Cn=["bfs","dfs","dijkstra"];function Ie(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 Sa(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 xa(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 Aa(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 Ce=new Map;function ti(t,e,n,s,i=!1){const r=JSON.stringify([t,e,n,s,i]),o=Ce.get(r);if(o)return o;if(!n.includes(e))throw new Error(`graph search: no node "${e}"`);const c=Ie(n,s,i),l=t==="bfs"?Sa(e,c):t==="dfs"?xa(e,c):Aa(e,n,c);return Ce.size>64&&Ce.clear(),Ce.set(r,l),l}function ei(t,e,n){const s=Ie(e,n,!0),i=Ie(e,n,!1),r=new Map,o=new Set([t]),c=[t];for(;c.length;){const g=c.shift(),p=(s.get(g)?.length?s.get(g):i.get(g)??[]).map(y=>y.to).filter(y=>!o.has(y));p.forEach(y=>o.add(y)),r.set(g,p),c.push(...p)}const l=new Map;let u=0;const h=(g,p)=>{const y=r.get(g)??[],a=y.length===0?u++:y.map(m=>h(m,p+1)).reduce((m,v,x,w)=>m+v/w.length,0);return l.set(g,[a,p===0?0:-p]),a};h(t,0);const d=[...l.values()].map(([g])=>g),f=(Math.min(...d)+Math.max(...d))/2;for(const[g,[p,y]]of l)l.set(g,[p-f,y]);return l}const Ta={"∪":"|","∩":"&","∖":"-","△":"^","¬":"!","\\":"-"};function Nn(t){const e=[...t].map(u=>Ta[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 ie(t){return t.type==="set"?[t.name]:t.type==="not"?ie(t.operand):[...new Set([...ie(t.left),...ie(t.right)])]}function re(t,e){switch(t.type){case"set":return e.has(t.name);case"not":return!re(t.operand,e);case"op":{const n=re(t.left,e),s=re(t.right,e);return t.operator==="&"?n&&s:t.operator==="|"?n||s:t.operator==="-"?n&&!s:n!==s}}}function ni(t,e){const n=[];for(let s=0;s<1<<e.length;s++){const i=e.filter((r,o)=>s&1<<o);re(t,new Set(i))&&n.push(i)}return n}function si(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 Ne(t){return t.edges.map(e=>Array.isArray(e)?{from:e[0],to:e[1],...e[2]!==void 0?{weight:e[2]}:{}}:e)}function ii(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 ei(t.tree.root,t.nodes.map(u=>u.id),Ne(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 ri(t,e){if(!t.search)return;const n=ti(t.search.kind,t.search.start,t.nodes.map(r=>r.id),Ne(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 Ea={bfs:"queue",dfs:"stack",dijkstra:"open"};function _a(t,e){const{plane:n,theme:s}=e,i=ii(t),r=Ne(t),o=ri(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=[],g=o?o.events.slice(0,o.done):[],p=new Set(g.map(S=>S.node)),y=new Set(g.filter(S=>S.parent!==void 0).map(S=>`${S.parent}>${S.node}`)),a=g.at(-1),m=new Set(a?.frontier??[]),v=o&&o.partial>0?o.events[o.done]:void 0,x=(S,T)=>y.has(`${S}>${T}`)||!t.directed&&y.has(`${T}>${S}`),w=S=>n.toScreen(i.get(S)??[0,0]),b=(S,T)=>{const A=w(S),_=w(T),[E,C]=Zt([_[0]-A[0],_[1]-A[1]]);return[[A[0]+E*c,A[1]+C*c],[_[0]-E*c,_[1]-C*c]]},k=t.weights??t.search?.kind==="dijkstra";if(r.forEach((S,T)=>{const[A,_]=b(S.from,S.to),E=x(S.from,S.to),C=E?h:u,N=(E?4:2)*n.scale,[P]=X([[A,_]],e.draw);if(P&&(f.push(t.directed?{type:"arrow",id:`${t.id}.edge.${T}`,points:P,stroke:C,width:N,head:11*n.scale,opacity:e.opacity}:{type:"line",id:`${t.id}.edge.${T}`,points:P,stroke:C,width:N,opacity:e.opacity}),k&&e.draw>=1)){const F=[(A[0]+_[0])/2,(A[1]+_[1])/2],[Y,J]=Zt([-(_[1]-A[1]),_[0]-A[0]]),j=14*n.scale;f.push({type:"text",id:`${t.id}.weight.${T}`,text:String(S.weight??1),x:F[0]+Y*j*.9,y:F[1]+J*j*.9+j*.35,size:j,font:Mt,color:E?h:u,align:"center",opacity:e.opacity})}}),v?.parent!==void 0){const[S,T]=b(v.parent,v.node),[A]=X([[S,T]],v.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 $=a?.distances;for(const S of t.nodes){const[T,A]=w(S.id),_=p.has(S.id),E=v?.node===S.id&&o.partial>=.999,C=!_&&m.has(S.id),N=_||E?h:C?d:s.background;f.push({type:"circle",id:`${t.id}.node.${S.id}`,x:T,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===S.id&&f.push({type:"circle",id:`${t.id}.current`,x:T,y:A,r:c*1.35,stroke:h,width:2*n.scale,opacity:e.opacity*.8});const P=_||C||E?s.background:l;if(f.push(...W(H(S.label??S.id,{style:"inline"}),{x:T,y:A,size:c*.95,color:P,opacity:e.opacity*e.draw,idPrefix:`${t.id}.label.${S.id}.`})),$){const F=$[S.id],Y=13*n.scale;f.push({type:"text",id:`${t.id}.distance.${S.id}`,text:F===1/0?"∞":String(Math.round(F*100)/100),x:T,y:A+c+Y*1.15,size:Y,font:Mt,color:d,align:"center",opacity:e.opacity})}}if(t.frontier&&t.search&&e.draw>=1){const[S,T]=t.frontier,A=16*n.scale,_=Ea[t.search.kind];f.push({type:"text",id:`${t.id}.frontier.name`,text:`${_}:`,x:S,y:T+A*.35,size:A,font:Mt,color:u,align:"left",opacity:e.opacity});const E=A*1.9;[...m].forEach((C,N)=>{const P=S+A*4+N*(E+A*.4),F=t.nodes.find(Y=>Y.id===C)?.label??C;f.push({type:"line",id:`${t.id}.frontier.box.${N}`,points:[[P,T-E/2],[P+E,T-E/2],[P+E,T+E/2],[P,T+E/2]],closed:!0,fill:d,opacity:e.opacity*.9}),f.push(...W(H(F,{style:"inline"}),{x:P+E/2,y:T,size:A*1.05,color:s.background,opacity:e.opacity,idPrefix:`${t.id}.frontier.label.${N}.`}))})}return f}function Pa(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 Oa(t,e){const{plane:n,theme:s}=e,i=t.radius??1.5,[r,o]=t.at??[0,0],c=Pa(t.sets.length).map(([a,m])=>[r+a*i,o+m*i]),l=c.map(([a,m])=>si(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),g=[],p=t.sets.map(a=>a.id);if(t.highlight){const a=O(s,t.highlightColor,s.colors.yellow);ni(Nn(t.highlight),p).forEach((m,v)=>{g.push({type:"line",id:`${t.id}.region.${v}`,points:f,closed:!0,fill:a,opacity:e.opacity*e.draw*.55,clip:p.map((x,w)=>({points:l[w],outside:!m.includes(x)}))})})}if(t.universe!==!1){g.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];g.push(...W(H("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 y=["blue","red","green"];return t.sets.forEach((a,m)=>{const v=O(s,a.color??y[m],s.colors.blue);for(const $ of X([[...l[m],l[m][0]]],e.draw))g.push({type:"line",id:`${t.id}.set.${a.id}`,points:$,stroke:v,width:3*n.scale,opacity:e.opacity});const[x,w]=Zt([c[m][0]-r||(m===0?-1:1),c[m][1]-o]),[b,k]=n.toScreen([c[m][0]+x*i*.78,c[m][1]+w*i*.78+(t.sets.length===2?i*.85:0)]);g.push(...W(H(a.label??a.id,{style:"inline"}),{x:b,y:k,size:26*n.scale,color:v,opacity:e.opacity*e.draw,idPrefix:`${t.id}.label.${a.id}.`}))}),g}const oi=(t,e)=>(Math.round(t)%e+e)%e;function Ia(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=(p,y)=>{const a=Math.PI/2-p/i*2*Math.PI;return n.toScreen([r+Math.cos(a)*c*y,o+Math.sin(a)*c*y])},f=[];for(const p of X([si(r,o,c,c,120).map(n.toScreen)],e.draw))f.push({type:"line",id:`${t.id}.face`,points:p,stroke:u,width:3*n.scale,opacity:e.opacity});const g=oi(l,i);for(let p=0;p<i;p++){const[y,a]=d(p,.8),m=Math.min(26,220/i+8)*n.scale;f.push({type:"line",id:`${t.id}.tick.${p}`,points:[d(p,.95),d(p,1)],stroke:u,width:2*n.scale,opacity:e.opacity*e.draw}),f.push({type:"text",id:`${t.id}.hour.${p}`,text:String(p),x:y,y:a+m*.35,size:m,font:Mt,color:p===g?h:u,align:"center",opacity:e.opacity*e.draw})}if(e.draw>=1){const p=n.toScreen([r,o]);f.push({type:"arrow",id:`${t.id}.hand`,points:[p,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:p[0],y:p[1],r:6*n.scale,fill:h,opacity:e.opacity})}return f}const Fn=["sigmoid","tanh","relu"],ai=(t,e)=>t==="sigmoid"?1/(1+Math.exp(-e)):t==="tanh"?Math.tanh(e):Math.max(0,e);function ci(t,e){const n=_t(typeof e=="number"?e:vt(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]},()=>wt(n)*o))),i.push(Array.from({length:t[r+1]},()=>wt(n)*.3))}return{layers:t,weights:s,biases:i}}function li(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)=>ai(n,o.reduce((l,u,h)=>l+u*(r[h]??0),t.biases[i][c]))))}return s}const oe=["viridis","heat","diverging"],Ca={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 Fe(t,e){const n=Ca[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 ui(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 Ln(t,e,n){const s=ui(t),i=ui(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 hi(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,g,p)=>{(f>p||f===p&&d>g)&&([d,f,g,p]=[g,p,d,f]);const y=t[f][d]-r,a=t[p][g]-r,m=y===a?.5:y/(y-a);return[e+(d+(g-d)*m)*s,n+(f+(p-f)*m)*i]};for(let d=0;d<c-1;d++)for(let f=0;f<l-1;f++){const g=[t[d][f],t[d][f+1],t[d+1][f+1],t[d+1][f]];if(g.some(a=>!Number.isFinite(a)))continue;const p=[],y=[[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,v,x,w,b]of y)g[a]>=r!=g[m]>=r&&p.push(u(v,x,w,b));if(p.length===2)o.push([p[0],p[1]]);else if(p.length===4){const a=(g[0]+g[1]+g[2]+g[3])/4>=r,m=g[0]>=r;a===m?o.push([p[0],p[1]],[p[2],p[3]]):o.push([p[0],p[3]],[p[1],p[2]])}}const h=1e-6*Math.min(Math.abs(s),Math.abs(i));return Na(o.filter(([d,f])=>Math.hypot(f[0]-d[0],f[1]-d[1])>h))}function Na(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 di(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 fi(t,e,n,s,i=0,r={}){const o=rt(t),c=Q(o,"x"),l=Q(o,"y"),u=(f,g)=>{const p={...r,x:f,y:g};return[st(c,p),st(l,p)]},h=[e];let d=[0,0];for(let f=0;f<s;f++){const[g,p]=h[h.length-1],[y,a]=u(g,p);d=[i*d[0]-n*y,i*d[1]-n*a];const m=[g+d[0],p+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 Le(t){const e=rt(t);return(n,s,i={})=>st(e,{...i,x:n,y:s})}function Rn(t,e,n,s){const i=_t(typeof s=="number"?s:vt(s)),r=[];for(let o=0;o<e;o++)t.forEach(([c,l],u)=>r.push({point:[c+wt(i)*n,l+wt(i)*n],label:u}));return r}const Fa=t=>1/(1+Math.exp(-t)),ae=(t,[e,n])=>Fa(t.w[0]*e+t.w[1]*n+t.b);function pi(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:g}of t){const p=ae({w:o,b:c},f)-g;l+=p*f[0],u+=p*f[1],h+=p}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 gi(t,e){return e.length===0?0:e.filter(({point:n,label:s})=>(ae(t,n)>=.5?1:0)===s).length/e.length}function yi(t,e){if(e.length===0)return 0;const n=1e-12;return-e.reduce((s,{point:i,label:r})=>{const o=ae(t,i);return s+Math.log(r?o+n:1-o+n)},0)/e.length}const Re=(t,e)=>(t[0]-e[0])**2+(t[1]-e[1])**2;function De(t,e){return t.map(n=>{let s=0;for(let i=1;i<e.length;i++)Re(n,e[i])<Re(n,e[s])&&(s=i);return s})}function mi(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=De(t,o),l=o.map((h,d)=>{const f=t.filter((g,p)=>c[p]===d);return f.length===0?h:[f.reduce((g,p)=>g+p[0],0)/f.length,f.reduce((g,p)=>g+p[1],0)/f.length]}),u=l.some((h,d)=>Re(h,o[d])>1e-12);if(i.push(l),!u)break}return i}function bi(t,e){const n=De(t,e);return t.reduce((s,i,r)=>s+Re(i,e[n[r]]),0)}const qe=(t,e,n)=>{let s=t.get(e);return s===void 0&&(s=n(),t.size>32&&t.clear(),t.set(e,s)),s},ze=t=>Number.isFinite(t)?t:0,vi=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 wi(t,e){const n=ci(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=li(n,s,t.activation??"sigmoid"),r=t.flow===void 0?t.layers.length-1:Math.min(t.layers.length-1,Math.max(0,ze(I(e,t.flow))));return{network:n,activations:i,flow:r}}function La(t,e){const{plane:n,theme:s}=e,{network:i,activations:r,flow:o}=wi(t,e.values),c=vi(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,g=t.layers,p=(w,b)=>{const k=h-l/2+(g.length===1?l/2:w/(g.length-1)*l),$=Math.min(u/Math.max(1,g[w]-1),u*.3),S=d+((g[w]-1)/2-b)*$;return n.toScreen([k,S])},y=O(s,"blue",s.colors.blue),a=O(s,"red",s.colors.red),m=[],v=Math.max(...i.weights.flat(2).map(Math.abs),1e-9);i.weights.forEach((w,b)=>{w.forEach((k,$)=>{k.forEach((S,T)=>{const A=p(b,T),_=p(b+1,$),E=Math.min(1,Math.max(0,o-b)),C=S>=0?y:a,N=(.6+3*(Math.abs(S)/v))*n.scale;for(const P of X([[A,_]],e.draw))m.push({type:"line",id:`${t.id}.w.${b}.${$}.${T}`,points:P,stroke:C,width:N,opacity:e.opacity*(.18+.5*E)});if(E>0&&E<1){const[P,F]=Qt(A,_,E);m.push({type:"circle",id:`${t.id}.pulse.${b}.${$}.${T}`,x:P,y:F,r:f*.22,fill:O(s,"yellow",s.colors.yellow),opacity:e.opacity*(.5+.5*Math.abs(r[b][T]??0))})}})})}),g.forEach((w,b)=>{const k=Math.min(1,Math.max(0,o-b+1));for(let $=0;$<w;$++){const[S,T]=p(b,$),A=r[b][$]??0,_=t.activation==="relu"?Math.min(1,A/2):t.activation==="tanh"?(A+1)/2:A;m.push({type:"circle",id:`${t.id}.node.${b}.${$}`,x:S,y:T,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.${b}.${$}`,x:S,y:T,r:f*.86,fill:Fe("viridis",_),opacity:e.opacity*k})}});const x=(w,b,k,$)=>m.push(...W(H(w,{values:e.scope,style:"inline"}),{x:b[0],y:b[1],size:20*n.scale,color:s.ink,align:k,opacity:e.opacity*e.draw,idPrefix:`${t.id}.${$}.`}));return t.labels?.inputs?.forEach((w,b)=>{const[k,$]=p(0,b);x(w,[k-f*1.5,$],"right",`in${b}`)}),t.labels?.outputs?.forEach((w,b)=>{const[k,$]=p(g.length-1,b);x(w,[k+f*1.5,$],"left",`out${b}`)}),m}const Ra=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 Da(t,e){if(t.cells){const u=vi(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(Ra):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=Le(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 qa(t,e){const{plane:n,theme:s}=e,{cells:i,box:r}=Da(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],[g,p]]=r,y=(g-d)/h,a=(p-f)/u,m=[],v=t.colormap??"viridis",x=Math.ceil(u*e.draw);for(let b=0;b<x;b++)for(let k=0;k<h;k++){const $=i[b][k];if(!Number.isFinite($))continue;const S=l===c?.5:($-c)/(l-c),T=d+k*y,A=p-b*a,_=[[T,A-a],[T+y*1.01,A-a],[T+y*1.01,A+a*.01],[T,A+a*.01]].map(n.toScreen);if(m.push({type:"line",id:`${t.id}.${b}.${k}`,points:_,closed:!0,fill:Ln(Fe(v,S),s.background,e.opacity)}),t.values){const[E,C]=n.toScreen([T+y/2,A-a/2]),N=Math.min(16*n.scale,Math.abs(y*n.unitX)*.32);m.push({type:"text",id:`${t.id}.v.${b}.${k}`,text:$.toFixed(2).replace(/^0/,""),x:E,y:C+N*.35,size:N,font:Mt,color:S>.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((b,k)=>{const[$,S]=n.toScreen([d,p-(k+.5)*a]);m.push(...W(H(b,{style:"inline"}),{x:$-w*.5,y:S,size:w,color:s.ink,align:"right",opacity:e.opacity*e.draw,idPrefix:`${t.id}.row.${k}.`}))}),t.colLabels?.forEach((b,k)=>{const[$,S]=n.toScreen([d+(k+.5)*y,p]);m.push(...W(H(b,{style:"inline"}),{x:$,y:S-w*.8,size:w,color:s.ink,opacity:e.opacity*e.draw,idPrefix:`${t.id}.col.${k}.`}))}),m}const za=new Map;function ja(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=qe(za,JSON.stringify([t.expr,t.levels,n,s,i]),()=>{const l=Le(t.expr),u=di((y,a)=>l(y,a,e.scope),n[0],n[1],s),h=u.values.flat().filter(Number.isFinite),d=Math.min(...h),f=Math.max(...h),g=typeof t.levels=="number"?t.levels:10;return(Array.isArray(t.levels)?t.levels:Array.from({length:g},(y,a)=>d+(f-d)*(a+1)/(g+1))).map(y=>hi(u.values,u.x0,u.y0,u.dx,u.dy,y))}),o=[],c=t.colormap??"viridis";return r.forEach((l,u)=>{const h=t.color?O(e.theme,t.color,e.theme.ink):Fe(c,r.length===1?.6:.15+.85*u/(r.length-1));X(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 Xa=new Map;function ki(t,e,n){const s=Ot(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,ze(I(e,t.steps)))),c=Object.entries(n).filter(([f])=>!f.includes(".")),l=qe(Xa,JSON.stringify([t.expr,s,i,r,c]),()=>fi(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?Qt(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 Ya(t,e){const{path:n,here:s}=ki(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 Ba=new Map;function Mi(t,e){const n=t.centres??[[-1.5,-1],[1.5,1]],s=Math.min(500,Math.max(0,ze(I(e,t.epochs)))),[i,r,o]=t.start??[.9,-1.1,.8],{data:c,models:l}=qe(Ba,JSON.stringify([n,t.count,t.spread,t.seed??t.id,t.rate,i,r,o]),()=>{const p=Rn(n,t.count??40,t.spread??.9,t.seed??t.id);return{data:p,models:pi(p,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)],g={w:Qt(d.w,f.w,h),b:d.b+(f.b-d.b)*h};return{data:c,model:g,epochs:s}}function Va(t,e){const{plane:n,theme:s}=e,{data:i,model:r}=Mi(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,[g,p]=n.y,y=(f-d)/32,a=(p-g)/32;for(let m=0;m<32;m++)for(let v=0;v<32;v++){const x=ae(r,[d+(v+.5)*y,g+(m+.5)*a]),w=[[d+v*y,g+m*a],[d+(v+1.02)*y,g+m*a],[d+(v+1.02)*y,g+(m+1.02)*a],[d+v*y,g+(m+1.02)*a]].map(n.toScreen);o.push({type:"line",id:`${t.id}.p.${m}.${v}`,points:w,closed:!0,fill:Ln(x>=.5?c[1]:c[0],s.background,e.opacity*Math.abs(x-.5)*.5)})}}i.forEach(({point:h,label:d},f)=>{const[g,p]=n.toScreen(h);o.push({type:"circle",id:`${t.id}.pt.${f}`,x:g,y:p,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,g]=n.y,p=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*g+r.b)/l,g]];o.push({type:"line",id:`${t.id}.boundary`,points:p.map(n.toScreen),stroke:s.ink,width:3*n.scale,opacity:e.opacity,dash:[12*n.scale,8*n.scale]})}return o}const Ha=new Map;function $i(t,e){const{points:n,history:s}=qe(Ha,JSON.stringify([t.centres,t.count,t.spread,t.seed??t.id,t.k]),()=>{const l=Rn(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,g)=>f+g[0],0)/l.length,l.reduce((f,g)=>f+g[1],0)/l.length],d=[...l].sort((f,g)=>Math.hypot(f[0]-h[0],f[1]-h[1])-Math.hypot(g[0]-h[0],g[1]-h[1])).slice(0,u);return{points:l,history:mi(l,u,20,d)}}),i=Math.min(s.length-1,Math.max(0,ze(I(e,t.iteration)))),r=Math.floor(i),o=i-r,c=s[r].map((l,u)=>Qt(l,s[Math.min(s.length-1,r+1)][u],o));return{points:n,history:s,centroids:c,owners:De(n,s[r]),iteration:i,iterations:s.length-1}}function Ua(t,e){const{plane:n,theme:s}=e,{points:i,centroids:r,owners:o,history:c,iteration:l}=$i(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[g,p]=n.toScreen(d);h.push({type:"circle",id:`${t.id}.pt.${f}`,x:g,y:p,r:4.5*n.scale,fill:u[o[f]%u.length],opacity:e.opacity*e.draw*.85})}),r.forEach((d,f)=>{const g=c.slice(0,Math.floor(l)+1).map(m=>m[f]);g.push(d),g.length>=2&&h.push({type:"line",id:`${t.id}.trail.${f}`,points:g.map(n.toScreen),stroke:u[f%u.length],width:2*n.scale,opacity:e.opacity*.7,dash:[6*n.scale,5*n.scale]});const[p,y]=n.toScreen(d),a=11*n.scale;h.push({type:"line",id:`${t.id}.centroid.${f}`,points:[[p,y-a],[p+a,y],[p,y+a],[p-a,y]],closed:!0,fill:u[f%u.length],stroke:s.ink,width:2.5*n.scale,opacity:e.opacity})}),h}function Wa(t,e,n){switch(t.kind){case"network":{const{activations:s}=wi(t,e);return Object.fromEntries(s[s.length-1].map((i,r)=>[`${t.id}.out${r}`,i]))}case"descent":{const{here:s,step:i}=ki(t,e,n);return{[`${t.id}.x`]:s[0],[`${t.id}.y`]:s[1],[`${t.id}.loss`]:Le(t.expr)(s[0],s[1],n),[`${t.id}.step`]:i}}case"classifier":{const{data:s,model:i,epochs:r}=Mi(t,e);return{[`${t.id}.accuracy`]:gi(i,s),[`${t.id}.loss`]:yi(i,s),[`${t.id}.epoch`]:Math.floor(r)}}case"kmeans":{const{points:s,centroids:i,iteration:r,iterations:o}=$i(t,e);return{[`${t.id}.inertia`]:bi(s,i),[`${t.id}.iteration`]:Math.floor(r),[`${t.id}.iterations`]:o}}}}function je(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 Si(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 xi=t=>Math.min(400,Math.max(1,Math.round(t)));function Ai(t,e,n){const s={},i={...n};for(const r of t)switch(r.kind){case"tangent":{const o=K(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:xe(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=K(r.expr),c=I(e,r.from),l=I(e,r.to),u=xi(I(e,r.n)),d=Si(f=>o(f,i),c,l,u,r.rule??"left").reduce((f,[g,p,y,a])=>f+(y+a)/2*(p-g),0);Object.assign(s,{[`${r.id}.sum`]:d,[`${r.id}.exact`]:je(f=>o(f,i),c,l),[`${r.id}.n`]:u});break}case"area":{const o=K(r.expr),c=r.lower?K(r.lower):()=>0;s[`${r.id}.value`]=je(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`]:K(r.on)(o,i)})}break;case"histogram":{const o=An(It(e,r.distribution),r.seed??r.id,Oe(I(e,r.count))),{mean:c,sd:l}=Zs(o);Object.assign(s,{[`${r.id}.count`]:o.length,[`${r.id}.mean`]:c,[`${r.id}.sd`]:l});break}case"distribution":{const o=It(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(se(o))for(let h=Math.max(0,Math.ceil(l));h<=Math.floor(u)&&h<=5e3;h++)c+=pt(o,h);else c=je(h=>pt(o,h),l,u,2048)}Object.assign(s,{[`${r.id}.p`]:c,[`${r.id}.mean`]:Nt(o),[`${r.id}.sd`]:Ft(o)});break}case"galton":s[`${r.id}.landed`]=Math.max(0,Math.floor(I(e,r.balls)));break;case"scatter":{const o=_n(Js(r,{values:e}),r.seed??r.id,Oe(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=Pn(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=Qs(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=ri(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`]:oi(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,Wa(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 Ga(t,e){const n=K(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((g,p)=>X([[h,g]],e.draw).map(y=>({type:"line",id:`${t.id}.${p}`,points:y,stroke:u,width:(t.width??3)*e.plane.scale,opacity:e.opacity})));if(t.points!==!1){const g=6*e.plane.scale;if(f.push({type:"circle",id:`${t.id}.point`,x:h[0],y:h[1],r:g,fill:u,opacity:e.opacity}),Math.abs(i)>1e-9){const[p,y]=e.plane.toScreen([s+i,n(s+i,e.scope)]);Number.isFinite(y)&&f.push({type:"circle",id:`${t.id}.secant`,x:p,y,r:g,fill:u,opacity:e.opacity})}}if(t.label&&e.draw>=1){const g=24*e.plane.scale,p=H(t.label,{values:e.scope,style:"inline"});f.push(...W(p,{x:h[0],y:h[1]-g*1.6,size:g,color:u,opacity:e.opacity,idPrefix:`${t.id}.label.`}))}return f}function Za(t,e){const n=K(t.expr),s=I(e.values,t.from),i=I(e.values,t.to),r=xi(I(e.values,t.n)),o=Si(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,g],p)=>{if(!Number.isFinite(f)||!Number.isFinite(g))return[];const y=[[h,0],[d,0],[d,g],[h,f]].map(e.plane.toScreen),m=(f+g)/2<0?O(e.theme,"red",e.theme.colors.red):c;return[{type:"line",id:`${t.id}.${p}`,points:y,closed:!0,fill:m,stroke:m,width:u,opacity:e.opacity*(t.fillOpacity??.35)}]})}function Qa(t,e){const n=K(t.expr),s=t.lower?K(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=[],g;const p=()=>{d.length>=2&&h.push({type:"line",id:`${t.id}.${h.length}`,points:[...d,...f.reverse()].map(e.plane.toScreen),closed:!0,fill:g?c:l,opacity:u}),d=[],f=[]};let y;for(let a=0;a<=o;a++){const m=i+(r-i)*a/o,v=n(m,e.scope),x=s(m,e.scope);if(!Number.isFinite(v)||!Number.isFinite(x)){p(),y=void 0;continue}const w=v-x>=0;if(y&&g!==void 0&&w!==g){const b=y.fy-y.gy,k=v-x,$=b/(b-k),S=y.x+(m-y.x)*$,T=y.gy+(x-y.gy)*$;d.push([S,T]),f.push([S,T]),p(),d.push([S,T]),f.push([S,T])}g=w,d.push([m,v]),f.push([m,x]),y={x:m,fy:v,gy:x}}return p(),h}const Ka=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 Ja(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)=>xe(t.expr,f)(n,e.scope)/Ka[f]),c=d=>{let f=0,g=1;for(let p=0;p<=i;p++)f+=o[p]*g,g*=d-n;return r>0&&i<20?f+r*o[i+1]*g: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 tc(t,e){switch(t.kind){case"grid":return Wo(t,e);case"axes":return Go(t,e);case"vector":return oa(t,e);case"basis":return aa(t,e);case"point":return ca(t,e);case"function":return ua(t,e);case"parametric":return ha(t,e);case"polygon":return fa(t,e);case"line":return pa(t,e);case"label":return ma(t,e);case"equation":return ba(t,e);case"tangent":return Ga(t,e);case"riemann":return Za(t,e);case"area":return Qa(t,e);case"taylor":return Ja(t,e);case"histogram":return va(t,e);case"distribution":return wa(t,e);case"galton":return ka(t,e);case"scatter":return Ma(t,e);case"bayes":return $a(t,e);case"graph":return _a(t,e);case"venn":return Oa(t,e);case"clock":return Ia(t,e);case"network":return La(t,e);case"heatmap":return qa(t,e);case"contours":return ja(t,e);case"descent":return Ya(t,e);case"classifier":return Va(t,e);case"kmeans":return Ua(t,e)}}const Ti=t=>Math.min(1,Math.max(0,t));function ce(t,e={}){const n=ve[t.theme??"dark"],s=hn(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=As(i),c={...o,...Ai(t.items,i,o)},l=[];for(const h of t.items){const d=p=>r.get(`${h.id}.${p}`),f=Ti(d("draw")??h.draw??1),g=Ti(d("opacity")??h.opacity??1);f<=0||g<=0||l.push(...tc(h,{plane:s,theme:n,values:i,scope:c,draw:f,opacity:g,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 ec=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 Lt(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(V("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)`),ec.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)||Pt(m)||e(`value "${a}" must be a number, an [x, y] vector or an [a, b, c, d] matrix`);const s=As(n),i=Object.keys(n).filter(a=>typeof n[a]=="number"),r=(a,m,v)=>{v!==void 0&&(typeof v=="string"?(v in n||e(`${a.id}.${m}: ${V("value",v,Object.keys(n))}`),ct(n[v])||e(`${a.id}.${m}: value "${v}" is not an [x, y] vector`)):ct(v)||e(`${a.id}.${m} must be [x, y] or the name of a vector value`))},o=(a,m,v)=>{v!==void 0&&(v in n||e(`${a.id}.${m}: ${V("value",v,Object.keys(n))}`),Pt(n[v])||e(`${a.id}.${m}: value "${v}" is not an [a, b, c, d] matrix`))},c=(a,m,v,x)=>{let w=[];try{w=kn(rt(v))}catch(b){e(`${a.id}.${m}: ${b.message}`)}for(const b of w)b!==x&&!(b in Jt)&&!i.includes(b)&&e(`${a.id}.${m}: "${b}" is neither ${x} nor a number value (${V("value",b,[x,...i])})`)},l=[],u=(a,m,v)=>{l.push([a,m,v])},h=(a,m,v)=>{v!==void 0&&(typeof v=="string"?(v in n||e(`${a.id}.${m}: ${V("value",v,i)}`),typeof n[v]!="number"&&e(`${a.id}.${m}: value "${v}" is not a number`)):Number.isFinite(v)||e(`${a.id}.${m} must be a number or the name of a number value`))},d=(a,m,v)=>{(!v||typeof v!="object"||!ne.includes(v.kind))&&e(`${a.id}.${m}: ${V("distribution",v?.kind,ne)}`);for(const[w,b]of Object.entries(v))w!=="kind"&&(w==="of"?d(a,`${m}.of`,b):h(a,`${m}.${w}`,b));const x=Tn(It(n,v));x&&e(`${a.id}.${m}: ${x}`)},f=(a,m,v)=>{let x=[];try{x=kn(rt(v))}catch(w){e(`${a.id}.${m}: ${w.message}`)}for(const w of x)w!=="x"&&w!=="y"&&!i.includes(w)&&e(`${a.id}.${m}: "${w}" is neither x, y nor a number value`)},g=(a,m,v,x)=>{try{let w=rt(v);for(let b=0;b<x;b++)w=Q(w)}catch(w){e(`${a.id}.${m}: ${w.message} (calculus needs functions with derivatives)`)}},p=new Set;for(const a of t.items)switch((!a||typeof a!="object")&&e("every item must be an object"),cn.includes(a.kind)||e(V("item kind",a.kind,cn)),(typeof a.id!="string"||!/^[A-Za-z_][\w-]*$/.test(a.id))&&e(`a ${a.kind} needs an id (letters, digits, _ and -)`),p.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`),p.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`),g(a,"expr",a.expr,a.derivative));break;case"tangent":c(a,"expr",a.expr,"x"),g(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: ${V("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,v)=>h(a,`shade[${v}]`,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: ${V("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(b=>b.id);new Set(m).size!==m.length&&e(`${a.id}: two nodes share an id`);const v=(b,k)=>{m.includes(k)||e(`${a.id}.${b}: ${V("node",k,m)}`)};Array.isArray(a.edges)||e(`${a.id}.edges must be an array`),Ne(a).forEach((b,k)=>{v(`edges[${k}]`,b.from),v(`edges[${k}]`,b.to),b.weight!==void 0&&!(b.weight>=0)&&e(`${a.id}.edges[${k}]: weights must be ≥ 0 (shortest paths need them)`)}),a.tree&&v("tree.root",a.tree.root);const x=ii(a),w=m.filter(b=>!x.has(b));w.length&&e(`${a.id}: nodes ${w.join(", ")} have no "at" and are not reached from the tree root`),a.search&&(Cn.includes(a.search.kind)||e(`${a.id}.search: ${V("search",a.search.kind,Cn)}`),v("search.start",a.search.start)),h(a,"step",a.step),a.nodes.forEach(b=>b.label!==void 0&&u(a,`nodes.${b.id}.label`,b.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(v=>v.id);if(m.every(v=>/^[A-Za-z]\w*$/.test(v))||e(`${a.id}.sets: ids must be names like A, B, Evens`),a.highlight)try{for(const v of ie(Nn(a.highlight)))m.includes(v)||e(`${a.id}.highlight: ${V("set",v,m)}`)}catch(v){e(`${a.id}.highlight: ${v.message}`)}a.sets.forEach(v=>v.label!==void 0&&u(a,`sets.${v.id}.label`,v.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&&!Fn.includes(a.activation)&&e(`${a.id}.activation: ${V("activation",a.activation,Fn)}`),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,v)=>h(a,`inputs[${v}]`,m)),h(a,"flow",a.flow),a.labels?.inputs?.forEach((m,v)=>u(a,`labels.inputs[${v}]`,m)),a.labels?.outputs?.forEach((m,v)=>u(a,`labels.outputs[${v}]`,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&&!oe.includes(a.colormap)&&e(`${a.id}.colormap: ${V("colormap",a.colormap,oe)}`),a.rowLabels?.forEach((m,v)=>u(a,`rowLabels[${v}]`,m)),a.colLabels?.forEach((m,v)=>u(a,`colLabels[${v}]`,m));break;case"contours":f(a,"expr",a.expr),a.colormap!==void 0&&!oe.includes(a.colormap)&&e(`${a.id}.colormap: ${V("colormap",a.colormap,oe)}`),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{Q(rt(a.expr),m)}catch(v){e(`${a.id}.expr: ${v.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"),g(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,v)=>u(a,`steps[${v}]`,m));break}const y={...s,...Ai(t.items,n,s)};for(const[a,m,v]of l)try{H(v,{values:y})}catch(x){e(`${a.id}.${m}: ${x.message}`)}return t}function Ei(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 z=t=>String(Math.round(t*100)/100),at=t=>t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),le=(t,e=!1)=>t.map(([n,s],i)=>`${i?"L":"M"}${z(n)} ${z(s)}`).join("")+(e?"Z":""),Xe=t=>t.opacity!==void 0&&t.opacity<1?` opacity="${z(t.opacity)}"`:"";function _i(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${le(o,!0)}`:le(o,!0),u=`tfclip${vt(`${c?"o":"i"}${l}`).toString(36)}`;return{id:u,def:`<clipPath id="${u}"><path d="${l}"${c?' clip-rule="evenodd"':""}/></clipPath>`}}),r=_i({...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="${z(t.width??1)}"`:"",s=t.dash?.length?` stroke-dasharray="${t.dash.map(z).join(" ")}"`:"";return`<path d="${le(t.points,t.closed)}"${e}${n}${s}${Xe(t)}/>`}case"arrow":{const{shaft:e,head:n}=Ei(t.points,t.head),s=at(t.stroke),i=e.length>=2?`<path d="${le(e)}" fill="none" stroke="${s}" stroke-width="${z(t.width)}"/>`:"",r=n?`<path d="${le(n,!0)}" fill="${s}"/>`:"";return`<g${Xe(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="${z(t.width??1)}"`:"";return`<circle cx="${z(t.x)}" cy="${z(t.y)}" r="${z(t.r)}"${e}${n}${Xe(t)}/>`}case"text":{const e=t.align==="center"?"middle":t.align==="right"?"end":"start",n=t.italic?' font-style="italic"':"";return`<text x="${z(t.x)}" y="${z(t.y)}" font-size="${z(t.size)}" font-family="${at(t.font)}"${n} text-anchor="${e}" fill="${at(t.color)}"${Xe(t)}>${at(t.text)}</text>`}}}function Ye(t){return`${t.background?`<rect width="${z(t.width)}" height="${z(t.height)}" fill="${at(t.background)}"/>`:""}<g stroke-linecap="round" stroke-linejoin="round">${t.shapes.map(_i).join("")}</g>`}function Pi(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 ${z(t.width)} ${z(t.height)}" width="${z(t.width)}" height="${z(t.height)}"${s}>${n}${Ye(t)}</svg>`}const nc="http://www.w3.org/2000/svg",Dn=new WeakMap;function sc(t,e){const n=t?.values.get(e);return n?Object.fromEntries(n):{}}async function Oi(t,e={}){const n=Dn.get(t);if(n)return n;const s=t.querySelector("script[data-tinyfly-figure]");let i;try{i=Lt(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(nc,"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=Ye(ce(i,f))};if(c({}),!(t.querySelector("script[data-tinyfly-timeline]")||t.hasAttribute("data-src"))){const f={element:t,figure:i,redraw:()=>c({})};return Dn.set(t,f),f}const u=await Co(t,e);if(!u)return;const h=()=>c(sc(u.player.state,r));u.player.subscribe(h),h();const d={...u,figure:i,redraw:h};return Dn.set(t,d),d}async function Ii(t=document,e={}){const n=Array.from(t.querySelectorAll("[data-tinyfly-math]"));return(await Promise.all(n.map(i=>Oi(i,e)))).filter(i=>i!==void 0)}function ic(){if(!(typeof document<"u"?document.currentScript:null)?.hasAttribute("data-tinyfly-auto"))return;const e=()=>{Ii()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}function Be(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 Ci(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)Be(t,n,!0),s?(t.rect(-1e6,-1e6,2e6,2e6),t.clip("evenodd")):t.clip();Ci(t,{...e,clip:void 0}),t.restore();return}Be(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}=Ei(e.points,e.head);t.strokeStyle=e.stroke,t.fillStyle=e.stroke,t.lineWidth=e.width,n.length>=2&&(Be(t,n),t.stroke()),s&&(Be(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 Ni(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)Ci(t,n);t.restore()}function Fi(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 rc(t,e={}){Lt(t);const n=Fi(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){Ni(i,ce(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 oc(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 ac="http://www.w3.org/2000/svg";function cc(t,e,n={}){Lt(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&&!ct(s[w.vector]))throw new Error(`mathExplorable: "${w.vector}" is not a vector value of the figure`);if("matrix"in w&&!Pt(s[w.matrix]))throw new Error(`mathExplorable: "${w.matrix}" is not a matrix value of the figure`)}const i=hn(e),r=t.ownerDocument,o=r.createElementNS(ac,"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[b,k,$,S]=s[w.matrix];return w.column===0?[b,$]:[k,S]},u=()=>{const w=c.map(b=>{const[k,$]=i.toScreen(l(b));return`<circle cx="${k}" cy="${$}" 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=Ye(ce(e,s))+w.join(""),n.onChange?.({...s})},h=(w,b)=>{if(!(w in s))throw new Error(`mathExplorable: no value "${w}"`);s[w]=b;const k=d.get(w);k&&typeof b=="number"&&(k.value=String(b),f.get(w).textContent=String(b)),u()},d=new Map,f=new Map;let g;if(n.sliders?.length){g=r.createElement("div"),g.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 b=r.createElement("label");b.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 $=r.createElement("output");$.textContent=String(s[w.value]),k.addEventListener("input",()=>h(w.value,Number(k.value))),b.append(w.label??w.value,k,$),g.appendChild(b),d.set(w.value,k),f.set(w.value,$)}t.appendChild(g)}const p=n.snap??.1,y=w=>{const b=o.getBoundingClientRect(),k=(w.clientX-b.left)/(b.width||e.width)*e.width,$=(w.clientY-b.top)/(b.height||e.height)*e.height,[S,T]=i.toWorld([k,$]),A=_=>p>0?Math.round(_/p)*p:_;return[Number(A(S).toFixed(6)),Number(A(T).toFixed(6))]};let a;const m=w=>{const b=o.getBoundingClientRect(),k=e.width/(b.width||e.width),$=[(w.clientX-b.left)*k,(w.clientY-b.top)*k];let S;for(const T of c){const[A,_]=i.toScreen(l(T)),E=Math.hypot(A-$[0],_-$[1]);E<30*i.scale*Math.max(1,k)&&(!S||E<S.distance)&&(S={handle:T,distance:E})}S&&(a=S.handle,o.setPointerCapture?.(w.pointerId),w.preventDefault())},v=w=>{if(!a)return;const[b,k]=y(w);if("vector"in a)h(a.vector,[b,k]);else{const[$,S,T,A]=s[a.matrix];h(a.matrix,a.column===0?[b,S,k,A]:[$,b,T,k])}},x=()=>{a=void 0};return o.addEventListener("pointerdown",m),o.addEventListener("pointermove",v),o.addEventListener("pointerup",x),o.addEventListener("pointercancel",x),u(),{get values(){return{...s}},set:h,destroy(){o.removeEventListener("pointerdown",m),o.removeEventListener("pointermove",v),o.removeEventListener("pointerup",x),o.removeEventListener("pointercancel",x),g?.remove()}}}const ue=(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}),Ve="\\begin{bmatrix} \\val{M.a} & \\val{M.b} \\\\ \\val{M.c} & \\val{M.d} \\end{bmatrix}",qn=t=>[(t.width??600)*.05,(t.height??600)*.1];function lc(t={}){return ue(t,{M:t.matrix??Wt},[{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:Ve,at:qn(t),screen:!0,align:"left"}])}function uc(t={}){return ue(t,{M:t.matrix??Wt},[{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:Ve,at:qn(t),screen:!0,align:"left"}])}function hc(t){return ue(t,{M:Wt,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:Ve,at:qn(t),screen:!0,align:"left"}])}function dc(t){const e=[t.u[0]+t.v[0],t.u[1]+t.v[1]];return ue(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 fc(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}"})),ue(t,n,e)}const Rt=(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 pc(t){return Rt(t,{a:t.at??1},[{id:"tangent",kind:"tangent",expr:t.expr,at:"a",color:"yellow",label:"\\text{slope} = \\val{tangent.slope}"}])}function gc(t){return Rt(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 yc(t){const e=Rt(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 mc(t){const e=Rt(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 bc(t){const e=Rt(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 vc(t){const e=Rt(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 xt=(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}),Dt=(t,e)=>({id:"readout",kind:"label",screen:!0,align:"left",size:24,at:[(t.width??600)*.05,(t.height??600)*.08],tex:e});function wc(t={}){const[e,n]=t.shade??[-1,1];return xt(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"]},Dt(t,"P(\\val{a:2} \\le X \\le \\val{b:2}) = \\val{dist.p:3}")])}function kc(t={}){const e=t.n??10;return xt(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"}},Dt(t,"n = \\val{n:0} \\quad p = \\val{p:2} \\quad \\mu = \\val{dist.mean:2}")])}function Mc(t={}){return xt(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"},Dt(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 xt(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},Dt(t,"\\val{board.landed:0} \\text{ balls}")])}function Sc(t={}){return xt(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},Dt(t,"\\frac{\\text{inside}}{\\text{all}} = \\frac{\\val{pts.inside:0}}{\\val{pts.count:0}} = \\val{pts.ratio:4} \\approx \\frac{\\pi}{4}")])}function xc(t={}){return xt(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},Dt(t,"y = \\val{pts.slope:2}\\,x + \\val{pts.intercept:2} \\quad r = \\val{pts.r:2}")])}function Ac(t={}){return xt(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 At=t=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{}}),he=(t,e)=>({id:"readout",kind:"label",screen:!0,align:"left",size:22,at:[(t.width??600)*.05,(t.height??600)*.07],tex:e}),de={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 Tc(t={}){const{width:e,height:n}=At(t);return{...At(t),x:[-4.2,4.2],y:[-3.6,3.6],values:{step:0},items:[{id:"g",kind:"graph",nodes:t.nodes??de.nodes,edges:t.edges??de.edges.map(([s,i])=>[s,i]),search:{kind:t.search??"bfs",start:t.start??"A"},step:"step",frontier:[e*.06,n*.92]},he(t,"\\text{visited } \\val{g.visited:0} \\text{ of } \\val{g.steps:0}")]}}function Ec(t={}){const{width:e,height:n}=At(t),s=t.target??"G";return{...At(t),x:[-4.2,4.2],y:[-3.6,3.6],values:{step:0},items:[{id:"g",kind:"graph",nodes:t.nodes??de.nodes,edges:t.edges??de.edges,search:{kind:"dijkstra",start:t.start??"A"},step:"step",frontier:[e*.06,n*.92]},he(t,`d(${s}) = \\val{g.d.${s}:0}`)]}}function _c(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{...At(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},he(t,"\\text{calls made: } \\val{calls.visited:0} \\text{ of } \\val{calls.steps:0}")]}}function Pc(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(he(t,t.label)),{...At(t),x:[-4,4],y:[-4,4],items:n}}function Oc(t={}){const e=t.modulus??12;return{...At(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]},he(t,`\\val{value:0} \\equiv \\val{clock.hour:0} \\pmod{${e}}`.replace("\\pmod","\\;(\\text{mod } ").replace(`{${e}}`,`${e})`))]}}const qt=t=>({width:t.width??600,height:t.height??600,...t.theme?{theme:t.theme}:{}}),fe=(t,e)=>({id:"readout",kind:"label",screen:!0,align:"left",size:22,at:[(t.width??600)*.05,(t.height??600)*.07],tex:e});function Ic(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{...qt(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}}`)}},fe(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 Cc(t={}){const e=t.expr??"(x^2 + 8 y^2) / 4";return{...qt(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"},fe(t,"\\text{step } \\val{gd.step:0} \\quad f = \\val{gd.loss:3}")]}}function Nc(t={}){const e=t.tokens??["The","cat","sat","on","the","mat"],n=_t(vt(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)+wt(n)*.8)),i=e.map(r=>`\\text{${r}}`);return{...qt(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 Fc(t={}){return{...qt(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},fe(t,"\\text{epoch } \\val{clf.epoch:0} \\quad \\text{accuracy } \\val{clf.accuracy:2} \\quad \\text{loss } \\val{clf.loss:3}")]}}function Lc(t={}){return{...qt(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},fe(t,"\\text{iteration } \\val{km.iteration:0} \\quad \\text{inertia } \\val{km.inertia:1}")]}}function Rc(t={}){return{...qt(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"},fe(t,"\\color{blue}{\\sigma(x)} \\quad \\color{yellow}{\\tanh x} \\quad \\color{red}{\\text{ReLU}(x)}")]}}function Dc(t){return Lt(t)}function qc(t,e={},n={}){return Pi(ce(Lt(t),e),n)}const zc={opacity:1,scale:1,scaleX:1,scaleY:1};function jc(t){const e=new Map,n=new Map,s=[],i={};let r=0,o=0,c;const l=(g,p)=>`${g}\0${p}`,u=(g,p)=>{const y=l(g,p);let a=e.get(y);if(!a){const m=n.get(y)??zc[p]??(p==="text"?"":0);a={id:`${g}-${p}`,target:g,property:p,keyframes:[{time:0,value:m}]},e.set(y,a)}return a},h=(g,p)=>{const y=g.keyframes[g.keyframes.length-1];y.time<p&&g.keyframes.push({time:p,value:y.value})},d=(g,p,y,a,m)=>{for(const[x,w]of Object.entries(p)){const b=u(g,x);if(typeof w=="string"&&!/^#|^rgb/.test(w)){h(b,y),b.keyframes.push({time:y+1,value:w});continue}h(b,y),b.keyframes.push({time:y+Math.max(a,1),value:w,...m&&{easing:m}})}const v=y+Math.max(a,1);return o=Math.max(o,v),v},f={get time(){return r},at(g){return r=Math.max(0,g),f},wait(g){return r+=g,o=Math.max(o,r),f},initial(g,p){for(const[y,a]of Object.entries(p)){const m=l(g,y);n.set(m,a);const v=e.get(m);v&&(v.keyframes[0].value=a)}return f},set(g,p){const y=c?c.start:r;return d(g,p,y,1,{type:"steps",count:1,position:"start"}),f},to(g,p,y={}){const a=(c?c.start:r)+(y.delay??0),m=d(g,p,a,y.duration??400,y.easing??"ease-in-out");return c?c.end=Math.max(c.end,m):r=m,f},together(g){const p=c;c={start:p?p.start:r,end:p?p.start:r},g();const y=c.end;return c=p,p?p.end=Math.max(p.end,y):r=y,f},marker(g,p={}){const{captions:y,...a}=p;s.push({id:g,time:r,...a});for(const[m,v]of Object.entries(y??{}))(i[m]??={})[g]=v;return o=Math.max(o,r),f},definition(){return{formatVersion:Ue,id:t.id,...t.name&&{name:t.name},config:{duration:o,...s.length>0&&{markers:[...s].sort((g,p)=>g.time-p.time)}},tracks:[...e.values()].map(g=>({...g,keyframes:g.keyframes.map(p=>({...p}))})),...Object.keys(i).length>0&&{captions:i}}}};return f}ic(),M.ACTIVATIONS=Fn,M.COLORMAPS=oe,M.CONSTANTS=Jt,M.DISTRIBUTION_KINDS=ne,M.ExpressionError=$t,M.FUNCTIONS=Me,M.ITEM_KINDS=cn,M.MATH_FONT=Ts,M.MATH_SYMBOL_FONT=Es,M.MATH_THEMES=ve,M.MATRIX_TEX=Ve,M.SAMPLE_GRAPH=de,M.SEARCH_KINDS=Cn,M.SYMBOLS=we,M.TEX_COMMANDS=Rs,M.TexError=Ls,M.accuracy=gi,M.activate=ai,M.activationFigure=Rc,M.adjacency=Ie,M.areaFigure=mc,M.assign=De,M.attentionFigure=Nc,M.ballAt=Ks,M.ballPath=On,M.bayesAreas=Qs,M.bayesFigure=Ac,M.binOf=Pe,M.binSamples=Gs,M.binomialFigure=kc,M.blendOver=Ln,M.blobs=Rn,M.clockFigure=Oc,M.cltFigure=Mc,M.colorAt=Fe,M.compile=K,M.compileDerivative=xe,M.contourLines=hi,M.decisionBoundaryFigure=Fc,M.defaultBins=En,M.density=pt,M.descentPath=fi,M.determinantFigure=uc,M.differentiate=Q,M.displayListToSvg=Pi,M.displayListToSvgContent=Ye,M.distributionProblem=Tn,M.drawDisplayList=Ni,M.eigenFigure=hc,M.evaluate=st,M.expressionNames=kn,M.expressionToString=ee,M.forward=li,M.galtonFigure=$c,M.gradientDescentFigure=Cc,M.graphSearchFigure=Tc,M.inRegion=re,M.inertia=bi,M.integrate=je,M.isDiscrete=se,M.kmeansFigure=Lc,M.kmeansHistory=mi,M.layoutFigure=ce,M.layoutTex=H,M.leastSquares=Pn,M.lesson=jc,M.limitFigure=vc,M.linearMapFigure=lc,M.logLoss=yi,M.mat2=jo,M.mathExplorable=cc,M.mathFigure=Dc,M.mathFigureProps=Fi,M.mathFigureToSvg=qc,M.mathSteps=oc,M.mathTarget=rc,M.meanOf=Nt,M.monteCarloPiFigure=Sc,M.morphEquation=Hs,M.mountAllMath=Ii,M.mountMath=Oi,M.neuralNetworkFigure=Ic,M.normalFigure=wc,M.nthDerivative=js,M.parseExpression=rt,M.parseSetExpression=Nn,M.parseTex=Ds,M.planeOf=hn,M.predict=ae,M.recursionTreeFigure=_c,M.regionCells=ni,M.regressionFigure=xc,M.riemannFigure=yc,M.sample=xn,M.sampleGrid=di,M.samples=An,M.scatterPoints=_n,M.sdOf=Ft,M.searchEvents=ti,M.secantFigure=gc,M.seededNetwork=ci,M.setNames=ie,M.shortestPathFigure=Ec,M.spanFigure=fc,M.summary=Zs,M.supportOf=Ws,M.surface=Le,M.tangentFigure=pc,M.taylorFigure=bc,M.texToShapes=W,M.trainLogistic=pi,M.treeLayout=ei,M.trimPolylines=X,M.validateMathFigure=Lt,M.vec2=Vo,M.vectorSumFigure=dc,M.vennFigure=Pc,Object.defineProperty(M,Symbol.toStringTag,{value:"Module"})})(this.tinyfly=this.tinyfly||{});
|