@mathzetta/inlinemath 0.2.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.
- package/README.md +37 -33
- package/dist/cas.external.js +2 -2
- package/dist/cas.js +2 -2
- package/dist/chunks/calculate-DHvovDQK.js +2 -0
- package/dist/chunks/draw-Bw547gEd.js +2 -0
- package/dist/chunks/edit-BC9D1cIE.js +2 -0
- package/dist/chunks/edit-CCe3uoyk.js +2 -0
- package/dist/chunks/html-6HJlblNm.js +2 -0
- package/dist/chunks/html-DzjcaM8w.js +2 -0
- package/dist/chunks/lite-6yr4ed_k.js +2 -0
- package/dist/fonts/README-inlinemath-greek.txt +15 -0
- package/dist/fonts/fonts.css +19 -1
- package/dist/fonts/inlinemath-greek-italic.woff2 +0 -0
- package/dist/fonts/inlinemath-greek-regular.woff2 +0 -0
- package/dist/inlinemath-cas.external.global.min.js +2 -2
- package/dist/inlinemath-cas.global.min.js +2 -2
- package/dist/inlinemath-lite-calc.global.min.js +2 -2
- package/dist/inlinemath-lite.external.global.min.js +2 -2
- package/dist/inlinemath-lite.global.min.js +2 -2
- package/dist/inlinemath.css +21 -9
- package/dist/inlinemath.external.global.min.js +2 -2
- package/dist/inlinemath.external.js +2 -2
- package/dist/inlinemath.global.min.js +2 -2
- package/dist/inlinemath.js +2 -2
- package/dist/lite-calc.js +2 -2
- package/dist/lite.external.js +2 -2
- package/dist/lite.js +2 -2
- package/dist/markdown.external.js +2 -2
- package/dist/markdown.js +2 -2
- package/fonts/README-inlinemath-greek.txt +15 -0
- package/fonts/fonts.css +19 -1
- package/fonts/inlinemath-greek-italic.woff2 +0 -0
- package/fonts/inlinemath-greek-regular.woff2 +0 -0
- package/inlinemath.css +21 -9
- package/package.json +6 -6
- package/src/cas.d.ts +1 -1
- package/src/cas.js +71 -13
- package/src/draw.js +13 -9
- package/src/edit.js +11 -4
- package/src/glyphs.js +3 -2
- package/src/html.js +1 -1
- package/src/index.js +1 -1
- package/src/layout.js +117 -37
- package/src/lite.js +1 -1
- package/src/markdown.d.ts +1 -1
- package/src/markdown.js +139 -57
- package/src/mathzetta.js +2 -2
- package/src/select.js +7 -0
- package/src/types.d.ts +12 -10
- package/src/variables.js +44 -10
- package/src/view.js +69 -18
- package/dist/chunks/calculate-Cz87Lt0N.js +0 -2
- package/dist/chunks/draw-Bev17BJJ.js +0 -2
- package/dist/chunks/edit-C65xXzo8.js +0 -2
- package/dist/chunks/edit-M68aRA5o.js +0 -2
- package/dist/chunks/html-BimAqn7x.js +0 -2
- package/dist/chunks/html-CupluJSh.js +0 -2
- package/dist/chunks/lite-3Fb-OHbt.js +0 -2
package/dist/inlinemath.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/* Inline Math 0.
|
|
2
|
-
import{t}from"./chunks/html-
|
|
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.
|
|
2
|
-
import{c}from"./chunks/calculate-
|
|
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};
|
package/dist/lite.external.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/* Inline Math 0.
|
|
2
|
-
export{D as DEFAULTS,l as layout,n as numberTree,s as select,t as toHTML,a as treeOf}from"./chunks/draw-
|
|
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.
|
|
2
|
-
export{D as DEFAULTS,l as layout,d as numberTree,s as select,e as toHTML,f as treeOf}from"./chunks/lite-
|
|
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.
|
|
2
|
-
import{t as e,a as t}from"./chunks/html-BimAqn7x.js";import{calculate as n}from"mathzetta/calculate";import{v as s,o as r,r as a,u as i,s as o,E as l,b as u,n as d,i as p}from"./chunks/edit-C65xXzo8.js";export{V as Variables,c as createVariables}from"./chunks/edit-C65xXzo8.js";import{toPostfix as m}from"mathzetta";import"mathzetta/speech";import{p as h,c as f,n as $}from"./chunks/draw-Bev17BJJ.js";const g=new RegExp("(\\d+)","g");function v(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let s="",r=0;const a=String(e),i=e=>0===e||"\n"===a[e-1],o=(e,t,s)=>(n.push({source:e,display:t,raw:s,start:r,end:r+s.length}),`${n.length-1}`);for(;r<a.length;){if(i(r)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(a.slice(r));if(e){const t=e[2],n=new RegExp(`\\n {0,3}${"`"===t[0]?"`":"~"}{${t.length},}[ \\t]*(?=\\n|$)`),i=a.slice(r+e[0].length),c=n.exec(`\n${i}`),l=c?i.slice(0,Math.max(0,c.index-1)):i,u=e[0].length+(c?c.index-1+c[0].length:i.length),d=a.slice(r,r+u);"math"===e[3].trim()?s+=o(l,!0,d):s+=d,r+=u;continue}}const e=a[r];if("`"===e){const e=/^`+/.exec(a.slice(r))[0],t=a.indexOf(e,r+e.length);if(t>-1){s+=a.slice(r,t+e.length),r=t+e.length;continue}s+=e,r+=e.length;continue}if("\\"===e){const e=a.slice(r,r+2),n="\\["===e?"\\]":"\\("===e?"\\)":null;if(n&&t.includes(e)){const t=a.indexOf(n,r+2);if(t>-1){s+=o(a.slice(r+2,t),"\\["===e,a.slice(r,t+2)),r=t+2;continue}}s+=e,r+=2;continue}if("$"===e)if("$"===a[r+1]&&t.includes("$$")){const e=a.indexOf("$$",r+2);if(e>-1){s+=o(a.slice(r+2,e),!0,a.slice(r,e+2)),r=e+2;continue}}else if(t.includes("$")&&a[r+1]&&!/\s/.test(a[r+1])){const e=b(a,r+1);if(e>-1){s+=o(a.slice(r+1,e),!1,a.slice(r,e+1)),r=e+1;continue}}s+=e,r++}return{text:s,math:n}}function b(e,t){for(let n=t;n<e.length;n++){const t=e[n];if("\\"!==t){if("`"===t)return-1;if("\n"===t&&/^\n[ \t]*\n/.test(e.slice(n)))return-1;if("$"===t&&!/\s/.test(e[n-1])&&!/\d/.test(e[n+1]??"")&&"$"!==e[n+1])return n}else n++}return-1}const x=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),y=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function k(s,r,a,i){const{text:c,math:h}=v(s,r),f=a?a.definitions(i):new Map,g=e=>a?a.textOf(e):e.text,b={...r.scope??{}},k={},w=new Map,S=new Set,E=[],j=()=>{for(const e of Object.keys(k))delete k[e];Object.assign(k,b);for(const e of f.keys())delete k[e];let e=[...f.values()];for(;e.length;){const t=e.filter(e=>{try{const t=n(g(e),k);if("number"==typeof t.value||"bigint"==typeof t.value||Array.isArray(t.value))return k[e.name]=t.exact?t.text:t.value,!1}catch{}return!0});if(t.length===e.length)break;e=t}const t={},s=_({});for(const e of f.keys()){const n=s(e);if(n)try{t[e]=m(o(n,t=>t===e?null:s(t)).tree)}catch{}}k[l]=t},_=t=>{const n=new Map;return s=>{const r=f.get(s);if(!r)return null;if(!n.has(s)){let a=null;try{a=e(g(r),t)}catch{}n.set(s,a)}return n.get(s)}};j();const M=h.map((s,a)=>{const{source:i,display:c}=s,l=c?"mv-md-display":"mv-md-math",m=(e,t="")=>`<span class="${l}${t}" data-mv-md="${a}">${e}</span>`;try{const l={...r.math,display:c,blocks:r.blocks,scope:k},h=function(t){let n=t.trim();const s=n.startsWith("_");s&&(n=n.slice(1).trimStart());let r=n.indexOf(":="),a=2;r<0&&s&&(r=n.search(/(?<![<>!≤≥=])=(?!=)/),a=1);const i=s?{error:"a hidden $_…$ saves a variable: $_A := 2+2$"}:null;if(r<=0)return i;const o=n.slice(0,r).trim(),c=n.slice(r+a).trim();let l=null;try{l=/\{\{/.test(o)?null:d(e(o))}catch{}return null!==l&&c?{hidden:s,lhs:o,name:l,rhs:c,input:p(c)}:i}(i);if(h&&h.error)throw new Error(h.error);if(h){const{name:n,input:r,hidden:i}=h,c=r?{name:n,text:r.default,input:r,key:`input:${JSON.stringify(r)}`}:{name:n,text:h.rhs,input:null,key:`expr:${h.rhs}`,start:s.start,end:s.end};let d="";if(r){const e=function(e,t){const{input:n,name:s}=e,r=`class="mv-md-input mv-md-${n.kind}" data-mv-var="${x(s)}" aria-label="${x(s)}"`;if("dropdown"===n.kind)return`<select ${r}>${n.options.map(e=>`<option value="${x(e)}"${e===t?" selected":""}>${x(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${r} min="${n.min}" max="${n.max}" step="${n.step}" value="${x(t)}"><output class="mv-md-output" data-mv-out="${x(s)}">${x(t)}</output>`:`<input type="text" ${r} value="${x(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(c,g(c));d=i?e:`${t(h.lhs,l)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,S.add(a)}else{const n=o(e(h.rhs,l),_(l)).tree;if(!i){const s=$({type:"op",op:"=",args:[u(e(h.lhs)),void 0===n.id?n:u(n)]});E[a]=s,d=function(e){return e.replace('<span class="mv-rel">=</span>','<span class="mv-rel mv-rel-def">≔</span>').replace(/(aria-label="[^"]*?) equals /,"$1 is defined as ").replace("<mo>=</mo>","<mo>≔</mo>")}(t(s,l))}}return f.delete(n),f.set(n,c),w.set(n,c),j(),i&&!r?"":m(d,r?" mv-md-input-def":"")}const{tree:v,changed:M}=o(e(i,l),_(l));M&&$(v),E[a]=v;const O=t(v,l);return!M&&!1!==r.define&&function(e,t,s){const r=y.exec(e);if(!r||/\{\{/.test(r[2]))return!1;const a=r[1].replace(/[{}]/g,"");if(s.has(a))return!1;try{const e=n(r[2],t);if("number"==typeof e.value||"bigint"==typeof e.value||Array.isArray(e.value))return t[a]=e.exact?e.text:e.value,!0}catch{}return!1}(i,b,f)&&j(),m(O)}catch(e){return`<span class="mv-md-error" data-mv-md="${a}" title="${x(e.message)}"><code>${x(s.raw)}</code></span>`}});return{text:c,math:h,drawn:M,defs:w,inputs:S,trees:E}}const w=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,S=e=>w.test(e.trim())?x(e.trim()):"#";function E(e,t,n){const s=[],r=e=>(s.push(e),`${s.length-1}`);let a=e;return a=a.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,s)=>r(`<code>${x(n(s.trim()))}</code>`)),a=a.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>r(x(t))),a=a.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>r(`<a href="${S(t)}">${x(t)}</a>`)),t.html&&(a=a.replace(/<\/?[A-Za-z][^>]*>/g,e=>r(e))),a=a.replace(/!\[([^\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,s)=>r(`<img src="${S(n)}" alt="${x(t)}"${s?` title="${x(s)}"`:""}>`)),a=a.replace(/\[([^\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,s,a,i)=>r(`<a href="${S(a)}"${i?` title="${x(i)}"`:""}>${E(s,t,n)}</a>`)),a=x(a),a=a.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),a=a.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),a=a.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),a=a.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),a=a.replace(/( {2,}|\\)\n/g,"<br>\n"),a.replace(/(\d+)/g,(e,t)=>s[Number(t)])}const j=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,_=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,M=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function O(e,t,n){const s=[];let r=0;const a=e=>E(e,t,n);for(;r<e.length;){const i=e[r];if(!i.trim()){r++;continue}const o=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(i);if(o){const t=[];for(r++;r<e.length&&!new RegExp(`^ {0,3}${"`"===o[1][0]?"`":"~"}{${o[1].length},}\\s*$`).test(e[r]);)t.push(e[r++]);r++;const a=o[2]?` class="language-${x(o[2])}"`:"";s.push(`<pre><code${a}>${x(n(t.join("\n")))}</code></pre>`);continue}const c=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(i);if(c){s.push(`<h${c[1].length}>${a(c[2])}</h${c[1].length}>`),r++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(i)){s.push("<hr>"),r++;continue}if(/^ {0,3}>/.test(i)){const a=[];for(;r<e.length&&e[r].trim()&&(/^ {0,3}>/.test(e[r])||a.length);)a.push(e[r].replace(/^ {0,3}> ?/,"")),r++;s.push(`<blockquote>\n${O(a,t,n)}\n</blockquote>`);continue}const l=_.exec(i);if(l){const a=/\d/.test(l[2]),i=a?parseInt(l[2],10):1,o=[];let c=!1;for(;r<e.length;){const t=_.exec(e[r]);if(!t||/\d/.test(t[2])!==a)break;const n=t[0].length,s=[e[r].slice(n)];for(r++;r<e.length;){const t=e[r];if(!t.trim()){const t=e[r+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){s.push(""),c=!0,r++;continue}void 0!==t&&_.test(t)&&(c=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))s.push(t.slice(Math.min(n,4)));else{if(_.test(t)||j.test(t))break;s.push(t)}r++}for(o.push(s);r<e.length&&!e[r].trim()&&void 0!==e[r+1]&&_.test(e[r+1]);)r++}const u=a?"ol":"ul",d=o.map(e=>{let s=O(e,t,n);return c||(s=s.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${s}</li>`});s.push(`<${u}${a&&1!==i?` start="${i}"`:""}>\n${d.join("\n")}\n</${u}>`);continue}if(i.includes("|")&&void 0!==e[r+1]&&M.test(e[r+1])&&e[r+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[r+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),o=(e,t,s)=>`<${e}${n[s]?` style="text-align:${n[s]}"`:""}>${a(t)}</${e}>`,c=t(i);r+=2;const l=[];for(;r<e.length&&e[r].trim()&&e[r].includes("|");)l.push(t(e[r++]));s.push(`<table>\n<thead><tr>${c.map((e,t)=>o("th",e,t)).join("")}</tr></thead>\n<tbody>\n${l.map(e=>`<tr>${c.map((t,n)=>o("td",e[n]??"",n)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(i)){const t=[];for(;r<e.length&&(/^( {4}|\t)/.test(e[r])||!e[r].trim());)t.push(e[r++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();s.push(`<pre><code>${x(n(t.join("\n")))}</code></pre>`);continue}const u=[];for(;r<e.length&&e[r].trim()&&(!u.length||!j.test(e[r])||/^ {0,3}[-=]+\s*$/.test(e[r]));){if(u.length&&/^ {0,3}(=+|-+)\s*$/.test(e[r])){const t="="===e[r].trim()[0]?1:2;s.push(`<h${t}>${a(u.join("\n"))}</h${t}>`),u.length=0,r++;break}u.push(e[r].replace(/^ {0,3}/,"")),r++}u.length&&s.push(`<p>${a(u.join("\n"))}</p>`)}return s.join("\n")}function A(e,t={},n=e=>e){return O(String(e).replace(/\r\n?/g,"\n").split("\n"),t,n)}function N({text:e,math:t,drawn:n},s){return(s.render?s.render(e):A(e,s,e=>e.replace(g,(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(g,(e,t)=>n[Number(t)]).replace(/<p>\s*<\/p>\n?/g,"")}function L(e,t={}){return N(k(e,t,t.variables||null),t)}const W=new WeakMap,q=new Set;function z(){for(const e of q)e.connected()&&!e.element.isConnected&&e.stop(!0)}function C(t,n,o={}){const c=void 0===o.variables?s:o.variables||null;z();const l=W.get(t);l&&l.stop(l.store!==c);let u=k(n,o,c,t);if(t.innerHTML=N(u,o),!c)return W.delete(t),t;c.own(t,u.defs);let d=t.isConnected;const p=n=>{const s=n.target,r=s&&s.dataset&&s.dataset.mvVar;if(void 0!==r&&t.contains(s)){if("text"===s.type)try{e(s.value,{blocks:o.blocks,scope:{}}),s.removeAttribute("aria-invalid")}catch{return void s.setAttribute("aria-invalid","true")}c.set(r,s.value)}},m=s=>{const l=s.target.closest?.("[data-node]"),d=l&&l.closest("[data-mv-md]");if(!d||!t.contains(d))return;const p=Number(d.dataset.mvMd),m=u.trees[p];if(!m)return;const $=Number(l.dataset.node),g=h(m,$)||[];let v=null;for(let e=g.length;e>=0&&!v;e--){const t=f(m,g.slice(0,e));t&&void 0!==t.from&&(v={node:t,depth:e})}const b=v&&c.definitions().get(v.node.from);if(b&&b.input&&"textbox"===b.input.kind){s.preventDefault();const n=b.name,u=t.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(n)}"]`),d=o.editable&&o.editable.toText;if(!d)return void(u&&(u.focus(),u.select()));const p=t=>e(t),h=f(m,g);return void r(l,d(i(h,p)),{label:`Edit ${n}`,parse:t=>e(t,{blocks:o.blocks}),commit:e=>{const t=a(i(v.node,p),g.slice(v.depth),e);c.set(n,d(t))}})}const x=b&&u.defs.get(b.name),y=x&&x.key===b.key&&void 0!==x.start?{...u.math[p],start:x.start,end:x.end,raw:n.slice(x.start,x.end)}:u.math[p];t.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:p,start:y.start,end:y.end,raw:y.raw,source:y.source,id:$,path:g}}))};t.addEventListener("input",p),t.addEventListener("change",p),t.addEventListener("dblclick",m);const $=c.subscribe(e=>{e!==t&&(t.isConnected?(d=!0,z(),(()=>{const e=k(n,o,c,t);e.drawn.forEach((n,s)=>{if(n===u.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=c.textOf(t);void 0!==n.dataset.mvOut?n.textContent=s:n.value!==s&&n!==n.ownerDocument?.activeElement&&(n.value=s)}u=e})()):d&&g(!0))});function g(e){$(),t.removeEventListener("input",p),t.removeEventListener("change",p),t.removeEventListener("dblclick",m),q.delete(v),W.delete(t),e&&c.own(t,null)}const v={element:t,store:c,stop:g,connected:()=>d};return q.add(v),W.set(t,v),t}export{v as extractMath,L as markdownToHTML,A as renderMarkdown,C as renderMarkdownInto,s 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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),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(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),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.
|
|
2
|
-
import{t as e,a as t}from"./chunks/html-CupluJSh.js";import{a as n}from"./chunks/calculate-Cz87Lt0N.js";import{v as s,o as r,r as a,u as i,s as o,E as l,b as u,n as d,i as p}from"./chunks/edit-M68aRA5o.js";export{V as Variables,c as createVariables}from"./chunks/edit-M68aRA5o.js";import{p as m,n as f,g as h,d as $}from"./chunks/lite-3Fb-OHbt.js";const g=new RegExp("(\\d+)","g");function v(e,{delimiters:t=["$$","$","\\[","\\("]}={}){const n=[];let s="",r=0;const a=String(e),i=e=>0===e||"\n"===a[e-1],o=(e,t,s)=>(n.push({source:e,display:t,raw:s,start:r,end:r+s.length}),`${n.length-1}`);for(;r<a.length;){if(i(r)){const e=/^( {0,3})(`{3,}|~{3,})([^\n]*)\n?/.exec(a.slice(r));if(e){const t=e[2],n=new RegExp(`\\n {0,3}${"`"===t[0]?"`":"~"}{${t.length},}[ \\t]*(?=\\n|$)`),i=a.slice(r+e[0].length),c=n.exec(`\n${i}`),l=c?i.slice(0,Math.max(0,c.index-1)):i,u=e[0].length+(c?c.index-1+c[0].length:i.length),d=a.slice(r,r+u);"math"===e[3].trim()?s+=o(l,!0,d):s+=d,r+=u;continue}}const e=a[r];if("`"===e){const e=/^`+/.exec(a.slice(r))[0],t=a.indexOf(e,r+e.length);if(t>-1){s+=a.slice(r,t+e.length),r=t+e.length;continue}s+=e,r+=e.length;continue}if("\\"===e){const e=a.slice(r,r+2),n="\\["===e?"\\]":"\\("===e?"\\)":null;if(n&&t.includes(e)){const t=a.indexOf(n,r+2);if(t>-1){s+=o(a.slice(r+2,t),"\\["===e,a.slice(r,t+2)),r=t+2;continue}}s+=e,r+=2;continue}if("$"===e)if("$"===a[r+1]&&t.includes("$$")){const e=a.indexOf("$$",r+2);if(e>-1){s+=o(a.slice(r+2,e),!0,a.slice(r,e+2)),r=e+2;continue}}else if(t.includes("$")&&a[r+1]&&!/\s/.test(a[r+1])){const e=b(a,r+1);if(e>-1){s+=o(a.slice(r+1,e),!1,a.slice(r,e+1)),r=e+1;continue}}s+=e,r++}return{text:s,math:n}}function b(e,t){for(let n=t;n<e.length;n++){const t=e[n];if("\\"!==t){if("`"===t)return-1;if("\n"===t&&/^\n[ \t]*\n/.test(e.slice(n)))return-1;if("$"===t&&!/\s/.test(e[n-1])&&!/\d/.test(e[n+1]??"")&&"$"!==e[n+1])return n}else n++}return-1}const x=e=>String(e).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),y=/^\s*([A-Za-z\u0370-\u03ff](?:_\{?\w+\}?)?)\s*=\s*([^=<>≤≥]+)$/;function k(s,r,a,i){const{text:c,math:m}=v(s,r),f=a?a.definitions(i):new Map,g=e=>a?a.textOf(e):e.text,b={...r.scope??{}},k={},w=new Map,S=new Set,j=[],E=()=>{for(const e of Object.keys(k))delete k[e];Object.assign(k,b);for(const e of f.keys())delete k[e];let e=[...f.values()];for(;e.length;){const t=e.filter(e=>{try{const t=n(g(e),k);if("number"==typeof t.value||"bigint"==typeof t.value||Array.isArray(t.value))return k[e.name]=t.exact?t.text:t.value,!1}catch{}return!0});if(t.length===e.length)break;e=t}const t={},s=_({});for(const e of f.keys()){const n=s(e);if(n)try{t[e]=h(o(n,t=>t===e?null:s(t)).tree)}catch{}}k[l]=t},_=t=>{const n=new Map;return s=>{const r=f.get(s);if(!r)return null;if(!n.has(s)){let a=null;try{a=e(g(r),t)}catch{}n.set(s,a)}return n.get(s)}};E();const M=m.map((s,a)=>{const{source:i,display:c}=s,l=c?"mv-md-display":"mv-md-math",m=(e,t="")=>`<span class="${l}${t}" data-mv-md="${a}">${e}</span>`;try{const l={...r.math,display:c,blocks:r.blocks,scope:k},h=function(t){let n=t.trim();const s=n.startsWith("_");s&&(n=n.slice(1).trimStart());let r=n.indexOf(":="),a=2;r<0&&s&&(r=n.search(/(?<![<>!≤≥=])=(?!=)/),a=1);const i=s?{error:"a hidden $_…$ saves a variable: $_A := 2+2$"}:null;if(r<=0)return i;const o=n.slice(0,r).trim(),c=n.slice(r+a).trim();let l=null;try{l=/\{\{/.test(o)?null:d(e(o))}catch{}return null!==l&&c?{hidden:s,lhs:o,name:l,rhs:c,input:p(c)}:i}(i);if(h&&h.error)throw new Error(h.error);if(h){const{name:n,input:r,hidden:i}=h,c=r?{name:n,text:r.default,input:r,key:`input:${JSON.stringify(r)}`}:{name:n,text:h.rhs,input:null,key:`expr:${h.rhs}`,start:s.start,end:s.end};let d="";if(r){const e=function(e,t){const{input:n,name:s}=e,r=`class="mv-md-input mv-md-${n.kind}" data-mv-var="${x(s)}" aria-label="${x(s)}"`;if("dropdown"===n.kind)return`<select ${r}>${n.options.map(e=>`<option value="${x(e)}"${e===t?" selected":""}>${x(e)}</option>`).join("")}</select>`;return"slider"===n.kind?`<input type="range" ${r} min="${n.min}" max="${n.max}" step="${n.step}" value="${x(t)}"><output class="mv-md-output" data-mv-out="${x(s)}">${x(t)}</output>`:`<input type="text" ${r} value="${x(t)}" size="${Math.max(4,t.length+1)}" spellcheck="false" autocomplete="off">`}(c,g(c));d=i?e:`${t(h.lhs,l)}<span class="mv-md-assign" aria-hidden="true">≔</span>${e}`,S.add(a)}else{const n=o(e(h.rhs,l),_(l)).tree;if(!i){const s=$({type:"op",op:"=",args:[u(e(h.lhs)),void 0===n.id?n:u(n)]});j[a]=s,d=function(e){return e.replace('<span class="mv-rel">=</span>','<span class="mv-rel mv-rel-def">≔</span>').replace(/(aria-label="[^"]*?) equals /,"$1 is defined as ").replace("<mo>=</mo>","<mo>≔</mo>")}(t(s,l))}}return f.delete(n),f.set(n,c),w.set(n,c),E(),i&&!r?"":m(d,r?" mv-md-input-def":"")}const{tree:v,changed:M}=o(e(i,l),_(l));M&&$(v),j[a]=v;const O=t(v,l);return!M&&!1!==r.define&&function(e,t,s){const r=y.exec(e);if(!r||/\{\{/.test(r[2]))return!1;const a=r[1].replace(/[{}]/g,"");if(s.has(a))return!1;try{const e=n(r[2],t);if("number"==typeof e.value||"bigint"==typeof e.value||Array.isArray(e.value))return t[a]=e.exact?e.text:e.value,!0}catch{}return!1}(i,b,f)&&E(),m(O)}catch(e){return`<span class="mv-md-error" data-mv-md="${a}" title="${x(e.message)}"><code>${x(s.raw)}</code></span>`}});return{text:c,math:m,drawn:M,defs:w,inputs:S,trees:j}}const w=/^(https?:|mailto:|#|\/|\.{0,2}\/|[^:]*$)/i,S=e=>w.test(e.trim())?x(e.trim()):"#";function j(e,t,n){const s=[],r=e=>(s.push(e),`${s.length-1}`);let a=e;return a=a.replace(/(`+)([\s\S]*?[^`])\1(?!`)/g,(e,t,s)=>r(`<code>${x(n(s.trim()))}</code>`)),a=a.replace(/\\([\\`*_{}[\]()#+\-.!|~$<>"'])/g,(e,t)=>r(x(t))),a=a.replace(/<((?:https?:\/\/|mailto:)[^\s>]+)>/g,(e,t)=>r(`<a href="${S(t)}">${x(t)}</a>`)),t.html&&(a=a.replace(/<\/?[A-Za-z][^>]*>/g,e=>r(e))),a=a.replace(/!\[([^\]]*)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,t,n,s)=>r(`<img src="${S(n)}" alt="${x(t)}"${s?` title="${x(s)}"`:""}>`)),a=a.replace(/\[([^\]]+)\]\(\s*((?:[^\s()]|\([^\s()]*\))+)(?:\s+"([^"]*)")?\s*\)/g,(e,s,a,i)=>r(`<a href="${S(a)}"${i?` title="${x(i)}"`:""}>${j(s,t,n)}</a>`)),a=x(a),a=a.replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/g,"<strong>$2</strong>"),a=a.replace(/(^|[^*\w])\*(?=\S)([\s\S]*?\S)\*(?!\*)/g,"$1<em>$2</em>"),a=a.replace(/(^|[^_\w])_(?=\S)([\s\S]*?\S)_(?![_\w])/g,"$1<em>$2</em>"),a=a.replace(/~~(?=\S)([\s\S]*?\S)~~/g,"<del>$1</del>"),a=a.replace(/( {2,}|\\)\n/g,"<br>\n"),a.replace(/(\d+)/g,(e,t)=>s[Number(t)])}const E=/^( {0,3})(#{1,6}\s|>|```|~~~|([-*+]|\d{1,9}[.)])\s|(\*[ \t]*){3,}$|(-[ \t]*){3,}$|(_[ \t]*){3,}$)/,_=/^( {0,3})([-*+]|\d{1,9}[.)])(\s+|$)/,M=/^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;function O(e,t,n){const s=[];let r=0;const a=e=>j(e,t,n);for(;r<e.length;){const i=e[r];if(!i.trim()){r++;continue}const o=/^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)/.exec(i);if(o){const t=[];for(r++;r<e.length&&!new RegExp(`^ {0,3}${"`"===o[1][0]?"`":"~"}{${o[1].length},}\\s*$`).test(e[r]);)t.push(e[r++]);r++;const a=o[2]?` class="language-${x(o[2])}"`:"";s.push(`<pre><code${a}>${x(n(t.join("\n")))}</code></pre>`);continue}const c=/^ {0,3}(#{1,6})\s+(.*?)\s*#*\s*$/.exec(i);if(c){s.push(`<h${c[1].length}>${a(c[2])}</h${c[1].length}>`),r++;continue}if(/^ {0,3}((\*[ \t]*){3,}|(-[ \t]*){3,}|(_[ \t]*){3,})$/.test(i)){s.push("<hr>"),r++;continue}if(/^ {0,3}>/.test(i)){const a=[];for(;r<e.length&&e[r].trim()&&(/^ {0,3}>/.test(e[r])||a.length);)a.push(e[r].replace(/^ {0,3}> ?/,"")),r++;s.push(`<blockquote>\n${O(a,t,n)}\n</blockquote>`);continue}const l=_.exec(i);if(l){const a=/\d/.test(l[2]),i=a?parseInt(l[2],10):1,o=[];let c=!1;for(;r<e.length;){const t=_.exec(e[r]);if(!t||/\d/.test(t[2])!==a)break;const n=t[0].length,s=[e[r].slice(n)];for(r++;r<e.length;){const t=e[r];if(!t.trim()){const t=e[r+1];if(void 0!==t&&t.startsWith(" ".repeat(Math.min(n,4)))&&t.trim()){s.push(""),c=!0,r++;continue}void 0!==t&&_.test(t)&&(c=!0);break}if(t.startsWith(" ".repeat(Math.min(n,4))))s.push(t.slice(Math.min(n,4)));else{if(_.test(t)||E.test(t))break;s.push(t)}r++}for(o.push(s);r<e.length&&!e[r].trim()&&void 0!==e[r+1]&&_.test(e[r+1]);)r++}const u=a?"ol":"ul",d=o.map(e=>{let s=O(e,t,n);return c||(s=s.replace(/^<p>([\s\S]*?)<\/p>/,"$1").replace(/\n<p>([\s\S]*?)<\/p>/g,"\n$1")),`<li>${s}</li>`});s.push(`<${u}${a&&1!==i?` start="${i}"`:""}>\n${d.join("\n")}\n</${u}>`);continue}if(i.includes("|")&&void 0!==e[r+1]&&M.test(e[r+1])&&e[r+1].includes("-")){const t=e=>e.trim().replace(/^\|/,"").replace(/\|$/,"").split(/(?<!\\)\|/).map(e=>e.trim()),n=t(e[r+1]).map(e=>e.startsWith(":")&&e.endsWith(":")?"center":e.endsWith(":")?"right":e.startsWith(":")?"left":""),o=(e,t,s)=>`<${e}${n[s]?` style="text-align:${n[s]}"`:""}>${a(t)}</${e}>`,c=t(i);r+=2;const l=[];for(;r<e.length&&e[r].trim()&&e[r].includes("|");)l.push(t(e[r++]));s.push(`<table>\n<thead><tr>${c.map((e,t)=>o("th",e,t)).join("")}</tr></thead>\n<tbody>\n${l.map(e=>`<tr>${c.map((t,n)=>o("td",e[n]??"",n)).join("")}</tr>`).join("\n")}\n</tbody>\n</table>`);continue}if(/^( {4}|\t)/.test(i)){const t=[];for(;r<e.length&&(/^( {4}|\t)/.test(e[r])||!e[r].trim());)t.push(e[r++].replace(/^( {4}|\t)/,""));for(;t.length&&!t[t.length-1].trim();)t.pop();s.push(`<pre><code>${x(n(t.join("\n")))}</code></pre>`);continue}const u=[];for(;r<e.length&&e[r].trim()&&(!u.length||!E.test(e[r])||/^ {0,3}[-=]+\s*$/.test(e[r]));){if(u.length&&/^ {0,3}(=+|-+)\s*$/.test(e[r])){const t="="===e[r].trim()[0]?1:2;s.push(`<h${t}>${a(u.join("\n"))}</h${t}>`),u.length=0,r++;break}u.push(e[r].replace(/^ {0,3}/,"")),r++}u.length&&s.push(`<p>${a(u.join("\n"))}</p>`)}return s.join("\n")}function A(e,t={},n=e=>e){return O(String(e).replace(/\r\n?/g,"\n").split("\n"),t,n)}function N({text:e,math:t,drawn:n},s){return(s.render?s.render(e):A(e,s,e=>e.replace(g,(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(g,(e,t)=>n[Number(t)]).replace(/<p>\s*<\/p>\n?/g,"")}function L(e,t={}){return N(k(e,t,t.variables||null),t)}const W=new WeakMap,q=new Set;function C(){for(const e of q)e.connected()&&!e.element.isConnected&&e.stop(!0)}function R(t,n,o={}){const c=void 0===o.variables?s:o.variables||null;C();const l=W.get(t);l&&l.stop(l.store!==c);let u=k(n,o,c,t);if(t.innerHTML=N(u,o),!c)return W.delete(t),t;c.own(t,u.defs);let d=t.isConnected;const p=n=>{const s=n.target,r=s&&s.dataset&&s.dataset.mvVar;if(void 0!==r&&t.contains(s)){if("text"===s.type)try{e(s.value,{blocks:o.blocks,scope:{}}),s.removeAttribute("aria-invalid")}catch{return void s.setAttribute("aria-invalid","true")}c.set(r,s.value)}},h=s=>{const l=s.target.closest?.("[data-node]"),d=l&&l.closest("[data-mv-md]");if(!d||!t.contains(d))return;const p=Number(d.dataset.mvMd),h=u.trees[p];if(!h)return;const $=Number(l.dataset.node),g=m(h,$)||[];let v=null;for(let e=g.length;e>=0&&!v;e--){const t=f(h,g.slice(0,e));t&&void 0!==t.from&&(v={node:t,depth:e})}const b=v&&c.definitions().get(v.node.from);if(b&&b.input&&"textbox"===b.input.kind){s.preventDefault();const n=b.name,u=t.ownerDocument.querySelector(`[data-mv-var="${CSS.escape(n)}"]`),d=o.editable&&o.editable.toText;if(!d)return void(u&&(u.focus(),u.select()));const p=t=>e(t),m=f(h,g);return void r(l,d(i(m,p)),{label:`Edit ${n}`,parse:t=>e(t,{blocks:o.blocks}),commit:e=>{const t=a(i(v.node,p),g.slice(v.depth),e);c.set(n,d(t))}})}const x=b&&u.defs.get(b.name),y=x&&x.key===b.key&&void 0!==x.start?{...u.math[p],start:x.start,end:x.end,raw:n.slice(x.start,x.end)}:u.math[p];t.dispatchEvent(new CustomEvent("inlinemath:select",{bubbles:!0,detail:{index:p,start:y.start,end:y.end,raw:y.raw,source:y.source,id:$,path:g}}))};t.addEventListener("input",p),t.addEventListener("change",p),t.addEventListener("dblclick",h);const $=c.subscribe(e=>{e!==t&&(t.isConnected?(d=!0,C(),(()=>{const e=k(n,o,c,t);e.drawn.forEach((n,s)=>{if(n===u.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=c.textOf(t);void 0!==n.dataset.mvOut?n.textContent=s:n.value!==s&&n!==n.ownerDocument?.activeElement&&(n.value=s)}u=e})()):d&&g(!0))});function g(e){$(),t.removeEventListener("input",p),t.removeEventListener("change",p),t.removeEventListener("dblclick",h),q.delete(v),W.delete(t),e&&c.own(t,null)}const v={element:t,store:c,stop:g,connected:()=>d};return q.add(v),W.set(t,v),t}export{v as extractMath,L as markdownToHTML,A as renderMarkdown,R as renderMarkdownInto,s 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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),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(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/&/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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),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};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
Inline Math Greek (inlinemath-greek-regular.woff2, inlinemath-greek-italic.woff2)
|
|
2
|
+
|
|
3
|
+
The Greek letters that maths uses (Α–Ω, α–ω and ϑ ϕ ϖ ϰ ϱ ϴ ϵ), cut from New Computer Modern 8.1.1
|
|
4
|
+
by Antonis Tsolomitis (CTAN: fonts/newcomputermodern):
|
|
5
|
+
|
|
6
|
+
inlinemath-greek-regular.woff2 from NewCM10-Book.otf
|
|
7
|
+
inlinemath-greek-italic.woff2 from NewCM10-Italic.otf
|
|
8
|
+
|
|
9
|
+
Both source fonts are under the GUST Font License (GUST-FONT-LICENSE.txt in this folder), which asks
|
|
10
|
+
that derived fonts carry new names: these are named "Inline Math Greek" inside the files and in their
|
|
11
|
+
file names. Nothing was changed but the letters kept, the kerning between them, and the names.
|
|
12
|
+
tools/make-greek-font.py makes them again from the source fonts.
|
|
13
|
+
|
|
14
|
+
fonts.css declares them as part of "Inline Math Roman" for the Greek letters only (unicode-range), so a
|
|
15
|
+
page downloads them only when it shows Greek.
|
package/fonts/fonts.css
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
/*
|
|
2
|
-
* Optional: Latin Modern Roman (the TeX look), about 95 kB for both files
|
|
2
|
+
* Optional: Latin Modern Roman (the TeX look), about 95 kB for both files, and its Greek
|
|
3
|
+
* letters from New Computer Modern (about 10 kB each, downloaded only by a page that shows Greek;
|
|
4
|
+
* see README-inlinemath-greek.txt).
|
|
3
5
|
* Link this before inlinemath.css; without it Inline Math uses the system serif.
|
|
4
6
|
* Licence: GUST Font License, see GUST-FONT-LICENSE.txt.
|
|
5
7
|
*/
|
|
@@ -15,3 +17,19 @@
|
|
|
15
17
|
font-style: italic;
|
|
16
18
|
font-display: swap;
|
|
17
19
|
}
|
|
20
|
+
/* Greek (Latin Modern Roman has none): the same design, from New Computer Modern. Declared last, so the
|
|
21
|
+
browser tries these first for the Greek letters, and only for them. */
|
|
22
|
+
@font-face {
|
|
23
|
+
font-family: "Inline Math Roman";
|
|
24
|
+
src: url("inlinemath-greek-regular.woff2") format("woff2");
|
|
25
|
+
font-style: normal;
|
|
26
|
+
font-display: swap;
|
|
27
|
+
unicode-range: U+0391-03A9, U+03B1-03C9, U+03D1, U+03D5-03D6, U+03F0-03F1, U+03F4-03F5;
|
|
28
|
+
}
|
|
29
|
+
@font-face {
|
|
30
|
+
font-family: "Inline Math Roman";
|
|
31
|
+
src: url("inlinemath-greek-italic.woff2") format("woff2");
|
|
32
|
+
font-style: italic;
|
|
33
|
+
font-display: swap;
|
|
34
|
+
unicode-range: U+0391-03A9, U+03B1-03C9, U+03D1, U+03D5-03D6, U+03F0-03F1, U+03F4-03F5;
|
|
35
|
+
}
|
|
Binary file
|
|
Binary file
|
package/inlinemath.css
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/*
|
|
2
|
-
* Inline Math stylesheet. Everything is under .mv;
|
|
2
|
+
* Inline Math stylesheet. Everything is under .mv; colors are left to the page.
|
|
3
3
|
*
|
|
4
4
|
* The numbers marked "metric" must match the constants at the top of
|
|
5
5
|
* src/layout.js (line-height 1, bar 0.06em, gap 0.1em); everything else can
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* .mv-var .mv-num .mv-word variables, numbers, function names
|
|
11
11
|
* .mv-op-frac .mv-op-pow … a kind of operation
|
|
12
12
|
* .mv-hl the class highlight() adds
|
|
13
|
-
* --mv-hl highlight
|
|
13
|
+
* --mv-hl highlight color
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
16
|
.mv {
|
|
@@ -31,10 +31,11 @@
|
|
|
31
31
|
|
|
32
32
|
/* ---- letters and signs -------------------------------------------------- */
|
|
33
33
|
.mv-var { font-style: italic; padding-right: 0.03em; }
|
|
34
|
-
.mv-num, .mv-word, .mv-name, .mv-ord, .mv-text, .mv-d { font-style: normal; }
|
|
34
|
+
.mv-num, .mv-word, .mv-name, .mv-ord, .mv-text, .mv-d, .mv-conj { font-style: normal; }
|
|
35
35
|
.mv-prime { margin-left: 0.04em; }
|
|
36
36
|
.mv-bin { margin: 0 0.22em; }
|
|
37
37
|
.mv-rel { margin: 0 0.28em; }
|
|
38
|
+
.mv-conj { margin: 0 0.6em; } /* x = 2 or x = 3 */
|
|
38
39
|
.mv-punct { margin-right: 0.17em; }
|
|
39
40
|
.mv-sign { margin-right: 0.04em; }
|
|
40
41
|
.mv-times { display: inline-block; width: 0.06em; }
|
|
@@ -69,8 +70,10 @@
|
|
|
69
70
|
|
|
70
71
|
/* ---- radicals (metric: border and padding-top) ----------------------------- */
|
|
71
72
|
.mv-sqrt { display: inline-block; white-space: nowrap; }
|
|
72
|
-
.mv-
|
|
73
|
-
|
|
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 */
|
|
74
77
|
.mv-rootindex { display: inline-block; margin: 0 -0.32em 0 0.12em; }
|
|
75
78
|
|
|
76
79
|
/* ---- delimiters: drawn at the full height of what they enclose -------------- */
|
|
@@ -104,16 +107,25 @@ span.mv-delim { width: 0.16em; border: 0 solid currentColor; box-sizing: border-
|
|
|
104
107
|
|
|
105
108
|
/* ---- decorations: \boxed \cancel \overline \vec … --------------------------- */
|
|
106
109
|
.mv-boxed { display: inline-block; border: 0.06em solid currentColor; padding: 0.16em 0.2em; }
|
|
107
|
-
.mv-over { display: inline-block;
|
|
110
|
+
.mv-over { display: inline-block; position: relative; padding-top: 0.14em; }
|
|
111
|
+
.mv-over::before { content: ''; position: absolute; left: 0; right: 0; top: 0.21em; border-top: 0.06em solid currentColor; } /* metric */
|
|
112
|
+
.mv-over-low::before { top: 0.48em; }
|
|
108
113
|
.mv-underline { display: inline-block; border-bottom: 0.06em solid currentColor; padding-bottom: 0.06em; }
|
|
109
114
|
.mv-cancel { display: inline-block; position: relative; }
|
|
110
115
|
.mv-cancel-line { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible; pointer-events: none; }
|
|
111
116
|
.mv-accent { display: inline-block; position: relative; padding-top: 0.3em; }
|
|
112
|
-
.mv-accent-mark { position: absolute; top: 0; left: 0; right: 0; text-align: center; font-size: 0.7em; line-height: 0.6; }
|
|
117
|
+
.mv-accent-mark { position: absolute; top: -0.27em; left: 0; right: 0; text-align: center; font-size: 0.7em; line-height: 0.6; } /* metric: measured over F, h, A */
|
|
118
|
+
/* ˆ ˜ ˙ ¨ are spacing marks that sit high in their em: full size, pulled down onto the letter */
|
|
119
|
+
.mv-accent-hat, .mv-accent-widehat, .mv-accent-tilde, .mv-accent-dot, .mv-accent-ddot { font-size: 1em; line-height: 1; top: 0.02em; }
|
|
120
|
+
/* over an italic letter the mark leans with it, right of the box's center */
|
|
121
|
+
.mv-accent:has(> .mv-var) > .mv-accent-mark { transform: translateX(0.1em); }
|
|
122
|
+
/* a letter with no ascender (x, u, α; layout.js adds -low): the mark comes down to its top */
|
|
123
|
+
.mv-accent-low > .mv-accent-mark { top: 0.08em; }
|
|
124
|
+
.mv-accent-low > .mv-accent-hat, .mv-accent-low > .mv-accent-widehat, .mv-accent-low > .mv-accent-tilde, .mv-accent-low > .mv-accent-dot, .mv-accent-low > .mv-accent-ddot { top: 0.31em; }
|
|
113
125
|
|
|
114
126
|
/* ---- interaction -------------------------------------------------------------- */
|
|
115
127
|
.mv-hl { background: var(--mv-hl, rgba(255, 200, 0, 0.35)); box-shadow: 0 0 0 0.08em var(--mv-hl, rgba(255, 200, 0, 0.35)); }
|
|
116
|
-
/* Windows high contrast (and other forced
|
|
128
|
+
/* Windows high contrast (and other forced colors) drops backgrounds and shadows: outline a highlight instead */
|
|
117
129
|
@media (forced-colors: active) {
|
|
118
130
|
.mv-hl { outline: 0.08em solid Highlight; outline-offset: 0.04em; }
|
|
119
131
|
}
|
|
@@ -143,7 +155,7 @@ span.mv-delim { width: 0.16em; border: 0 solid currentColor; box-sizing: border-
|
|
|
143
155
|
.mv-step-arrow { color: #888; }
|
|
144
156
|
.mv-step-why { margin: 0.1em 0 0; font-size: 0.9em; color: #444; }
|
|
145
157
|
|
|
146
|
-
/* ---- Markdown with
|
|
158
|
+
/* ---- Markdown with math (markdownToHTML from '@mathzetta/inlinemath/markdown') ------------------- */
|
|
147
159
|
.mv-md-math { display: inline-block; vertical-align: middle; }
|
|
148
160
|
.mv-md-display { display: block; text-align: center; margin: 0.6em 0; overflow-x: auto; }
|
|
149
161
|
.mv-md-block { margin: 0.8em 0; }
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mathzetta/inlinemath",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Draw calculus-level
|
|
3
|
+
"version": "0.4.0",
|
|
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",
|
|
7
7
|
"types": "src/index.d.ts",
|
|
@@ -46,13 +46,13 @@
|
|
|
46
46
|
"prepublishOnly": "npm test && npm run build"
|
|
47
47
|
},
|
|
48
48
|
"peerDependencies": {
|
|
49
|
-
"@mathzetta/cas": "^0.
|
|
50
|
-
"mathzetta": "^1.
|
|
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.
|
|
55
|
-
"mathzetta": "^1.
|
|
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.d.ts
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
// '@mathzetta/inlinemath/cas' — @mathzetta/cas in drawn
|
|
1
|
+
// '@mathzetta/inlinemath/cas' — @mathzetta/cas in drawn math (needs @mathzetta/cas). See types.d.ts.
|
|
2
2
|
export type { CAS, CASStep } from './types.js';
|
|
3
3
|
export { mathCAS, casBlocks, stepsHTML, tokensOf } from './types.js';
|
package/src/cas.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* '@mathzetta/inlinemath/cas' — @mathzetta/cas in Inline Math: `{{…}}` blocks that simplify,
|
|
3
|
-
* solve, differentiate …, and step lists drawn as
|
|
3
|
+
* solve, differentiate …, and step lists drawn as math.
|
|
4
4
|
*
|
|
5
5
|
* import { toHTML } from '@mathzetta/inlinemath';
|
|
6
6
|
* import { casBlocks, stepsHTML, mathCAS } from '@mathzetta/inlinemath/cas';
|
|
@@ -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,
|
|
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
|
-
|
|
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,
|
|
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,27 +124,54 @@ 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);
|
|
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
|
|
138
|
+
const worked = calculus && node.op !== head;
|
|
103
139
|
const args = symbolic ? node.args : [node];
|
|
104
140
|
const word = (n) => (n ? n.s : undefined);
|
|
141
|
+
// d/dx exactly; at a point (x = a, as der(f, x = a) and diff(f, x = a) write it), then a put in for x
|
|
142
|
+
const derivative = (f, by, order) => {
|
|
143
|
+
if (!(by && by.op === '=')) return cas.diff(f, word(by), { ...how, order });
|
|
144
|
+
const name = by.args[0].s;
|
|
145
|
+
const d = cas.diff(f, name, { ...how, order });
|
|
146
|
+
const at = cas.substitute(d.result, { [name]: by.args[1].s }, how);
|
|
147
|
+
return { ...at, steps: [...(d.steps ?? []), ...(at.steps ?? [])] };
|
|
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
|
+
};
|
|
105
160
|
let r;
|
|
106
161
|
try {
|
|
107
|
-
switch (symbolic ? name : head === 'der' ? 'derivative' : 'antiderivative') {
|
|
162
|
+
switch (worked ? 'simplify-read' : symbolic ? name : head === 'der' ? 'derivative' : head === 'lim' ? 'lim' : 'antiderivative') {
|
|
163
|
+
case 'simplify-read': r = cas.simplify(node, how); break;
|
|
108
164
|
case 'simplify': r = cas.simplify(args[0], how); break;
|
|
109
165
|
case 'expand': r = cas.expand(args[0], how); break;
|
|
110
166
|
case 'factor': r = cas.factor(args[0], how); break;
|
|
111
167
|
case 'cancel': r = cas.cancel(args[0], how); break;
|
|
112
|
-
case 'diff': r =
|
|
168
|
+
case 'diff': r = derivative(args[0], args[1], args[2] ? Number(args[2].s) : 1); break;
|
|
113
169
|
case 'integrate': r = cas.integrate(args[0], word(args[1]), { ...how, ...(args[3] ? { from: args[2].s, to: args[3].s } : {}) }); break;
|
|
114
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;
|
|
115
173
|
case 'approx': r = cas.approximate(args[0], { ...how, digits: args[1] ? Number(args[1].s) : 15 }); break;
|
|
116
|
-
case 'derivative': r =
|
|
174
|
+
case 'derivative': r = derivative(node.args[0], node.args[1], 1); break;
|
|
117
175
|
default: r = cas.integrate(node, undefined, how); break;
|
|
118
176
|
}
|
|
119
177
|
} catch (error) {
|