@mathzetta/inlinemath 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,2 @@
1
- /* Inline Math 0.3.0 — MIT license; includes mathzetta (and @mathzetta/cas, for the CAS) */
2
- import{t}from"./chunks/html-D5QiXGXD.js";export{a as toHTML}from"./chunks/html-D5QiXGXD.js";import{l as e,a as s,t as i,s as r,p as n,n as o,b as h,c as l}from"./chunks/lite-Bo8THzyq.js";export{D as DEFAULTS,P as PATHS,d as numberTree}from"./chunks/lite-Bo8THzyq.js";import{o as c,r as u}from"./chunks/edit-CTMRUElt.js";import"./chunks/calculate-BGMEvf3f.js";class f{constructor(t,e,s={}){this.element=t,this.options=s,this.p=s.prefix||"mv",this.handlers=[],this.clicks=[],this.active=null,this.live=m(t,s.announce,this.p),this.set(e)}set(i,{animate:r=!1,duration:n=600,easing:o="ease-in-out"}={}){const h=t(i,this.options),{html:a}=e(h,s(h,this.options));if(this.editor){const t=this.editor;this.editor=null,t.cancelEdit?.()}const l=p(r)&&this.tree?this.snapshot():null,c=void 0!==this.tree;return this.tree=h,this.element.innerHTML=a,this.root=this.element.firstElementChild,this.handlers.length&&this.root.classList.add(`${this.p}-clickable`),this.editing&&this.root.classList.add(`${this.p}-editable`),this.active=null,(this.clicks.length||this.editing)&&this.focusable(),l&&this.morph(l,{duration:n,easing:o}),c&&this.live&&this.announce(this.spoken()),this}spoken(){const t=this.root&&this.root.getAttribute&&this.root.getAttribute("aria-label");if(t)return t;try{return i(this.tree)}catch{return""}}announce(t){return this.say(this.live,t)}say(t,e){if(!t)return this;t.textContent="";const s=()=>{t.textContent=e};return"function"==typeof requestAnimationFrame?requestAnimationFrame(()=>requestAnimationFrame(s)):setTimeout(s,50),this}nodes(t){return r(this.tree,t)}elements(t){return this.nodes(t).map(t=>this.elementOf(t)).filter(Boolean)}elementOf(t){return void 0===t.id?null:this.root.querySelector(`[data-node="${t.id}"]`)}highlight(t,e=`${this.p}-hl`){return this.elements(t).forEach(t=>t.classList.add(e)),this}unhighlight(t=null,e=`${this.p}-hl`){return(null===t?this.root.querySelectorAll(`.${e}`):this.elements(t)).forEach(t=>t.classList.remove(e)),this}color(t,e){return this.elements(t).forEach(t=>{t.style.color=e||""}),this}on(t,e){const s=t=>{const s=t.target.closest?.("[data-node]");if(!s||!this.root.contains(s))return;const i=Number(s.dataset.node),o=r(this.tree,i)[0];e({node:o,id:i,path:n(this.tree,i),element:s,event:t})};this.element.addEventListener(t,s);const i=[t,s];return this.handlers.push(i),this.root.classList.add(`${this.p}-clickable`),"click"===t&&(this.clicks.push(e),this.keyboard()),()=>{this.element.removeEventListener(t,s),this.clicks=this.clicks.filter(t=>t!==e),this.handlers=this.handlers.filter(t=>t!==i),!this.handlers.length&&this.root&&this.root.classList.remove(`${this.p}-clickable`)}}destroy(){if(this.editor){const t=this.editor;this.editor=null,t.cancelEdit?.()}for(const[t,e]of this.handlers)this.element.removeEventListener(t,e);this.handlers=[],this.clicks=[],this.keyListener&&this.element.removeEventListener("keydown",this.keyListener),this.editListener&&this.element.removeEventListener("dblclick",this.editListener),this.keyListener=this.editListener=null,this.keysOn=this.editOn=!1;for(const t of new Set([this.live,this.partsLive]))t&&"view"===t.dataset?.mvMadeBy&&t.remove();return this.live=this.partsLive=null,this}editable({toText:t,onEdit:e}={}){if("function"!=typeof t)throw new Error("editable needs { toText } (import { toText } from 'mathzetta/text')");return this.editing={toText:t,onEdit:e},this.root&&this.root.classList&&this.root.classList.add(`${this.p}-editable`),this.keyboard(),!this.editOn&&this.element.addEventListener&&(this.editOn=!0,this.editListener=t=>{const e=t.target.closest?.("[data-node]");e&&this.root.contains(e)&&(t.preventDefault(),this.edit(r(this.tree,Number(e.dataset.node))[0]))},this.element.addEventListener("dblclick",this.editListener)),this}edit(e=this.tree,{returnFocus:s=!1}={}){if(!this.editing)throw new Error("call editable({ toText }) first");const r="object"==typeof e&&e&&e.type?e:this.nodes(e)[0];if(!r)return null;const h=n(this.tree,r.id)||[],a=this.elementOf(r)||this.root;let l="Edit";try{l=`Edit ${i(r)}`}catch{}const d=()=>{s&&this.root.focus&&this.root.focus()};return this.editor=c(a,this.editing.toText(r),{label:l,prefix:this.p,parse:e=>t(e,this.options),commit:(t,e)=>{this.set(u(this.tree,h,t),{animate:!0});const i=o(this.tree,h);s&&i&&this.focusPart(i===this.tree?null:i),d(),this.editing.onEdit&&this.editing.onEdit({tree:this.tree,text:this.editing.toText(this.tree),path:h,part:e})},cancel:d}),this.editor}focusable(){this.root&&this.root.setAttribute&&(this.root.setAttribute("tabindex","0"),this.root.getAttribute("aria-label")||(this.root.setAttribute("role","math"),this.root.setAttribute("aria-label",this.spoken())),this.root.setAttribute("aria-description",this.editing?"Arrow keys move between parts, F2 edits one.":"Arrow keys move between parts, Enter selects one."))}keyboard(){this.focusable(),!this.keysOn&&this.element.addEventListener&&(this.keysOn=!0,this.partsLive=this.live||m(this.element,!0,this.p),this.keyListener=t=>this.key(t),this.element.addEventListener("keydown",this.keyListener))}key(t){if(!this.root||!this.root.contains(t.target))return;const e=this.active;let s;switch(t.key){case"ArrowDown":s=e?this.partsOf(e)[0]:this.partsOf(this.tree)[0];break;case"ArrowUp":s=e?this.outerOf(e):void 0;break;case"ArrowRight":s=e?this.neighbor(e,1):this.partsOf(this.tree)[0];break;case"ArrowLeft":s=e?this.neighbor(e,-1):void 0;break;case"Home":case"Escape":s=null;break;case"F2":if(!this.editing)return;return t.preventDefault(),void this.edit(e||this.tree,{returnFocus:!0});case"Enter":case" ":{t.preventDefault();const s=e||this.tree,i=this.elementOf(s)||this.root,r={node:s,id:s.id,path:n(this.tree,s.id),element:i,event:t};for(const t of this.clicks)t(r);return}default:return}t.preventDefault(),void 0!==s&&this.focusPart(s)}focusPart(t){const e=`${this.p}-focus`;this.root.querySelectorAll(`.${e}`).forEach(t=>t.classList.remove(e)),this.active=t;const s=t&&this.elementOf(t);s&&s.classList.add(e);let r="";try{r=t?i(t):this.spoken()}catch{r=""}return this.say(this.partsLive,r),this}partsOf(t){const e=[],s=t=>{this.elementOf(t)?e.push(t):"op"===t.type&&t.args.forEach(s)};return t&&"op"===t.type&&t.args.forEach(s),e}outerOf(t){const e=n(this.tree,t.id);for(let t=e?e.length-1:-1;t>0;t--){const s=o(this.tree,e.slice(0,t));if(s&&this.elementOf(s))return s}return null}neighbor(t,e){const s=this.partsOf(this.outerOf(t)||this.tree),i=s.indexOf(t);return i<0?void 0:s[i+e]}segments(t={}){return h(this.tree,t)}showSegment(t,e=`${this.p}-hl`){return this.unhighlight(null,e),t&&void 0!==t.id&&this.highlight(t.id,e),this}snapshot(){const t=new Map,e=s=>{const i=this.elementOf(s);if(i){const e=l(s);t.has(e)||t.set(e,[]),t.get(e).push({rect:i.getBoundingClientRect(),node:s,sig:e})}"op"===s.type&&s.args.forEach(e)};return e(this.tree),t}morph(t,{duration:e,easing:s}){if("undefined"==typeof Element||!Element.prototype.animate)return;const i=e=>{if("op"===e.type)for(const s of e.args){const e=t.get(l(s)),r=e?e.findIndex(t=>t.node===s):-1;r>-1&&e.splice(r,1),i(s)}},r=n=>{const o=this.elementOf(n),h=o&&t.get(l(n));if(h&&h.length){const{rect:t,node:r}=h.shift();i(r);const n=o.getBoundingClientRect(),a=t.left-n.left,l=t.top-n.top,c=n.width?t.width/n.width:1,d=n.height?t.height/n.height:1;return void((Math.abs(a)+Math.abs(l)>.5||Math.abs(c-1)+Math.abs(d-1)>.01)&&o.animate([{transformOrigin:"0 0",transform:`translate(${a}px, ${l}px) scale(${c}, ${d})`},{transformOrigin:"0 0",transform:"none"}],{duration:e,easing:s}))}"op"===n.type?n.args.forEach(r):o&&o.animate([{opacity:0},{opacity:0},{opacity:1}],{duration:e,easing:s})};r(this.tree)}}function m(t,e,s){if(!e)return null;if("object"==typeof e&&1===e.nodeType)return e;if("undefined"==typeof document||!t.insertAdjacentElement)return null;const i=t.nextElementSibling;if(i&&"view"===i.dataset?.mvMadeBy&&i.classList.contains(`${s}-sr-only`))return i;const r=document.createElement("span");return r.dataset.mvMadeBy="view",r.className=`${s}-sr-only`,r.setAttribute("aria-live","polite"),r.setAttribute("aria-atomic","true"),t.insertAdjacentElement("afterend",r),r}function p(t){return!!t&&("always"===t||!("function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion: reduce)").matches))}function g(t,e,s={}){return new f(t,e,s)}export{f as View,e as layout,o as nodeAt,n as pathOf,g as render,r as select,p as shouldAnimate,l as signature,t as treeOf};
1
+ /* Inline Math 0.4.0 — MIT license; includes mathzetta (and @mathzetta/cas, for the CAS) */
2
+ import{t}from"./chunks/html-DzjcaM8w.js";export{a as toHTML}from"./chunks/html-DzjcaM8w.js";import{l as e,a as s,t as i,s as r,p as n,n as o,b as h,c as l}from"./chunks/lite-6yr4ed_k.js";export{D as DEFAULTS,P as PATHS,d as numberTree}from"./chunks/lite-6yr4ed_k.js";import{o as c,r as u}from"./chunks/edit-BC9D1cIE.js";import"./chunks/calculate-DHvovDQK.js";class f{constructor(t,e,s={}){this.element=t,this.options=s,this.p=s.prefix||"mv",this.handlers=[],this.clicks=[],this.active=null,this.live=m(t,s.announce,this.p),this.set(e)}set(i,{animate:r=!1,duration:n=600,easing:o="ease-in-out"}={}){const h=t(i,this.options),{html:a}=e(h,s(h,this.options));if(this.editor){const t=this.editor;this.editor=null,t.cancelEdit?.()}const l=p(r)&&this.tree?this.snapshot():null,c=void 0!==this.tree;return this.tree=h,this.element.innerHTML=a,this.root=this.element.firstElementChild,this.handlers.length&&this.root.classList.add(`${this.p}-clickable`),this.editing&&this.root.classList.add(`${this.p}-editable`),this.active=null,(this.clicks.length||this.editing)&&this.focusable(),l&&this.morph(l,{duration:n,easing:o}),c&&this.live&&this.announce(this.spoken()),this}spoken(){const t=this.root&&this.root.getAttribute&&this.root.getAttribute("aria-label");if(t)return t;try{return i(this.tree)}catch{return""}}announce(t){return this.say(this.live,t)}say(t,e){if(!t)return this;t.textContent="";const s=()=>{t.textContent=e};return"function"==typeof requestAnimationFrame?requestAnimationFrame(()=>requestAnimationFrame(s)):setTimeout(s,50),this}nodes(t){return r(this.tree,t)}elements(t){return this.nodes(t).map(t=>this.elementOf(t)).filter(Boolean)}elementOf(t){return void 0===t.id?null:this.root.querySelector(`[data-node="${t.id}"]`)}highlight(t,e=`${this.p}-hl`){return this.elements(t).forEach(t=>t.classList.add(e)),this}unhighlight(t=null,e=`${this.p}-hl`){return(null===t?this.root.querySelectorAll(`.${e}`):this.elements(t)).forEach(t=>t.classList.remove(e)),this}color(t,e){return this.elements(t).forEach(t=>{t.style.color=e||""}),this}on(t,e){const s=t=>{const s=t.target.closest?.("[data-node]");if(!s||!this.root.contains(s))return;const i=Number(s.dataset.node),o=r(this.tree,i)[0];e({node:o,id:i,path:n(this.tree,i),element:s,event:t})};this.element.addEventListener(t,s);const i=[t,s];return this.handlers.push(i),this.root.classList.add(`${this.p}-clickable`),"click"===t&&(this.clicks.push(e),this.keyboard()),()=>{this.element.removeEventListener(t,s),this.clicks=this.clicks.filter(t=>t!==e),this.handlers=this.handlers.filter(t=>t!==i),!this.handlers.length&&this.root&&this.root.classList.remove(`${this.p}-clickable`)}}destroy(){if(this.editor){const t=this.editor;this.editor=null,t.cancelEdit?.()}for(const[t,e]of this.handlers)this.element.removeEventListener(t,e);this.handlers=[],this.clicks=[],this.keyListener&&this.element.removeEventListener("keydown",this.keyListener),this.editListener&&this.element.removeEventListener("dblclick",this.editListener),this.keyListener=this.editListener=null,this.keysOn=this.editOn=!1;for(const t of new Set([this.live,this.partsLive]))t&&"view"===t.dataset?.mvMadeBy&&t.remove();return this.live=this.partsLive=null,this}editable({toText:t,onEdit:e}={}){if("function"!=typeof t)throw new Error("editable needs { toText } (import { toText } from 'mathzetta/text')");return this.editing={toText:t,onEdit:e},this.root&&this.root.classList&&this.root.classList.add(`${this.p}-editable`),this.keyboard(),!this.editOn&&this.element.addEventListener&&(this.editOn=!0,this.editListener=t=>{const e=t.target.closest?.("[data-node]");e&&this.root.contains(e)&&(t.preventDefault(),this.edit(r(this.tree,Number(e.dataset.node))[0]))},this.element.addEventListener("dblclick",this.editListener)),this}edit(e=this.tree,{returnFocus:s=!1}={}){if(!this.editing)throw new Error("call editable({ toText }) first");const r="object"==typeof e&&e&&e.type?e:this.nodes(e)[0];if(!r)return null;const h=n(this.tree,r.id)||[],a=this.elementOf(r)||this.root;let l="Edit";try{l=`Edit ${i(r)}`}catch{}const d=()=>{s&&this.root.focus&&this.root.focus()};return this.editor=c(a,this.editing.toText(r),{label:l,prefix:this.p,parse:e=>t(e,this.options),commit:(t,e)=>{this.set(u(this.tree,h,t),{animate:!0});const i=o(this.tree,h);s&&i&&this.focusPart(i===this.tree?null:i),d(),this.editing.onEdit&&this.editing.onEdit({tree:this.tree,text:this.editing.toText(this.tree),path:h,part:e})},cancel:d}),this.editor}focusable(){this.root&&this.root.setAttribute&&(this.root.setAttribute("tabindex","0"),this.root.getAttribute("aria-label")||(this.root.setAttribute("role","math"),this.root.setAttribute("aria-label",this.spoken())),this.root.setAttribute("aria-description",this.editing?"Arrow keys move between parts, F2 edits one.":"Arrow keys move between parts, Enter selects one."))}keyboard(){this.focusable(),!this.keysOn&&this.element.addEventListener&&(this.keysOn=!0,this.partsLive=this.live||m(this.element,!0,this.p),this.keyListener=t=>this.key(t),this.element.addEventListener("keydown",this.keyListener))}key(t){if(!this.root||!this.root.contains(t.target))return;const e=this.active;let s;switch(t.key){case"ArrowDown":s=e?this.partsOf(e)[0]:this.partsOf(this.tree)[0];break;case"ArrowUp":s=e?this.outerOf(e):void 0;break;case"ArrowRight":s=e?this.neighbor(e,1):this.partsOf(this.tree)[0];break;case"ArrowLeft":s=e?this.neighbor(e,-1):void 0;break;case"Home":case"Escape":s=null;break;case"F2":if(!this.editing)return;return t.preventDefault(),void this.edit(e||this.tree,{returnFocus:!0});case"Enter":case" ":{t.preventDefault();const s=e||this.tree,i=this.elementOf(s)||this.root,r={node:s,id:s.id,path:n(this.tree,s.id),element:i,event:t};for(const t of this.clicks)t(r);return}default:return}t.preventDefault(),void 0!==s&&this.focusPart(s)}focusPart(t){const e=`${this.p}-focus`;this.root.querySelectorAll(`.${e}`).forEach(t=>t.classList.remove(e)),this.active=t;const s=t&&this.elementOf(t);s&&s.classList.add(e);let r="";try{r=t?i(t):this.spoken()}catch{r=""}return this.say(this.partsLive,r),this}partsOf(t){const e=[],s=t=>{this.elementOf(t)?e.push(t):"op"===t.type&&t.args.forEach(s)};return t&&"op"===t.type&&t.args.forEach(s),e}outerOf(t){const e=n(this.tree,t.id);for(let t=e?e.length-1:-1;t>0;t--){const s=o(this.tree,e.slice(0,t));if(s&&this.elementOf(s))return s}return null}neighbor(t,e){const s=this.partsOf(this.outerOf(t)||this.tree),i=s.indexOf(t);return i<0?void 0:s[i+e]}segments(t={}){return h(this.tree,t)}showSegment(t,e=`${this.p}-hl`){return this.unhighlight(null,e),t&&void 0!==t.id&&this.highlight(t.id,e),this}snapshot(){const t=new Map,e=s=>{const i=this.elementOf(s);if(i){const e=l(s);t.has(e)||t.set(e,[]),t.get(e).push({rect:i.getBoundingClientRect(),node:s,sig:e})}"op"===s.type&&s.args.forEach(e)};return e(this.tree),t}morph(t,{duration:e,easing:s}){if("undefined"==typeof Element||!Element.prototype.animate)return;const i=e=>{if("op"===e.type)for(const s of e.args){const e=t.get(l(s)),r=e?e.findIndex(t=>t.node===s):-1;r>-1&&e.splice(r,1),i(s)}},r=n=>{const o=this.elementOf(n),h=o&&t.get(l(n));if(h&&h.length){const{rect:t,node:r}=h.shift();i(r);const n=o.getBoundingClientRect(),a=t.left-n.left,l=t.top-n.top,c=n.width?t.width/n.width:1,d=n.height?t.height/n.height:1;return void((Math.abs(a)+Math.abs(l)>.5||Math.abs(c-1)+Math.abs(d-1)>.01)&&o.animate([{transformOrigin:"0 0",transform:`translate(${a}px, ${l}px) scale(${c}, ${d})`},{transformOrigin:"0 0",transform:"none"}],{duration:e,easing:s}))}"op"===n.type?n.args.forEach(r):o&&o.animate([{opacity:0},{opacity:0},{opacity:1}],{duration:e,easing:s})};r(this.tree)}}function m(t,e,s){if(!e)return null;if("object"==typeof e&&1===e.nodeType)return e;if("undefined"==typeof document||!t.insertAdjacentElement)return null;const i=t.nextElementSibling;if(i&&"view"===i.dataset?.mvMadeBy&&i.classList.contains(`${s}-sr-only`))return i;const r=document.createElement("span");return r.dataset.mvMadeBy="view",r.className=`${s}-sr-only`,r.setAttribute("aria-live","polite"),r.setAttribute("aria-atomic","true"),t.insertAdjacentElement("afterend",r),r}function p(t){return!!t&&("always"===t||!("function"==typeof matchMedia&&matchMedia("(prefers-reduced-motion: reduce)").matches))}function g(t,e,s={}){return new f(t,e,s)}export{f as View,e as layout,o as nodeAt,n as pathOf,g as render,r as select,p as shouldAnimate,l as signature,t as treeOf};
package/dist/lite-calc.js CHANGED
@@ -1,2 +1,2 @@
1
- /* Inline Math 0.3.0 — MIT license; includes mathzetta (and @mathzetta/cas, for the CAS) */
2
- import{c}from"./chunks/calculate-BGMEvf3f.js";export{a as calculate}from"./chunks/calculate-BGMEvf3f.js";import{e as o,f as e}from"./chunks/lite-Bo8THzyq.js";export{D as DEFAULTS,l as layout,d as numberTree,s as select}from"./chunks/lite-Bo8THzyq.js";const t=(s,a={})=>o(s,{...a,blocks:a.blocks??c}),r=(s,a={})=>e(s,{...a,blocks:a.blocks??c});export{c as calculateBlock,t as toHTML,r as treeOf};
1
+ /* Inline Math 0.4.0 — MIT license; includes mathzetta (and @mathzetta/cas, for the CAS) */
2
+ import{c}from"./chunks/calculate-DHvovDQK.js";export{a as calculate}from"./chunks/calculate-DHvovDQK.js";import{e as o,f as e}from"./chunks/lite-6yr4ed_k.js";export{D as DEFAULTS,l as layout,d as numberTree,s as select}from"./chunks/lite-6yr4ed_k.js";const t=(s,a={})=>o(s,{...a,blocks:a.blocks??c}),r=(s,a={})=>e(s,{...a,blocks:a.blocks??c});export{c as calculateBlock,t as toHTML,r as treeOf};
@@ -1,2 +1,2 @@
1
- /* Inline Math 0.3.0 — MIT license; MathZetta not included: map mathzetta, mathzetta/speech and mathzetta/calculate (and mathzetta/text, for cas.external.js) with an import map */
2
- export{D as DEFAULTS,l as layout,n as numberTree,s as select,t as toHTML,a as treeOf}from"./chunks/draw-q86mDDWm.js";import"mathzetta";import"mathzetta/speech";
1
+ /* Inline Math 0.4.0 — MIT license; MathZetta not included: map mathzetta, mathzetta/speech and mathzetta/calculate (and mathzetta/text, for cas.external.js) with an import map */
2
+ export{D as DEFAULTS,l as layout,n as numberTree,s as select,t as toHTML,a as treeOf}from"./chunks/draw-Bw547gEd.js";import"mathzetta";import"mathzetta/speech";
package/dist/lite.js CHANGED
@@ -1,2 +1,2 @@
1
- /* Inline Math 0.3.0 — MIT license; includes mathzetta (and @mathzetta/cas, for the CAS) */
2
- export{D as DEFAULTS,l as layout,d as numberTree,s as select,e as toHTML,f as treeOf}from"./chunks/lite-Bo8THzyq.js";
1
+ /* Inline Math 0.4.0 — MIT license; includes mathzetta (and @mathzetta/cas, for the CAS) */
2
+ export{D as DEFAULTS,l as layout,d as numberTree,s as select,e as toHTML,f as treeOf}from"./chunks/lite-6yr4ed_k.js";
@@ -1,2 +1,2 @@
1
- /* Inline Math 0.3.0 — MIT license; MathZetta not included: map mathzetta, mathzetta/speech and mathzetta/calculate (and mathzetta/text, for cas.external.js) with an import map */
2
- import{t as e,a as t}from"./chunks/html-1wCO6EpZ.js";import{calculate as n}from"mathzetta/calculate";import{e as s,p as r,c as i,n as o}from"./chunks/draw-q86mDDWm.js";import{firstVariable as a,toPostfix as c}from"mathzetta";import"mathzetta/speech";import{o as l,r as u}from"./chunks/edit-D2RO7fg0.js";const d=Symbol.for("inlinemath.expressions"),p=new Set(["symbol","number"]);function m(e){return e?"symbol"===e.type?e.value:"op"===e.type&&"_"===e.op&&2===e.args.length&&"symbol"===e.args[0].type&&p.has(e.args[1].type)?`${e.args[0].value}_${e.args[1].value}`:null:null}function h(e){const{id:t,...n}=e;return n.args&&(n.args=n.args.map(h)),n}function f(e,t){const n=(e,s)=>{if(!s&&void 0!==e.from)return t(e.from);const{id:r,from:i,...o}=e;return o.args&&(o.args=o.args.map(e=>n(e,!1))),o};return n(e,!0)}const g=new Set;function $(e,t){let n=!1;const r=new Set,i=(e,o=g)=>{const c=m(e);if(null!==c){if(!r.has(c)&&!o.has(c)){const e=t(c);if(e){n=!0,r.add(c);const t={...i(s(e)),from:c};return r.delete(c),t}}return e}if(e.args){const t=function(e){const[t,n]=e.args,s=e=>e&&"symbol"===e.type?e.value:null;switch(e.op){case"der":return"="===n?.op?s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1}:s(n)&&{name:s(n),where:e=>e<=1};case"int":{const r=s(n)??(3===e.args.length||1===e.args.length?a(t)||"x":null);return r&&{name:r,where:e=>0===e||1===e&&s(n)===r}}case"lim":return"→"===n?.op&&s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1};case"\\sumidx":case"\\prodidx":return("="===n?.op||"∈"===n?.op)&&s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1};default:return null}}(e);if(!t)return{...e,args:e.args.map(e=>i(e,o))};const n=new Set([...o,t.name]);return{...e,args:e.args.map((e,s)=>s===t.index?{...e,args:e.args.map((e,t)=>i(e,0===t?n:o))}:i(e,t.where(s)?n:o))}}return e},o=i(e);return{tree:n?h(o):e,changed:n}}const v="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)",b=new RegExp(`^(${v})\\s*\\.\\.\\s*(${v})(?:\\s+step\\s+(${v}))?(?:\\s*=\\s*(${v}))?$`);function x(e){const t=/^\s*\[\[([\s\S]*)\]\]\s*$/.exec(e);if(!t||/\]\s*,\s*\[/.test(t[1]))return null;const n=t[1].trim(),s=b.exec(n);if(s){const e=Number(s[1]),t=Number(s[2]);if(!(t>e))return null;const n=void 0!==s[3]?Number(s[3]):Number.isInteger(e)&&Number.isInteger(t)?1:(t-e)/100;if(!(n>0))return null;const r=void 0!==s[4]?Math.min(t,Math.max(e,Number(s[4]))):e;return{kind:"slider",min:e,max:t,step:n,default:String(r)}}if(n.includes("|")){const e=n.split("|").map(e=>e.trim()).filter(Boolean);if(e.length)return{kind:"dropdown",options:e,default:e[0]}}return{kind:"textbox",default:n}}const w=Symbol("set on the page");class y{constructor(){this.owners=new Map,this.chosen=new Map,this.listeners=new Set}definitions(e){const t=new Map;for(const[n,s]of this.owners)if(n!==e)for(const[e,n]of s)t.delete(e),t.set(e,n);return t}textOf(e){const t=this.chosen.get(e.name);return t&&t.key===e.key?t.text:e.text}get(e){const t=this.definitions().get(e);return t?this.textOf(t):void 0}names(){return[...this.definitions().keys()]}set(e,t){t=String(t);const n=this.definitions().get(e);if(n&&n.input){const s=this.chosen.get(e);if(s&&s.key===n.key&&s.text===t)return this;this.chosen.set(e,{key:n.key,text:t})}else{const n=new Map(this.owners.get(w));n.set(e,{name:e,text:t,key:`page:${t}`,input:null}),this.owners.delete(w),this.owners.set(w,n)}return this.notify(null,e),this}clear(e){return void 0===e?(this.owners.clear(),this.chosen.clear()):(this.owners.get(w)?.delete(e),this.chosen.delete(e)),this.notify(null,e),this}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}own(e,t){const n=this.owners.get(e);var s,r;(s=n,r=t,(s?.size??0)===(r?.size??0)&&[...s??[]].every(([e,t])=>r?.get(e)?.key===t.key))?t&&this.owners.set(e,t):(t&&t.size?this.owners.set(e,t):this.owners.delete(e),this.notify(e))}notify(e,t){for(const n of[...this.listeners])n(e,t)}}function S(){return new y}const k=S(),_=new RegExp("(\\d+)","g");function E(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let s="",r=0;const i=String(e).replace(/[\uE000-\uE003]/g,"�"),o=e=>0===e||"\n"===i[e-1],a=function(e){const t=new Map,n=e=>/^( {4}|\t)/.test(e);let s=0,r=!0,i=!1,o=-1;for(const a of e.split("\n")){const e=!a.trim();o>-1&&!e&&!n(a)&&(t.set(o,s-1),o=-1),o<0&&!e&&n(a)&&r&&!i&&(o=s),e||n(a)||(i=C.test(a)||i&&/^\s/.test(a)),r=e,s+=a.length+1}o>-1&&t.set(o,e.length);return t}(i);let c=-1;const l=new Set,u=(e,t,s)=>(n.push({source:e,display:t,raw:s,start:r,end:r+s.length}),`${n.length-1}`);for(;r<i.length;){if(a.has(r)){s+=i.slice(r,a.get(r)),r=a.get(r);continue}if(o(r)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(i.slice(r));if(e){const t=e[2],n=new RegExp(`\\n {0,3}${"`"===t[0]?"`":"~"}{${t.length},}[ \\t]*(?=\\n|$)`),o=i.slice(r+e[0].length),a=n.exec(`\n${o}`),c=a?o.slice(0,Math.max(0,a.index-1)):o,l=e[0].length+(a?a.index-1+a[0].length:o.length),d=i.slice(r,r+l);"math"===e[3].trim()?s+=u(c,!0,d):s+=d,r+=l;continue}}const e=i[r];if("`"===e){const e=/^`+/.exec(i.slice(r))[0],t=i.indexOf(e,r+e.length);if(t>-1){s+=i.slice(r,t+e.length),r=t+e.length;continue}s+=e,r+=e.length;continue}if("\\"===e){const e=i.slice(r,r+2),n="\\["===e?"\\]":"\\("===e?"\\)":null;if(n&&t.includes(e)){const t=l.has(n)?-1:i.indexOf(n,r+2);if(t<0&&l.add(n),t>-1){s+=u(i.slice(r+2,t),"\\["===e,i.slice(r,t+2)),r=t+2;continue}}s+=e,r+=2;continue}if("$"===e)if("$"===i[r+1]&&t.includes("$$")){const e=i.indexOf("$$",r+2);if(e>-1){s+=u(i.slice(r+2,e),!0,i.slice(r,e+2)),r=e+2;continue}}else if(t.includes("$")&&i[r+1]&&!/\s/.test(i[r+1])&&r+1>=c){const{end:e,stop:t}=M(i,r+1);if(e>-1){s+=u(i.slice(r+1,e),!1,i.slice(r,e+1)),r=e+1;continue}c=t}s+=e,r++}return{text:s,math:n}}function M(e,t){for(let n=t;n<e.length;n++){const t=e[n];if("\\"!==t){if("`"===t)return{end:-1,stop:n};if("\n"===t&&/^\n[ \t]*\n/.test(e.slice(n,n+64)))return{end:-1,stop:n};if("$"===t&&!/\s/.test(e[n-1])&&!/\d/.test(e[n+1]??"")&&"$"!==e[n+1])return{end:n,stop:n}}else n++}return{end:-1,stop:e.length}}const j=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),N=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function O(r,i,a,l){const{text:u,math:p}=E(r,i),h=a?a.definitions(l):new Map,f=e=>a?a.textOf(e):e.text,g={...i.scope??{}},v={},b=new Map,w=new Set,y=[],S=t=>{const n=new Map;return s=>{const r=h.get(s);if(!r)return null;if(!n.has(s)){let i=null;try{i=e(f(r),t)}catch{}n.set(s,i)}return n.get(s)}};let k=!0;const _=p.map((r,a)=>{const{source:l,display:u}=r;k&&l.includes("{{")&&((()=>{for(const e of Object.keys(v))delete v[e];Object.assign(v,g);for(const e of h.keys())delete v[e];let e=[...h.values()];for(;e.length;){const t=e.filter(e=>{try{const t=n(f(e),v);if("number"==typeof t.value||"bigint"==typeof t.value||Array.isArray(t.value))return v[e.name]=t.exact?t.text:t.value,!1}catch{}return!0});if(t.length===e.length)break;e=t}const t={},s=S({});for(const e of h.keys()){const n=s(e);if(n)try{t[e]=c($(n,t=>t===e?null:s(t)).tree)}catch{}}v[d]=t})(),k=!1);const p=u?"mv-md-display":"mv-md-math",_=(e,t="")=>`<span class="${p}${t}" data-mv-md="${a}">${e}</span>`;try{const c={...i.math,display:u,blocks:i.blocks,scope:v},d=function(t){let n=t.trim();const s=n.startsWith("_");s&&(n=n.slice(1).trimStart());let r=n.indexOf(":="),i=2;r<0&&s&&(r=n.search(/(?<![<>!≤≥=])=(?!=)/),i=1);const o=s?{error:"a hidden $_…$ saves a variable: $_A := 2+2$"}:null;if(r<=0)return o;const a=n.slice(0,r).trim(),c=n.slice(r+i).trim();let l=null;try{l=/\{\{/.test(a)?null:m(e(a))}catch{}return null!==l&&c?{hidden:s,lhs:a,name:l,rhs:c,input:x(c)}:o}(l);if(d&&d.error)throw new Error(d.error);if(d){const{name:n,input:i,hidden:l}=d,u=i?{name:n,text:i.default,input:i,key:`input:${JSON.stringify(i)}`}:{name:n,text:d.rhs,input:null,key:`expr:${d.rhs}`,start:r.start,end:r.end};let p="";if(i){const e=function(e,t){const{input:n,name:s}=e,r=`class="mv-md-input mv-md-${n.kind}" data-mv-var="${j(s)}" aria-label="${j(s)}"`;if("dropdown"===n.kind)return`<select ${r}>${n.options.map(e=>`<option value="${j(e)}"${e===t?" selected":""}>${j(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${r} min="${n.min}" max="${n.max}" step="${n.step}" value="${j(t)}"><output class="mv-md-output" data-mv-out="${j(s)}">${j(t)}</output>`:`<input type="text" ${r} value="${j(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(u,f(u));p=l?e:`${t(d.lhs,c)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,w.add(a)}else{const n=$(e(d.rhs,c),S(c)).tree;if(!l){const r=o({type:"op",op:"=",args:[s(e(d.lhs)),void 0===n.id?n:s(n)]});y[a]=r,p=function(e,t="mv"){return e.replace(`<span class="${t}-rel">=</span>`,`<span class="${t}-rel ${t}-rel-def">≔</span>`).replace(/(aria-label="[^"]*?) equals /,"$1 is defined as ").replace("<mo>=</mo>","<mo>≔</mo>")}(t(r,c),c.prefix)}}return h.delete(n),h.set(n,u),b.set(n,u),k=!0,l&&!i?"":_(p,i?" mv-md-input-def":"")}const{tree:p,changed:E}=$(e(l,c),S(c));E&&o(p),y[a]=p;const M=t(p,c);return!E&&!1!==i.define&&function(e,t,s){const r=N.exec(e);if(!r||/\{\{/.test(r[2]))return!1;const i=r[1].replace(/[{}]/g,"");if(s.has(i))return!1;try{const e=n(r[2],t);if("number"==typeof e.value||"bigint"==typeof e.value||Array.isArray(e.value))return t[i]=e.exact?e.text:e.value,!0}catch{}return!1}(l,g,h)&&(k=!0),_(M)}catch(e){return`<span class="mv-md-error" data-mv-md="${a}" title="${j(e.message)}"><code>${j(r.raw)}</code></span>`}});return{text:u,math:p,drawn:_,defs:b,inputs:w,trees:y}}const z=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,A=e=>z.test(e.trim())?j(e.trim()):"#",q=/\uE002(\d+)\uE003/g;function L(e,t,n,s=[]){const r=e=>(s.push(e),`${s.length-1}`),i=e=>(e=>e.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"))(n(e).replace(q,(e,t)=>(s[Number(t)]??"").replace(/<[^>]*>/g,"")));let o=e;o=o.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,s)=>r(`<code>${j(n(s.trim()))}</code>`)),o=o.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>r(j(t))),o=o.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>r(`<a href="${A(t)}">${j(t)}</a>`)),t.html&&(o=o.replace(/<\/?[A-Za-z][^>]*>/g,e=>r(e))),o=o.replace(/!\[([^\[\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,s)=>r(`<img src="${A(i(n))}" alt="${j(i(t))}"${s?` title="${j(i(s))}"`:""}>`)),o=o.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,o,a,c)=>r(`<a href="${A(i(a))}"${c?` title="${j(i(c))}"`:""}>${L(o,t,n,s)}</a>`)),o=o.replace(/&(?!#\d{1,7};|#x[0-9a-f]{1,6};|[a-z][a-z0-9]{1,31};)/gi,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),o=o.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g,"<strong><em>$2</em></strong>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*\*|__)(?![*_])([\s\S]*?\S)(\*|_)(?![*_])/g,"<em><strong>$2</strong>$4</em>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*|_)(?![*_])([\s\S]*?\S)(\*\*|__)(?![*_])/g,"<strong><em>$2</em>$4</strong>"),o=o.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),o=o.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),o=o.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),o=o.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),o=o.replace(/( {2,}|\\)\n/g,"<br>\n");for(let e=0;e<8&&/\uE002\d+\uE003/.test(o);e++)o=o.replace(q,(e,t)=>s[Number(t)]??"");return o}const W=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,C=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,R=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/,D=e=>W.test(e)&&!/^ {0,3}[-=]+\s*$/.test(e)&&!/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(e);function I(e){const t=e.trim();let n=t.length;for(;n>0&&"#"===t[n-1];)n--;return n===t.length?t:0===n?"":/[ \t]/.test(t[n-1])?t.slice(0,n).trimEnd():t}function T(e,t,n,s=0){const r=[];let i=0;const o=e=>L(e,t,n);if(s>100)return`<p>${o(e.join("\n"))}</p>`;for(;i<e.length;){const a=e[i];if(!a.trim()){i++;continue}const c=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(a);if(c){const t=[];for(i++;i<e.length&&!new RegExp(`^ {0,3}${"`"===c[1][0]?"`":"~"}{${c[1].length},}\\s*$`).test(e[i]);)t.push(e[i++]);i++;const s=c[2]?` class="language-${j(c[2])}"`:"";r.push(`<pre><code${s}>${j(n(t.join("\n")))}</code></pre>`);continue}const l=/^ {0,3}(#{1,6})[ \t]+/.exec(a);if(l){r.push(`<h${l[1].length}>${o(I(a.slice(l[0].length)))}</h${l[1].length}>`),i++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(a)){r.push("<hr>"),i++;continue}if(/^ {0,3}>/.test(a)){const o=[];for(;i<e.length&&e[i].trim()&&(/^ {0,3}>/.test(e[i])||o.length);)o.push(e[i].replace(/^ {0,3}> ?/,"")),i++;r.push(`<blockquote>\n${T(o,t,n,s+1)}\n</blockquote>`);continue}const u=C.exec(a);if(u){const o=/\d/.test(u[2]),a=o?parseInt(u[2],10):1,c=[];let l=!1;for(;i<e.length;){const t=C.exec(e[i]);if(!t||/\d/.test(t[2])!==o)break;const n=t[0].length,s=[e[i].slice(n)];for(i++;i<e.length;){const t=e[i];if(!t.trim()){const t=e[i+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){s.push(""),l=!0,i++;continue}void 0!==t&&C.test(t)&&(l=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))s.push(t.slice(Math.min(n,4)));else{if(C.test(t)||W.test(t))break;s.push(t)}i++}for(c.push(s);i<e.length&&!e[i].trim()&&void 0!==e[i+1]&&C.test(e[i+1]);)i++}const d=o?"ol":"ul",p=c.map(e=>{let r=T(e,t,n,s+1);return l||(r=r.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${r}</li>`});r.push(`<${d}${o&&1!==a?` start="${a}"`:""}>\n${p.join("\n")}\n</${d}>`);continue}if(a.includes("|")&&void 0!==e[i+1]&&R.test(e[i+1])&&e[i+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[i+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),s=(e,t,s)=>`<${e}${n[s]?` style="text-align:${n[s]}"`:""}>${o(t)}</${e}>`,c=t(a);i+=2;const l=[];for(;i<e.length&&e[i].trim()&&e[i].includes("|");)l.push(t(e[i++]));r.push(`<table>\n<thead><tr>${c.map((e,t)=>s("th",e,t)).join("")}</tr></thead>\n<tbody>\n${l.map(e=>`<tr>${c.map((t,n)=>s("td",e[n]??"",n)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(a)){const t=[];for(;i<e.length&&(/^( {4}|\t)/.test(e[i])||!e[i].trim());)t.push(e[i++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();r.push(`<pre><code>${j(n(t.join("\n")))}</code></pre>`);continue}const d=[];for(;i<e.length&&e[i].trim()&&(!d.length||!D(e[i]));){if(d.length&&/^ {0,3}(=+|-+)\s*$/.test(e[i])){const t="="===e[i].trim()[0]?1:2;r.push(`<h${t}>${o(d.join("\n"))}</h${t}>`),d.length=0,i++;break}d.push(e[i].replace(/^ {0,3}/,"")),i++}d.length&&r.push(`<p>${o(d.join("\n"))}</p>`)}return r.join("\n")}function H(e,t={},n=e=>e){return T(String(e).replace(/\r\n?/g,"\n").replace(/[\uE002\uE003]/g,"�").split("\n"),t,n)}function V({text:e,math:t,drawn:n},s){return(s.render?s.render(e):H(e,s,e=>e.replace(_,(e,n)=>t[Number(n)]?.raw??""))).replace(new RegExp("<p>\\s*(\\d+)\\s*</p>","g"),(e,s)=>t[Number(s)].display&&n[Number(s)]?`<div class="mv-md-block">${n[Number(s)]}</div>`:e).replace(_,(e,t)=>n[Number(t)]??"").replace(/<p>\s*<\/p>\n?/g,"")}function Z(e,t={}){return V(O(e,t,t.variables||null),t)}const B=new WeakMap,J=new Set;function F(){for(const e of J)e.connected()&&!e.element.isConnected&&e.stop(!0)}function G(t,n,s={}){const o=void 0===s.variables?k:s.variables||null;F();const a=B.get(t);a&&a.stop(a.store!==o);let c=O(n,s,o,t);if(t.innerHTML=V(c,s),!o)return B.delete(t),t;o.own(t,c.defs);let d=t.isConnected;const p=n=>{const r=n.target,i=r&&r.dataset&&r.dataset.mvVar;if(void 0!==i&&t.contains(r)){if("text"===r.type)try{e(r.value,{blocks:s.blocks,scope:{}}),r.removeAttribute("aria-invalid")}catch{return void r.setAttribute("aria-invalid","true")}o.set(i,r.value)}},m=a=>{const d=a.target.closest?.("[data-node]"),p=d&&d.closest("[data-mv-md]");if(!p||!t.contains(p))return;const m=Number(p.dataset.mvMd),h=c.trees[m];if(!h)return;const g=Number(d.dataset.node),$=r(h,g)||[];let v=null;for(let e=$.length;e>=0&&!v;e--){const t=i(h,$.slice(0,e));t&&void 0!==t.from&&(v={node:t,depth:e})}const b=v&&o.definitions().get(v.node.from);if(b&&b.input&&"textbox"===b.input.kind){a.preventDefault();const n=b.name,r=t.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(n)}"]`),c=s.editable&&s.editable.toText;if(!c)return void(r&&(r.focus(),r.select()));const p=t=>e(t),m=i(h,$);return void l(d,c(f(m,p)),{label:`Edit ${n}`,parse:t=>e(t,{blocks:s.blocks}),commit:e=>{const t=u(f(v.node,p),$.slice(v.depth),e);o.set(n,c(t))}})}const x=b&&c.defs.get(b.name),w=x&&x.key===b.key&&void 0!==x.start?{...c.math[m],start:x.start,end:x.end,raw:n.slice(x.start,x.end)}:c.math[m];t.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:m,start:w.start,end:w.end,raw:w.raw,source:w.source,id:g,path:$}}))};t.addEventListener("input",p),t.addEventListener("change",p),t.addEventListener("dblclick",m);const h=o.subscribe(e=>{e!==t&&(t.isConnected?(d=!0,F(),(()=>{const e=O(n,s,o,t);e.drawn.forEach((n,s)=>{if(n===c.drawn[s]||e.inputs.has(s))return;const r=t.querySelector(`[data-mv-md="${s}"]`);r&&(r.outerHTML=n)});for(const n of t.querySelectorAll("[data-mv-var], [data-mv-out]")){const t=e.defs.get(n.dataset.mvVar??n.dataset.mvOut);if(!t)continue;const s=o.textOf(t);void 0!==n.dataset.mvOut?n.textContent=s:n.value!==s&&n!==n.ownerDocument?.activeElement&&(n.value=s)}c=e})()):d&&g(!0))});function g(e){h(),t.removeEventListener("input",p),t.removeEventListener("change",p),t.removeEventListener("dblclick",m),J.delete($),B.delete(t),e&&o.own(t,null)}const $={element:t,store:o,stop:g,connected:()=>d};return J.add($),B.set(t,$),t}export{y as Variables,S as createVariables,E as extractMath,Z as markdownToHTML,H as renderMarkdown,G as renderMarkdownInto,k as variables};
1
+ /* Inline Math 0.4.0 — MIT license; MathZetta not included: map mathzetta, mathzetta/speech and mathzetta/calculate (and mathzetta/text, for cas.external.js) with an import map */
2
+ import{t as e,a as t}from"./chunks/html-6HJlblNm.js";import{calculate as n}from"mathzetta/calculate";import{e as s,p as r,c as i,n as o}from"./chunks/draw-Bw547gEd.js";import{firstVariable as a,toPostfix as c}from"mathzetta";import"mathzetta/speech";import{o as l,r as u}from"./chunks/edit-CCe3uoyk.js";const d=Symbol.for("inlinemath.expressions"),p=new Set(["symbol","number"]);function m(e){return e?"symbol"===e.type?e.value:"op"===e.type&&"_"===e.op&&2===e.args.length&&"symbol"===e.args[0].type&&p.has(e.args[1].type)?`${e.args[0].value}_${e.args[1].value}`:null:null}function h(e){const{id:t,...n}=e;return n.args&&(n.args=n.args.map(h)),n}function f(e,t){const n=(e,s)=>{if(!s&&void 0!==e.from)return t(e.from);const{id:r,from:i,...o}=e;return o.args&&(o.args=o.args.map(e=>n(e,!1))),o};return n(e,!0)}const g=new Set;function $(e,t){let n=!1;const r=new Set,i=(e,o=g)=>{const c=m(e);if(null!==c){if(!r.has(c)&&!o.has(c)){const e=t(c);if(e){n=!0,r.add(c);const t={...i(s(e)),from:c};return r.delete(c),t}}return e}if(e.args){const t=function(e){const[t,n]=e.args,s=e=>e&&"symbol"===e.type?e.value:null;switch(e.op){case"der":return"="===n?.op?s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1}:s(n)&&{name:s(n),where:e=>e<=1};case"int":{const r=s(n)??(3===e.args.length||1===e.args.length?a(t)||"x":null);return r&&{name:r,where:e=>0===e||1===e&&s(n)===r}}case"lim":return"→"===n?.op&&s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1};case"\\sumidx":case"\\prodidx":return("="===n?.op||"∈"===n?.op)&&s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1};default:return null}}(e);if(!t)return{...e,args:e.args.map(e=>i(e,o))};const n=new Set([...o,t.name]);return{...e,args:e.args.map((e,s)=>s===t.index?{...e,args:e.args.map((e,t)=>i(e,0===t?n:o))}:i(e,t.where(s)?n:o))}}return e},o=i(e);return{tree:n?h(o):e,changed:n}}const v="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)",b=new RegExp(`^(${v})\\s*\\.\\.\\s*(${v})(?:\\s+step\\s+(${v}))?(?:\\s*=\\s*(${v}))?$`);function x(e){const t=/^\s*\[\[([\s\S]*)\]\]\s*$/.exec(e);if(!t||/\]\s*,\s*\[/.test(t[1]))return null;const n=t[1].trim(),s=b.exec(n);if(s){const e=Number(s[1]),t=Number(s[2]);if(!(t>e))return null;const n=void 0!==s[3]?Number(s[3]):Number.isInteger(e)&&Number.isInteger(t)?1:(t-e)/100;if(!(n>0))return null;const r=void 0!==s[4]?Math.min(t,Math.max(e,Number(s[4]))):e;return{kind:"slider",min:e,max:t,step:n,default:String(r)}}if(n.includes("|")){const e=n.split("|").map(e=>e.trim()).filter(Boolean);if(e.length)return{kind:"dropdown",options:e,default:e[0]}}return{kind:"textbox",default:n}}const w=Symbol("set on the page");class y{constructor(){this.owners=new Map,this.chosen=new Map,this.listeners=new Set}definitions(e){const t=new Map;for(const[n,s]of this.owners)if(n!==e)for(const[e,n]of s)t.delete(e),t.set(e,n);return t}textOf(e){const t=this.chosen.get(e.name);return t&&t.key===e.key?t.text:e.text}get(e){const t=this.definitions().get(e);return t?this.textOf(t):void 0}names(){return[...this.definitions().keys()]}set(e,t){t=String(t);const n=this.definitions().get(e);if(n&&n.input){const s=this.chosen.get(e);if(s&&s.key===n.key&&s.text===t)return this;this.chosen.set(e,{key:n.key,text:t})}else{const n=new Map(this.owners.get(w));n.set(e,{name:e,text:t,key:`page:${t}`,input:null}),this.owners.delete(w),this.owners.set(w,n)}return this.notify(null,e),this}clear(e){return void 0===e?(this.owners.clear(),this.chosen.clear()):(this.owners.get(w)?.delete(e),this.chosen.delete(e)),this.notify(null,e),this}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}own(e,t){const n=this.owners.get(e);var s,r;(s=n,r=t,(s?.size??0)===(r?.size??0)&&[...s??[]].every(([e,t])=>r?.get(e)?.key===t.key))?t&&this.owners.set(e,t):(t&&t.size?this.owners.set(e,t):this.owners.delete(e),this.notify(e))}notify(e,t){for(const n of[...this.listeners])n(e,t)}}function S(){return new y}const k=S(),_=new RegExp("(\\d+)","g");function E(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let s="",r=0;const i=String(e).replace(/[\uE000-\uE003]/g,"�"),o=e=>0===e||"\n"===i[e-1],a=function(e){const t=new Map,n=e=>/^( {4}|\t)/.test(e);let s=0,r=!0,i=!1,o=-1;for(const a of e.split("\n")){const e=!a.trim();o>-1&&!e&&!n(a)&&(t.set(o,s-1),o=-1),o<0&&!e&&n(a)&&r&&!i&&(o=s),e||n(a)||(i=C.test(a)||i&&/^\s/.test(a)),r=e,s+=a.length+1}o>-1&&t.set(o,e.length);return t}(i);let c=-1;const l=new Set,u=(e,t,s)=>(n.push({source:e,display:t,raw:s,start:r,end:r+s.length}),`${n.length-1}`);for(;r<i.length;){if(a.has(r)){s+=i.slice(r,a.get(r)),r=a.get(r);continue}if(o(r)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(i.slice(r));if(e){const t=e[2],n=new RegExp(`\\n {0,3}${"`"===t[0]?"`":"~"}{${t.length},}[ \\t]*(?=\\n|$)`),o=i.slice(r+e[0].length),a=n.exec(`\n${o}`),c=a?o.slice(0,Math.max(0,a.index-1)):o,l=e[0].length+(a?a.index-1+a[0].length:o.length),d=i.slice(r,r+l);"math"===e[3].trim()?s+=u(c,!0,d):s+=d,r+=l;continue}}const e=i[r];if("`"===e){const e=/^`+/.exec(i.slice(r))[0],t=i.indexOf(e,r+e.length);if(t>-1){s+=i.slice(r,t+e.length),r=t+e.length;continue}s+=e,r+=e.length;continue}if("\\"===e){const e=i.slice(r,r+2),n="\\["===e?"\\]":"\\("===e?"\\)":null;if(n&&t.includes(e)){const t=l.has(n)?-1:i.indexOf(n,r+2);if(t<0&&l.add(n),t>-1){s+=u(i.slice(r+2,t),"\\["===e,i.slice(r,t+2)),r=t+2;continue}}s+=e,r+=2;continue}if("$"===e)if("$"===i[r+1]&&t.includes("$$")){const e=i.indexOf("$$",r+2);if(e>-1){s+=u(i.slice(r+2,e),!0,i.slice(r,e+2)),r=e+2;continue}}else if(t.includes("$")&&i[r+1]&&!/\s/.test(i[r+1])&&r+1>=c){const{end:e,stop:t}=M(i,r+1);if(e>-1){s+=u(i.slice(r+1,e),!1,i.slice(r,e+1)),r=e+1;continue}c=t}s+=e,r++}return{text:s,math:n}}function M(e,t){for(let n=t;n<e.length;n++){const t=e[n];if("\\"!==t){if("`"===t)return{end:-1,stop:n};if("\n"===t&&/^\n[ \t]*\n/.test(e.slice(n,n+64)))return{end:-1,stop:n};if("$"===t&&!/\s/.test(e[n-1])&&!/\d/.test(e[n+1]??"")&&"$"!==e[n+1])return{end:n,stop:n}}else n++}return{end:-1,stop:e.length}}const j=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),N=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function O(r,i,a,l){const{text:u,math:p}=E(r,i),h=a?a.definitions(l):new Map,f=e=>a?a.textOf(e):e.text,g={...i.scope??{}},v={},b=new Map,w=new Set,y=[],S=t=>{const n=new Map;return s=>{const r=h.get(s);if(!r)return null;if(!n.has(s)){let i=null;try{i=e(f(r),t)}catch{}n.set(s,i)}return n.get(s)}};let k=!0;const _=p.map((r,a)=>{const{source:l,display:u}=r;k&&l.includes("{{")&&((()=>{for(const e of Object.keys(v))delete v[e];Object.assign(v,g);for(const e of h.keys())delete v[e];let e=[...h.values()];for(;e.length;){const t=e.filter(e=>{try{const t=n(f(e),v);if("number"==typeof t.value||"bigint"==typeof t.value||Array.isArray(t.value))return v[e.name]=t.exact?t.text:t.value,!1}catch{}return!0});if(t.length===e.length)break;e=t}const t={},s=S({});for(const e of h.keys()){const n=s(e);if(n)try{t[e]=c($(n,t=>t===e?null:s(t)).tree)}catch{}}v[d]=t})(),k=!1);const p=u?"mv-md-display":"mv-md-math",_=(e,t="")=>`<span class="${p}${t}" data-mv-md="${a}">${e}</span>`;try{const c={...i.math,display:u,blocks:i.blocks,scope:v},d=function(t){let n=t.trim();const s=n.startsWith("_");s&&(n=n.slice(1).trimStart());let r=n.indexOf(":="),i=2;r<0&&s&&(r=n.search(/(?<![<>!≤≥=])=(?!=)/),i=1);const o=s?{error:"a hidden $_…$ saves a variable: $_A := 2+2$"}:null;if(r<=0)return o;const a=n.slice(0,r).trim(),c=n.slice(r+i).trim();let l=null;try{l=/\{\{/.test(a)?null:m(e(a))}catch{}return null!==l&&c?{hidden:s,lhs:a,name:l,rhs:c,input:x(c)}:o}(l);if(d&&d.error)throw new Error(d.error);if(d){const{name:n,input:i,hidden:l}=d,u=i?{name:n,text:i.default,input:i,key:`input:${JSON.stringify(i)}`}:{name:n,text:d.rhs,input:null,key:`expr:${d.rhs}`,start:r.start,end:r.end};let p="";if(i){const e=function(e,t){const{input:n,name:s}=e,r=`class="mv-md-input mv-md-${n.kind}" data-mv-var="${j(s)}" aria-label="${j(s)}"`;if("dropdown"===n.kind)return`<select ${r}>${n.options.map(e=>`<option value="${j(e)}"${e===t?" selected":""}>${j(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${r} min="${n.min}" max="${n.max}" step="${n.step}" value="${j(t)}"><output class="mv-md-output" data-mv-out="${j(s)}">${j(t)}</output>`:`<input type="text" ${r} value="${j(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(u,f(u));p=l?e:`${t(d.lhs,c)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,w.add(a)}else{const n=$(e(d.rhs,c),S(c)).tree;if(!l){const r=o({type:"op",op:"=",args:[s(e(d.lhs)),void 0===n.id?n:s(n)]});y[a]=r,p=function(e,t="mv"){return e.replace(`<span class="${t}-rel">=</span>`,`<span class="${t}-rel ${t}-rel-def">≔</span>`).replace(/(aria-label="[^"]*?) equals /,"$1 is defined as ").replace("<mo>=</mo>","<mo>≔</mo>")}(t(r,c),c.prefix)}}return h.delete(n),h.set(n,u),b.set(n,u),k=!0,l&&!i?"":_(p,i?" mv-md-input-def":"")}const{tree:p,changed:E}=$(e(l,c),S(c));E&&o(p),y[a]=p;const M=t(p,c);return!E&&!1!==i.define&&function(e,t,s){const r=N.exec(e);if(!r||/\{\{/.test(r[2]))return!1;const i=r[1].replace(/[{}]/g,"");if(s.has(i))return!1;try{const e=n(r[2],t);if("number"==typeof e.value||"bigint"==typeof e.value||Array.isArray(e.value))return t[i]=e.exact?e.text:e.value,!0}catch{}return!1}(l,g,h)&&(k=!0),_(M)}catch(e){return`<span class="mv-md-error" data-mv-md="${a}" title="${j(e.message)}"><code>${j(r.raw)}</code></span>`}});return{text:u,math:p,drawn:_,defs:b,inputs:w,trees:y}}const z=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,A=e=>z.test(e.trim())?j(e.trim()):"#",q=/\uE002(\d+)\uE003/g;function L(e,t,n,s=[]){const r=e=>(s.push(e),`${s.length-1}`),i=e=>(e=>e.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"))(n(e).replace(q,(e,t)=>(s[Number(t)]??"").replace(/<[^>]*>/g,"")));let o=e;o=o.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,s)=>r(`<code>${j(n(s.trim()))}</code>`)),o=o.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>r(j(t))),o=o.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>r(`<a href="${A(t)}">${j(t)}</a>`)),t.html&&(o=o.replace(/<\/?[A-Za-z][^>]*>/g,e=>r(e))),o=o.replace(/!\[([^\[\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,s)=>r(`<img src="${A(i(n))}" alt="${j(i(t))}"${s?` title="${j(i(s))}"`:""}>`)),o=o.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,o,a,c)=>r(`<a href="${A(i(a))}"${c?` title="${j(i(c))}"`:""}>${L(o,t,n,s)}</a>`)),o=o.replace(/&(?!#\d{1,7};|#x[0-9a-f]{1,6};|[a-z][a-z0-9]{1,31};)/gi,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),o=o.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g,"<strong><em>$2</em></strong>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*\*|__)(?![*_])([\s\S]*?\S)(\*|_)(?![*_])/g,"<em><strong>$2</strong>$4</em>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*|_)(?![*_])([\s\S]*?\S)(\*\*|__)(?![*_])/g,"<strong><em>$2</em>$4</strong>"),o=o.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),o=o.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),o=o.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),o=o.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),o=o.replace(/( {2,}|\\)\n/g,"<br>\n");for(let e=0;e<8&&/\uE002\d+\uE003/.test(o);e++)o=o.replace(q,(e,t)=>s[Number(t)]??"");return o}const W=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,C=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,R=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/,D=e=>W.test(e)&&!/^ {0,3}[-=]+\s*$/.test(e)&&!/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(e);function I(e){const t=e.trim();let n=t.length;for(;n>0&&"#"===t[n-1];)n--;return n===t.length?t:0===n?"":/[ \t]/.test(t[n-1])?t.slice(0,n).trimEnd():t}function T(e,t,n,s=0){const r=[];let i=0;const o=e=>L(e,t,n);if(s>100)return`<p>${o(e.join("\n"))}</p>`;for(;i<e.length;){const a=e[i];if(!a.trim()){i++;continue}const c=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(a);if(c){const t=[];for(i++;i<e.length&&!new RegExp(`^ {0,3}${"`"===c[1][0]?"`":"~"}{${c[1].length},}\\s*$`).test(e[i]);)t.push(e[i++]);i++;const s=c[2]?` class="language-${j(c[2])}"`:"";r.push(`<pre><code${s}>${j(n(t.join("\n")))}</code></pre>`);continue}const l=/^ {0,3}(#{1,6})[ \t]+/.exec(a);if(l){r.push(`<h${l[1].length}>${o(I(a.slice(l[0].length)))}</h${l[1].length}>`),i++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(a)){r.push("<hr>"),i++;continue}if(/^ {0,3}>/.test(a)){const o=[];for(;i<e.length&&e[i].trim()&&(/^ {0,3}>/.test(e[i])||o.length);)o.push(e[i].replace(/^ {0,3}> ?/,"")),i++;r.push(`<blockquote>\n${T(o,t,n,s+1)}\n</blockquote>`);continue}const u=C.exec(a);if(u){const o=/\d/.test(u[2]),a=o?parseInt(u[2],10):1,c=[];let l=!1;for(;i<e.length;){const t=C.exec(e[i]);if(!t||/\d/.test(t[2])!==o)break;const n=t[0].length,s=[e[i].slice(n)];for(i++;i<e.length;){const t=e[i];if(!t.trim()){const t=e[i+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){s.push(""),l=!0,i++;continue}void 0!==t&&C.test(t)&&(l=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))s.push(t.slice(Math.min(n,4)));else{if(C.test(t)||W.test(t))break;s.push(t)}i++}for(c.push(s);i<e.length&&!e[i].trim()&&void 0!==e[i+1]&&C.test(e[i+1]);)i++}const d=o?"ol":"ul",p=c.map(e=>{let r=T(e,t,n,s+1);return l||(r=r.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${r}</li>`});r.push(`<${d}${o&&1!==a?` start="${a}"`:""}>\n${p.join("\n")}\n</${d}>`);continue}if(a.includes("|")&&void 0!==e[i+1]&&R.test(e[i+1])&&e[i+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[i+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),s=(e,t,s)=>`<${e}${n[s]?` style="text-align:${n[s]}"`:""}>${o(t)}</${e}>`,c=t(a);i+=2;const l=[];for(;i<e.length&&e[i].trim()&&e[i].includes("|");)l.push(t(e[i++]));r.push(`<table>\n<thead><tr>${c.map((e,t)=>s("th",e,t)).join("")}</tr></thead>\n<tbody>\n${l.map(e=>`<tr>${c.map((t,n)=>s("td",e[n]??"",n)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(a)){const t=[];for(;i<e.length&&(/^( {4}|\t)/.test(e[i])||!e[i].trim());)t.push(e[i++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();r.push(`<pre><code>${j(n(t.join("\n")))}</code></pre>`);continue}const d=[];for(;i<e.length&&e[i].trim()&&(!d.length||!D(e[i]));){if(d.length&&/^ {0,3}(=+|-+)\s*$/.test(e[i])){const t="="===e[i].trim()[0]?1:2;r.push(`<h${t}>${o(d.join("\n"))}</h${t}>`),d.length=0,i++;break}d.push(e[i].replace(/^ {0,3}/,"")),i++}d.length&&r.push(`<p>${o(d.join("\n"))}</p>`)}return r.join("\n")}function H(e,t={},n=e=>e){return T(String(e).replace(/\r\n?/g,"\n").replace(/[\uE002\uE003]/g,"�").split("\n"),t,n)}function V({text:e,math:t,drawn:n},s){return(s.render?s.render(e):H(e,s,e=>e.replace(_,(e,n)=>t[Number(n)]?.raw??""))).replace(new RegExp("<p>\\s*(\\d+)\\s*</p>","g"),(e,s)=>t[Number(s)].display&&n[Number(s)]?`<div class="mv-md-block">${n[Number(s)]}</div>`:e).replace(_,(e,t)=>n[Number(t)]??"").replace(/<p>\s*<\/p>\n?/g,"")}function Z(e,t={}){return V(O(e,t,t.variables||null),t)}const B=new WeakMap,J=new Set;function F(){for(const e of J)e.connected()&&!e.element.isConnected&&e.stop(!0)}function G(t,n,s={}){const o=void 0===s.variables?k:s.variables||null;F();const a=B.get(t);a&&a.stop(a.store!==o);let c=O(n,s,o,t);if(t.innerHTML=V(c,s),!o)return B.delete(t),t;o.own(t,c.defs);let d=t.isConnected;const p=n=>{const r=n.target,i=r&&r.dataset&&r.dataset.mvVar;if(void 0!==i&&t.contains(r)){if("text"===r.type)try{e(r.value,{blocks:s.blocks,scope:{}}),r.removeAttribute("aria-invalid")}catch{return void r.setAttribute("aria-invalid","true")}o.set(i,r.value)}},m=a=>{const d=a.target.closest?.("[data-node]"),p=d&&d.closest("[data-mv-md]");if(!p||!t.contains(p))return;const m=Number(p.dataset.mvMd),h=c.trees[m];if(!h)return;const g=Number(d.dataset.node),$=r(h,g)||[];let v=null;for(let e=$.length;e>=0&&!v;e--){const t=i(h,$.slice(0,e));t&&void 0!==t.from&&(v={node:t,depth:e})}const b=v&&o.definitions().get(v.node.from);if(b&&b.input&&"textbox"===b.input.kind){a.preventDefault();const n=b.name,r=t.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(n)}"]`),c=s.editable&&s.editable.toText;if(!c)return void(r&&(r.focus(),r.select()));const p=t=>e(t),m=i(h,$);return void l(d,c(f(m,p)),{label:`Edit ${n}`,parse:t=>e(t,{blocks:s.blocks}),commit:e=>{const t=u(f(v.node,p),$.slice(v.depth),e);o.set(n,c(t))}})}const x=b&&c.defs.get(b.name),w=x&&x.key===b.key&&void 0!==x.start?{...c.math[m],start:x.start,end:x.end,raw:n.slice(x.start,x.end)}:c.math[m];t.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:m,start:w.start,end:w.end,raw:w.raw,source:w.source,id:g,path:$}}))};t.addEventListener("input",p),t.addEventListener("change",p),t.addEventListener("dblclick",m);const h=o.subscribe(e=>{e!==t&&(t.isConnected?(d=!0,F(),(()=>{const e=O(n,s,o,t);e.drawn.forEach((n,s)=>{if(n===c.drawn[s]||e.inputs.has(s))return;const r=t.querySelector(`[data-mv-md="${s}"]`);r&&(r.outerHTML=n)});for(const n of t.querySelectorAll("[data-mv-var], [data-mv-out]")){const t=e.defs.get(n.dataset.mvVar??n.dataset.mvOut);if(!t)continue;const s=o.textOf(t);void 0!==n.dataset.mvOut?n.textContent=s:n.value!==s&&n!==n.ownerDocument?.activeElement&&(n.value=s)}c=e})()):d&&g(!0))});function g(e){h(),t.removeEventListener("input",p),t.removeEventListener("change",p),t.removeEventListener("dblclick",m),J.delete($),B.delete(t),e&&o.own(t,null)}const $={element:t,store:o,stop:g,connected:()=>d};return J.add($),B.set(t,$),t}export{y as Variables,S as createVariables,E as extractMath,Z as markdownToHTML,H as renderMarkdown,G as renderMarkdownInto,k as variables};
package/dist/markdown.js CHANGED
@@ -1,2 +1,2 @@
1
- /* Inline Math 0.3.0 — MIT license; includes mathzetta (and @mathzetta/cas, for the CAS) */
2
- import{t as e,a as t}from"./chunks/html-D5QiXGXD.js";import{a as n}from"./chunks/calculate-BGMEvf3f.js";import{g as s,h as r,p as i,n as o,d as a,i as c}from"./chunks/lite-Bo8THzyq.js";import{o as l,r as u}from"./chunks/edit-CTMRUElt.js";const d=Symbol.for("inlinemath.expressions"),p=new Set(["symbol","number"]);function h(e){return e?"symbol"===e.type?e.value:"op"===e.type&&"_"===e.op&&2===e.args.length&&"symbol"===e.args[0].type&&p.has(e.args[1].type)?`${e.args[0].value}_${e.args[1].value}`:null:null}function m(e){const{id:t,...n}=e;return n.args&&(n.args=n.args.map(m)),n}function f(e,t){const n=(e,s)=>{if(!s&&void 0!==e.from)return t(e.from);const{id:r,from:i,...o}=e;return o.args&&(o.args=o.args.map(e=>n(e,!1))),o};return n(e,!0)}const g=new Set;function $(e,t){let n=!1;const i=new Set,o=(e,a=g)=>{const c=h(e);if(null!==c){if(!i.has(c)&&!a.has(c)){const e=t(c);if(e){n=!0,i.add(c);const t={...o(s(e)),from:c};return i.delete(c),t}}return e}if(e.args){const t=function(e){const[t,n]=e.args,s=e=>e&&"symbol"===e.type?e.value:null;switch(e.op){case"der":return"="===n?.op?s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1}:s(n)&&{name:s(n),where:e=>e<=1};case"int":{const i=s(n)??(3===e.args.length||1===e.args.length?r(t)||"x":null);return i&&{name:i,where:e=>0===e||1===e&&s(n)===i}}case"lim":return"→"===n?.op&&s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1};case"\\sumidx":case"\\prodidx":return("="===n?.op||"∈"===n?.op)&&s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1};default:return null}}(e);if(!t)return{...e,args:e.args.map(e=>o(e,a))};const n=new Set([...a,t.name]);return{...e,args:e.args.map((e,s)=>s===t.index?{...e,args:e.args.map((e,t)=>o(e,0===t?n:a))}:o(e,t.where(s)?n:a))}}return e},a=o(e);return{tree:n?m(a):e,changed:n}}const v="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)",b=new RegExp(`^(${v})\\s*\\.\\.\\s*(${v})(?:\\s+step\\s+(${v}))?(?:\\s*=\\s*(${v}))?$`);function x(e){const t=/^\s*\[\[([\s\S]*)\]\]\s*$/.exec(e);if(!t||/\]\s*,\s*\[/.test(t[1]))return null;const n=t[1].trim(),s=b.exec(n);if(s){const e=Number(s[1]),t=Number(s[2]);if(!(t>e))return null;const n=void 0!==s[3]?Number(s[3]):Number.isInteger(e)&&Number.isInteger(t)?1:(t-e)/100;if(!(n>0))return null;const r=void 0!==s[4]?Math.min(t,Math.max(e,Number(s[4]))):e;return{kind:"slider",min:e,max:t,step:n,default:String(r)}}if(n.includes("|")){const e=n.split("|").map(e=>e.trim()).filter(Boolean);if(e.length)return{kind:"dropdown",options:e,default:e[0]}}return{kind:"textbox",default:n}}const w=Symbol("set on the page");class y{constructor(){this.owners=new Map,this.chosen=new Map,this.listeners=new Set}definitions(e){const t=new Map;for(const[n,s]of this.owners)if(n!==e)for(const[e,n]of s)t.delete(e),t.set(e,n);return t}textOf(e){const t=this.chosen.get(e.name);return t&&t.key===e.key?t.text:e.text}get(e){const t=this.definitions().get(e);return t?this.textOf(t):void 0}names(){return[...this.definitions().keys()]}set(e,t){t=String(t);const n=this.definitions().get(e);if(n&&n.input){const s=this.chosen.get(e);if(s&&s.key===n.key&&s.text===t)return this;this.chosen.set(e,{key:n.key,text:t})}else{const n=new Map(this.owners.get(w));n.set(e,{name:e,text:t,key:`page:${t}`,input:null}),this.owners.delete(w),this.owners.set(w,n)}return this.notify(null,e),this}clear(e){return void 0===e?(this.owners.clear(),this.chosen.clear()):(this.owners.get(w)?.delete(e),this.chosen.delete(e)),this.notify(null,e),this}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}own(e,t){const n=this.owners.get(e);var s,r;(s=n,r=t,(s?.size??0)===(r?.size??0)&&[...s??[]].every(([e,t])=>r?.get(e)?.key===t.key))?t&&this.owners.set(e,t):(t&&t.size?this.owners.set(e,t):this.owners.delete(e),this.notify(e))}notify(e,t){for(const n of[...this.listeners])n(e,t)}}function S(){return new y}const k=S(),_=new RegExp("(\\d+)","g");function E(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let s="",r=0;const i=String(e).replace(/[\uE000-\uE003]/g,"�"),o=e=>0===e||"\n"===i[e-1],a=function(e){const t=new Map,n=e=>/^( {4}|\t)/.test(e);let s=0,r=!0,i=!1,o=-1;for(const a of e.split("\n")){const e=!a.trim();o>-1&&!e&&!n(a)&&(t.set(o,s-1),o=-1),o<0&&!e&&n(a)&&r&&!i&&(o=s),e||n(a)||(i=C.test(a)||i&&/^\s/.test(a)),r=e,s+=a.length+1}o>-1&&t.set(o,e.length);return t}(i);let c=-1;const l=new Set,u=(e,t,s)=>(n.push({source:e,display:t,raw:s,start:r,end:r+s.length}),`${n.length-1}`);for(;r<i.length;){if(a.has(r)){s+=i.slice(r,a.get(r)),r=a.get(r);continue}if(o(r)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(i.slice(r));if(e){const t=e[2],n=new RegExp(`\\n {0,3}${"`"===t[0]?"`":"~"}{${t.length},}[ \\t]*(?=\\n|$)`),o=i.slice(r+e[0].length),a=n.exec(`\n${o}`),c=a?o.slice(0,Math.max(0,a.index-1)):o,l=e[0].length+(a?a.index-1+a[0].length:o.length),d=i.slice(r,r+l);"math"===e[3].trim()?s+=u(c,!0,d):s+=d,r+=l;continue}}const e=i[r];if("`"===e){const e=/^`+/.exec(i.slice(r))[0],t=i.indexOf(e,r+e.length);if(t>-1){s+=i.slice(r,t+e.length),r=t+e.length;continue}s+=e,r+=e.length;continue}if("\\"===e){const e=i.slice(r,r+2),n="\\["===e?"\\]":"\\("===e?"\\)":null;if(n&&t.includes(e)){const t=l.has(n)?-1:i.indexOf(n,r+2);if(t<0&&l.add(n),t>-1){s+=u(i.slice(r+2,t),"\\["===e,i.slice(r,t+2)),r=t+2;continue}}s+=e,r+=2;continue}if("$"===e)if("$"===i[r+1]&&t.includes("$$")){const e=i.indexOf("$$",r+2);if(e>-1){s+=u(i.slice(r+2,e),!0,i.slice(r,e+2)),r=e+2;continue}}else if(t.includes("$")&&i[r+1]&&!/\s/.test(i[r+1])&&r+1>=c){const{end:e,stop:t}=M(i,r+1);if(e>-1){s+=u(i.slice(r+1,e),!1,i.slice(r,e+1)),r=e+1;continue}c=t}s+=e,r++}return{text:s,math:n}}function M(e,t){for(let n=t;n<e.length;n++){const t=e[n];if("\\"!==t){if("`"===t)return{end:-1,stop:n};if("\n"===t&&/^\n[ \t]*\n/.test(e.slice(n,n+64)))return{end:-1,stop:n};if("$"===t&&!/\s/.test(e[n-1])&&!/\d/.test(e[n+1]??"")&&"$"!==e[n+1])return{end:n,stop:n}}else n++}return{end:-1,stop:e.length}}const j=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),N=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function O(r,i,o,l){const{text:u,math:p}=E(r,i),m=o?o.definitions(l):new Map,f=e=>o?o.textOf(e):e.text,g={...i.scope??{}},v={},b=new Map,w=new Set,y=[],S=t=>{const n=new Map;return s=>{const r=m.get(s);if(!r)return null;if(!n.has(s)){let i=null;try{i=e(f(r),t)}catch{}n.set(s,i)}return n.get(s)}};let k=!0;const _=p.map((r,o)=>{const{source:l,display:u}=r;k&&l.includes("{{")&&((()=>{for(const e of Object.keys(v))delete v[e];Object.assign(v,g);for(const e of m.keys())delete v[e];let e=[...m.values()];for(;e.length;){const t=e.filter(e=>{try{const t=n(f(e),v);if("number"==typeof t.value||"bigint"==typeof t.value||Array.isArray(t.value))return v[e.name]=t.exact?t.text:t.value,!1}catch{}return!0});if(t.length===e.length)break;e=t}const t={},s=S({});for(const e of m.keys()){const n=s(e);if(n)try{t[e]=c($(n,t=>t===e?null:s(t)).tree)}catch{}}v[d]=t})(),k=!1);const p=u?"mv-md-display":"mv-md-math",_=(e,t="")=>`<span class="${p}${t}" data-mv-md="${o}">${e}</span>`;try{const c={...i.math,display:u,blocks:i.blocks,scope:v},d=function(t){let n=t.trim();const s=n.startsWith("_");s&&(n=n.slice(1).trimStart());let r=n.indexOf(":="),i=2;r<0&&s&&(r=n.search(/(?<![<>!≤≥=])=(?!=)/),i=1);const o=s?{error:"a hidden $_…$ saves a variable: $_A := 2+2$"}:null;if(r<=0)return o;const a=n.slice(0,r).trim(),c=n.slice(r+i).trim();let l=null;try{l=/\{\{/.test(a)?null:h(e(a))}catch{}return null!==l&&c?{hidden:s,lhs:a,name:l,rhs:c,input:x(c)}:o}(l);if(d&&d.error)throw new Error(d.error);if(d){const{name:n,input:i,hidden:l}=d,u=i?{name:n,text:i.default,input:i,key:`input:${JSON.stringify(i)}`}:{name:n,text:d.rhs,input:null,key:`expr:${d.rhs}`,start:r.start,end:r.end};let p="";if(i){const e=function(e,t){const{input:n,name:s}=e,r=`class="mv-md-input mv-md-${n.kind}" data-mv-var="${j(s)}" aria-label="${j(s)}"`;if("dropdown"===n.kind)return`<select ${r}>${n.options.map(e=>`<option value="${j(e)}"${e===t?" selected":""}>${j(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${r} min="${n.min}" max="${n.max}" step="${n.step}" value="${j(t)}"><output class="mv-md-output" data-mv-out="${j(s)}">${j(t)}</output>`:`<input type="text" ${r} value="${j(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(u,f(u));p=l?e:`${t(d.lhs,c)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,w.add(o)}else{const n=$(e(d.rhs,c),S(c)).tree;if(!l){const r=a({type:"op",op:"=",args:[s(e(d.lhs)),void 0===n.id?n:s(n)]});y[o]=r,p=function(e,t="mv"){return e.replace(`<span class="${t}-rel">=</span>`,`<span class="${t}-rel ${t}-rel-def">≔</span>`).replace(/(aria-label="[^"]*?) equals /,"$1 is defined as ").replace("<mo>=</mo>","<mo>≔</mo>")}(t(r,c),c.prefix)}}return m.delete(n),m.set(n,u),b.set(n,u),k=!0,l&&!i?"":_(p,i?" mv-md-input-def":"")}const{tree:p,changed:E}=$(e(l,c),S(c));E&&a(p),y[o]=p;const M=t(p,c);return!E&&!1!==i.define&&function(e,t,s){const r=N.exec(e);if(!r||/\{\{/.test(r[2]))return!1;const i=r[1].replace(/[{}]/g,"");if(s.has(i))return!1;try{const e=n(r[2],t);if("number"==typeof e.value||"bigint"==typeof e.value||Array.isArray(e.value))return t[i]=e.exact?e.text:e.value,!0}catch{}return!1}(l,g,m)&&(k=!0),_(M)}catch(e){return`<span class="mv-md-error" data-mv-md="${o}" title="${j(e.message)}"><code>${j(r.raw)}</code></span>`}});return{text:u,math:p,drawn:_,defs:b,inputs:w,trees:y}}const A=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,q=e=>A.test(e.trim())?j(e.trim()):"#",z=/\uE002(\d+)\uE003/g;function L(e,t,n,s=[]){const r=e=>(s.push(e),`${s.length-1}`),i=e=>(e=>e.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"))(n(e).replace(z,(e,t)=>(s[Number(t)]??"").replace(/<[^>]*>/g,"")));let o=e;o=o.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,s)=>r(`<code>${j(n(s.trim()))}</code>`)),o=o.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>r(j(t))),o=o.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>r(`<a href="${q(t)}">${j(t)}</a>`)),t.html&&(o=o.replace(/<\/?[A-Za-z][^>]*>/g,e=>r(e))),o=o.replace(/!\[([^\[\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,s)=>r(`<img src="${q(i(n))}" alt="${j(i(t))}"${s?` title="${j(i(s))}"`:""}>`)),o=o.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,o,a,c)=>r(`<a href="${q(i(a))}"${c?` title="${j(i(c))}"`:""}>${L(o,t,n,s)}</a>`)),o=o.replace(/&(?!#\d{1,7};|#x[0-9a-f]{1,6};|[a-z][a-z0-9]{1,31};)/gi,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),o=o.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g,"<strong><em>$2</em></strong>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*\*|__)(?![*_])([\s\S]*?\S)(\*|_)(?![*_])/g,"<em><strong>$2</strong>$4</em>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*|_)(?![*_])([\s\S]*?\S)(\*\*|__)(?![*_])/g,"<strong><em>$2</em>$4</strong>"),o=o.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),o=o.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),o=o.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),o=o.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),o=o.replace(/( {2,}|\\)\n/g,"<br>\n");for(let e=0;e<8&&/\uE002\d+\uE003/.test(o);e++)o=o.replace(z,(e,t)=>s[Number(t)]??"");return o}const W=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,C=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,R=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/,D=e=>W.test(e)&&!/^ {0,3}[-=]+\s*$/.test(e)&&!/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(e);function I(e){const t=e.trim();let n=t.length;for(;n>0&&"#"===t[n-1];)n--;return n===t.length?t:0===n?"":/[ \t]/.test(t[n-1])?t.slice(0,n).trimEnd():t}function T(e,t,n,s=0){const r=[];let i=0;const o=e=>L(e,t,n);if(s>100)return`<p>${o(e.join("\n"))}</p>`;for(;i<e.length;){const a=e[i];if(!a.trim()){i++;continue}const c=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(a);if(c){const t=[];for(i++;i<e.length&&!new RegExp(`^ {0,3}${"`"===c[1][0]?"`":"~"}{${c[1].length},}\\s*$`).test(e[i]);)t.push(e[i++]);i++;const s=c[2]?` class="language-${j(c[2])}"`:"";r.push(`<pre><code${s}>${j(n(t.join("\n")))}</code></pre>`);continue}const l=/^ {0,3}(#{1,6})[ \t]+/.exec(a);if(l){r.push(`<h${l[1].length}>${o(I(a.slice(l[0].length)))}</h${l[1].length}>`),i++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(a)){r.push("<hr>"),i++;continue}if(/^ {0,3}>/.test(a)){const o=[];for(;i<e.length&&e[i].trim()&&(/^ {0,3}>/.test(e[i])||o.length);)o.push(e[i].replace(/^ {0,3}> ?/,"")),i++;r.push(`<blockquote>\n${T(o,t,n,s+1)}\n</blockquote>`);continue}const u=C.exec(a);if(u){const o=/\d/.test(u[2]),a=o?parseInt(u[2],10):1,c=[];let l=!1;for(;i<e.length;){const t=C.exec(e[i]);if(!t||/\d/.test(t[2])!==o)break;const n=t[0].length,s=[e[i].slice(n)];for(i++;i<e.length;){const t=e[i];if(!t.trim()){const t=e[i+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){s.push(""),l=!0,i++;continue}void 0!==t&&C.test(t)&&(l=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))s.push(t.slice(Math.min(n,4)));else{if(C.test(t)||W.test(t))break;s.push(t)}i++}for(c.push(s);i<e.length&&!e[i].trim()&&void 0!==e[i+1]&&C.test(e[i+1]);)i++}const d=o?"ol":"ul",p=c.map(e=>{let r=T(e,t,n,s+1);return l||(r=r.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${r}</li>`});r.push(`<${d}${o&&1!==a?` start="${a}"`:""}>\n${p.join("\n")}\n</${d}>`);continue}if(a.includes("|")&&void 0!==e[i+1]&&R.test(e[i+1])&&e[i+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[i+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),s=(e,t,s)=>`<${e}${n[s]?` style="text-align:${n[s]}"`:""}>${o(t)}</${e}>`,c=t(a);i+=2;const l=[];for(;i<e.length&&e[i].trim()&&e[i].includes("|");)l.push(t(e[i++]));r.push(`<table>\n<thead><tr>${c.map((e,t)=>s("th",e,t)).join("")}</tr></thead>\n<tbody>\n${l.map(e=>`<tr>${c.map((t,n)=>s("td",e[n]??"",n)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(a)){const t=[];for(;i<e.length&&(/^( {4}|\t)/.test(e[i])||!e[i].trim());)t.push(e[i++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();r.push(`<pre><code>${j(n(t.join("\n")))}</code></pre>`);continue}const d=[];for(;i<e.length&&e[i].trim()&&(!d.length||!D(e[i]));){if(d.length&&/^ {0,3}(=+|-+)\s*$/.test(e[i])){const t="="===e[i].trim()[0]?1:2;r.push(`<h${t}>${o(d.join("\n"))}</h${t}>`),d.length=0,i++;break}d.push(e[i].replace(/^ {0,3}/,"")),i++}d.length&&r.push(`<p>${o(d.join("\n"))}</p>`)}return r.join("\n")}function H(e,t={},n=e=>e){return T(String(e).replace(/\r\n?/g,"\n").replace(/[\uE002\uE003]/g,"�").split("\n"),t,n)}function V({text:e,math:t,drawn:n},s){return(s.render?s.render(e):H(e,s,e=>e.replace(_,(e,n)=>t[Number(n)]?.raw??""))).replace(new RegExp("<p>\\s*(\\d+)\\s*</p>","g"),(e,s)=>t[Number(s)].display&&n[Number(s)]?`<div class="mv-md-block">${n[Number(s)]}</div>`:e).replace(_,(e,t)=>n[Number(t)]??"").replace(/<p>\s*<\/p>\n?/g,"")}function Z(e,t={}){return V(O(e,t,t.variables||null),t)}const B=new WeakMap,J=new Set;function F(){for(const e of J)e.connected()&&!e.element.isConnected&&e.stop(!0)}function G(t,n,s={}){const r=void 0===s.variables?k:s.variables||null;F();const a=B.get(t);a&&a.stop(a.store!==r);let c=O(n,s,r,t);if(t.innerHTML=V(c,s),!r)return B.delete(t),t;r.own(t,c.defs);let d=t.isConnected;const p=n=>{const i=n.target,o=i&&i.dataset&&i.dataset.mvVar;if(void 0!==o&&t.contains(i)){if("text"===i.type)try{e(i.value,{blocks:s.blocks,scope:{}}),i.removeAttribute("aria-invalid")}catch{return void i.setAttribute("aria-invalid","true")}r.set(o,i.value)}},h=a=>{const d=a.target.closest?.("[data-node]"),p=d&&d.closest("[data-mv-md]");if(!p||!t.contains(p))return;const h=Number(p.dataset.mvMd),m=c.trees[h];if(!m)return;const g=Number(d.dataset.node),$=i(m,g)||[];let v=null;for(let e=$.length;e>=0&&!v;e--){const t=o(m,$.slice(0,e));t&&void 0!==t.from&&(v={node:t,depth:e})}const b=v&&r.definitions().get(v.node.from);if(b&&b.input&&"textbox"===b.input.kind){a.preventDefault();const n=b.name,i=t.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(n)}"]`),c=s.editable&&s.editable.toText;if(!c)return void(i&&(i.focus(),i.select()));const p=t=>e(t),h=o(m,$);return void l(d,c(f(h,p)),{label:`Edit ${n}`,parse:t=>e(t,{blocks:s.blocks}),commit:e=>{const t=u(f(v.node,p),$.slice(v.depth),e);r.set(n,c(t))}})}const x=b&&c.defs.get(b.name),w=x&&x.key===b.key&&void 0!==x.start?{...c.math[h],start:x.start,end:x.end,raw:n.slice(x.start,x.end)}:c.math[h];t.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:h,start:w.start,end:w.end,raw:w.raw,source:w.source,id:g,path:$}}))};t.addEventListener("input",p),t.addEventListener("change",p),t.addEventListener("dblclick",h);const m=r.subscribe(e=>{e!==t&&(t.isConnected?(d=!0,F(),(()=>{const e=O(n,s,r,t);e.drawn.forEach((n,s)=>{if(n===c.drawn[s]||e.inputs.has(s))return;const r=t.querySelector(`[data-mv-md="${s}"]`);r&&(r.outerHTML=n)});for(const n of t.querySelectorAll("[data-mv-var], [data-mv-out]")){const t=e.defs.get(n.dataset.mvVar??n.dataset.mvOut);if(!t)continue;const s=r.textOf(t);void 0!==n.dataset.mvOut?n.textContent=s:n.value!==s&&n!==n.ownerDocument?.activeElement&&(n.value=s)}c=e})()):d&&g(!0))});function g(e){m(),t.removeEventListener("input",p),t.removeEventListener("change",p),t.removeEventListener("dblclick",h),J.delete($),B.delete(t),e&&r.own(t,null)}const $={element:t,store:r,stop:g,connected:()=>d};return J.add($),B.set(t,$),t}export{y as Variables,S as createVariables,E as extractMath,Z as markdownToHTML,H as renderMarkdown,G as renderMarkdownInto,k as variables};
1
+ /* Inline Math 0.4.0 — MIT license; includes mathzetta (and @mathzetta/cas, for the CAS) */
2
+ import{t as e,a as t}from"./chunks/html-DzjcaM8w.js";import{a as n}from"./chunks/calculate-DHvovDQK.js";import{g as s,h as r,p as i,n as o,d as a,i as c}from"./chunks/lite-6yr4ed_k.js";import{o as l,r as u}from"./chunks/edit-BC9D1cIE.js";const d=Symbol.for("inlinemath.expressions"),p=new Set(["symbol","number"]);function h(e){return e?"symbol"===e.type?e.value:"op"===e.type&&"_"===e.op&&2===e.args.length&&"symbol"===e.args[0].type&&p.has(e.args[1].type)?`${e.args[0].value}_${e.args[1].value}`:null:null}function m(e){const{id:t,...n}=e;return n.args&&(n.args=n.args.map(m)),n}function f(e,t){const n=(e,s)=>{if(!s&&void 0!==e.from)return t(e.from);const{id:r,from:i,...o}=e;return o.args&&(o.args=o.args.map(e=>n(e,!1))),o};return n(e,!0)}const g=new Set;function $(e,t){let n=!1;const i=new Set,o=(e,a=g)=>{const c=h(e);if(null!==c){if(!i.has(c)&&!a.has(c)){const e=t(c);if(e){n=!0,i.add(c);const t={...o(s(e)),from:c};return i.delete(c),t}}return e}if(e.args){const t=function(e){const[t,n]=e.args,s=e=>e&&"symbol"===e.type?e.value:null;switch(e.op){case"der":return"="===n?.op?s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1}:s(n)&&{name:s(n),where:e=>e<=1};case"int":{const i=s(n)??(3===e.args.length||1===e.args.length?r(t)||"x":null);return i&&{name:i,where:e=>0===e||1===e&&s(n)===i}}case"lim":return"→"===n?.op&&s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1};case"\\sumidx":case"\\prodidx":return("="===n?.op||"∈"===n?.op)&&s(n.args[0])&&{name:s(n.args[0]),where:e=>0===e,index:1};default:return null}}(e);if(!t)return{...e,args:e.args.map(e=>o(e,a))};const n=new Set([...a,t.name]);return{...e,args:e.args.map((e,s)=>s===t.index?{...e,args:e.args.map((e,t)=>o(e,0===t?n:a))}:o(e,t.where(s)?n:a))}}return e},a=o(e);return{tree:n?m(a):e,changed:n}}const v="[-+]?(?:\\d+\\.?\\d*|\\.\\d+)",b=new RegExp(`^(${v})\\s*\\.\\.\\s*(${v})(?:\\s+step\\s+(${v}))?(?:\\s*=\\s*(${v}))?$`);function x(e){const t=/^\s*\[\[([\s\S]*)\]\]\s*$/.exec(e);if(!t||/\]\s*,\s*\[/.test(t[1]))return null;const n=t[1].trim(),s=b.exec(n);if(s){const e=Number(s[1]),t=Number(s[2]);if(!(t>e))return null;const n=void 0!==s[3]?Number(s[3]):Number.isInteger(e)&&Number.isInteger(t)?1:(t-e)/100;if(!(n>0))return null;const r=void 0!==s[4]?Math.min(t,Math.max(e,Number(s[4]))):e;return{kind:"slider",min:e,max:t,step:n,default:String(r)}}if(n.includes("|")){const e=n.split("|").map(e=>e.trim()).filter(Boolean);if(e.length)return{kind:"dropdown",options:e,default:e[0]}}return{kind:"textbox",default:n}}const w=Symbol("set on the page");class y{constructor(){this.owners=new Map,this.chosen=new Map,this.listeners=new Set}definitions(e){const t=new Map;for(const[n,s]of this.owners)if(n!==e)for(const[e,n]of s)t.delete(e),t.set(e,n);return t}textOf(e){const t=this.chosen.get(e.name);return t&&t.key===e.key?t.text:e.text}get(e){const t=this.definitions().get(e);return t?this.textOf(t):void 0}names(){return[...this.definitions().keys()]}set(e,t){t=String(t);const n=this.definitions().get(e);if(n&&n.input){const s=this.chosen.get(e);if(s&&s.key===n.key&&s.text===t)return this;this.chosen.set(e,{key:n.key,text:t})}else{const n=new Map(this.owners.get(w));n.set(e,{name:e,text:t,key:`page:${t}`,input:null}),this.owners.delete(w),this.owners.set(w,n)}return this.notify(null,e),this}clear(e){return void 0===e?(this.owners.clear(),this.chosen.clear()):(this.owners.get(w)?.delete(e),this.chosen.delete(e)),this.notify(null,e),this}subscribe(e){return this.listeners.add(e),()=>this.listeners.delete(e)}own(e,t){const n=this.owners.get(e);var s,r;(s=n,r=t,(s?.size??0)===(r?.size??0)&&[...s??[]].every(([e,t])=>r?.get(e)?.key===t.key))?t&&this.owners.set(e,t):(t&&t.size?this.owners.set(e,t):this.owners.delete(e),this.notify(e))}notify(e,t){for(const n of[...this.listeners])n(e,t)}}function S(){return new y}const k=S(),_=new RegExp("(\\d+)","g");function E(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let s="",r=0;const i=String(e).replace(/[\uE000-\uE003]/g,"�"),o=e=>0===e||"\n"===i[e-1],a=function(e){const t=new Map,n=e=>/^( {4}|\t)/.test(e);let s=0,r=!0,i=!1,o=-1;for(const a of e.split("\n")){const e=!a.trim();o>-1&&!e&&!n(a)&&(t.set(o,s-1),o=-1),o<0&&!e&&n(a)&&r&&!i&&(o=s),e||n(a)||(i=C.test(a)||i&&/^\s/.test(a)),r=e,s+=a.length+1}o>-1&&t.set(o,e.length);return t}(i);let c=-1;const l=new Set,u=(e,t,s)=>(n.push({source:e,display:t,raw:s,start:r,end:r+s.length}),`${n.length-1}`);for(;r<i.length;){if(a.has(r)){s+=i.slice(r,a.get(r)),r=a.get(r);continue}if(o(r)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(i.slice(r));if(e){const t=e[2],n=new RegExp(`\\n {0,3}${"`"===t[0]?"`":"~"}{${t.length},}[ \\t]*(?=\\n|$)`),o=i.slice(r+e[0].length),a=n.exec(`\n${o}`),c=a?o.slice(0,Math.max(0,a.index-1)):o,l=e[0].length+(a?a.index-1+a[0].length:o.length),d=i.slice(r,r+l);"math"===e[3].trim()?s+=u(c,!0,d):s+=d,r+=l;continue}}const e=i[r];if("`"===e){const e=/^`+/.exec(i.slice(r))[0],t=i.indexOf(e,r+e.length);if(t>-1){s+=i.slice(r,t+e.length),r=t+e.length;continue}s+=e,r+=e.length;continue}if("\\"===e){const e=i.slice(r,r+2),n="\\["===e?"\\]":"\\("===e?"\\)":null;if(n&&t.includes(e)){const t=l.has(n)?-1:i.indexOf(n,r+2);if(t<0&&l.add(n),t>-1){s+=u(i.slice(r+2,t),"\\["===e,i.slice(r,t+2)),r=t+2;continue}}s+=e,r+=2;continue}if("$"===e)if("$"===i[r+1]&&t.includes("$$")){const e=i.indexOf("$$",r+2);if(e>-1){s+=u(i.slice(r+2,e),!0,i.slice(r,e+2)),r=e+2;continue}}else if(t.includes("$")&&i[r+1]&&!/\s/.test(i[r+1])&&r+1>=c){const{end:e,stop:t}=M(i,r+1);if(e>-1){s+=u(i.slice(r+1,e),!1,i.slice(r,e+1)),r=e+1;continue}c=t}s+=e,r++}return{text:s,math:n}}function M(e,t){for(let n=t;n<e.length;n++){const t=e[n];if("\\"!==t){if("`"===t)return{end:-1,stop:n};if("\n"===t&&/^\n[ \t]*\n/.test(e.slice(n,n+64)))return{end:-1,stop:n};if("$"===t&&!/\s/.test(e[n-1])&&!/\d/.test(e[n+1]??"")&&"$"!==e[n+1])return{end:n,stop:n}}else n++}return{end:-1,stop:e.length}}const j=e=>String(e).replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),N=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function O(r,i,o,l){const{text:u,math:p}=E(r,i),m=o?o.definitions(l):new Map,f=e=>o?o.textOf(e):e.text,g={...i.scope??{}},v={},b=new Map,w=new Set,y=[],S=t=>{const n=new Map;return s=>{const r=m.get(s);if(!r)return null;if(!n.has(s)){let i=null;try{i=e(f(r),t)}catch{}n.set(s,i)}return n.get(s)}};let k=!0;const _=p.map((r,o)=>{const{source:l,display:u}=r;k&&l.includes("{{")&&((()=>{for(const e of Object.keys(v))delete v[e];Object.assign(v,g);for(const e of m.keys())delete v[e];let e=[...m.values()];for(;e.length;){const t=e.filter(e=>{try{const t=n(f(e),v);if("number"==typeof t.value||"bigint"==typeof t.value||Array.isArray(t.value))return v[e.name]=t.exact?t.text:t.value,!1}catch{}return!0});if(t.length===e.length)break;e=t}const t={},s=S({});for(const e of m.keys()){const n=s(e);if(n)try{t[e]=c($(n,t=>t===e?null:s(t)).tree)}catch{}}v[d]=t})(),k=!1);const p=u?"mv-md-display":"mv-md-math",_=(e,t="")=>`<span class="${p}${t}" data-mv-md="${o}">${e}</span>`;try{const c={...i.math,display:u,blocks:i.blocks,scope:v},d=function(t){let n=t.trim();const s=n.startsWith("_");s&&(n=n.slice(1).trimStart());let r=n.indexOf(":="),i=2;r<0&&s&&(r=n.search(/(?<![<>!≤≥=])=(?!=)/),i=1);const o=s?{error:"a hidden $_…$ saves a variable: $_A := 2+2$"}:null;if(r<=0)return o;const a=n.slice(0,r).trim(),c=n.slice(r+i).trim();let l=null;try{l=/\{\{/.test(a)?null:h(e(a))}catch{}return null!==l&&c?{hidden:s,lhs:a,name:l,rhs:c,input:x(c)}:o}(l);if(d&&d.error)throw new Error(d.error);if(d){const{name:n,input:i,hidden:l}=d,u=i?{name:n,text:i.default,input:i,key:`input:${JSON.stringify(i)}`}:{name:n,text:d.rhs,input:null,key:`expr:${d.rhs}`,start:r.start,end:r.end};let p="";if(i){const e=function(e,t){const{input:n,name:s}=e,r=`class="mv-md-input mv-md-${n.kind}" data-mv-var="${j(s)}" aria-label="${j(s)}"`;if("dropdown"===n.kind)return`<select ${r}>${n.options.map(e=>`<option value="${j(e)}"${e===t?" selected":""}>${j(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${r} min="${n.min}" max="${n.max}" step="${n.step}" value="${j(t)}"><output class="mv-md-output" data-mv-out="${j(s)}">${j(t)}</output>`:`<input type="text" ${r} value="${j(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(u,f(u));p=l?e:`${t(d.lhs,c)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,w.add(o)}else{const n=$(e(d.rhs,c),S(c)).tree;if(!l){const r=a({type:"op",op:"=",args:[s(e(d.lhs)),void 0===n.id?n:s(n)]});y[o]=r,p=function(e,t="mv"){return e.replace(`<span class="${t}-rel">=</span>`,`<span class="${t}-rel ${t}-rel-def">≔</span>`).replace(/(aria-label="[^"]*?) equals /,"$1 is defined as ").replace("<mo>=</mo>","<mo>≔</mo>")}(t(r,c),c.prefix)}}return m.delete(n),m.set(n,u),b.set(n,u),k=!0,l&&!i?"":_(p,i?" mv-md-input-def":"")}const{tree:p,changed:E}=$(e(l,c),S(c));E&&a(p),y[o]=p;const M=t(p,c);return!E&&!1!==i.define&&function(e,t,s){const r=N.exec(e);if(!r||/\{\{/.test(r[2]))return!1;const i=r[1].replace(/[{}]/g,"");if(s.has(i))return!1;try{const e=n(r[2],t);if("number"==typeof e.value||"bigint"==typeof e.value||Array.isArray(e.value))return t[i]=e.exact?e.text:e.value,!0}catch{}return!1}(l,g,m)&&(k=!0),_(M)}catch(e){return`<span class="mv-md-error" data-mv-md="${o}" title="${j(e.message)}"><code>${j(r.raw)}</code></span>`}});return{text:u,math:p,drawn:_,defs:b,inputs:w,trees:y}}const A=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,q=e=>A.test(e.trim())?j(e.trim()):"#",z=/\uE002(\d+)\uE003/g;function L(e,t,n,s=[]){const r=e=>(s.push(e),`${s.length-1}`),i=e=>(e=>e.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&amp;/g,"&"))(n(e).replace(z,(e,t)=>(s[Number(t)]??"").replace(/<[^>]*>/g,"")));let o=e;o=o.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,s)=>r(`<code>${j(n(s.trim()))}</code>`)),o=o.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>r(j(t))),o=o.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>r(`<a href="${q(t)}">${j(t)}</a>`)),t.html&&(o=o.replace(/<\/?[A-Za-z][^>]*>/g,e=>r(e))),o=o.replace(/!\[([^\[\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,s)=>r(`<img src="${q(i(n))}" alt="${j(i(t))}"${s?` title="${j(i(s))}"`:""}>`)),o=o.replace(/\[([^\[\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,o,a,c)=>r(`<a href="${q(i(a))}"${c?` title="${j(i(c))}"`:""}>${L(o,t,n,s)}</a>`)),o=o.replace(/&(?!#\d{1,7};|#x[0-9a-f]{1,6};|[a-z][a-z0-9]{1,31};)/gi,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;"),o=o.replace(/(\*\*\*|___)(?=\S)([\s\S]*?\S)\1/g,"<strong><em>$2</em></strong>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*\*|__)(?![*_])([\s\S]*?\S)(\*|_)(?![*_])/g,"<em><strong>$2</strong>$4</em>"),o=o.replace(/(\*\*\*|___)(?=\S)([^*_]*?\S)(\*|_)(?![*_])([\s\S]*?\S)(\*\*|__)(?![*_])/g,"<strong><em>$2</em>$4</strong>"),o=o.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),o=o.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),o=o.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),o=o.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),o=o.replace(/( {2,}|\\)\n/g,"<br>\n");for(let e=0;e<8&&/\uE002\d+\uE003/.test(o);e++)o=o.replace(z,(e,t)=>s[Number(t)]??"");return o}const W=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,C=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,R=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/,D=e=>W.test(e)&&!/^ {0,3}[-=]+\s*$/.test(e)&&!/^ {0,3}(?!1[.)])\d{1,9}[.)]\s/.test(e);function I(e){const t=e.trim();let n=t.length;for(;n>0&&"#"===t[n-1];)n--;return n===t.length?t:0===n?"":/[ \t]/.test(t[n-1])?t.slice(0,n).trimEnd():t}function T(e,t,n,s=0){const r=[];let i=0;const o=e=>L(e,t,n);if(s>100)return`<p>${o(e.join("\n"))}</p>`;for(;i<e.length;){const a=e[i];if(!a.trim()){i++;continue}const c=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(a);if(c){const t=[];for(i++;i<e.length&&!new RegExp(`^ {0,3}${"`"===c[1][0]?"`":"~"}{${c[1].length},}\\s*$`).test(e[i]);)t.push(e[i++]);i++;const s=c[2]?` class="language-${j(c[2])}"`:"";r.push(`<pre><code${s}>${j(n(t.join("\n")))}</code></pre>`);continue}const l=/^ {0,3}(#{1,6})[ \t]+/.exec(a);if(l){r.push(`<h${l[1].length}>${o(I(a.slice(l[0].length)))}</h${l[1].length}>`),i++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(a)){r.push("<hr>"),i++;continue}if(/^ {0,3}>/.test(a)){const o=[];for(;i<e.length&&e[i].trim()&&(/^ {0,3}>/.test(e[i])||o.length);)o.push(e[i].replace(/^ {0,3}> ?/,"")),i++;r.push(`<blockquote>\n${T(o,t,n,s+1)}\n</blockquote>`);continue}const u=C.exec(a);if(u){const o=/\d/.test(u[2]),a=o?parseInt(u[2],10):1,c=[];let l=!1;for(;i<e.length;){const t=C.exec(e[i]);if(!t||/\d/.test(t[2])!==o)break;const n=t[0].length,s=[e[i].slice(n)];for(i++;i<e.length;){const t=e[i];if(!t.trim()){const t=e[i+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){s.push(""),l=!0,i++;continue}void 0!==t&&C.test(t)&&(l=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))s.push(t.slice(Math.min(n,4)));else{if(C.test(t)||W.test(t))break;s.push(t)}i++}for(c.push(s);i<e.length&&!e[i].trim()&&void 0!==e[i+1]&&C.test(e[i+1]);)i++}const d=o?"ol":"ul",p=c.map(e=>{let r=T(e,t,n,s+1);return l||(r=r.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${r}</li>`});r.push(`<${d}${o&&1!==a?` start="${a}"`:""}>\n${p.join("\n")}\n</${d}>`);continue}if(a.includes("|")&&void 0!==e[i+1]&&R.test(e[i+1])&&e[i+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[i+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),s=(e,t,s)=>`<${e}${n[s]?` style="text-align:${n[s]}"`:""}>${o(t)}</${e}>`,c=t(a);i+=2;const l=[];for(;i<e.length&&e[i].trim()&&e[i].includes("|");)l.push(t(e[i++]));r.push(`<table>\n<thead><tr>${c.map((e,t)=>s("th",e,t)).join("")}</tr></thead>\n<tbody>\n${l.map(e=>`<tr>${c.map((t,n)=>s("td",e[n]??"",n)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(a)){const t=[];for(;i<e.length&&(/^( {4}|\t)/.test(e[i])||!e[i].trim());)t.push(e[i++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();r.push(`<pre><code>${j(n(t.join("\n")))}</code></pre>`);continue}const d=[];for(;i<e.length&&e[i].trim()&&(!d.length||!D(e[i]));){if(d.length&&/^ {0,3}(=+|-+)\s*$/.test(e[i])){const t="="===e[i].trim()[0]?1:2;r.push(`<h${t}>${o(d.join("\n"))}</h${t}>`),d.length=0,i++;break}d.push(e[i].replace(/^ {0,3}/,"")),i++}d.length&&r.push(`<p>${o(d.join("\n"))}</p>`)}return r.join("\n")}function H(e,t={},n=e=>e){return T(String(e).replace(/\r\n?/g,"\n").replace(/[\uE002\uE003]/g,"�").split("\n"),t,n)}function V({text:e,math:t,drawn:n},s){return(s.render?s.render(e):H(e,s,e=>e.replace(_,(e,n)=>t[Number(n)]?.raw??""))).replace(new RegExp("<p>\\s*(\\d+)\\s*</p>","g"),(e,s)=>t[Number(s)].display&&n[Number(s)]?`<div class="mv-md-block">${n[Number(s)]}</div>`:e).replace(_,(e,t)=>n[Number(t)]??"").replace(/<p>\s*<\/p>\n?/g,"")}function Z(e,t={}){return V(O(e,t,t.variables||null),t)}const B=new WeakMap,J=new Set;function F(){for(const e of J)e.connected()&&!e.element.isConnected&&e.stop(!0)}function G(t,n,s={}){const r=void 0===s.variables?k:s.variables||null;F();const a=B.get(t);a&&a.stop(a.store!==r);let c=O(n,s,r,t);if(t.innerHTML=V(c,s),!r)return B.delete(t),t;r.own(t,c.defs);let d=t.isConnected;const p=n=>{const i=n.target,o=i&&i.dataset&&i.dataset.mvVar;if(void 0!==o&&t.contains(i)){if("text"===i.type)try{e(i.value,{blocks:s.blocks,scope:{}}),i.removeAttribute("aria-invalid")}catch{return void i.setAttribute("aria-invalid","true")}r.set(o,i.value)}},h=a=>{const d=a.target.closest?.("[data-node]"),p=d&&d.closest("[data-mv-md]");if(!p||!t.contains(p))return;const h=Number(p.dataset.mvMd),m=c.trees[h];if(!m)return;const g=Number(d.dataset.node),$=i(m,g)||[];let v=null;for(let e=$.length;e>=0&&!v;e--){const t=o(m,$.slice(0,e));t&&void 0!==t.from&&(v={node:t,depth:e})}const b=v&&r.definitions().get(v.node.from);if(b&&b.input&&"textbox"===b.input.kind){a.preventDefault();const n=b.name,i=t.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(n)}"]`),c=s.editable&&s.editable.toText;if(!c)return void(i&&(i.focus(),i.select()));const p=t=>e(t),h=o(m,$);return void l(d,c(f(h,p)),{label:`Edit ${n}`,parse:t=>e(t,{blocks:s.blocks}),commit:e=>{const t=u(f(v.node,p),$.slice(v.depth),e);r.set(n,c(t))}})}const x=b&&c.defs.get(b.name),w=x&&x.key===b.key&&void 0!==x.start?{...c.math[h],start:x.start,end:x.end,raw:n.slice(x.start,x.end)}:c.math[h];t.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:h,start:w.start,end:w.end,raw:w.raw,source:w.source,id:g,path:$}}))};t.addEventListener("input",p),t.addEventListener("change",p),t.addEventListener("dblclick",h);const m=r.subscribe(e=>{e!==t&&(t.isConnected?(d=!0,F(),(()=>{const e=O(n,s,r,t);e.drawn.forEach((n,s)=>{if(n===c.drawn[s]||e.inputs.has(s))return;const r=t.querySelector(`[data-mv-md="${s}"]`);r&&(r.outerHTML=n)});for(const n of t.querySelectorAll("[data-mv-var], [data-mv-out]")){const t=e.defs.get(n.dataset.mvVar??n.dataset.mvOut);if(!t)continue;const s=r.textOf(t);void 0!==n.dataset.mvOut?n.textContent=s:n.value!==s&&n!==n.ownerDocument?.activeElement&&(n.value=s)}c=e})()):d&&g(!0))});function g(e){m(),t.removeEventListener("input",p),t.removeEventListener("change",p),t.removeEventListener("dblclick",h),J.delete($),B.delete(t),e&&r.own(t,null)}const $={element:t,store:r,stop:g,connected:()=>d};return J.add($),B.set(t,$),t}export{y as Variables,S as createVariables,E as extractMath,Z as markdownToHTML,H as renderMarkdown,G as renderMarkdownInto,k as variables};
package/inlinemath.css CHANGED
@@ -70,8 +70,10 @@
70
70
 
71
71
  /* ---- radicals (metric: border and padding-top) ----------------------------- */
72
72
  .mv-sqrt { display: inline-block; white-space: nowrap; }
73
- .mv-hook { display: inline-block; overflow: visible; margin-left: 0.05em; }
74
- .mv-radicand { display: inline-block; border-top: 0.06em solid currentColor; padding: 0.1em 0.1em 0 0.06em; }
73
+ .mv-radicand { display: inline-block; position: relative; border-top: 0.06em solid currentColor; padding: 0.1em 0.1em 0 0.06em; }
74
+ /* the hook, in the radicand's left margin (layout.js sets its width and that margin): from the bar's center
75
+ (just below the middle of the 0.06em border above the box) to the bottom of what it holds, so the tip always meets the bar */
76
+ .mv-hook { position: absolute; top: -0.02em; height: calc(100% + 0.02em); overflow: visible; } /* a hair below the center: never above the bar */
75
77
  .mv-rootindex { display: inline-block; margin: 0 -0.32em 0 0.12em; }
76
78
 
77
79
  /* ---- delimiters: drawn at the full height of what they enclose -------------- */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mathzetta/inlinemath",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Draw calculus-level math as HTML and CSS from anything MathZetta reads, with every part addressable.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -46,13 +46,13 @@
46
46
  "prepublishOnly": "npm test && npm run build"
47
47
  },
48
48
  "peerDependencies": {
49
- "@mathzetta/cas": "^0.2.0",
50
- "mathzetta": "^1.2.0"
49
+ "@mathzetta/cas": "^0.3.0",
50
+ "mathzetta": "^1.3.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@rollup/plugin-terser": "^0.4.4",
54
- "@mathzetta/cas": "^0.2.0",
55
- "mathzetta": "^1.2.0",
54
+ "@mathzetta/cas": "^0.3.0",
55
+ "mathzetta": "^1.3.0",
56
56
  "rollup": "^4.65.0"
57
57
  },
58
58
  "license": "MIT",
package/src/cas.js CHANGED
@@ -9,7 +9,8 @@
9
9
  * toHTML('{{solve(x^2 - 5x + 6 = 0, x)}}', { blocks: casBlocks() }) // x = 2 or x = 3
10
10
  * stepsHTML(mathCAS().diff('x^2 sin x', 'x', { steps: 'brief' }).steps)
11
11
  *
12
- * Block functions: simplify, expand, factor, cancel, diff(f, x[, n]) (or der, derivative,
12
+ * Block functions: simplify, expand, factor, cancel, limit(f, x, a[, right | left]) or limit(f, x -> a^+) (and \lim_{x \to a} as
13
+ * written), diff(f, x[, n]) (or der, derivative,
13
14
  * differentiate), integrate(f, x[, a, b]) (or integral), solve(equation, x), approx(expr[, digits]);
14
15
  * d/dx … and ∫ … without limits go to the CAS too. In Markdown, saved variables ($_f := x^3$)
15
16
  * stand for their expressions: {{diff(f, x)}}. Everything else is MathZetta's calculator (calculateBlock), as without this.
@@ -19,7 +20,7 @@
19
20
 
20
21
  import { createCAS, toText as plainText } from '@mathzetta/cas';
21
22
  import { parse as parsePostfix } from '@mathzetta/cas/engine';
22
- import { parse, operator } from './mathzetta.js';
23
+ import { parse, operator, fromPostfix, walk } from './mathzetta.js';
23
24
  import { calculateBlock } from './calculator.js';
24
25
  // Only this entry needs MathZetta's text writer (so only pages using inlinemath/cas map 'mathzetta/text').
25
26
  import { toText } from 'mathzetta/text';
@@ -51,6 +52,38 @@ export function tokensOf(node) {
51
52
  return out;
52
53
  }
53
54
 
55
+ /** The names a call works in: diff(f, x), diff(f, x = a), integrate(f, x …), solve(eq, x), limit(f, x, a); d/dx, ∫ … dx, lim_{x→a}. */
56
+ function boundNames(tokens) {
57
+ let tree;
58
+ try { tree = fromPostfix(tokens); } catch { return new Set(); }
59
+ const name = (n) => (n?.type === 'symbol' ? n.value : n?.type === 'op' && ['=', '→'].includes(n.op) && n.args[0].type === 'symbol' ? n.args[0].value : null);
60
+ const out = new Set();
61
+ walk(tree, (n) => {
62
+ if (n.type !== 'op' || n.args.length < 2) return;
63
+ const call = n.op.startsWith('\\:') ? n.op.slice(2) : n.op;
64
+ if (['der', 'int', 'lim', 'diff', 'derivative', 'differentiate', 'integrate', 'integral', 'solve', 'limit'].includes(call) && name(n.args[1])) out.add(name(n.args[1]));
65
+ });
66
+ return out;
67
+ }
68
+
69
+ /** Postfix with the scope's numbers (and number-like text: '1/3') put in for its names, but not for the names a call binds. */
70
+ function withValues(tokens, scope) {
71
+ if (!scope) return tokens;
72
+ const values = new Map();
73
+ for (const [k, v] of Object.entries(scope)) {
74
+ if (typeof v === 'number' ? !Number.isFinite(v) : typeof v !== 'bigint' && typeof v !== 'string') continue;
75
+ try { values.set(k, parse(String(v))); } catch { /* not a value: left as the name */ }
76
+ }
77
+ if (!values.size) return tokens;
78
+ const bound = boundNames(tokens);
79
+ return tokens.flatMap((t) => (values.has(t) && !bound.has(t) ? values.get(t) : [t]));
80
+ }
81
+
82
+ const SIDES = { right: 'right', r: 'right', '+': 'right', left: 'left', l: 'left', '-': 'left' };
83
+ const CALLS = new Set(['simplify', 'expand', 'factor', 'cancel', 'diff', 'integrate', 'solve', 'approx', 'limit']);
84
+ // other names people write for them
85
+ const ALIASES = { integral: 'integrate', differentiate: 'diff', approximate: 'approx', simp: 'simplify' };
86
+
54
87
  /**
55
88
  * A CAS that reads and writes MathZetta text. Options go to @mathzetta/cas's createCAS
56
89
  * (rules: your rule files; complex: true for i = √-1); `names` are functions of your
@@ -60,10 +93,11 @@ export function tokensOf(node) {
60
93
  export function mathCAS(options = {}) {
61
94
  const key = options.rules || options.names ? null : options.complex ? 'complex' : 'default';
62
95
  if (key && shared.has(key)) return shared.get(key);
63
- const names = [...(options.names ?? []), ...(options.complex ? COMPLEX_NAMES : [])];
96
+ // the block calls are names too: in LaTeX ({{simplify(\sec^2 x - \tan^2 x)}}) a word is otherwise letters side by side
97
+ const names = [...(options.names ?? []), ...(options.complex ? COMPLEX_NAMES : []), ...CALLS, ...Object.keys(ALIASES)];
64
98
  const cas = createCAS({
65
99
  ...options,
66
- read: (text) => parse(text, names.length ? { names } : {}),
100
+ read: (text) => parse(text, { names }),
67
101
  // explanations read "3x^2", "sin(3x)"; a block's answer is MathZetta text, so it is read back exactly
68
102
  format: plainText,
69
103
  });
@@ -71,9 +105,6 @@ export function mathCAS(options = {}) {
71
105
  return cas;
72
106
  }
73
107
 
74
- const CALLS = new Set(['simplify', 'expand', 'factor', 'cancel', 'diff', 'integrate', 'solve', 'approx']);
75
- // other names people write for them
76
- const ALIASES = { integral: 'integrate', differentiate: 'diff', approximate: 'approx', simp: 'simplify' };
77
108
 
78
109
  /**
79
110
  * A `{{…}}` handler: pass it as toHTML(input, { blocks: casBlocks() }).
@@ -93,11 +124,14 @@ export function casBlocks(options = {}) {
93
124
  // saved variables ($_f := x^3$ in Markdown) stand for their expressions: {{diff(f, x)}}
94
125
  const saved = scope && scope[EXPRESSIONS];
95
126
  if (saved) tokens = tokens.flatMap((t) => (Object.hasOwn(saved, t) ? saved[t] : [t]));
127
+ // values for every name but the one the call works in: with a = 2, {{diff(x^3, x = a)}} is 12 and {{solve(x^2 = a, x)}}
128
+ // is x = ±√2, while the x of diff(…, x) stays a variable
129
+ tokens = withValues(tokens, scope);
96
130
  const head = tokens[tokens.length - 1];
97
131
  const name = head?.startsWith('\\:') ? (ALIASES[head.slice(2)] ?? head.slice(2)) : null;
98
132
  const symbolic = name && CALLS.has(name);
99
- // d/dx …, ∫ … dx and ∫ from a to b … dx (MathZetta writes the limits as int's 3rd and 4th operands)
100
- const calculus = head === 'der' || head === 'int';
133
+ // d/dx …, ∫ … dx and ∫ from a to b … dx (MathZetta writes the limits as int's 3rd and 4th operands), lim
134
+ const calculus = head === 'der' || head === 'int' || head === 'lim';
101
135
  if (!symbolic && !calculus) return calculateBlock(text, scope);
102
136
  const node = cas.node(tokens);
103
137
  // the CAS works a derivative at a point out as it reads it (der(f, x = a)): what arrives is the answer's expression
@@ -112,9 +146,20 @@ export function casBlocks(options = {}) {
112
146
  const at = cas.substitute(d.result, { [name]: by.args[1].s }, how);
113
147
  return { ...at, steps: [...(d.steps ?? []), ...(at.steps ?? [])] };
114
148
  };
149
+ // limit(f, x, a[, side]) with side right/left (r, l, +, -), or limit(f, x -> a), limit(f, x -> a^+)
150
+ const limitCall = ([f, by, to, side]) => {
151
+ let where = side ? SIDES[side.s.replace(/^\\/, '')] : undefined;
152
+ if (side && !where) throw new Error(`a side is right or left, not ${side.s}`);
153
+ if (by && by.op === '→') {
154
+ [by, to] = by.args;
155
+ const mark = to.op === '^' ? to.args[1].s.replace(/^\\/, '') : null;
156
+ if (mark === '+' || mark === '-') { where = SIDES[mark]; to = to.args[0]; }
157
+ }
158
+ return cas.limit(f, word(by), to, { ...how, ...(where ? { side: where } : {}) });
159
+ };
115
160
  let r;
116
161
  try {
117
- switch (worked ? 'simplify-read' : symbolic ? name : head === 'der' ? 'derivative' : 'antiderivative') {
162
+ switch (worked ? 'simplify-read' : symbolic ? name : head === 'der' ? 'derivative' : head === 'lim' ? 'lim' : 'antiderivative') {
118
163
  case 'simplify-read': r = cas.simplify(node, how); break;
119
164
  case 'simplify': r = cas.simplify(args[0], how); break;
120
165
  case 'expand': r = cas.expand(args[0], how); break;
@@ -123,6 +168,8 @@ export function casBlocks(options = {}) {
123
168
  case 'diff': r = derivative(args[0], args[1], args[2] ? Number(args[2].s) : 1); break;
124
169
  case 'integrate': r = cas.integrate(args[0], word(args[1]), { ...how, ...(args[3] ? { from: args[2].s, to: args[3].s } : {}) }); break;
125
170
  case 'solve': r = cas.solve(args[0], word(args[1]), how); break;
171
+ case 'lim': r = cas.limit(node, undefined, undefined, how); break;
172
+ case 'limit': r = limitCall(args); break;
126
173
  case 'approx': r = cas.approximate(args[0], { ...how, digits: args[1] ? Number(args[1].s) : 15 }); break;
127
174
  case 'derivative': r = derivative(node.args[0], node.args[1], 1); break;
128
175
  default: r = cas.integrate(node, undefined, how); break;
package/src/glyphs.js CHANGED
@@ -16,8 +16,9 @@ export const PATHS = {
16
16
  ')': { fill: 'M0.08,0 C0.9,0.2 0.9,0.8 0.08,1 L0,0.975 C0.52,0.75 0.52,0.25 0,0.025 Z' },
17
17
  '{': { fill: 'M1,0 C0.45,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.35,0.49 0.05,0.5 C0.35,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.45,1 1,1 L1,0.985 C0.68,0.985 0.64,0.95 0.64,0.8 L0.64,0.62 C0.64,0.53 0.55,0.505 0.3,0.5 C0.55,0.495 0.64,0.47 0.64,0.38 L0.64,0.2 C0.64,0.05 0.68,0.015 1,0.015 Z' },
18
18
  '}': { fill: 'M0,0 C0.55,0 0.5,0.05 0.5,0.2 L0.5,0.38 C0.5,0.46 0.65,0.49 0.95,0.5 C0.65,0.51 0.5,0.54 0.5,0.62 L0.5,0.8 C0.5,0.95 0.55,1 0,1 L0,0.985 C0.32,0.985 0.36,0.95 0.36,0.8 L0.36,0.62 C0.36,0.53 0.45,0.505 0.7,0.5 C0.45,0.495 0.36,0.47 0.36,0.38 L0.36,0.2 C0.36,0.05 0.32,0.015 0,0.015 Z' },
19
- // Radical: short tick, long down-stroke, long up-stroke to the top right.
20
- 'sqrt': { stroke: 'M0,0.62 L0.18,0.55 L0.45,0.97 L0.98,0.015' },
19
+ // Radical: short tick, long down-stroke, long up-stroke to the top right, ending at the very top
20
+ // (y = 0), which CSS puts on the center of the bar (.mv-hook).
21
+ 'sqrt': { stroke: 'M0,0.62 L0.18,0.55 L0.45,0.97 L0.98,0' },
21
22
  // \cancel: one stroke, bottom left to top right, stretched over what it crosses out.
22
23
  'cancel': { stroke: 'M0,1 L1,0' },
23
24
  // Integral: an S slanted to the right with small hooks at each end.
package/src/layout.js CHANGED
@@ -39,7 +39,7 @@ const OP_CLASS = {
39
39
  '+': 'add', '-': 'sub', '*': 'mul', '/': 'frac', '^': 'pow', '_': 'subscript', 'neg': 'neg', 'pm': 'pm',
40
40
  '!': 'factorial', '=': 'eq', '===': 'eq', '≠': 'neq', '≠=': 'neq', '<': 'lt', '>': 'gt', '≤': 'le', '≥': 'ge',
41
41
  '≈': 'approx', '≡': 'equiv', '∈': 'in', '∉': 'notin', '∪': 'union', '∩': 'intersect', '→': 'to', '±': 'pm',
42
- '&': 'and', '|': 'or', '\\not': 'not', '\\xor': 'xor', '\\nand': 'nand', '\\nor': 'nor', '?:': 'cases',
42
+ '&': 'and', '|': 'or', '\\not': 'not', '\\xor': 'xor', '\\nand': 'nand', '\\nor': 'nor', '\\implies': 'implies', '\\iff': 'iff', '?:': 'cases',
43
43
  '()': 'tuple', '[]': 'list', '{}': 'set', '(]': 'interval', '[)': 'interval',
44
44
  '\\sumidx': 'sum', '\\prodidx': 'prod', 'mod': 'mod', 'pmod': 'pmod',
45
45
  pmatrix: 'matrix', bmatrix: 'matrix', vmatrix: 'matrix',
@@ -48,12 +48,12 @@ const OP_CLASS = {
48
48
  const RELATIONS = {
49
49
  '=': '=', '===': '=', '≠': '≠', '≠=': '≠', '<': '<', '>': '>', '≤': '≤', '≥': '≥',
50
50
  '∈': '∈', '∉': '∉', '→': '→', '≈': '≈', '≡': '≡',
51
- '&': '∧', '|': '∨', '\\xor': '⊕', '\\nand': '↑', '\\nor': '↓',
51
+ '&': '∧', '|': '∨', '\\xor': '⊕', '\\nand': '↑', '\\nor': '↓', '\\implies': '⇒', '\\iff': '⇔',
52
52
  };
53
53
  const BINARY = { '±': '±', '∪': '∪', '∩': '∩', 'mod': 'mod' };
54
54
 
55
55
  const TRIG = ['sin', 'cos', 'tan', 'csc', 'sec', 'cot', 'sinh', 'cosh', 'tanh'];
56
- const INVERSE = { arcsin: 'sin', arccos: 'cos', arctan: 'tan', arcsinh: 'sinh', arccosh: 'cosh', arctanh: 'tanh' };
56
+ const INVERSE = { arcsin: 'sin', arccos: 'cos', arctan: 'tan', arcsec: 'sec', arccsc: 'csc', arccot: 'cot', arcsinh: 'sinh', arccosh: 'cosh', arctanh: 'tanh' };
57
57
  /** Functions written with a name and, when the argument is simple, no brackets: sin x, ln x. */
58
58
  const NAMED = [...TRIG, ...Object.keys(INVERSE), 'ln', 'det'];
59
59
  /** Functions always written with brackets: max(a, b). */
@@ -191,6 +191,18 @@ class Layout {
191
191
  }
192
192
 
193
193
  number(node) {
194
+ // a repeating decimal, 0.166.. (read from 0.1\overline{6}): the block drawn once, with a bar over it
195
+ const repeating = /^(-?\d*\.)(\d*)\.\.$/.exec(node.value);
196
+ if (repeating) {
197
+ const [, head, frac] = repeating;
198
+ let L = 1;
199
+ for (let k = 1; 2 * k <= frac.length; k++) if (frac.slice(-k) === frac.slice(-2 * k, -k)) { L = k; break; }
200
+ let prefix = frac;
201
+ while (prefix.endsWith(frac.slice(-L)) && prefix.length >= L) prefix = prefix.slice(0, -L);
202
+ const first = this.text('num', (head + prefix).replace(/^-/, MINUS));
203
+ const block = this.text('num', frac.slice(-L));
204
+ return this.wrap(node, ['number'], row(first, box(this.el('over', block.html), block.h + 0.14, block.d)));
205
+ }
194
206
  return this.wrap(node, ['number'], this.text('num', node.value.replace(/^-/, MINUS)));
195
207
  }
196
208
 
@@ -202,6 +214,7 @@ class Layout {
202
214
  if (/^[A-Za-z]$/.test(v) || /^[α-ω]$/.test(v)) return this.text('var', v);
203
215
  if (/^[A-Za-z]′+$/.test(v)) return box(this.el('var', escape(v[0])) + this.el('prime', escape(v.slice(1))));
204
216
  if (/^Δ[A-Za-z]$/.test(v)) return box(this.el('ord', 'Δ') + this.el('var', v[1]));
217
+ if (/^d[A-Za-zα-ω]$/.test(v)) return box(this.el('ord', 'd') + this.el('var', v[1])); // a differential: dx, dθ (the d upright)
205
218
  if (v.endsWith('⁻¹')) return this.script(this.symbol(v.slice(0, -2)), this.text('num', MINUS + '1'), { level: 0 });
206
219
  if (/^\\[A-Za-z]+$/.test(v)) return this.text('name', v.slice(1));
207
220
  if (/^[A-Za-z]{2,}$/.test(v)) return this.text('name', v); // upright, like \mathrm
@@ -223,6 +236,7 @@ class Layout {
223
236
  if (isCustomFunction(op)) return wrap(this.custom(node, ctx));
224
237
  const rows = matrixRows(node); // pmatrix, bmatrix, vmatrix, and [[1, 2], [3, 4]]
225
238
  if (rows) return wrap(this.matrix(node, rows, ctx));
239
+ if (op === '{}' && !args.length) return wrap(this.text('op', '∅')); // the empty set
226
240
  if (GROUPS[op]) return wrap(this.fence(this.list(args, ctx), ...GROUPS[op]));
227
241
  // a choice of equations or inequalities (a CAS's solutions) reads in words: x = 2 or x = 3
228
242
  if ((op === '|' || op === '&') && args.length >= 2 && args.every(isStatement)) {
@@ -292,6 +306,12 @@ class Layout {
292
306
  const term = (n, i) => (needsBrackets(parent, n, i ? 'right' : 'left') ? this.fence(r(n)) : r(n));
293
307
  return wrap(row(args.map((n, i) => (i ? [this.bin(op === 'sum' ? '+' : '·'), term(n, i)] : [term(n, i)])).flat()));
294
308
  }
309
+ case 'setbuilder': // {x | x > 2}
310
+ return wrap(this.fence(row(r(a), this.bin('|'), r(b)), '{', '}'));
311
+ case 'evaluated': { // [F]_a^b: F in square brackets, the limits on the right (the variable isn't drawn)
312
+ const limit = (n) => this.render(n, { ...ctx, level: ctx.level + 1 });
313
+ return wrap(this.script(this.fence(r(a), '[', ']'), limit(args[3]), ctx, limit(args[2])));
314
+ }
295
315
  case 'der':
296
316
  return wrap(this.derivative(node, ctx));
297
317
  case 'int':
@@ -460,13 +480,16 @@ class Layout {
460
480
  const top = Math.max(inner.h, LH) + GAP + RULE;
461
481
  const depth = Math.max(inner.d, LD);
462
482
  const height = top + depth;
463
- const hook = svg('sqrt', `${this.p}-hook`, `height:${em(height)};width:${em(0.5 + 0.06 * (height - 1))};vertical-align:${em(-depth)}`);
483
+ // The hook is drawn inside the radicand's box and sized by CSS to it (inlinemath.css .mv-hook), from the
484
+ // bar's center down: its tip meets the bar whatever the font or the content. Only its width is estimated.
485
+ const width = 0.5 + 0.06 * (height - 1);
486
+ const hook = svg('sqrt', `${this.p}-hook`, `width:${em(width)};left:${em(-width)}`);
464
487
  let pre = '';
465
488
  if (index) {
466
489
  const k = SCRIPT * 0.8;
467
490
  pre = this.el('rootindex', index.html, `font-size:${em(k)};vertical-align:${em((-depth + 0.55 * height) / k)}`);
468
491
  }
469
- return box(this.el('sqrt', pre + hook + this.el('radicand', inner.html)), top, depth);
492
+ return box(this.el('sqrt', pre + this.el('radicand', hook + inner.html, `margin-left:${em(width + 0.05)}`)), top, depth);
470
493
  }
471
494
 
472
495
  /**