@algorisys/tinyfly 0.114.0 → 0.116.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +13 -8
  2. package/docs/api-reference.md +2 -1
  3. package/docs/character-appearance.md +27 -2
  4. package/docs/editor-guide.md +1 -1
  5. package/docs/examples.md +1 -1
  6. package/docs/getting-started.md +1 -1
  7. package/docs/gsap-compat.md +1 -1
  8. package/docs/llm-guide.md +18 -0
  9. package/docs/maps.md +2 -2
  10. package/docs/math.md +280 -0
  11. package/docs/teaching.md +1 -1
  12. package/lib/addons/characters.js +2646 -2584
  13. package/lib/addons/{cricket-play-BZNhfgOK.js → cricket-play-C5CkNOc6.js} +2187 -2005
  14. package/lib/addons/math.js +2864 -0
  15. package/lib/addons/sports.js +1 -1
  16. package/lib/browser/tinyfly-math.iife.js +53 -0
  17. package/lib/browser/tinyfly.iife.js +12 -12
  18. package/lib/browser/tinyfly.js +4948 -4699
  19. package/lib/browser/tinyfly.umd.js +12 -12
  20. package/lib/embed/tinyfly-embed.iife.js +1 -1
  21. package/lib/embed/tinyfly-embed.js +8 -0
  22. package/lib/player/tinyfly-player.es.js +8 -0
  23. package/lib/player/tinyfly-player.iife.js +1 -1
  24. package/lib/player/tinyfly-player.umd.js +1 -1
  25. package/lib/types/characters/capabilities.d.ts +8 -0
  26. package/lib/types/characters/character.d.ts +4 -0
  27. package/lib/types/characters/index.d.ts +2 -0
  28. package/lib/types/characters/look/illustrated-pen.d.ts +36 -0
  29. package/lib/types/characters/look/illustration-color.d.ts +13 -0
  30. package/lib/types/characters/look/pen.d.ts +18 -5
  31. package/lib/types/math/browser-entry.d.ts +3 -0
  32. package/lib/types/math/embed/auto-mount-math.d.ts +7 -0
  33. package/lib/types/math/embed/explorable.d.ts +46 -0
  34. package/lib/types/math/embed/mount-math.d.ts +31 -0
  35. package/lib/types/math/expr/differentiate.d.ts +7 -0
  36. package/lib/types/math/expr/evaluate.d.ts +21 -0
  37. package/lib/types/math/expr/parse-expression.d.ts +50 -0
  38. package/lib/types/math/figure/derived.d.ts +17 -0
  39. package/lib/types/math/figure/display-list.d.ts +87 -0
  40. package/lib/types/math/figure/figure-spec.d.ts +239 -0
  41. package/lib/types/math/figure/item-context.d.ts +33 -0
  42. package/lib/types/math/figure/items/calculus.d.ts +7 -0
  43. package/lib/types/math/figure/items/curves.d.ts +7 -0
  44. package/lib/types/math/figure/items/grid.d.ts +5 -0
  45. package/lib/types/math/figure/items/regions.d.ts +5 -0
  46. package/lib/types/math/figure/items/text.d.ts +5 -0
  47. package/lib/types/math/figure/items/vectors.d.ts +9 -0
  48. package/lib/types/math/figure/layout-figure.d.ts +13 -0
  49. package/lib/types/math/figure/plane.d.ts +20 -0
  50. package/lib/types/math/figure/validate-spec.d.ts +2 -0
  51. package/lib/types/math/index.d.ts +43 -0
  52. package/lib/types/math/linear/mat2.d.ts +41 -0
  53. package/lib/types/math/linear/vec2.d.ts +18 -0
  54. package/lib/types/math/presets/calculus.d.ts +59 -0
  55. package/lib/types/math/presets/linear-algebra.d.ts +42 -0
  56. package/lib/types/math/render/arrow.d.ts +10 -0
  57. package/lib/types/math/render/display-list-to-svg.d.ts +10 -0
  58. package/lib/types/math/render/draw-display-list.d.ts +6 -0
  59. package/lib/types/math/steps/math-steps.d.ts +34 -0
  60. package/lib/types/math/targets/math-target.d.ts +43 -0
  61. package/lib/types/math/tex/equation-morph.d.ts +21 -0
  62. package/lib/types/math/tex/glyph-metrics.d.ts +24 -0
  63. package/lib/types/math/tex/tex-layout.d.ts +59 -0
  64. package/lib/types/math/tex/tex-parser.d.ts +88 -0
  65. package/lib/types/player/player.d.ts +6 -0
  66. package/llms-full.txt +388 -12
  67. package/llms.txt +32 -31
  68. package/package.json +6 -2
  69. package/skills/tinyfly/SKILL.md +13 -1
@@ -1,4 +1,4 @@
1
- import { C, a as s, b as c, c as e, d as r, e as t, f as I, g as E, h as T, i as l, j as k, k as _, l as R, m as A, n as S, o as n, p as K, q as P, r as F, s as O, t as o, u as N, v as g, w as m, x as y, y as L, z as d } from "./cricket-play-BZNhfgOK.js";
1
+ import { C, a as s, b as c, c as e, d as r, e as t, f as I, g as E, h as T, i as l, j as k, k as _, l as R, m as A, n as S, o as n, p as K, q as P, r as F, s as O, t as o, u as N, v as g, w as m, x as y, y as L, z as d } from "./cricket-play-C5CkNOc6.js";
2
2
  export {
3
3
  C as CRICKET_ACTIONS,
4
4
  s as CRICKET_CAMERA_ANGLES,
@@ -0,0 +1,53 @@
1
+ (function(S){"use strict";function li(t){return typeof t=="object"&&t!==null&&t.type==="cubic-bezier"}function ui(t){return typeof t=="object"&&t!==null&&t.type!=="cubic-bezier"}const ae=2;function hi(t){return t.some(e=>e.interpolation!==void 0)?2:1}function Xe(t){return t.property==="text"&&"textConfig"in t}function ce(t){return t.kind==="inertia"&&"inertia"in t}function le(t){return t.kind==="spring"&&"spring"in t}function di(t){return t.property==="motionPath"&&"motionPathConfig"in t}function fi(t,e){if(!(e>0))return t;const n=1e3/e;return Math.floor(t/n+1e-9)*n}function Ye(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 pi(t,e="start"){if(t<=1)return 0;let n=0;for(let i=0;i<t;i++)n=Math.max(n,Ye(i,t,e));return n}function Ve(t,e,n){if(n.offsets)return n.offsets[t]??0;const i=n.from??"start",r=Ye(t,e,i);if(n.amount!==void 0){const s=pi(e,i);return s===0?0:n.amount*r/s}return n.each!==void 0?n.each*r:0}function mi(t,e){return Array.from({length:t},(n,i)=>Ve(i,t,e))}function ue(t,e){return t<=1?0:Math.max(...mi(t,e))}const At=1,We=6e4,Wt=We/At,vt={stiffness:180,damping:12,mass:1,velocity:0,restDelta:.01,restSpeed:.1};class gi{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??vt.stiffness,this.damping=e.damping??vt.damping,this.mass=e.mass??vt.mass,this.restDelta=e.restDelta??vt.restDelta,this.restSpeed=e.restSpeed??vt.restSpeed,this.distance=Math.abs(this.to-this.from)||1,this.samples=[this.from],this.velocity=e.velocity??vt.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/At);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/At-n;return i+(r-i)*s}settleTime(){return this.simulateTo(Wt+1),this.settledStep!==null?this.settledStep*At:We}simulateTo(e){if(this.settledStep!==null)return;const n=Math.min(e,Wt+1),i=At/1e3;for(;this.samples.length<n;){const r=this.samples[this.samples.length-1],s=r-this.to,o=-this.stiffness*s,c=-this.damping*this.velocity,l=(o+c)/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>Wt&&(this.settledStep=Wt)}}const Ue=4,yi=.002,bi=1e-4,vi=6e4;function he(t){const e=t.friction??Ue;return e>0?e:Ue}function wi(t){return t.from+t.velocity/he(t)}function ki(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 Be(t){let e=ki(wi(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 He(t){const e=Math.abs(Be(t)-t.from);if(e===0)return 0;const n=t.restDelta??Math.max(bi,e*yi);if(n>=e)return 0;const i=Math.log(e/n)/he(t);return Math.min(vi,i*1e3)}function Ge(t,e){if(e<=0)return t.from;const n=Be(t);if(e>=He(t))return n;const i=he(t);return t.from+(n-t.from)*(1-Math.exp(-i*e/1e3))}const de=t=>t,Mi=t=>t*t,xi=t=>1-(1-t)*(1-t),Si=t=>t<.5?2*t*t:1-Math.pow(-2*t+2,2)/2,Ze=t=>t*t*t,Qe=t=>1-Math.pow(1-t,3),Ke=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2,$i={linear:de,"ease-in":Ze,"ease-out":Qe,"ease-in-out":Ke,"ease-in-quad":Mi,"ease-out-quad":xi,"ease-in-out-quad":Si,"ease-in-cubic":Ze,"ease-out-cubic":Qe,"ease-in-out-cubic":Ke};function Ti(t){const[e,n,i,r]=t,s=3*e,o=3*(i-e)-s,c=1-s-o,l=3*n,h=3*(r-n)-l,u=1-l-h,d=f=>((c*f+o)*f+s)*f,p=f=>((u*f+h)*f+l)*f,m=f=>(3*c*f+2*o)*f+s,a=f=>{let g=f;for(let M=0;M<8;M++){const w=d(g)-f;if(Math.abs(w)<1e-7)return g;const b=m(g);if(Math.abs(b)<1e-7)break;g-=w/b}let y=0,v=1;for(g=f;y<v;){const M=d(g);if(Math.abs(M-f)<1e-7)return g;f>M?y=g:v=g,g=(y+v)/2}return g};return f=>{if(f<=0)return 0;if(f>=1)return 1;const g=a(f);return p(g)}}function fe(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 Ai(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 Ei=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 _i(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 Pi(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 Oi(t){switch(t.type){case"steps":return Pi(t.count,t.position);case"elastic":return fe(Ai(t.amplitude,t.period),t.mode);case"bounce":return fe(Ei,t.mode);case"back":return fe(_i(t.overshoot),t.mode)}}function Ci(t){return t===void 0?de:li(t)?Ti(t.points):ui(t)?Oi(t):$i[t]??de}const Je=32,Ii=256,Et=new Map,Li=/[MmLlHhVvCcSsQqTtAaZz]/,Ri=/^[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/,Di={M:2,L:2,H:1,V:1,C:6,S:4,Q:4,T:2,A:7,Z:0};function Fi(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(Li.test(s)){i={type:s,args:[]},e.push(i),n++;continue}if(!i)break;const o=i.type==="A"||i.type==="a",c=i.args.length%7;if(o&&(c===3||c===4)){if(s!=="0"&&s!=="1")break;i.args.push(s==="1"?1:0),n++;continue}const l=Ri.exec(t.slice(n));if(!l)break;i.args.push(parseFloat(l[0])),n+=l[0].length}return e}function Ni(t,e,n,i,r,s,o,c,l){if(t===c&&e===l)return[];let h=Math.abs(n),u=Math.abs(i);if(h===0||u===0)return[[t,e,c,l,c,l]];const d=r*Math.PI/180,p=Math.cos(d),m=Math.sin(d),a=(t-c)/2,f=(e-l)/2,g=p*a+m*f,y=-m*a+p*f,v=g*g/(h*h)+y*y/(u*u);if(v>1){const I=Math.sqrt(v);h*=I,u*=I}const M=s===o?-1:1,w=h*h*u*u-h*h*y*y-u*u*g*g,b=h*h*y*y+u*u*g*g,k=M*Math.sqrt(Math.max(0,w/b)),x=k*h*y/u,$=-k*u*g/h,P=p*x-m*$+(t+c)/2,A=m*x+p*$+(e+l)/2,C=(I,z,U,Tt)=>{const qe=I*U+z*Tt,oe=Math.sqrt((I*I+z*z)*(U*U+Tt*Tt)),Vt=Math.acos(Math.max(-1,Math.min(1,qe/oe)));return I*Tt-z*U<0?-Vt:Vt},E=C(1,0,(g-x)/h,(y-$)/u);let N=C((g-x)/h,(y-$)/u,(-g-x)/h,(-y-$)/u);!o&&N>0&&(N-=2*Math.PI),o&&N<0&&(N+=2*Math.PI);const G=Math.max(1,Math.ceil(Math.abs(N)/(Math.PI/2))),T=N/G,D=4/3*Math.tan(T/4),rt=I=>{const z=h*Math.cos(I),U=u*Math.sin(I);return[p*z-m*U+P,m*z+p*U+A]},J=I=>{const z=-h*Math.sin(I),U=u*Math.cos(I);return[p*z-m*U,m*z+p*U]},W=[];for(let I=0;I<G;I++){const z=E+I*T,U=z+T,[Tt,qe]=rt(z),[oe,Vt]=I===G-1?[c,l]:rt(U),[xo,So]=J(z),[$o,To]=J(U);W.push([Tt+D*xo,qe+D*So,oe-D*$o,Vt-D*To,oe,Vt])}return W}function ct(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 _t(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 Ut(t,e,n){const[i,r,s,o,c,l]=n,h=[0];let u=t,d=e,p=0;for(let m=1;m<=Je;m++){const a=m/Je,f=ct(t,i,s,c,a),g=ct(e,r,o,l,a);p+=Math.hypot(f-u,g-d),h.push(p),u=f,d=g}return{subpath:0,type:"C",points:[i,r,s,o,c,l],startX:t,startY:e,endX:c,endY:l,length:p,lengths:h}}function Bt(t){const e=Et.get(t);if(e)return e;const n=[];let i=0,r=0,s=0,o=0,c=null,l=null,h=-1;const u=new Set,d=f=>{h<0&&(h=0),f.subpath=h,n.push(f)};for(const{type:f,args:g}of Fi(t)){const y=f.toUpperCase(),v=f!==y,M=Di[y];if(y==="Z"){(i!==s||r!==o)&&d(_t(i,r,s,o)),h>=0&&u.add(h),i=s,r=o,c=l=null;continue}for(let w=0;w+M<=g.length;w+=M){const b=g.slice(w,w+M),k=v?i:0,x=v?r:0;let $=null,P=null;switch(y){case"M":w===0?(i=b[0]+k,r=b[1]+x,s=i,o=r,(h<0||n[n.length-1]?.subpath===h)&&h++):(d(_t(i,r,b[0]+k,b[1]+x)),i=b[0]+k,r=b[1]+x);break;case"L":d(_t(i,r,b[0]+k,b[1]+x)),i=b[0]+k,r=b[1]+x;break;case"H":d(_t(i,r,b[0]+k,r)),i=b[0]+k;break;case"V":d(_t(i,r,i,b[0]+x)),r=b[0]+x;break;case"C":{const A=[b[0]+k,b[1]+x,b[2]+k,b[3]+x,b[4]+k,b[5]+x];d(Ut(i,r,A)),$=[A[2],A[3]],i=A[4],r=A[5];break}case"S":{const[A,C]=c?[2*i-c[0],2*r-c[1]]:[i,r],E=[A,C,b[0]+k,b[1]+x,b[2]+k,b[3]+x];d(Ut(i,r,E)),$=[E[2],E[3]],i=E[4],r=E[5];break}case"Q":case"T":{let A=i,C=r;y==="Q"?(A=b[0]+k,C=b[1]+x):l&&(A=2*i-l[0],C=2*r-l[1]);const E=y==="Q"?b[2]+k:b[0]+k,N=y==="Q"?b[3]+x:b[1]+x;d(Ut(i,r,[i+2/3*(A-i),r+2/3*(C-r),E+2/3*(A-E),N+2/3*(C-N),E,N])),P=[A,C],i=E,r=N;break}case"A":{const A=b[5]+k,C=b[6]+x;let E=i,N=r;for(const G of Ni(i,r,b[0],b[1],b[2],b[3],b[4],A,C))d(Ut(E,N,G)),E=G[4],N=G[5];i=A,r=C;break}}c=$,l=P}}const p=n.reduce((f,g)=>f+g.length,0),m=[];for(let f=0;f<n.length;){const g=n[f].subpath;let y=f,v=0;for(;y<n.length&&n[y].subpath===g;)v+=n[y++].length;const M=n[f],w=n[y-1],b=u.has(g)||Math.abs(w.endX-M.startX)<1e-9&&Math.abs(w.endY-M.startY)<1e-9;m.push({start:f,end:y,length:v,closed:b}),f=y}const a={segments:n,totalLength:p,subpaths:m};return Et.size>=Ii&&Et.delete(Et.keys().next().value),Et.set(t,a),a}function zi(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 c=i+r>>1;n[c]<e?i=c:r=c}const s=n[r]-n[i],o=s>0?(e-n[i])/s:0;return(i+o)/(n.length-1)}function ji(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,c]=t.points,l=zi(t,e);let h=tn(t.startX,n,r,o,l),u=tn(t.startY,i,s,c,l);if(Math.hypot(h,u)<1e-9){const d=l<.5?Math.min(1,l+.001):Math.max(0,l-.001),p=ct(t.startX,n,r,o,d),m=ct(t.startY,i,s,c,d),a=ct(t.startX,n,r,o,l),f=ct(t.startY,i,s,c,l);h=l<.5?p-a:a-p,u=l<.5?m-f:f-m}return{x:ct(t.startX,n,r,o,l),y:ct(t.startY,i,s,c,l),angle:Math.atan2(u,h)*180/Math.PI}}function en(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 ji(o,e-r);r+=o.length}return{x:0,y:0,angle:0}}function qi(t,e){const{segments:n,totalLength:i}=Bt(t);return en(n,Math.max(0,Math.min(1,e))*i)}const Xi=24,Yi=320,Vi=2.5,Pt=72,Wi=.2,Ui=128,Ht=new Map;let pe=0,ht;const nn=t=>Math.round(t*100)/100;function rn(t,e){const{segments:n,subpaths:i,totalLength:r}=Bt(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 me(t,e){const n=t.closed?(e%1+1)%1:Math.max(0,Math.min(1,e)),i=en(t.segments,n*t.length,t.start,t.end);return[i.x,i.y]}function sn(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(me(t,t.closed?i/e:i/(e-1)));return n}function an(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 Bi(t,e,n){const i=t.closed&&e.closed;if(n!==void 0)return{offset:i?Math.abs(n)%Pt/Pt:0,reversed:n<0};const r=an(on(t,Pt)),s=an(on(e,Pt)),o=Pt;let c={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 p=0;for(let m=0;m<o&&p<l;m++){const a=i?h?(d-m+o)%o:(m+d)%o:h?o-1-m:m,f=r[m][0]-s[a][0],g=r[m][1]-s[a][1];p+=f*f+g*g}p<l&&(l=p,c={offset:i?d/o:0,reversed:h})}}return c}function Hi(t,e,n){return n?((e.reversed?e.offset-t:t+e.offset)%1+1)%1:e.reversed?1-t:t}function Gi(t,e,n){return n?((e.reversed?e.offset-t:t-e.offset)%1+1)%1:e.reversed?1-t:t}function Zi(t,e,n){const i=t.closed&&e.closed,r=Bi(t,e,n.shapeIndex),s=Math.max(Xi,Math.min(Yi,Math.ceil(Math.max(t.length,e.length)/Vi))),o=new Set,c=d=>o.add(Math.round(d*1e7)/1e7);for(let d=0;d<=s;d++)c(d/s);for(const d of sn(t))c(d);for(const d of sn(e))c(Gi(d,r,i));let l=[...o].sort((d,p)=>d-p);i&&(l=l.filter(d=>d<1));const h=[],u=[];for(const d of l)h.push(...me(t,d)),u.push(...me(e,Hi(d,r,i)));return Qi({from:h,to:u,closed:i})}function Qi(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,c]=i.pop();let l=-1,h=Wi;for(let u=o+1;u<c;u++){const d=Math.max(cn(t.from,o,c,u),cn(t.to,o,c,u));d>h&&(h=d,l=u)}l!==-1&&(n[l]=1,i.push([o,l],[l,c]))}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,c=t[n*2+1]-s,l=t[i*2]-r,h=t[i*2+1]-s,u=o*o+c*c,d=u===0?0:Math.max(0,Math.min(1,(l*o+h*c)/u));return Math.hypot(l-d*o,h-d*c)}function Ki(t,e,n){const i=n.shapeIndex;if(ht&&ht.from===t&&ht.to===e&&ht.shapeIndex===i)return ht.plan;const s=Ht.get(String(i??"auto"))?.get(t)?.get(e);if(s)return ht={from:t,to:e,shapeIndex:i,plan:s},s;const o=Bt(t).subpaths.filter(m=>m.length>0).length===Bt(e).subpaths.filter(m=>m.length>0).length,c=rn(t,!o),l=rn(e,!o),h={pairs:c.map((m,a)=>Zi(m,l[a],n))};pe>=Ui&&(Ht.clear(),pe=0);const u=String(i??"auto"),d=Ht.get(u)??new Map;Ht.set(u,d);const p=d.get(t)??new Map;return d.set(t,p),p.set(e,h),pe++,ht={from:t,to:e,shapeIndex:i,plan:h},h}function Ji(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=Ki(t,e,i);if(s.pairs.length===0)return r<.5?t:e;let o="";for(const c of s.pairs){for(let l=0;l<c.from.length;l+=2){const h=nn(c.from[l]+(c.to[l]-c.from[l])*r),u=nn(c.from[l+1]+(c.to[l+1]-c.from[l+1])*r);o+=`${l===0?o?" M":"M":" L"}${h} ${u}`}c.closed&&(o+=" Z")}return o}function tr(t){return/^\s*[Mm]\s*[-+]?(?:\d|\.\d)/.test(t)}const er=.9995;function nr(){return[0,0,0,1]}function ir(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 Ot(t){const e=rr(t);return e===0?nr():[t[0]/e,t[1]/e,t[2]/e,t[3]/e]}function sr(t,e,n){const i=Ot(t);let r=Ot(e),s=ir(i,r);if(s<0&&(r=[-r[0],-r[1],-r[2],-r[3]],s=-s),s>er)return Ot([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),c=Math.sin(o),l=Math.sin((1-n)*o)/c,h=Math.sin(n*o)/c;return Ot([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 st=(t,e,n)=>t+(e-t)*n,ln=512,ge=new Map,ye=new Map;function un(t){const e=ge.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 ge.size<ln&&ge.set(t,i),i}const hn=t=>t.charCodeAt(0)===35,dn=t=>t.startsWith("rgb"),fn=t=>t.startsWith("rgba"),or=/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*([\d.]+))?\s*\)/,be=t=>Math.round(t).toString(16).padStart(2,"0");function ar(t,e,n){return`#${be(t)}${be(e)}${be(n)}`}function pn(t){const e=ye.get(t);if(e)return e;const n=t.match(or);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 ye.size<ln&&ye.set(t,o),o}const cr=(t,e,n)=>{if(hn(t)&&hn(e)){const[i,r,s]=un(t),[o,c,l]=un(e),h=st(i,o,n),u=st(r,c,n),d=st(s,l,n);return ar(h,u,d)}if((dn(t)||fn(t))&&(dn(e)||fn(e))){const i=pn(t),r=pn(e),s=Math.round(st(i[0],r[0],n)),o=Math.round(st(i[1],r[1],n)),c=Math.round(st(i[2],r[2],n));if(i.length===4||r.length===4){const l=i[3]??1,h=r[3]??1,u=st(l,h,n);return`rgba(${s}, ${o}, ${c}, ${u})`}return`rgb(${s}, ${o}, ${c})`}return n<1?t:e},lr=(t,e,n)=>{const i=Math.min(t.length,e.length),r=[];for(let s=0;s<i;s++)r.push(st(t[s],e[s],n));return r},ur=(t,e,n)=>sr(t,e,n),mn=(t,e,n)=>n<1?t:e,hr=(t,e,n)=>Ji(t,e,n);function dr(t,e){return e==="slerp"?ur:typeof t=="number"?st:Array.isArray(t)?lr:typeof t=="string"?t.startsWith("#")||t.startsWith("rgb")?cr:tr(t)?hr:mn:mn}function fr(t){const e=[...t.keyframes].sort((n,i)=>n.time-i.time);return{...t,keyframes:e}}function dt(t){return t.targets&&t.targets.length>0?t.targets:[t.target]}function wt(t,e,n,i){const r=n??0;return!i||e<=1?r:r+Ve(t,e,i)}class ve{track;targets;constructor(e){this.track=e,this.targets=dt(e)}getValueAtTime(e){return this.valueForOffset(e-wt(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=wt(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?ue(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=Ci(r.easing)(o);return dr(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 pr{track;targets;sampler;constructor(e){this.track=e,this.targets=dt(e),this.sampler=new gi(e.spring)}getValueAtTime(e){return this.sampler.valueAt(e-wt(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=wt(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?ue(this.targets.length,this.track.stagger):0;return this.sampler.settleTime()+(this.track.delay??0)+e}getTrack(){return this.track}}class mr{track;targets;duration;constructor(e){this.track=e,this.targets=dt(e),this.duration=He(e.inertia)}getValueAtTime(e){return Ge(this.track.inertia,e-wt(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=wt(r,n,this.track.delay,this.track.stagger);i.push({target:this.targets[r],value:Ge(this.track.inertia,e-s),start:s})}return i}getDuration(){const e=this.track.stagger?ue(this.targets.length,this.track.stagger):0;return this.duration+(this.track.delay??0)+e}getTrack(){return this.track}}function gr(t,e){const n={...qi(t.pathData,e)};if(t.matrix){const[i,r,s,o,c,l]=t.matrix,{x:h,y:u}=n;n.x=i*h+s*u+c,n.y=r*h+o*u+l;const d=n.angle*Math.PI/180,p=Math.cos(d),m=Math.sin(d);n.angle=Math.atan2(r*p+o*m,i*p+s*m)*180/Math.PI}return t.autoRotate&&t.rotateOffset&&(n.angle+=t.rotateOffset),n}const we={upperCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZ",lowerCase:"abcdefghijklmnopqrstuvwxyz",upperAndLowerCase:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",numbers:"0123456789"},yr=20;function br(t){const e=we[t??"upperCase"]??t??we.upperCase,n=Array.from(e);return n.length>0?n:Array.from(we.upperCase)}function vr(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 wr(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),c=Array.from(r),l=t.rightToLeft??!1;if(t.mode==="type"){const v=Math.round(s*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 h=Math.max(0,Math.min(.999,t.revealDelay??0)),u=Math.max(0,(s-h)/(1-h)),d=Math.floor(u*c.length),p=t.tweenLength===!1?c.length:Math.round(o.length+(c.length-o.length)*s),m=br(t.chars),a=t.refreshRate??yr,f=a>0?Math.floor(n*a/1e3):0,g=t.seed??1;let y="";for(let v=0;v<p;v++){const M=l?v>=p-d:v<d,w=l?c[c.length-(p-v)]:c[v];M&&w!==void 0||w===" "||w===`
2
+ `?y+=w:y+=m[vr(g,v,f)%m.length]}return y}class kr{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 c=Math.min(this._repeatDelayRemaining,r);if(this._repeatDelayRemaining-=c,r-=c,this._repeatDelayRemaining>0){this.onUpdate?.(this.getStateAtTime(this._currentTime));return}this._wrapAfterDelay&&(this._wrapAfterDelay=!1,this._currentTime=0)}const s=1e3;for(let c=0;c<s&&r>0&&this._playbackState==="playing";c++)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=fi(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:c,start:l}of r.getTargetValues(e))this._write(n,i,o,s,c,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:c,value:l,start:h}of s.getTargetValues(e)){const u=`${c}\0${o}`,d=h<=e,p=i.get(u);(!p||(d!==p.started?d:d?h>=p.start:h<=p.start))&&i.set(u,{trackId:r,target:c,property:o,value:l,start:h,started:d})}}for(const{trackId:r,target:s,property:o,value:c,start:l}of i.values())this._write(n,r,s,o,c,e-l)}_write(e,n,i,r,s,o){if(s===void 0)return;let c=e.get(i);c||(c=new Map,e.set(i,c));const l=this._textTracks.get(n);if(l&&typeof s=="number"){c.set("text",wr(l.textConfig,s,Math.max(0,o)));return}const h=this._motionPathTracks.get(n);if(h&&typeof s=="number"){const u=gr(h.motionPathConfig,s);c.set("motionPathX",u.x),c.set("motionPathY",u.y),h.motionPathConfig.autoRotate&&c.set("motionPathRotate",u.angle)}else c.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 dt(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,ce(e)){this._trackPlayers.set(e.id,new mr(e));return}if(le(e)){this._trackPlayers.set(e.id,new pr(e)),this._springTracks.set(e.id,e);return}if(Xe(e))this._trackPlayers.set(e.id,new ve(e)),this._textTracks.set(e.id,e);else if(di(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 ve(n)),this._motionPathTracks.set(e.id,e)}else this._trackPlayers.set(e.id,new ve(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(le(i)||ce(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 c=dt(o).filter(d=>dt(i).includes(d));if(c.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 c)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&&!dt(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:hi(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 Mr=100;function xr(t,e,n,i){const r=[],s=[],{duration:o,alternate:c}=i,l=(m,a,f,g)=>{s.push([m,a]);const y=[];t.forEach((v,M)=>{(f==="forward"?(g?v>=m:v>m)&&v<=a:(g?v<=m:v<m)&&v>=a)&&y.push(M)}),y.sort((v,M)=>(f==="forward"?t[v]-t[M]:t[M]-t[v])||v-M);for(const v of y)r.push({kind:"event",index:v,direction:f})};let h=e.time,u=e.direction,d=e.fresh===!0;const p=Math.min(Mr,Math.max(0,n.iteration-e.iteration));for(let m=0;m<p;m++){const a=u==="forward"?o:0;l(h,a,u,d),r.push({kind:"repeat"}),c?(u=u==="forward"?"reverse":"forward",h=a,d=!1):(h=u==="forward"?0:o,d=!0)}return p>0&&i.holding&&!c?{crossings:r,passes:s}:(l(h,n.time,u,d),{crossings:r,passes:s})}function Sr(t){return{...t,...Array.isArray(t.end)&&{end:[...t.end]}}}function Ct(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 $r(t){if(ce(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"inertia",inertia:Sr(e.inertia),...Ct(e)}}if(le(t)){const e=t;return{id:e.id,target:e.target,property:e.property,kind:"spring",spring:{...e.spring},...Ct(e)}}if(Xe(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),...Ct(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,...Ct(e)}}return fr({id:t.id,target:t.target,property:t.property,keyframes:t.keyframes,...t.interpolation!==void 0&&{interpolation:t.interpolation},...Ct(t)})}function gn(t){const e=t.formatVersion??1;if(e>ae)throw new Error(`tinyfly: this animation uses format version ${e}, but this tinyfly reads up to version ${ae}. Update tinyfly to play it.`);return new kr({id:t.id,name:t.name,config:t.config,tracks:t.tracks.map($r),captions:t.captions})}function Tr(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 c=1;c<=i.length;c++)o[c]=Math.min(r[c]+1,o[c-1]+1,r[c-1]+(n[s-1]===i[c-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 c=Tr(t,o);c<s&&(s=c,r=o)}return r!==void 0&&s<=Math.max(2,Math.floor(t.length/3))?r:void 0}function ft(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 Ar(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 Er(t){return!Array.isArray(t)||t.length!==4?null:`matrix3d(${Ar(Ot(t)).map(n=>Math.round(n*1e6)/1e6+0).join(", ")})`}const _r=new Set(["blur","brightness","glow","glowColor","shadowX","shadowY","shadowBlur","shadowColor"]),Pr="#ffffff",Or="rgba(0, 0, 0, 0.5)";function Cr(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??Pr})`),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??Or})`)}return e.length>0?e.join(" "):null}function Ir(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 Lr(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"]),Rr=new Set(["x","y","z","rotate","rotateX","rotateY","rotateZ","scale","scaleX","scaleY","scaleZ","skewX","skewY","quaternion","motionPathX","motionPathY","motionPathRotate"]),Dr=["x","motionPathX","y","motionPathY","z","rotate","rotateZ","motionPathRotate","rotateX","rotateY","quaternion","scale","scaleX","scaleY","scaleZ","skewX","skewY"],Fr=new Set(["childPerspective","perspectiveOriginX","perspectiveOriginY"]),Nr=new Set(["originX","originY"]),zr=new Set(["clipTop","clipRight","clipBottom","clipLeft"]),jr=new Set(["drawOn"]),qr={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"},Xr="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,c=null;const l=n.has("motionPathX"),h=n.has("motionPathY"),u=n.has("motionPathRotate");for(const[a,f]of n)if(!(a==="x"&&l)&&!(a==="y"&&h)&&!((a==="rotate"||a==="rotateZ")&&u)&&!jr.has(a)){if(Rr.has(a))(i??={})[a]=f;else if(Fr.has(a))typeof f=="number"&&((r??={})[a]=f);else if(Nr.has(a))typeof f=="number"&&((s??={})[a]=f);else if(zr.has(a))typeof f=="number"&&((o??={})[a]=f);else if(_r.has(a))(c??={})[a]=f;else if(a!=="perspective"){if(a!=="shine")if(a==="text"&&typeof f=="string")Ir(e,f);else if(a==="d"&&typeof f=="string"){const g=e;(g.tagName?.toLowerCase()==="path"?g:g.querySelector?.("path"))?.setAttribute?.("d",f)}else this.applyStyleProperty(e,a,f)}}const d=n.get("shine");typeof d=="number"&&this.applyShine(e,d);const p=[],m=n.get("perspective");if(typeof m=="number"&&m>0&&p.push(`perspective(${m}px)`),i)for(const a of Dr){const f=i[a];if(f===void 0)continue;const g=this.buildTransformPart(a,f);g&&p.push(g)}if(p.length>0&&(e.style.transform=p.join(" "),Lr(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 a=s.originX??50,f=s.originY??50;e.style.transformOrigin=`${a}% ${f}%`}if(o){const a=o.clipTop??0,f=o.clipRight??0,g=o.clipBottom??0,y=o.clipLeft??0;e.style.clipPath=`inset(${a}% ${f}% ${g}% ${y}%)`}if(c){const a=Cr(c);a&&(e.style.filter=a)}}buildTransformPart(e,n){if(e==="quaternion")return Er(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===Xr&&n in vn){const c=Array.isArray(i)?i.join(", "):String(i);e.style[vn[n]]=c;return}else n==="fill"&&e.dataset?.elementType==="text"?r="color":r=qr[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 kn{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 Yr(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 Vr{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=gn({...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(c=>c.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(c=>c.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 kn(i)})})}syncAllMedia(e,n){for(const i of this.mediaTargets)Yr(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(c=>{const l=c.getAttribute("data-tinyfly");l&&o.registerTarget(l,c)}),this.symbolInstances.push({adapter:o,timeline:gn(s.timeline)})})}attachMedia(e,n){this.mediaSync=new kn(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}=xr(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 c=r[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 i=n.timeline.duration;n.adapter.applyState(n.timeline.getStateAtTime(i>0?e%i:e))}}}const Wr={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"},Mn="tinyfly-controls-style",Ur=`
3
+ .tf-ctl { --tf-ctl-fg: #1d1d1f; --tf-ctl-bg: #f4f2ee; --tf-ctl-accent: #c2410c; --tf-ctl-radius: 8px;
4
+ font: 14px/1.4 var(--tf-ctl-font, system-ui, sans-serif); color: var(--tf-ctl-fg); margin-top: 8px; }
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); }
6
+ .tf-ctl-btn { min-width: 36px; height: 36px; padding: 0 10px; border: 0; border-radius: calc(var(--tf-ctl-radius) - 2px); background: transparent; color: inherit; font: inherit; cursor: pointer; }
7
+ .tf-ctl-btn:hover { background: color-mix(in srgb, var(--tf-ctl-fg) 8%, transparent); }
8
+ .tf-ctl-btn:focus-visible, .tf-ctl-scrub:focus-visible, .tf-ctl-speed:focus-visible { outline: 2px solid var(--tf-ctl-accent); outline-offset: 2px; }
9
+ .tf-ctl-btn[disabled] { opacity: 0.4; cursor: default; }
10
+ .tf-ctl-primary { background: var(--tf-ctl-accent); color: #fff; }
11
+ .tf-ctl-primary:hover { background: var(--tf-ctl-accent); filter: brightness(1.08); }
12
+ .tf-ctl-scrub { flex: 1 1 120px; min-width: 80px; accent-color: var(--tf-ctl-accent); }
13
+ .tf-ctl-speed { height: 32px; border: 0; border-radius: 6px; background: transparent; color: inherit; font: inherit; }
14
+ .tf-ctl-step { font-variant-numeric: tabular-nums; opacity: 0.75; padding: 0 4px; }
15
+ .tf-ctl-caption { margin: 6px 2px 0; min-height: 1.4em; }
16
+ .tf-ctl-question { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 6px 2px 0; font-weight: 600; }
17
+ .tf-ctl-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
18
+ /* The hidden attribute only hides through the browser's default stylesheet; any rule
19
+ above that sets display would override it, so enforce it for everything here. */
20
+ .tf-ctl [hidden] { display: none !important; }
21
+ .tf-ctl-choices { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; margin: 8px 0 0; padding: 0; border: 0; }
22
+ .tf-ctl-choices legend { float: left; margin-right: 4px; padding: 0; font-weight: 600; }
23
+ .tf-ctl-choice { position: relative; display: inline-flex; }
24
+ .tf-ctl-choice input { position: absolute; opacity: 0; width: 1px; height: 1px; }
25
+ .tf-ctl-choice span { display: inline-block; padding: 6px 12px; border-radius: var(--tf-ctl-radius); background: var(--tf-ctl-bg); cursor: pointer; }
26
+ .tf-ctl-choice input:checked + span { background: var(--tf-ctl-accent); color: #fff; }
27
+ .tf-ctl-choice input:focus-visible + span { outline: 2px solid var(--tf-ctl-accent); outline-offset: 2px; }
28
+ .tf-ctl-choice-slider { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin: 8px 0 0; }
29
+ .tf-ctl-choice-slider span { font-weight: 600; }
30
+ .tf-ctl-choice-slider input { flex: 1 1 140px; accent-color: var(--tf-ctl-accent); }
31
+ .tf-ctl-choice-slider input:focus-visible { outline: 2px solid var(--tf-ctl-accent); outline-offset: 2px; }
32
+ .tf-ctl-choice-slider output { font-variant-numeric: tabular-nums; min-width: 4em; }
33
+ .tf-ctl-fullscreen { margin-left: auto; display: inline-flex; align-items: center; justify-content: center; }
34
+ .tf-ctl-fullscreen svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 2; stroke-linecap: round; }
35
+ /* Full screen, by either route. The figure becomes a column: the drawing takes the room
36
+ that's left after the controls and captions. !important because the host page's own
37
+ figure rules (a max-width, a min-width that makes a diagram scroll on phones) would
38
+ otherwise keep the drawing at its in-page size. */
39
+ .tf-fullscreen { box-sizing: border-box !important; display: flex !important; flex-direction: column; width: 100% !important; max-width: none !important; height: 100vh; height: 100dvh; margin: 0 !important; padding: max(12px, env(safe-area-inset-top)) max(12px, env(safe-area-inset-right)) max(12px, env(safe-area-inset-bottom)) max(12px, env(safe-area-inset-left)) !important; overflow: auto !important; background: var(--tf-fullscreen-bg, #fff); }
40
+ .tf-fullscreen > * { flex: none; }
41
+ .tf-fullscreen > svg, .tf-fullscreen > canvas { flex: 1 1 0; min-height: 0; width: 100% !important; min-width: 0 !important; height: 100% !important; }
42
+ .tf-fullscreen-overlay { position: fixed !important; inset: 0; z-index: 2147483000; }
43
+ /* A short landscape screen (a phone on its side): stacking the controls under the drawing
44
+ leaves the drawing a thin strip, so put them in a column beside it instead. */
45
+ @media (orientation: landscape) and (max-height: 520px) {
46
+ .tf-fullscreen { display: grid !important; grid-template-columns: minmax(0, 1fr) minmax(200px, 34%); grid-auto-rows: min-content; column-gap: 12px; align-content: start; }
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
+ .tf-fullscreen > :not(svg):not(canvas) { grid-column: 2; }
49
+ }
50
+ `;let Br=0;function Hr(t){if(t.getElementById(Mn))return;const e=t.createElement("style");e.id=Mn,e.textContent=Ur,t.head.appendChild(e)}function Gr(t,e,n={}){const i=e.ownerDocument;Hr(i);const r={...Wr,...n.labels},s=n.speeds??[.5,1,2],o=()=>t.markers.length>0,c=()=>t.markers.some(T=>T.label!==void 0||t.caption(T.id)!==void 0),l=i.createElement("div");l.className="tf-ctl";const h=i.createElement("div");h.className="tf-ctl-bar",h.setAttribute("role","group");const u=(T,D,rt,J="")=>{const W=i.createElement("button");return W.type="button",W.className=`tf-ctl-btn ${J}`.trim(),W.setAttribute("aria-label",T),W.title=T,W.textContent=D,W.addEventListener("click",rt),W},d=u(r.restart,"⟲",()=>{t.pause(),t.seek(0)}),p=u(r.prev,"|◀",()=>t.prev()),m=u(r.play,"▶",()=>t.isPlaying?t.pause():f(),"tf-ctl-primary"),a=u(r.next,"▶|",()=>t.next()),f=()=>{t.currentTime>=t.duration-.5&&t.seek(0),t.play()},g=i.createElement("input");g.type="range",g.className="tf-ctl-scrub",g.min="0",g.max="1000",g.step="1",g.setAttribute("aria-label",r.scrub),g.addEventListener("input",()=>{t.pause(),t.seek(Number(g.value)/1e3*t.duration)});const y=i.createElement("span");y.className="tf-ctl-step";const v=i.createElement("select");v.className="tf-ctl-speed",v.setAttribute("aria-label",r.speed);for(const T of s){const D=i.createElement("option");D.value=String(T),D.textContent=`${T}×`,T===1&&(D.selected=!0),v.appendChild(D)}v.addEventListener("change",()=>t.setSpeed(Number(v.value))),h.append(d,p,m,a,g,y),s.length>0&&h.append(v),l.append(h);const M=n.fullscreen?Jr(e,i,r):void 0;M&&h.append(M.button);const w=i.createElement("p");w.className="tf-ctl-caption",w.setAttribute("aria-live","polite"),n.captions!==!1&&l.append(w);const b=i.createElement("div");b.className="tf-ctl-question",b.hidden=!0;const k=i.createElement("span"),x=u(r.reveal,r.reveal,()=>t.play(),"tf-ctl-primary");b.append(k,x),l.append(b);const $=Zr(t,i,r.scenario,n.scenarioControl??"buttons");$&&l.append($.element);const P=n.mount;P?P.appendChild(l):e.insertAdjacentElement("afterend",l);const A=()=>{const T=t.isPlaying;m.textContent=T?"❚❚":"▶",m.setAttribute("aria-label",T?r.pause:r.play),m.title=T?r.pause:r.play;const D=t.duration;i.activeElement!==g&&(g.value=String(D>0?Math.round(t.currentTime/D*1e3):0));const rt=t.markers;if(p.hidden=a.hidden=y.hidden=rt.length===0,rt.length>0){const J=t.currentMarker,W=J?rt.indexOf(J)+1:0;y.textContent=r.stepFormat.replace("{index}",String(W)).replace("{total}",String(rt.length)),y.setAttribute("aria-label",`${r.step} ${W} ${r.of} ${rt.length}`),p.disabled=t.currentTime<=.5,a.disabled=t.currentTime>=D-.5;const I=t.caption()??"";w.textContent!==I&&(w.textContent=I),w.hidden=!c();const z=!T&&J?.question!==void 0&&Math.abs(t.currentTime-J.time)<1;b.hidden=!z,z&&k.textContent!==J.question&&(k.textContent=J.question)}else b.hidden=!0,w.hidden=!0;$?.update()},C=t.subscribe(A);A();const E=n.keyboardScope??e;!E.hasAttribute("tabindex")&&E.tabIndex<0&&(E.tabIndex=0);const N=new WeakSet,G=T=>{if(N.has(T)||(N.add(T),T.defaultPrevented||T.altKey||T.ctrlKey||T.metaKey))return;const D=T.target;if(!(D.tagName==="INPUT"||D.tagName==="SELECT")&&!(T.key===" "&&D.tagName==="BUTTON"))switch(T.key){case" ":T.preventDefault(),t.isPlaying?t.pause():f();break;case"ArrowRight":if(!o())return;T.preventDefault(),t.next();break;case"ArrowLeft":if(!o())return;T.preventDefault(),t.prev();break;case"Home":T.preventDefault(),t.pause(),t.seek(0);break;case"f":case"F":if(!M)return;T.preventDefault(),M.active?M.exit():M.enter();break}};return E.addEventListener("keydown",G),l.addEventListener("keydown",G),{element:l,fullscreen:M&&{get active(){return M.active},enter:M.enter,exit:M.exit},destroy(){M?.destroy(),C(),E.removeEventListener("keydown",G),l.removeEventListener("keydown",G),l.remove()}}}function Zr(t,e,n,i){const r=t.scenarios;if(r.length<2)return;if(i==="slider"){const u=e.createElement("div");u.className="tf-ctl-choice-slider";const d=e.createElement("span");d.textContent=n,d.setAttribute("aria-hidden","true");const p=e.createElement("input");p.type="range",p.min="0",p.max=String(r.length-1),p.step="1",p.setAttribute("aria-label",n);const m=e.createElement("output");return m.setAttribute("aria-hidden","true"),p.addEventListener("input",()=>{const f=r[Number(p.value)];f&&t.setScenario(f.id)}),u.append(d,p,m),{element:u,update:()=>{const f=Math.max(0,r.findIndex(y=>y.id===t.scenario));e.activeElement!==p&&(p.value=String(f));const g=r[f].label;m.textContent!==g&&(m.textContent=g),p.setAttribute("aria-valuetext",g)}}}const s=e.createElement("fieldset");s.className="tf-ctl-choices";const o=e.createElement("legend");o.textContent=n,s.append(o);const c=`tf-ctl-scenario-${++Br}`,l=r.map(u=>{const d=e.createElement("label");d.className="tf-ctl-choice";const p=e.createElement("input");p.type="radio",p.name=c,p.value=u.id,p.addEventListener("change",()=>{p.checked&&t.setScenario(u.id)});const m=e.createElement("span");return m.textContent=u.label,d.append(p,m),s.append(d),p});return{element:s,update:()=>{for(const u of l){const d=u.value===t.scenario;u.checked!==d&&(u.checked=d)}}}}const Qr='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M4 9V4h5M20 9V4h-5M4 15v5h5M20 15v5h-5"/></svg>',Kr='<svg viewBox="0 0 24 24" aria-hidden="true"><path d="M9 4v5H4M15 4v5h5M9 20v-5H4M15 20v-5h5"/></svg>';function Jr(t,e,n){const i=e,r=t,s=e.createElement("button");s.type="button",s.className="tf-ctl-btn tf-ctl-fullscreen";let o,c="";const l=()=>{const f=o!==void 0;s.innerHTML=f?Kr:Qr;const g=f?n.exitFullscreen:n.fullscreen;s.setAttribute("aria-label",g),s.title=g,s.setAttribute("aria-pressed",String(f)),t.classList.toggle("tf-fullscreen",f),t.classList.toggle("tf-fullscreen-overlay",o==="overlay")},h=()=>i.fullscreenElement??i.webkitFullscreenElement??null,u=()=>{h()===t?o="native":o==="native"&&(o=void 0),l()},d=f=>{f.key==="Escape"&&a()},p=()=>{o="overlay",c=e.documentElement.style.overflow,e.documentElement.style.overflow="hidden",e.addEventListener("keydown",d),l()};async function m(){if(o)return;const f=r.requestFullscreen?.bind(r)??r.webkitRequestFullscreen?.bind(r),g=i.fullscreenEnabled??i.webkitFullscreenEnabled??!1;if(f&&g)try{if(await f(),h()===t){o="native",l();return}}catch{}p()}async function a(){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 f=i.exitFullscreen?.bind(i)??i.webkitExitFullscreen?.bind(i);h()===t&&f&&await f()}}return s.addEventListener("click",()=>{o?a():m()}),e.addEventListener("fullscreenchange",u),e.addEventListener("webkitfullscreenchange",u),l(),{button:s,get active(){return o!==void 0},enter:m,exit:a,destroy(){a(),e.removeEventListener("fullscreenchange",u),e.removeEventListener("webkitfullscreenchange",u),s.remove()}}}const xn="tinyfly-choices-style",ts=`
51
+ [data-tinyfly-choose] { cursor: pointer; }
52
+ [data-tinyfly-choose]:focus-visible { outline: 2px solid var(--tf-ctl-accent, #c2410c); outline-offset: 2px; }
53
+ `;function es(t){if(t.getElementById(xn))return;const e=t.createElement("style");e.id=xn,e.textContent=ts,t.head.appendChild(e)}function ns(t,e){const n=Array.from(e.querySelectorAll("[data-tinyfly-choose]"));if(n.length===0)return()=>{};es(e.ownerDocument);const i=[],r=[];for(const c of n){const l=c.getAttribute("data-tinyfly-choose")??"",h=[],u=(a,f)=>{c.hasAttribute(a)||(c.setAttribute(a,f),h.push(a))};u("role","button"),u("tabindex","0");const d=t.scenarios.find(a=>a.id===l)?.label;d!==void 0&&u("aria-label",d),c.setAttribute("aria-pressed","false"),h.push("aria-pressed"),i.push({element:c,attributes:h});const p=()=>t.setScenario(l),m=a=>{const f=a.key;f!=="Enter"&&f!==" "||(a.preventDefault(),p())};c.addEventListener("click",p),c.addEventListener("keydown",m),r.push(()=>{c.removeEventListener("click",p),c.removeEventListener("keydown",m)})}const s=()=>{for(const{element:c}of i)c.setAttribute("aria-pressed",String(c.getAttribute("data-tinyfly-choose")===t.scenario))},o=t.subscribe(s);return s(),()=>{o();for(const c of r)c();for(const{element:c,attributes:l}of i)for(const h of l)c.removeAttribute(h)}}const Sn=new WeakMap,is=new WeakMap;let rs=0;function It(t,e,n){if(t)try{return JSON.parse(t)}catch(i){console.warn(`tinyfly: invalid ${e} JSON on`,n,i);return}}async function ss(t,e={}){const n=Sn.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=as(t.getAttribute("data-markers")),c=i.length>1||r?.hasAttribute("data-scenario")?os(i,o,t):void 0;if(c&&c.length===0)return;let l=r&&!c?It(r.textContent,"timeline",t):void 0;if(!l&&s&&o){const m=await fetch(s);m.ok&&(l=await m.json())}if(l&&o&&(l=$n(l,o)),!l&&!s&&!c){console.warn('tinyfly: embed has no timeline (a <script type="application/json" data-tinyfly-timeline> or data-src)',t);return}const h=It(t.querySelector("script[data-tinyfly-captions]")?.textContent,"captions",t),u={playWhenVisible:!0,...e.player,...h&&{captions:h},...It(t.getAttribute("data-options"),"data-options",t)};cs(t);const d=new Vr(t,u),p={element:t,player:d};if(Sn.set(t,p),t.setAttribute("data-tinyfly-mounted",""),c){const m=t.getAttribute("data-scenario")??void 0;await d.loadScenarios(c,{initial:c.some(a=>a.id===m)?m:void 0}),is.set(t,ns(d,t))}else await d.load(l??s);if(t.getAttribute("data-controls")!=="false"){const m=It(t.getAttribute("data-labels"),"data-labels",t),a=t.querySelector("figcaption"),f=t.getAttribute("data-scenario-legend"),g=t.getAttribute("data-scenario-control");p.controls=Gr(d,t,{...e.controls,...t.getAttribute("data-fullscreen")==="true"?{fullscreen:!0}:{},...g==="slider"||g==="buttons"?{scenarioControl:g}:{},labels:{...e.controls?.labels,...m,...f?{scenario:f}:{}},mount:void 0}),a?t.insertBefore(p.controls.element,a):t.appendChild(p.controls.element)}return p}function os(t,e,n){const i=[];return t.forEach((r,s)=>{const o=It(r.textContent,"timeline",n);if(!o)return;const c=r.getAttribute("data-scenario")||`scenario-${s+1}`;if(i.some(h=>h.id===c)){console.warn(`tinyfly: scenario id "${c}" is used more than once; the later one is skipped`,n);return}const l=r.getAttribute("data-scenario-label")??void 0;i.push({id:c,label:l,timeline:e?$n(o,e):o})}),i}function $n(t,e){return t.config.markers?.length?t:{...t,config:{...t.config,markers:e.map((n,i)=>({id:`step-${i+1}`,time:n}))}}}function as(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 cs(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 ke=["grid","axes","vector","basis","point","function","parametric","polygon","line","label","equation","tangent","riemann","area","taylor"],Gt={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"}}},Lt=[1,0,0,1],Z=([t,e,n,i],[r,s])=>[t*r+e*s,n*r+i*s];function ls(t,e){const[n,i,r,s]=t,[o,c,l,h]=e;return[n*o+i*l,n*c+i*h,r*o+s*l,r*c+s*h]}const Rt=([t,e,n,i])=>t*i-e*n;function us(t){const e=Rt(t);if(Math.abs(e)<1e-12)return;const[n,i,r,s]=t;return[s/e,-i/e,-r/e,n/e]}const hs=(t,e,n)=>t.map((i,r)=>i+(e[r]-i)*n),ds=t=>[Math.cos(t),-Math.sin(t),Math.sin(t),Math.cos(t)];function Tn(t){const[e,n,i,r]=t,s=e+r,o=Rt(t),c=s*s-4*o,l=1e-9;if(c<-l)return[];const h=Math.sqrt(Math.max(0,c)),u=h<l?[s/2]:[(s+h)/2,(s-h)/2],d=[];for(const p of u){const a=[[e-p,n],[i,r-p]].reduce((v,M)=>Math.hypot(...M)>Math.hypot(...v)?M:v);if(Math.hypot(...a)<l){d.push({value:p,vector:[1,0]},{value:p,vector:[0,1]});continue}const f=[-a[1],a[0]],g=Math.hypot(...f),y=f[0]<-l||Math.abs(f[0])<=l&&f[1]<0?-1:1;d.push({value:p,vector:[y*f[0]/g+0,y*f[1]/g+0]})}return d}function kt(t){return Array.isArray(t)&&t.length===4&&t.every(Number.isFinite)}const fs=Object.freeze(Object.defineProperty({__proto__:null,IDENTITY:Lt,apply:Z,determinant:Rt,eigen:Tn,inverse:us,isMat2:kt,lerp:hs,multiply:ls,rotation:ds},Symbol.toStringTag,{value:"Module"})),ps=(t,e)=>[t[0]+e[0],t[1]+e[1]],Me=(t,e)=>[t[0]-e[0],t[1]-e[1]],xe=(t,e)=>[t[0]*e,t[1]*e],ms=(t,e)=>t[0]*e[0]+t[1]*e[1],gs=(t,e)=>t[0]*e[1]-t[1]*e[0],An=t=>Math.hypot(t[0],t[1]);function En(t){const e=An(t);return e===0?[0,0]:[t[0]/e,t[1]/e]}const ys=(t,e,n)=>[t[0]+(e[0]-t[0])*n,t[1]+(e[1]-t[1])*n];function lt(t){return Array.isArray(t)&&t.length===2&&t.every(Number.isFinite)}const bs=Object.freeze(Object.defineProperty({__proto__:null,add:ps,cross:gs,dot:ms,isVec2:lt,length:An,lerp:ys,normalize:En,scale:xe,sub:Me},Symbol.toStringTag,{value:"Module"}));function _n(t){const e={};for(const[n,i]of Object.entries(t))if(typeof i=="number")e[n]=i;else if(kt(i)){const[r,s,o,c]=i;Object.assign(e,{[`${n}.a`]:r,[`${n}.b`]:s,[`${n}.c`]:o,[`${n}.d`]:c,[`${n}.det`]:Rt(i)})}else lt(i)&&Object.assign(e,{[`${n}.x`]:i[0],[`${n}.y`]:i[1],[`${n}.length`]:Math.hypot(i[0],i[1])});return e}function j(t,e,n){return e?Object.prototype.hasOwnProperty.call(t.colors,e)?t.colors[e]:e:n}function Dt(t,e){if(typeof e!="string")return e;const n=t[e];if(!lt(n))throw new Error(`math figure: value "${e}" is not an [x, y] vector`);return n}function pt(t,e){if(e===void 0)return Lt;const n=t[e];if(!kt(n))throw new Error(`math figure: value "${e}" is not a [a, b, c, d] matrix`);return n}function F(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 Se(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:([c,l])=>[(c-i[0])*r,(s[1]-l)*o],toWorld:([c,l])=>[i[0]+c/r,s[1]-l/o]}}const Pn='"Latin Modern Math", "STIX Two Math", "Cambria Math", "Times New Roman", "Liberation Serif", "Noto Serif", Times, serif',On=.25,Ft=.05,Cn={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 $e(t){return t.length!==1?t.length*.5:/[0-9]/.test(t)?.5:Object.prototype.hasOwnProperty.call(Cn,t)?Cn[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 In(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 Ln='system-ui, -apple-system, "Segoe UI", sans-serif',Rn=(t,e)=>Math.hypot(e[0]-t[0],e[1]-t[1]);function ot(t,e){if(e>=1)return t;if(e<=0)return[];const n=t.map(s=>s.slice(1).reduce((o,c,l)=>o+Rn(s[l],c),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 c=[o[0]];for(let l=1;l<o.length;l++){const h=Rn(o[l-1],o[l]);if(h>=i){const u=h===0?0:i/h;c.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}c.push(o[l]),i-=h}r.push(c),i=0}return r}function Te(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 Dn(t,e,n){const[i,r]=e,s=n.size,o=n.opacity??1;return t.map(c=>{const l=c.color??n.color,h=o*(c.opacity??1),u=`${n.idPrefix}${c.id}`;if(c.kind==="glyph")return{type:"text",id:u,text:c.text,x:i+(c.x+c.width/2)*s,y:r+c.y*s,size:c.size*s,font:Pn,italic:c.italic,color:l,align:"center",opacity:h};if(c.kind==="rule"){const d=i+c.x*s,p=r+c.y*s,m=c.width*s,a=Math.max(1,c.height*s);return{type:"line",id:u,points:[[d,p],[d+m,p],[d+m,p+a],[d,p+a]],closed:!0,fill:l,opacity:h}}return{type:"line",id:u,points:c.points.map(([d,p])=>[i+d*s,r+p*s]),stroke:l,width:Math.max(1,c.width*s),opacity:h}})}function Mt(t,e){return Dn(t.pieces,Te(t,e),e)}function vs(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,c=Math.hypot(i,r,s,o),l=c===0?0:Math.abs(Rt(e))/c;return Math.min(n*12,n/Math.max(l,.08))+1}function Fn(t,e,n){const i=vs(t,e),r=Math.min(120,Math.ceil(i/n)),s=[];for(let o=-r;o<=r;o++){const c=o*n;s.push({line:[Z(e,[c,-i]),Z(e,[c,i])].map(t.toScreen),axis:o===0}),s.push({line:[Z(e,[-i,c]),Z(e,[i,c])].map(t.toScreen),axis:o===0})}return s}function ws(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 Fn(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 c=j(i,t.color,i.grid);for(const[l,{line:h,axis:u}]of Fn(n,pt(e.values,t.transform),r).entries()){const[d]=ot([h],e.draw);d&&s.push({type:"line",id:`${t.id}.${l}`,points:d,stroke:u?i.ink:c,width:u?o*1.6:o,opacity:e.opacity})}return s}function ks(t,e){const{plane:n,theme:i}=e,r=j(i,t.color,i.axes),s=2*n.scale,o=e.opacity,c=ot([[n.toScreen([n.x[0],0]),n.toScreen([n.x[1],0])]],e.draw),l=ot([[n.toScreen([0,n.y[0]]),n.toScreen([0,n.y[1]])]],e.draw),h=[...c,...l].map((f,g)=>({type:"line",id:`${t.id}.${g?"y":"x"}`,points:f,stroke:r,width:s,opacity:o})),u=t.ticks??1;if(u<=0||e.draw<1)return h;const d=5*n.scale,p=13*n.scale,m=(f,g)=>{const y=[];for(let v=Math.ceil(f/u)*u;v<=g+1e-9;v+=u)Math.abs(v)>1e-9&&y.push(Number(v.toFixed(6)));return y},a=f=>String(f).replace("-","−");for(const f of m(n.x[0],n.x[1])){const[g,y]=n.toScreen([f,0]);h.push({type:"line",id:`${t.id}.tick.x${f}`,points:[[g,y-d],[g,y+d]],stroke:r,width:s*.8,opacity:o}),t.labels!==!1&&h.push({type:"text",id:`${t.id}.label.x${f}`,text:a(f),x:g,y:y+d+p*1.1,size:p,font:Ln,color:r,align:"center",opacity:o*.8})}for(const f of m(n.y[0],n.y[1])){const[g,y]=n.toScreen([0,f]);h.push({type:"line",id:`${t.id}.tick.y${f}`,points:[[g-d,y],[g+d,y]],stroke:r,width:s*.8,opacity:o}),t.labels!==!1&&h.push({type:"text",id:`${t.id}.label.y${f}`,text:a(f),x:g-d-p*.4,y:y+p*.35,size:p,font:Ln,color:r,align:"right",opacity:o*.8})}return h}const Ae={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:"Ω"},Zt={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"]},Ee={sum:["∑",!0],prod:["∏",!0],int:["∫",!1],oint:["∮",!1]},_e={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},Pe={",":3/18,":":4/18,";":5/18,"!":-3/18,quad:1,qquad:2},Nn=new Set(["pmatrix","bmatrix","vmatrix","matrix"]);class zn 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 jn=[...Object.keys(Ae),...Object.keys(Zt),...Object.keys(Ee),...Object.keys(_e),...Object.keys(Pe).filter(t=>t.length>1),"frac","sqrt","vec","hat","bar","text","color","id","val","begin","end","left","right"].sort();function qn(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 zn(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 p=t.slice(e+1,d);return e=d+1,p},o=u=>{if(n(),e>=t.length&&i(`Missing ${u}`),t[e]==="{"){e++;const p=c("}");return e++,{type:"group",body:p}}const d=l();return d||i(`Missing ${u}`),d},c=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 m=e,a=t[e]==="^";e++;const f=o(a?"superscript":"subscript");let g=d.pop()??{type:"group",body:[]};g.type!=="scripts"&&(g={type:"scripts",base:g}),g.type==="scripts"&&((a&&g.sup||!a&&g.sub)&&i(`Double ${a?"superscript":"subscript"}`,m),a?g.sup=f:g.sub=f),d.push(g);continue}if(t[e]==="'"){e++;const m={type:"symbol",text:"′",cls:"ord",italic:!1},a=d.pop()??{type:"group",body:[]};d.push(a.type==="scripts"&&!a.sup?{...a,sup:m}:{type:"scripts",base:a,sup:m});continue}const p=l();p&&d.push(p)}},l=()=>{const u=t[e];if(u==="{"){e++;const d=c("}");return e++,{type:"group",body:d}}if(u==="&"&&i('"&" outside a matrix'),u==="\\"){const d=e;e++;const p=r();if(p==="\\"&&i('"\\\\" outside a matrix',d),p in Pe)return{type:"space",width:Pe[p]};if(p==="{"||p==="}")return{type:"symbol",text:p,cls:p==="{"?"open":"close",italic:!1};if(p==="|")return{type:"symbol",text:"‖",cls:"ord",italic:!1};if(Object.prototype.hasOwnProperty.call(Ae,p))return{type:"symbol",text:Ae[p],cls:"ord",italic:p[0]===p[0].toLowerCase()};if(Object.prototype.hasOwnProperty.call(Zt,p)){const[a,f]=Zt[p];return{type:"symbol",text:a,cls:f,italic:!1}}if(Object.prototype.hasOwnProperty.call(Ee,p)){const[a,f]=Ee[p];return{type:"bigop",text:a,limits:f}}if(Object.prototype.hasOwnProperty.call(_e,p))return{type:"opname",text:p,limits:_e[p]};switch(p){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:p,body:o(`\\${p}'s body`)};case"text":return{type:"text",text:s("\\text")};case"color":{const a=s("\\color").trim();return/^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+)$/.test(a)||i(`"${a}" is not a colour name or #hex`,d),{type:"color",color:a,body:o("\\color's body")}}case"id":{const a=s("\\id").trim();return/^[\w.-]+$/.test(a)||i(`"${a}" is not a term id (letters, digits, _ . -)`,d),{type:"id",id:a,body:o("\\id's body")}}case"val":{const a=s("\\val").trim(),f=/^([A-Za-z_][\w.]*)(?::(\d))?$/.exec(a);return f||i(`"${a}" is not a value name (name or name:digits)`,d),{type:"value",name:f[1],digits:f[2]===void 0?2:Number(f[2])}}case"left":case"right":{n();const a=t[e]==="\\"?(e++,r()):t[e++];if(a===".")return{type:"space",width:0};const g={"(":"(",")":")","[":"[","]":"]","|":"|","{":"{","}":"}",langle:"⟨",rangle:"⟩","|.":"‖"}[a];return g||i(`"${a}" is not a delimiter`,d),{type:"symbol",text:g,cls:p==="left"?"open":"close",italic:!1}}case"begin":{const a=s("\\begin").trim();Nn.has(a)||i(`Unknown environment "${a}" (use ${[...Nn].join(", ")})`,d);const f=[[]];for(;;){const g=c("cell");if(f[f.length-1].push({type:"group",body:g}),t[e]==="&")e++;else if(t.startsWith("\\\\",e))e+=2,f.push([]);else{e+=4;const y=s("\\end").trim();y!==a&&i(`\\begin{${a}} ended by \\end{${y}}`);break}}return f.length>1&&f[f.length-1].every(g=>g.type==="group"&&g.body.length===0)&&f.pop(),{type:"matrix",delimiters:a,rows:f}}case"end":return i("\\end without \\begin",d)}const m=yn(p,jn);return i(`Unknown command "\\${p}"${m?` (did you mean "\\${m}"?)`:""}`,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:c("")}}const tt=[1,1,.7,.5],Ms=t=>t<=1?2:3,xs=t=>Math.min(3,t+1),Oe=()=>({width:0,height:0,depth:0,pieces:[]});function et(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 xt(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 Xn(t,e,n,i=1,r=t){const s=tt[n.level]*i,o=$e(t)*s,{height:c,depth:l}=In(t);return{width:o,height:c*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:xt(n,r)}]}}function Ce(t,e,n){const i=Oe(),r=xt(e,n),s=tt[e.level];for(const o of t){const c=(o===" "?.28:/[A-Za-z]/.test(o)?$e(o)-.04:$e(o))*s;if(o!==" "){const{height:l,depth:h}=In(o);i.pieces.push({kind:"glyph",text:o,x:i.width,y:0,width:c,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+=c}return i}function Ie(t){switch(t.type){case"symbol":return t.cls;case"bigop":case"opname":return"op";case"scripts":return Ie(t.base);case"id":case"color":return Ie(t.body);default:return"ord"}}function Ss(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 $s(t,e){const n=Oe();let i;return t.forEach(r=>{if(r.type==="space"){n.width+=r.width*tt[e.level];return}let s=Ie(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+=Ss(i,s)/18*tt[e.level]);const o=B(r,e);n.pieces.push(...et(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 Ts(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 B(t,e){const n=tt[e.level];switch(t.type){case"symbol":return Xn(t.text,t.italic,e);case"group":return $s(t.body,e);case"space":return{...Oe(),width:t.width*n};case"text":return Ce(t.text,e,`text:${t.text}`);case"opname":return Ce(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 Ce(Ts(i,t.digits),{...e,id:e.id??`val:${t.name}`},`val:${t.name}`)}case"bigop":return Xn(t.text,!1,e,e.level===0?1.4:1.1);case"color":return B(t.body,{...e,color:t.color});case"id":return B(t.body,{...e,id:t.id});case"scripts":return As(t,e);case"frac":return Es(t,e);case"sqrt":return _s(t,e);case"accent":return Ps(t,e);case"matrix":return Os(t,e)}}function As(t,e){const n=B(t.base,e),i={...e,level:Ms(e.level)},r=t.sup?B(t.sup,i):void 0,s=t.sub?B(t.sub,i):void 0,o=tt[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 m=Math.max(n.width,r?.width??0,s?.width??0),a=et(n,(m-n.width)/2,0);let f=n.height,g=n.depth;const y=.12*o;if(r){const v=-(n.height+y+r.depth);a.push(...et(r,(m-r.width)/2,v)),f=-v+r.height}if(s){const v=n.depth+y+s.height;a.push(...et(s,(m-s.width)/2,v)),g=v+s.depth}return{width:m,height:f,depth:g,pieces:a}}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 m=h-r.depth-(s.height-u);m<.2*o&&(u+=.2*o-m)}const d=n.width+.03*o;let p=n.width;return r?(l.pieces.push(...et(r,d,-h)),l.height=Math.max(l.height,h+r.height),p=Math.max(p,d+r.width)):h=0,s&&(l.pieces.push(...et(s,d,u)),l.depth=Math.max(l.depth,u+s.depth),p=Math.max(p,d+s.width)),l.width=p+.04*o,l}function Es(t,e){const n={...e,level:xs(e.level)},i=B(t.num,n),r=B(t.den,n),s=tt[e.level],o=Ft*s,c=On*s,l=(e.level===0?.16:.1)*s,h=.1*s,u=Math.max(i.width,r.width)+h*2,d=-(c+o/2+l+i.depth),p=-c+o/2+l+r.height;return{width:u,height:-d+i.height,depth:p+r.depth,pieces:[...et(i,(u-i.width)/2,d),{kind:"rule",x:0,y:-c-o/2,width:u,height:o,...e.color?{color:e.color}:{},id:xt(e,"frac")},...et(r,(u-r.width)/2,p)]}}function _s(t,e){const n=B(t.body,e),i=tt[e.level],r=Math.max(n.height,.7*i)+.14*i,s=Math.max(n.depth,.05*i)+.05*i,o=.56*i,c=o+n.width+.08*i,l=[[.02*i,-.36*i],[.13*i,-.44*i],[.3*i,s],[o-.04*i,-r],[c,-r]];return{width:c,height:r+Ft*i,depth:s,pieces:[{kind:"stroke",points:l,width:Ft*i,...e.color?{color:e.color}:{},id:xt(e,"sqrt")},...et(n,o,0)]}}function Ps(t,e){const n=B(t.body,e),i=tt[e.level],r=-(n.height+.12*i),s=.04*i,o=Math.max(n.width-.02*i,s+.3*i),c=e.color?{color:e.color}:{},l=xt(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:Ft*i*.9,...c,id:l}))]}}function Os(t,e){const n={...e,level:Math.max(e.level,1)},i=tt[n.level],r=t.rows.map(k=>k.map(x=>B(x,n))),s=Math.max(...r.map(k=>k.length)),o=Array.from({length:s},(k,x)=>Math.max(0,...r.map($=>$[x]?.width??0))),c=r.map(k=>Math.max(.7*i,...k.map(x=>x.height))),l=r.map(k=>Math.max(.2*i,...k.map(x=>x.depth))),h=.9*i,u=.25*i,d=t.delimiters==="matrix"?0:.55*i,p=o.reduce((k,x)=>k+x,0)+h*(s-1),m=c.reduce((k,x,$)=>k+x+l[$],0)+u*(r.length-1),a=-On*i-m/2,f=[];let g=a;r.forEach((k,x)=>{g+=c[x];let $=d;k.forEach((P,A)=>{f.push(...et(P,$+(o[A]-P.width)/2,g)),$+=o[A]+h}),g+=l[x]+u});const y=p+d*2,v=a+m,M=e.color?{color:e.color}:{},w=(k,x)=>({kind:"stroke",points:k,width:Ft*i*1.1,...M,id:xt(e,x)}),b=.08*i;if(t.delimiters==="pmatrix"){const k=x=>{const $=x===1?d*.75:y-d*.75,P=x*d*.5;return Array.from({length:17},(A,C)=>{const E=C/16;return[$-P*Math.sin(Math.PI*E),a-b+(m+b*2)*E]})};f.push(w(k(1),"("),w(k(-1),")"))}else if(t.delimiters==="bmatrix"){const k=d*.35,x=d*.2,$=y-d*.2;f.push(w([[x+k,a-b],[x,a-b],[x,v+b],[x+k,v+b]],"["),w([[$-k,a-b],[$,a-b],[$,v+b],[$-k,v+b]],"]"))}else t.delimiters==="vmatrix"&&f.push(w([[d*.4,a-b],[d*.4,v+b]],"|"),w([[y-d*.4,a-b],[y-d*.4,v+b]],"|"));return{width:y,height:-a+b,depth:v+b,pieces:f}}function mt(t,e={}){const n=typeof t=="string"?qn(t):t,i={level:e.style==="inline"?1:0,values:e.values??{},counts:new Map},r=B(n,i);return{width:r.width,height:r.height,depth:r.depth,pieces:r.pieces}}function Qt(t,e,n,i,r,s){const o=26*s.plane.scale,[c,l]=En(n),h=mt(t,{values:s.scope,style:"inline"}),u=o*(.55+Math.abs(c)*h.width*.5);return Mt(h,{x:e[0]+c*u,y:e[1]+l*u,size:o,color:i,opacity:s.opacity,idPrefix:`${r}.label.`})}function Yn(t,e,n,i,r,s){const o=s.plane.toScreen(e),c=s.plane.toScreen(n),[l]=ot([[o,c]],s.draw);if(!l)return[];const h=Math.hypot(c[0]-o[0],c[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 Cs(t,e){const n=pt(e.values,t.transform),i=Z(n,t.from===void 0?[0,0]:Dt(e.values,t.from)),r=Z(n,Dt(e.values,t.to)),s=j(e.theme,t.color,e.theme.colors.yellow),o=Yn(t.id,i,r,s,(t.width??4)*e.plane.scale,e);if(t.label&&e.draw>=1){const c=e.plane.toScreen(r),l=e.plane.toScreen(i),h=Me(c,l);if(t.labelAt==="middle"){const u=[(c[0]+l[0])/2,(c[1]+l[1])/2];o.push(...Qt(t.label,u,[h[1],-h[0]],s,t.id,e))}else o.push(...Qt(t.label,c,h,s,t.id,e))}return o}function Is(t,e){const n=pt(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[c,l,h,u]of o){const d=Z(n,l);if(s.push(...Yn(`${t.id}.${c}`,[0,0],d,h,i,e)),t.labels!==!1&&e.draw>=1){const p=e.plane.toScreen(d);s.push(...Qt(u,p,Me(p,r),h,`${t.id}.${c}`,e))}}return s}function Ls(t,e){const n=t.on!==void 0?[e.scope[`${t.id}.x`],e.scope[`${t.id}.y`]]:Dt(e.values,t.at);if(!Number.isFinite(n[0])||!Number.isFinite(n[1]))return[];const i=Z(pt(e.values,t.transform),n),[r,s]=e.plane.toScreen(i),o=j(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:r,y:s,r:c,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:c,fill:o,opacity:e.opacity},h=c>0?[l]:[];return t.label&&e.draw>=1&&h.push(...Qt(t.label,[r,s],[.7,-.7],o,t.id,e)),h}const Kt={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)}},Nt={pi:Math.PI,e:Math.E,tau:Math.PI*2};class gt 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 Rs(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 gt(`Unexpected "${i}"`,t,n)}return e.push({kind:"end",at:t.length}),e}function zt(t){if(typeof t!="string")throw new TypeError("parseExpression: expected a string");const e=Rs(t);let n=0;const i=()=>e[n],r=p=>{const m=i();return m.kind==="op"&&m.value===p},s=p=>{if(!r(p))throw new gt(`Expected "${p}"`,t,i().at);n++},o=()=>{let p=c();for(;r("+")||r("-");)p={type:"binary",operator:e[n++].value,left:p,right:c()};return p},c=()=>{let p=l();for(;;)if(r("*")||r("/"))p={type:"binary",operator:e[n++].value,left:p,right:l()};else if(i().kind==="name"||i().kind==="number"||r("("))p={type:"binary",operator:"*",left:p,right:h()};else return p},l=()=>r("-")||r("+")?{type:"unary",operator:e[n++].value,operand:l()}:h(),h=()=>{const p=u();return r("^")?(n++,{type:"binary",operator:"^",left:p,right:l()}):p},u=()=>{const p=i();if(p.kind==="number")return n++,{type:"number",value:p.value};if(p.kind==="name"){if(n++,!r("("))return{type:"name",name:p.value};const m=Object.prototype.hasOwnProperty.call(Kt,p.value)?Kt[p.value]:void 0;if(!m)throw new gt(`Unknown function "${p.value}"`,t,p.at);n++;const a=[];if(!r(")"))for(a.push(o());r(",");)n++,a.push(o());if(s(")"),a.length!==m.arity)throw new gt(`"${p.value}" takes ${m.arity} argument${m.arity===1?"":"s"}, got ${a.length}`,t,p.at);return{type:"call",name:p.value,args:a}}if(r("(")){n++;const m=o();return s(")"),m}throw new gt(p.kind==="end"?"Unexpected end":`Unexpected "${p.value}"`,t,p.at)},d=o();if(i().kind!=="end")throw new gt(`Unexpected "${i().value}"`,t,i().at);return d}function Vn(t){const e=new Set,n=i=>{i.type==="name"&&!(i.name in Nt)?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 _=t=>({type:"number",value:t}),jt=_(0),L=_(1),q=t=>t.type==="number",H=(t,e)=>t.type==="number"&&t.value===e;function ut(t,e){return q(t)&&q(e)?_(t.value+e.value):H(t,0)?e:H(e,0)?t:{type:"binary",operator:"+",left:t,right:e}}function nt(t,e){return q(t)&&q(e)?_(t.value-e.value):H(e,0)?t:H(t,0)?Jt(e):{type:"binary",operator:"-",left:t,right:e}}function O(t,e){return q(t)&&q(e)?_(t.value*e.value):H(t,0)||H(e,0)?jt:H(t,1)?e:H(e,1)?t:q(e)?O(e,t):q(t)&&e.type==="binary"&&e.operator==="*"&&q(e.left)?O(_(t.value*e.left.value),e.right):{type:"binary",operator:"*",left:t,right:e}}function X(t,e){return H(t,0)?jt:H(e,1)?t:q(t)&&q(e)&&e.value!==0?_(t.value/e.value):{type:"binary",operator:"/",left:t,right:e}}function at(t,e){return H(e,0)?L:H(e,1)?t:q(t)&&q(e)?_(t.value**e.value):{type:"binary",operator:"^",left:t,right:e}}function Jt(t){return q(t)?_(-t.value):t.type==="unary"&&t.operator==="-"?t.operand:{type:"unary",operator:"-",operand:t}}const Y=(t,...e)=>({type:"call",name:t,args:e});function yt(t,e){switch(t.type){case"number":return!0;case"name":return t.name!==e;case"unary":return yt(t.operand,e);case"binary":return yt(t.left,e)&&yt(t.right,e);case"call":return t.args.every(n=>yt(n,e))}}function it(t,e="x"){if(yt(t,e))return jt;switch(t.type){case"number":return jt;case"name":return t.name===e?L:jt;case"unary":return t.operator==="-"?Jt(it(t.operand,e)):it(t.operand,e);case"binary":{const{left:n,right:i}=t,r=()=>it(n,e),s=()=>it(i,e);switch(t.operator){case"+":return ut(r(),s());case"-":return nt(r(),s());case"*":return ut(O(r(),i),O(n,s()));case"/":return X(nt(O(r(),i),O(n,s())),at(i,_(2)));case"^":if(yt(i,e)){const o=q(i)?_(i.value-1):nt(i,L);return O(O(i,at(n,o)),r())}return yt(n,e)?O(O(t,Y("ln",n)),s()):O(t,ut(O(s(),Y("ln",n)),X(O(i,r()),n)))}break}case"call":{const[n,i]=t.args,r=()=>it(n,e),s=o=>O(o,r());switch(t.name){case"sin":return s(Y("cos",n));case"cos":return s(Jt(Y("sin",n)));case"tan":return s(X(L,at(Y("cos",n),_(2))));case"asin":return s(X(L,Y("sqrt",nt(L,at(n,_(2))))));case"acos":return s(Jt(X(L,Y("sqrt",nt(L,at(n,_(2)))))));case"atan":return s(X(L,ut(L,at(n,_(2)))));case"sinh":return s(Y("cosh",n));case"cosh":return s(Y("sinh",n));case"tanh":return s(nt(L,at(Y("tanh",n),_(2))));case"exp":return s(t);case"ln":return s(X(L,n));case"log":return s(X(L,O(n,_(Math.LN10))));case"log2":return s(X(L,O(n,_(Math.LN2))));case"sqrt":return s(X(L,O(_(2),t)));case"abs":return s(Y("sign",n));case"sigmoid":return s(O(t,nt(L,t)));case"relu":return s(X(ut(Y("sign",n),L),_(2)));case"atan2":{const o=it(i,e);return X(nt(O(i,r()),O(n,o)),ut(at(n,_(2)),at(i,_(2))))}case"min":case"max":{const o=t.name==="max"?1:-1,c=it(i,e),l=X(ut(L,O(_(o),Y("sign",nt(n,i)))),_(2));return ut(O(l,r()),O(nt(L,l),c))}}throw new Error(`differentiate: "${t.name}" has no derivative rule`)}}throw new Error("differentiate: malformed expression")}function Wn(t,e,n="x"){let i=t;for(let r=0;r<e;r++)i=it(i,n);return i}function qt(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}${qt(t.operand)})`;case"binary":return`(${qt(t.left)} ${t.operator} ${qt(t.right)})`;case"call":return`${t.name}(${t.args.map(qt).join(", ")})`}}function bt(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(Nt,t.name))return Nt[t.name];throw new Error(`evaluate: unknown name "${t.name}"`)}case"unary":{const n=bt(t.operand,e);return t.operator==="-"?-n:n}case"binary":{const n=bt(t.left,e),i=bt(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 Kt[t.name].apply(...t.args.map(n=>bt(n,e)))}throw new Error("evaluate: malformed expression")}const te=new Map;function V(t,e="x"){let n=te.get(t);n||(n=zt(t),te.size<256&&te.set(t,n));const i=n;return(r,s={})=>bt(i,{...s,[e]:r})}const Le=new Map;function ee(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=Le.get(i);if(!r){let o=te.get(t);o||(o=zt(t)),r=Wn(o,e,n),Le.size<512&&Le.set(i,r)}const s=r;return(o,c={})=>bt(s,{...c,[n]:o})}const ne=480;function Un(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 Bn(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 Hn(t,e,n,i,r,s){return ot(e,r.draw).map((o,c)=>({type:"line",id:`${t}.${c}`,points:o,stroke:n,width:i,opacity:r.opacity,...s?{dash:s}:{}}))}function Gn(t,e,n,i,r,s,o,c){const l=Array.from({length:ne+1},(h,u)=>{const d=n+(i-n)*u/ne;return Bn(o.plane.toScreen([d,e(d)]),o)});return Hn(t,Un(l,o.plane.height),r,s,o,c)}function Ds(t,e){const n=t.derivative?ee(t.expr,t.derivative):V(t.expr,"x"),[i,r]=t.domain??e.plane.x,s=j(e.theme,t.color,e.theme.colors.blue),o=t.dashed?[10*e.plane.scale,8*e.plane.scale]:void 0;return Gn(t.id,c=>n(c,e.scope),i,r,s,(t.width??3.5)*e.plane.scale,e,o)}function Fs(t,e){const n=V(t.x,"t"),i=V(t.y,"t"),r=pt(e.values,t.transform),[s,o]=t.t??[0,Math.PI*2],c=Array.from({length:ne+1},(h,u)=>{const d=s+(o-s)*u/ne;return Bn(e.plane.toScreen(Z(r,[n(d,e.scope),i(d,e.scope)])),e)}),l=j(e.theme,t.color,e.theme.colors.blue);return Hn(t.id,Un(c,e.plane.height),l,(t.width??3.5)*e.plane.scale,e)}const Ns=[[0,0],[1,0],[1,1],[0,1]];function zs(t,e){const n=pt(e.values,t.transform),i=(t.points??Ns).map(c=>Z(n,c)),r=i.map(e.plane.toScreen),s=j(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},...ot([[...r,r[0]]],e.draw).map(c=>({type:"line",id:`${t.id}.outline`,points:c,stroke:s,width:2.5*e.plane.scale,opacity:e.opacity}))];if(t.label&&e.draw>=1){const c=i.reduce((u,d)=>[u[0]+d[0]/i.length,u[1]+d[1]/i.length],[0,0]),[l,h]=e.plane.toScreen(c);o.push(...Mt(mt(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 js(t,e){const n=t.eigen?Tn(pt(e.values,t.eigen)).map(o=>o.vector):t.along!==void 0?[Dt(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=j(e.theme,t.color,e.theme.colors.yellow),s=(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 h=xe(o,i/l),u=[xe(h,-1),h].map(e.plane.toScreen);return ot([u],e.draw).map(d=>({type:"line",id:`${t.id}.${c}`,points:d,stroke:r,width:s,opacity:e.opacity,...t.dashed?{dash:[10*e.plane.scale,8*e.plane.scale]}:{}}))})}const Q=(t,e,n)=>t+(e-t)*n;function Zn(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 qs(t,e,n){if(t.kind==="glyph"&&e.kind==="glyph"&&t.text===e.text)return{...e,x:Q(t.x,e.x,n),y:Q(t.y,e.y,n),width:Q(t.width,e.width,n),size:Q(t.size,e.size,n)};if(t.kind==="rule"&&e.kind==="rule")return{...e,x:Q(t.x,e.x,n),y:Q(t.y,e.y,n),width:Q(t.width,e.width,n),height:Q(t.height,e.height,n)};if(t.kind==="stroke"&&e.kind==="stroke"&&t.points.length===e.points.length)return{...e,width:Q(t.width,e.width,n),points:t.points.map(([i,r],s)=>[Q(i,e.points[s][0],n),Q(r,e.points[s][1],n)])}}const Xs=t=>t*t*(3-2*t);function Qn(t,e,n){const i=Math.min(1,Math.max(0,n)),r=t.layout.pieces.map(m=>Zn(m,t.x,t.y)),s=e.layout.pieces.map(m=>Zn(m,e.x,e.y));if(i===0)return r.map(m=>({...m,opacity:1}));if(i===1)return s.map(m=>({...m,opacity:1}));const o=m=>{const a=new Map;for(const f of m)a.set(f.id,[...a.get(f.id)??[],f]);return a},c=o(r),l=o(s),h=[],u=Xs(i),d=Math.max(0,1-i*2),p=Math.max(0,i*2-1);for(const m of new Set([...c.keys(),...l.keys()])){const a=c.get(m)??[],f=l.get(m)??[],g=Math.max(a.length,f.length);for(let y=0;y<g;y++){const v=a[y],M=f[y],w=v&&M?qs(v,M,u):void 0;if(w){h.push({...w,opacity:1});continue}v&&h.push({...v,opacity:d}),M&&h.push({...M,opacity:p})}}return h.filter(m=>m.opacity>0)}function Re(t,e,n,i){const r=n.size*.35;let s=1/0,o=1/0,c=-1/0,l=-1/0;for(const h of e){const[u,d]=Te(h,n);s=Math.min(s,u-r),c=Math.max(c,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],[c,o],[c,l],[s,l]],closed:!0,fill:i.theme.background,opacity:(n.opacity??1)*.85}]}function Kn(t,e,n){const i=Dt(n.values,t);return e?i:n.plane.toScreen(i)}function Ys(t,e){const[n,i]=Kn(t.at,t.screen,e),r=(t.size??28)*e.plane.scale,s=j(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}.`},c=mt(t.tex,{values:e.scope});return[...t.backdrop??t.screen??!1?Re(t.id,[c],o,e):[],...Mt(c,o)]}function Vs(t,e){const[n,i]=Kn(t.at,t.screen,e),r=(t.size??36)*e.plane.scale,s=j(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),h=c-l,u={x:n,y:i,size:r,color:s,align:t.align,opacity:e.opacity*e.draw,idPrefix:`${t.id}.`},d=g=>mt(t.steps[g],{values:e.scope}),p=t.backdrop??t.screen??!1;if(h===0||l>=o){const g=d(l);return[...p?Re(t.id,[g],u,e):[],...Mt(g,u)]}const m=g=>{const[y,v]=Te(g,u);return{layout:g,x:y/r,y:v/r}},a=d(l),f=d(l+1);return[...p?Re(t.id,[a,f],u,e):[],...Dn(Qn(m(a),m(f),h),[0,0],u)]}function De(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 Jn(t,e,n,i,r){const s=(n-e)/i;return Array.from({length:i},(o,c)=>{const l=e+c*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 ti=t=>Math.min(400,Math.max(1,Math.round(t)));function ei(t,e,n){const i={},r={...n};for(const s of t)switch(s.kind){case"tangent":{const o=V(s.expr),c=F(e,s.at),l=s.h===void 0?0:F(e,s.h),h=Math.abs(l)>1e-9?(o(c+l,r)-o(c,r))/l:ee(s.expr,1)(c,r);Object.assign(i,{[`${s.id}.slope`]:h,[`${s.id}.x`]:c,[`${s.id}.y`]:o(c,r)});break}case"riemann":{const o=V(s.expr),c=F(e,s.from),l=F(e,s.to),h=ti(F(e,s.n)),d=Jn(p=>o(p,r),c,l,h,s.rule??"left").reduce((p,[m,a,f,g])=>p+(f+g)/2*(a-m),0);Object.assign(i,{[`${s.id}.sum`]:d,[`${s.id}.exact`]:De(p=>o(p,r),c,l),[`${s.id}.n`]:h});break}case"area":{const o=V(s.expr),c=s.lower?V(s.lower):()=>0;i[`${s.id}.value`]=De(l=>o(l,r)-c(l,r),F(e,s.from),F(e,s.to));break}case"point":if(s.on!==void 0&&s.x!==void 0){const o=F(e,s.x);Object.assign(i,{[`${s.id}.x`]:o,[`${s.id}.y`]:V(s.on)(o,r)})}break;case"taylor":i[`${s.id}.order`]=Math.min(20,Math.max(0,F(e,s.order))),i[`${s.id}.degree`]=Math.floor(i[`${s.id}.order`]);break}return i}function Ws(t,e){const n=V(t.expr),i=F(e.values,t.at),r=t.h===void 0?0:F(e.values,t.h),s=n(i,e.scope),o=e.scope[`${t.id}.slope`];if(!Number.isFinite(s)||!Number.isFinite(o))return[];const c=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-c,s-o*c],[i+c,s+o*c]],h=j(e.theme,t.color,e.theme.colors.yellow),u=e.plane.toScreen([i,s]),d=l.map(e.plane.toScreen),p=[d[0],d[1]].flatMap((m,a)=>ot([[u,m]],e.draw).map(f=>({type:"line",id:`${t.id}.${a}`,points:f,stroke:h,width:(t.width??3)*e.plane.scale,opacity:e.opacity})));if(t.points!==!1){const m=6*e.plane.scale;if(p.push({type:"circle",id:`${t.id}.point`,x:u[0],y:u[1],r:m,fill:h,opacity:e.opacity}),Math.abs(r)>1e-9){const[a,f]=e.plane.toScreen([i+r,n(i+r,e.scope)]);Number.isFinite(f)&&p.push({type:"circle",id:`${t.id}.secant`,x:a,y:f,r:m,fill:h,opacity:e.opacity})}}if(t.label&&e.draw>=1){const m=24*e.plane.scale,a=mt(t.label,{values:e.scope,style:"inline"});p.push(...Mt(a,{x:u[0],y:u[1]-m*1.6,size:m,color:h,opacity:e.opacity,idPrefix:`${t.id}.label.`}))}return p}function Us(t,e){const n=V(t.expr),i=F(e.values,t.from),r=F(e.values,t.to),s=ti(F(e.values,t.n)),o=Jn(u=>n(u,e.scope),i,r,s,t.rule??"left"),c=j(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,p,m],a)=>{if(!Number.isFinite(p)||!Number.isFinite(m))return[];const f=[[u,0],[d,0],[d,m],[u,p]].map(e.plane.toScreen),y=(p+m)/2<0?j(e.theme,"red",e.theme.colors.red):c;return[{type:"line",id:`${t.id}.${a}`,points:f,closed:!0,fill:y,stroke:y,width:h,opacity:e.opacity*(t.fillOpacity??.35)}]})}function Bs(t,e){const n=V(t.expr),i=t.lower?V(t.lower):()=>0,r=F(e.values,t.from),s=r+(F(e.values,t.to)-r)*e.draw;if(r===s)return[];const o=240,c=j(e.theme,t.color,e.theme.colors.blue),l=j(e.theme,t.negativeColor,e.theme.colors.red),h=e.opacity*(t.fillOpacity??.4),u=[];let d=[],p=[],m;const a=()=>{d.length>=2&&u.push({type:"line",id:`${t.id}.${u.length}`,points:[...d,...p.reverse()].map(e.plane.toScreen),closed:!0,fill:m?c:l,opacity:h}),d=[],p=[]};let f;for(let g=0;g<=o;g++){const y=r+(s-r)*g/o,v=n(y,e.scope),M=i(y,e.scope);if(!Number.isFinite(v)||!Number.isFinite(M)){a(),f=void 0;continue}const w=v-M>=0;if(f&&m!==void 0&&w!==m){const b=f.fy-f.gy,k=v-M,x=b/(b-k),$=f.x+(y-f.x)*x,P=f.gy+(M-f.gy)*x;d.push([$,P]),p.push([$,P]),a(),d.push([$,P]),p.push([$,P])}m=w,d.push([y,v]),p.push([y,M]),f={x:y,fy:v,gy:M}}return a(),u}const Hs=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 Gs(t,e){const n=F(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,p)=>ee(t.expr,p)(n,e.scope)/Hs[p]),c=d=>{let p=0,m=1;for(let a=0;a<=r;a++)p+=o[a]*m,m*=d-n;return s>0&&r<20?p+s*o[r+1]*m:p},l=j(e.theme,t.color,e.theme.colors.yellow),[h,u]=t.domain??e.plane.x;return Gn(t.id,d=>c(d),h,u,l,(t.width??3.5)*e.plane.scale,e)}function Zs(t,e){switch(t.kind){case"grid":return ws(t,e);case"axes":return ks(t,e);case"vector":return Cs(t,e);case"basis":return Is(t,e);case"point":return Ls(t,e);case"function":return Ds(t,e);case"parametric":return Fs(t,e);case"polygon":return zs(t,e);case"line":return js(t,e);case"label":return Ys(t,e);case"equation":return Vs(t,e);case"tangent":return Ws(t,e);case"riemann":return Us(t,e);case"area":return Bs(t,e);case"taylor":return Gs(t,e)}}const ni=t=>Math.min(1,Math.max(0,t));function Xt(t,e={}){const n=Gt[t.theme??"dark"],i=Se(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=_n(r),c={...o,...ei(t.items,r,o)},l=[];for(const u of t.items){const d=a=>s.get(`${u.id}.${a}`),p=ni(d("draw")??u.draw??1),m=ni(d("opacity")??u.opacity??1);p<=0||m<=0||l.push(...Zs(u,{plane:i,theme:n,values:r,scope:c,draw:p,opacity:m,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 Qs=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 St(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 f=t[a];f!==void 0&&!(Array.isArray(f)&&f.length===2&&f.every(Number.isFinite)&&f[0]<f[1])&&e(`${a} must be [min, max] with min < max`)}t.theme!==void 0&&!(t.theme in Gt)&&e(ft("theme",t.theme,Object.keys(Gt))),Array.isArray(t.items)||e("items must be an array");const n=t.values??{};for(const[a,f]of Object.entries(n))/^[A-Za-z_]\w*$/.test(a)||e(`value name "${a}" must be letters, digits and _ (starting with a letter)`),Qs.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 f=="number"&&Number.isFinite(f)||lt(f)||kt(f)||e(`value "${a}" must be a number, an [x, y] vector or an [a, b, c, d] matrix`);const i=_n(n),r=Object.keys(n).filter(a=>typeof n[a]=="number"),s=(a,f,g)=>{g!==void 0&&(typeof g=="string"?(g in n||e(`${a.id}.${f}: ${ft("value",g,Object.keys(n))}`),lt(n[g])||e(`${a.id}.${f}: value "${g}" is not an [x, y] vector`)):lt(g)||e(`${a.id}.${f} must be [x, y] or the name of a vector value`))},o=(a,f,g)=>{g!==void 0&&(g in n||e(`${a.id}.${f}: ${ft("value",g,Object.keys(n))}`),kt(n[g])||e(`${a.id}.${f}: value "${g}" is not an [a, b, c, d] matrix`))},c=(a,f,g,y)=>{let v=[];try{v=Vn(zt(g))}catch(M){e(`${a.id}.${f}: ${M.message}`)}for(const M of v)M!==y&&!(M in Nt)&&!r.includes(M)&&e(`${a.id}.${f}: "${M}" is neither ${y} nor a number value (${ft("value",M,[y,...r])})`)},l=[],h=(a,f,g)=>{l.push([a,f,g])},u=(a,f,g)=>{g!==void 0&&(typeof g=="string"?(g in n||e(`${a.id}.${f}: ${ft("value",g,r)}`),typeof n[g]!="number"&&e(`${a.id}.${f}: value "${g}" is not a number`)):Number.isFinite(g)||e(`${a.id}.${f} must be a number or the name of a number value`))},d=(a,f,g,y)=>{try{let v=zt(g);for(let M=0;M<y;M++)v=it(v)}catch(v){e(`${a.id}.${f}: ${v.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"),ke.includes(a.kind)||e(ft("item kind",a.kind,ke)),(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":s(a,"to",a.to),s(a,"from",a.from),o(a,"transform",a.transform),a.label&&h(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"),u(a,"x",a.x)),s(a,"at",a.at),o(a,"transform",a.transform),a.label&&h(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`),d(a,"expr",a.expr,a.derivative));break;case"tangent":c(a,"expr",a.expr,"x"),d(a,"expr",a.expr,1),u(a,"at",a.at),u(a,"h",a.h),a.label&&h(a,"label",a.label);break;case"riemann":c(a,"expr",a.expr,"x"),u(a,"from",a.from),u(a,"to",a.to),u(a,"n",a.n),a.rule!==void 0&&!["left","right","midpoint","trapezoid"].includes(a.rule)&&e(`${a.id}.rule: ${ft("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"),u(a,"from",a.from),u(a,"to",a.to);break;case"taylor":c(a,"expr",a.expr,"x"),d(a,"expr",a.expr,3),u(a,"at",a.at),u(a,"order",a.order);break;case"parametric":c(a,"x",a.x,"t"),c(a,"y",a.y,"t"),o(a,"transform",a.transform);break;case"polygon":a.points!==void 0&&!(Array.isArray(a.points)&&a.points.length>=3&&a.points.every(lt))&&e(`${a.id}.points must be three or more [x, y] points`),o(a,"transform",a.transform),a.label&&h(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`),s(a,"along",a.along),o(a,"eigen",a.eigen);break;case"label":s(a,"at",a.at),h(a,"tex",a.tex);break;case"equation":s(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((f,g)=>h(a,`steps[${g}]`,f));break}const m={...i,...ei(t.items,n,i)};for(const[a,f,g]of l)try{mt(g,{values:m})}catch(y){e(`${a.id}.${f}: ${y.message}`)}return t}function ii(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 c=r/o,l=s/o,h=Math.min(e,o),u=[n[0]-c*h,n[1]-l*h],d=h*.55;return{shaft:[...t.slice(0,-1),u],head:[n,[u[0]-l*d,u[1]+c*d],[u[0]+l*d,u[1]-c*d]]}}const R=t=>String(Math.round(t*100)/100),K=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),Fe=(t,e=!1)=>t.map(([n,i],r)=>`${r?"L":"M"}${R(n)} ${R(i)}`).join("")+(e?"Z":""),ie=t=>t.opacity!==void 0&&t.opacity<1?` opacity="${R(t.opacity)}"`:"";function Ks(t){switch(t.type){case"line":{if(t.points.length<2)return"";const e=t.fill?` fill="${K(t.fill)}"`:' fill="none"',n=t.stroke&&(t.width??1)>0?` stroke="${K(t.stroke)}" stroke-width="${R(t.width??1)}"`:"",i=t.dash?.length?` stroke-dasharray="${t.dash.map(R).join(" ")}"`:"";return`<path d="${Fe(t.points,t.closed)}"${e}${n}${i}${ie(t)}/>`}case"arrow":{const{shaft:e,head:n}=ii(t.points,t.head),i=K(t.stroke),r=e.length>=2?`<path d="${Fe(e)}" fill="none" stroke="${i}" stroke-width="${R(t.width)}"/>`:"",s=n?`<path d="${Fe(n,!0)}" fill="${i}"/>`:"";return`<g${ie(t)}>${r}${s}</g>`}case"circle":{const e=t.fill?` fill="${K(t.fill)}"`:' fill="none"',n=t.stroke?` stroke="${K(t.stroke)}" stroke-width="${R(t.width??1)}"`:"";return`<circle cx="${R(t.x)}" cy="${R(t.y)}" r="${R(t.r)}"${e}${n}${ie(t)}/>`}case"text":{const e=t.align==="center"?"middle":t.align==="right"?"end":"start",n=t.italic?' font-style="italic"':"";return`<text x="${R(t.x)}" y="${R(t.y)}" font-size="${R(t.size)}" font-family="${K(t.font)}"${n} text-anchor="${e}" fill="${K(t.color)}"${ie(t)}>${K(t.text)}</text>`}}}function re(t){return`${t.background?`<rect width="${R(t.width)}" height="${R(t.height)}" fill="${K(t.background)}"/>`:""}<g stroke-linecap="round" stroke-linejoin="round">${t.shapes.map(Ks).join("")}</g>`}function ri(t,e={}){const n=e.title?`<title>${K(e.title)}</title>`:"",i=e.title?` role="img" aria-label="${K(e.title)}"`:"";return`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${R(t.width)} ${R(t.height)}" width="${R(t.width)}" height="${R(t.height)}"${i}>${n}${re(t)}</svg>`}const Js="http://www.w3.org/2000/svg",Ne=new WeakMap;function to(t,e){const n=t?.values.get(e);return n?Object.fromEntries(n):{}}async function si(t,e={}){const n=Ne.get(t);if(n)return n;const i=t.querySelector("script[data-tinyfly-figure]");let r;try{r=St(JSON.parse(i?.textContent??"null"))}catch(p){console.warn("tinyfly: math figure is missing or invalid",t,p);return}const s=t.getAttribute("data-target")??"fig";let o=t.querySelector("svg[data-tinyfly-math-svg]");o||(o=t.ownerDocument.createElementNS(Js,"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 c=p=>{o.innerHTML=re(Xt(r,p))};if(c({}),!(t.querySelector("script[data-tinyfly-timeline]")||t.hasAttribute("data-src"))){const p={element:t,figure:r,redraw:()=>c({})};return Ne.set(t,p),p}const h=await ss(t,e);if(!h)return;const u=()=>c(to(h.player.state,s));h.player.subscribe(u),u();const d={...h,figure:r,redraw:u};return Ne.set(t,d),d}async function oi(t=document,e={}){const n=Array.from(t.querySelectorAll("[data-tinyfly-math]"));return(await Promise.all(n.map(r=>si(r,e)))).filter(r=>r!==void 0)}function eo(){if(!(typeof document<"u"?document.currentScript:null)?.hasAttribute("data-tinyfly-auto"))return;const e=()=>{oi()};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",e,{once:!0}):e()}function ze(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 no(t,e){switch(t.globalAlpha=e.opacity??1,e.type){case"line":if(e.points.length<2)return;ze(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}=ii(e.points,e.head);t.strokeStyle=e.stroke,t.fillStyle=e.stroke,t.lineWidth=e.width,n.length>=2&&(ze(t,n),t.stroke()),i&&(ze(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 ai(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)no(t,n);t.restore()}function ci(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 io(t,e={}){St(t);const n=ci(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){ai(r,Xt(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 ro(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 c={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}),c},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 c.toValue(u,l,{duration:1600,...d})},drawOn(l,h){return s(l),t.to(e,{[`${l}.draw`]:1},{duration:900,...h}),c},fadeIn(l,h){return s(l),t.set(e,{[`${l}.draw`]:1,[`${l}.opacity`]:0}),t.to(e,{[`${l}.opacity`]:1},{duration:500,...h}),c},fadeOut(l,h){return s(l),t.to(e,{[`${l}.opacity`]:0},{duration:500,...h}),c},showStep(l,h,u){return s(l),t.to(e,{[`${l}.step`]:h},{duration:900,...u}),c}};return c}const so="http://www.w3.org/2000/svg";function oo(t,e,n={}){St(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&&!lt(i[w.vector]))throw new Error(`mathExplorable: "${w.vector}" is not a vector value of the figure`);if("matrix"in w&&!kt(i[w.matrix]))throw new Error(`mathExplorable: "${w.matrix}" is not a matrix value of the figure`)}const r=Se(e),s=t.ownerDocument,o=s.createElementNS(so,"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 i[w.vector];const[b,k,x,$]=i[w.matrix];return w.column===0?[b,x]:[k,$]},h=()=>{const w=c.map(b=>{const[k,x]=r.toScreen(l(b));return`<circle cx="${k}" cy="${x}" 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=re(Xt(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),p.get(w).textContent=String(b)),h()},d=new Map,p=new Map;let m;if(n.sliders?.length){m=s.createElement("div"),m.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 x=s.createElement("output");x.textContent=String(i[w.value]),k.addEventListener("input",()=>u(w.value,Number(k.value))),b.append(w.label??w.value,k,x),m.appendChild(b),d.set(w.value,k),p.set(w.value,x)}t.appendChild(m)}const a=n.snap??.1,f=w=>{const b=o.getBoundingClientRect(),k=(w.clientX-b.left)/(b.width||e.width)*e.width,x=(w.clientY-b.top)/(b.height||e.height)*e.height,[$,P]=r.toWorld([k,x]),A=C=>a>0?Math.round(C/a)*a:C;return[Number(A($).toFixed(6)),Number(A(P).toFixed(6))]};let g;const y=w=>{const b=o.getBoundingClientRect(),k=e.width/(b.width||e.width),x=[(w.clientX-b.left)*k,(w.clientY-b.top)*k];let $;for(const P of c){const[A,C]=r.toScreen(l(P)),E=Math.hypot(A-x[0],C-x[1]);E<30*r.scale*Math.max(1,k)&&(!$||E<$.distance)&&($={handle:P,distance:E})}$&&(g=$.handle,o.setPointerCapture?.(w.pointerId),w.preventDefault())},v=w=>{if(!g)return;const[b,k]=f(w);if("vector"in g)u(g.vector,[b,k]);else{const[x,$,P,A]=i[g.matrix];u(g.matrix,g.column===0?[b,$,k,A]:[x,b,P,k])}},M=()=>{g=void 0};return o.addEventListener("pointerdown",y),o.addEventListener("pointermove",v),o.addEventListener("pointerup",M),o.addEventListener("pointercancel",M),h(),{get values(){return{...i}},set:u,destroy(){o.removeEventListener("pointerdown",y),o.removeEventListener("pointermove",v),o.removeEventListener("pointerup",M),o.removeEventListener("pointercancel",M),m?.remove()}}}const Yt=(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}),se="\\begin{bmatrix} \\val{M.a} & \\val{M.b} \\\\ \\val{M.c} & \\val{M.d} \\end{bmatrix}",je=t=>[(t.width??600)*.05,(t.height??600)*.1];function ao(t={}){return Yt(t,{M:t.matrix??Lt},[{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:se,at:je(t),screen:!0,align:"left"}])}function co(t={}){return Yt(t,{M:t.matrix??Lt},[{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:se,at:je(t),screen:!0,align:"left"}])}function lo(t){return Yt(t,{M:Lt,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:se,at:je(t),screen:!0,align:"left"}])}function uo(t){const e=[t.u[0]+t.v[0],t.u[1]+t.v[1]];return Yt(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 ho(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}"})),Yt(t,n,e)}const $t=(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 fo(t){return $t(t,{a:t.at??1},[{id:"tangent",kind:"tangent",expr:t.expr,at:"a",color:"yellow",label:"\\text{slope} = \\val{tangent.slope}"}])}function po(t){return $t(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 mo(t){const e=$t(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 go(t){const e=$t(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 yo(t){const e=$t(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 bo(t){const e=$t(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}function vo(t){return St(t)}function wo(t,e={},n={}){return ri(Xt(St(t),e),n)}const ko={opacity:1,scale:1,scaleX:1,scaleY:1};function Mo(t){const e=new Map,n=new Map,i=[],r={};let s=0,o=0,c;const l=(m,a)=>`${m}\0${a}`,h=(m,a)=>{const f=l(m,a);let g=e.get(f);if(!g){const y=n.get(f)??ko[a]??(a==="text"?"":0);g={id:`${m}-${a}`,target:m,property:a,keyframes:[{time:0,value:y}]},e.set(f,g)}return g},u=(m,a)=>{const f=m.keyframes[m.keyframes.length-1];f.time<a&&m.keyframes.push({time:a,value:f.value})},d=(m,a,f,g,y)=>{for(const[M,w]of Object.entries(a)){const b=h(m,M);if(typeof w=="string"&&!/^#|^rgb/.test(w)){u(b,f),b.keyframes.push({time:f+1,value:w});continue}u(b,f),b.keyframes.push({time:f+Math.max(g,1),value:w,...y&&{easing:y}})}const v=f+Math.max(g,1);return o=Math.max(o,v),v},p={get time(){return s},at(m){return s=Math.max(0,m),p},wait(m){return s+=m,o=Math.max(o,s),p},initial(m,a){for(const[f,g]of Object.entries(a)){const y=l(m,f);n.set(y,g);const v=e.get(y);v&&(v.keyframes[0].value=g)}return p},set(m,a){const f=c?c.start:s;return d(m,a,f,1,{type:"steps",count:1,position:"start"}),p},to(m,a,f={}){const g=(c?c.start:s)+(f.delay??0),y=d(m,a,g,f.duration??400,f.easing??"ease-in-out");return c?c.end=Math.max(c.end,y):s=y,p},together(m){const a=c;c={start:a?a.start:s,end:a?a.start:s},m();const f=c.end;return c=a,a?a.end=Math.max(a.end,f):s=f,p},marker(m,a={}){const{captions:f,...g}=a;i.push({id:m,time:s,...g});for(const[y,v]of Object.entries(f??{}))(r[y]??={})[m]=v;return o=Math.max(o,s),p},definition(){return{formatVersion:ae,id:t.id,...t.name&&{name:t.name},config:{duration:o,...i.length>0&&{markers:[...i].sort((m,a)=>m.time-a.time)}},tracks:[...e.values()].map(m=>({...m,keyframes:m.keyframes.map(a=>({...a}))})),...Object.keys(r).length>0&&{captions:r}}}};return p}eo(),S.CONSTANTS=Nt,S.ExpressionError=gt,S.FUNCTIONS=Kt,S.ITEM_KINDS=ke,S.MATH_FONT=Pn,S.MATH_THEMES=Gt,S.MATRIX_TEX=se,S.SYMBOLS=Zt,S.TEX_COMMANDS=jn,S.TexError=zn,S.areaFigure=go,S.compile=V,S.compileDerivative=ee,S.determinantFigure=co,S.differentiate=it,S.displayListToSvg=ri,S.displayListToSvgContent=re,S.drawDisplayList=ai,S.eigenFigure=lo,S.evaluate=bt,S.expressionNames=Vn,S.expressionToString=qt,S.integrate=De,S.layoutFigure=Xt,S.layoutTex=mt,S.lesson=Mo,S.limitFigure=bo,S.linearMapFigure=ao,S.mat2=fs,S.mathExplorable=oo,S.mathFigure=vo,S.mathFigureProps=ci,S.mathFigureToSvg=wo,S.mathSteps=ro,S.mathTarget=io,S.morphEquation=Qn,S.mountAllMath=oi,S.mountMath=si,S.nthDerivative=Wn,S.parseExpression=zt,S.parseTex=qn,S.planeOf=Se,S.riemannFigure=mo,S.secantFigure=po,S.spanFigure=ho,S.tangentFigure=fo,S.taylorFigure=yo,S.texToShapes=Mt,S.trimPolylines=ot,S.validateMathFigure=St,S.vec2=bs,S.vectorSumFigure=uo,Object.defineProperty(S,Symbol.toStringTag,{value:"Module"})})(this.tinyfly=this.tinyfly||{});