formula-composer 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +122 -2
  3. package/angular/esm2020/formula-composer-tinymce-angular.mjs +4 -0
  4. package/angular/esm2020/lib/formula-composer.directive.mjs +52 -0
  5. package/angular/esm2020/lib/formula-composer.module.mjs +21 -0
  6. package/angular/esm2020/lib/init.mjs +9 -0
  7. package/angular/esm2020/lib/provide.mjs +11 -0
  8. package/angular/esm2020/public-api.mjs +8 -0
  9. package/angular/fesm2015/formula-composer-tinymce-angular.mjs +99 -0
  10. package/angular/fesm2020/formula-composer-tinymce-angular.mjs +101 -0
  11. package/angular/formula-composer-tinymce-angular.d.ts +5 -0
  12. package/angular/lib/formula-composer.directive.d.ts +22 -0
  13. package/angular/lib/formula-composer.module.d.ts +15 -0
  14. package/angular/lib/init.d.ts +23 -0
  15. package/angular/lib/provide.d.ts +10 -0
  16. package/angular/package.json +10 -0
  17. package/angular/public-api.d.ts +5 -0
  18. package/dist/editor-ui/catalog-types.d.ts +30 -0
  19. package/dist/editor-ui/catalog.generated.d.ts +2 -0
  20. package/dist/editor-ui/commands.d.ts +44 -0
  21. package/dist/editor-ui/dom.d.ts +8 -0
  22. package/dist/editor-ui/editor.d.ts +86 -0
  23. package/dist/editor-ui/icons.d.ts +5 -0
  24. package/dist/editor-ui/index.d.ts +9 -0
  25. package/dist/editor-ui/index.js +119 -0
  26. package/dist/editor-ui/modal.d.ts +81 -0
  27. package/dist/editor-ui/periodic.d.ts +8 -0
  28. package/dist/editor-ui/pickers.d.ts +23 -0
  29. package/dist/editor-ui/popover.d.ts +24 -0
  30. package/dist/editor-ui/special-chars.generated.d.ts +10 -0
  31. package/dist/editor-ui/strings.d.ts +48 -0
  32. package/dist/editor-ui/styles.d.ts +3 -0
  33. package/dist/editor-ui/toolbar.d.ts +47 -0
  34. package/dist/integration/content.d.ts +52 -0
  35. package/dist/integration/controller.d.ts +76 -0
  36. package/dist/integration/index.d.ts +3 -0
  37. package/dist/integration/index.js +1 -0
  38. package/dist/integration/options.d.ts +46 -0
  39. package/dist/math-core/a11y.d.ts +3 -0
  40. package/dist/math-core/caret-speech.d.ts +3 -0
  41. package/dist/math-core/editor.d.ts +212 -0
  42. package/dist/math-core/functions.d.ts +8 -0
  43. package/dist/math-core/history.d.ts +16 -0
  44. package/dist/math-core/index.d.ts +17 -0
  45. package/dist/math-core/index.js +3 -0
  46. package/dist/math-core/latex/parse.d.ts +11 -0
  47. package/dist/math-core/latex/serialize.d.ts +4 -0
  48. package/dist/math-core/latex/symbols.d.ts +32 -0
  49. package/dist/math-core/mathml.d.ts +33 -0
  50. package/dist/math-core/model.d.ts +69 -0
  51. package/dist/math-core/safe-xml.d.ts +7 -0
  52. package/dist/math-core/sanitize.d.ts +6 -0
  53. package/dist/math-core/tree-index.d.ts +26 -0
  54. package/dist/math-core/xml.d.ts +21 -0
  55. package/dist/renderer/alphanumerics.d.ts +3 -0
  56. package/dist/renderer/attributes.d.ts +10 -0
  57. package/dist/renderer/core.d.ts +13 -0
  58. package/dist/renderer/image.d.ts +29 -0
  59. package/dist/renderer/index.d.ts +22 -0
  60. package/dist/renderer/index.js +9 -0
  61. package/dist/renderer/layout.d.ts +14 -0
  62. package/dist/renderer/styles.d.ts +9 -0
  63. package/dist/renderer/view.d.ts +30 -0
  64. package/dist/renderer/vnode.d.ts +25 -0
  65. package/dist/tinymce/browser/plugin.min.js +129 -0
  66. package/dist/tinymce/compat.d.ts +24 -0
  67. package/dist/tinymce/index.d.ts +5 -0
  68. package/dist/tinymce/index.js +1 -0
  69. package/dist/tinymce/init.d.ts +22 -0
  70. package/dist/tinymce/plugin.d.ts +30 -0
  71. package/dist/tinymce/tinymce-types.d.ts +127 -0
  72. package/dist/tinymce-react/editor.d.ts +19 -0
  73. package/dist/tinymce-react/index.d.ts +3 -0
  74. package/dist/tinymce-react/index.js +1 -0
  75. package/dist/tinymce-react/init.d.ts +23 -0
  76. package/editor-ui/package.json +6 -0
  77. package/images/edit-formula.png +0 -0
  78. package/images/editor-content.png +0 -0
  79. package/integration/package.json +6 -0
  80. package/math-core/package.json +6 -0
  81. package/package.json +101 -4
  82. package/react/package.json +6 -0
  83. package/renderer/package.json +6 -0
@@ -0,0 +1,69 @@
1
+ export type Attrs = Record<string, string>;
2
+ export type TokenTag = 'mi' | 'mn' | 'mo' | 'mtext' | 'ms';
3
+ export type LeafTag = 'mspace' | 'none' | 'mprescripts' | 'msline' | 'malignmark' | 'maligngroup' | 'mglyph';
4
+ export type RowTag = 'mrow' | 'msrow' | 'mscarry';
5
+ /** Token a slot stands for when it is an operator placeholder such as `<mo largeop="true"></mo>`. */
6
+ export interface TokenHint {
7
+ tag: TokenTag;
8
+ attrs: Attrs;
9
+ }
10
+ export interface RowNode {
11
+ readonly kind: 'row';
12
+ id: number;
13
+ tag: RowTag;
14
+ attrs: Attrs;
15
+ children: MathNode[];
16
+ tokenHint?: TokenHint;
17
+ }
18
+ export interface TokenNode {
19
+ readonly kind: 'token';
20
+ id: number;
21
+ tag: TokenTag;
22
+ attrs: Attrs;
23
+ text: string;
24
+ }
25
+ export interface LeafNode {
26
+ readonly kind: 'leaf';
27
+ id: number;
28
+ tag: LeafTag;
29
+ attrs: Attrs;
30
+ }
31
+ /**
32
+ * A layout element. `children` holds editable rows (slots) and, for structural elements such as
33
+ * `mtable`, `mstack` or `mmultiscripts`, nested elements and leaves.
34
+ */
35
+ export interface ElementNode {
36
+ readonly kind: 'element';
37
+ id: number;
38
+ tag: string;
39
+ attrs: Attrs;
40
+ children: Array<RowNode | ElementNode | LeafNode>;
41
+ }
42
+ export type MathNode = TokenNode | LeafNode | ElementNode;
43
+ export type AnyNode = MathNode | RowNode;
44
+ /** Root document: top-level math attributes and the main row. */
45
+ export interface MathDocument {
46
+ attrs: Attrs;
47
+ root: RowNode;
48
+ }
49
+ export declare function newId(): number;
50
+ export declare function row(children?: MathNode[], tag?: RowTag, attrs?: Attrs): RowNode;
51
+ export declare function token(tag: TokenTag, text: string, attrs?: Attrs): TokenNode;
52
+ export declare function leaf(tag: LeafTag, attrs?: Attrs): LeafNode;
53
+ export declare function element(tag: string, children: Array<RowNode | ElementNode | LeafNode>, attrs?: Attrs): ElementNode;
54
+ export declare function emptyDocument(): MathDocument;
55
+ /** Deep clone; `freshIds` assigns new ids (used when pasting or inserting templates). */
56
+ export declare function cloneNode<T extends AnyNode>(node: T, freshIds?: boolean): T;
57
+ export declare function cloneDocument(doc: MathDocument, freshIds?: boolean): MathDocument;
58
+ export declare function isRow(node: AnyNode | undefined): node is RowNode;
59
+ /** Elements whose MathML content is an inferred mrow: the single slot serializes without an mrow wrapper. */
60
+ export declare const INFERRED_ROW_TAGS: ReadonlySet<string>;
61
+ /** Fixed-arity layout elements and their slot count. */
62
+ export declare const SLOT_COUNT: Readonly<Record<string, number>>;
63
+ export declare function isEmptyRow(r: RowNode): boolean;
64
+ /** Visits every node depth-first; return `false` from `visit` to skip a subtree. */
65
+ export declare function walk(node: AnyNode, visit: (n: AnyNode, parent: AnyNode | null) => boolean | void, parent?: AnyNode | null): void;
66
+ export declare function findById(root: AnyNode, id: number): {
67
+ node: AnyNode;
68
+ parent: AnyNode | null;
69
+ } | null;
@@ -0,0 +1,7 @@
1
+ export declare function isSafeXml(text: string): boolean;
2
+ /**
3
+ * Encodes MathML as safeXml. Characters that collide with the safe alphabet are first written as
4
+ * numeric references so decoding is lossless.
5
+ */
6
+ export declare function encodeSafeXml(mathml: string): string;
7
+ export declare function decodeSafeXml(safe: string): string;
@@ -0,0 +1,6 @@
1
+ import { type MathDocument } from './model.js';
2
+ /**
3
+ * Copy of `doc` that is safe to embed in HTML: unknown element names become `mrow`, event handlers,
4
+ * script URLs and style values that can fetch or run code are dropped.
5
+ */
6
+ export declare function sanitizeMathDocument(doc: MathDocument): MathDocument;
@@ -0,0 +1,26 @@
1
+ import type { AnyNode, ElementNode, LeafNode, MathNode, RowNode } from './model.js';
2
+ /** Where a row lives: the atom (direct child of a row) that owns it, and that atom's position. */
3
+ export interface RowOwner {
4
+ atom: MathNode;
5
+ parentRow: RowNode;
6
+ index: number;
7
+ }
8
+ export interface TreeIndex {
9
+ readonly rows: ReadonlyMap<number, RowNode>;
10
+ readonly owners: ReadonlyMap<number, RowOwner>;
11
+ readonly parents: ReadonlyMap<number, AnyNode>;
12
+ /** Rows of each atom in reading order. */
13
+ readonly atomRows: ReadonlyMap<number, readonly RowNode[]>;
14
+ /** For each node id, the row that directly contains it (only for atoms). */
15
+ readonly atomParent: ReadonlyMap<number, {
16
+ row: RowNode;
17
+ index: number;
18
+ }>;
19
+ }
20
+ /** Rows reachable from `node` without crossing another row, in reading order. */
21
+ export declare function ownRows(node: ElementNode | LeafNode | MathNode): RowNode[];
22
+ export declare function buildIndex(root: RowNode): TreeIndex;
23
+ /** Chain of rows from the root to `rowId` (inclusive). */
24
+ export declare function rowPath(index: TreeIndex, rowId: number): RowNode[];
25
+ /** Nearest ancestor element with the given tag that encloses the row. */
26
+ export declare function enclosingElement(index: TreeIndex, rowId: number, tag: string): ElementNode | null;
@@ -0,0 +1,21 @@
1
+ export interface XmlElement {
2
+ readonly type: 'element';
3
+ name: string;
4
+ attrs: Record<string, string>;
5
+ children: XmlNode[];
6
+ }
7
+ export interface XmlText {
8
+ readonly type: 'text';
9
+ text: string;
10
+ }
11
+ export type XmlNode = XmlElement | XmlText;
12
+ export declare class XmlParseError extends Error {
13
+ readonly position: number;
14
+ constructor(message: string, position: number);
15
+ }
16
+ export declare function decodeEntities(text: string): string;
17
+ /** Escapes text for XML; non-ASCII characters become `&#xHEX;` (uppercase), matching MathType output. */
18
+ export declare function escapeXml(text: string, attribute?: boolean): string;
19
+ /** Small, strict XML parser for MathML fragments. No DTDs, no processing instructions are evaluated. */
20
+ export declare function parseXml(source: string): XmlElement[];
21
+ export declare function textContent(node: XmlNode): string;
@@ -0,0 +1,3 @@
1
+ /** Returns styled text, or `null` when the variant has no Unicode mapping (CSS is used instead). */
2
+ export declare function applyMathVariant(text: string, variant: string): string | null;
3
+ export declare function hasUnicodeVariant(variant: string): boolean;
@@ -0,0 +1,10 @@
1
+ import type { Attrs } from '../math-core/index';
2
+ /** Converts MathML 3 named spaces and keywords to CSS lengths accepted by MathML Core. */
3
+ export declare function normalizeLength(value: string): string;
4
+ export declare function normalizeMathSize(value: string): string;
5
+ export declare function normalizeLineThickness(value: string): string;
6
+ /** Keeps only presentational declarations with inert values. */
7
+ export declare function sanitizeStyle(style: string | undefined): string | null;
8
+ /** Allowlisted, Core-compatible attributes for `tag`. `mathvariant` is handled by the caller. */
9
+ export declare function coreAttributes(tag: string, attrs: Attrs): Record<string, string>;
10
+ export declare function appendStyle(attrs: Record<string, string>, declarations: readonly string[]): void;
@@ -0,0 +1,13 @@
1
+ import type { MathDocument } from '../math-core/index';
2
+ import { type VElement } from './vnode.js';
3
+ export interface BuildOptions {
4
+ /** Adds placeholders for empty slots and model ids for caret mapping. */
5
+ editable: boolean;
6
+ /** Placeholders without editing ids (toolbar icons). Defaults to `editable`. */
7
+ placeholders?: boolean;
8
+ /** Math fonts tried after a formula's own `font-family`, for the characters that family lacks. */
9
+ fallbackFonts?: string;
10
+ }
11
+ export declare const PLACEHOLDER_CLASS = "sw-placeholder";
12
+ /** Converts a model document to a MathML Core render tree. */
13
+ export declare function buildCoreTree(doc: MathDocument, options: BuildOptions): VElement;
@@ -0,0 +1,29 @@
1
+ import { type MathDocument } from '../math-core/index';
2
+ export interface FormulaImageOptions {
3
+ /** CSS pixels. */
4
+ fontSize?: number;
5
+ color?: string;
6
+ backgroundColor?: string;
7
+ }
8
+ export interface FormulaImage {
9
+ svg: string;
10
+ dataUri: string;
11
+ width: number;
12
+ height: number;
13
+ /** Distance from the top edge to the baseline. */
14
+ baseline: number;
15
+ /** CSS `vertical-align` value (negative descent) that aligns the image baseline with the text baseline. */
16
+ verticalAlign: number;
17
+ }
18
+ export declare const DEFAULT_IMAGE_FONT_SIZE = 16;
19
+ /** Resolves when the local math face is loaded (needed before measuring). Never rejects. */
20
+ export declare function ensureMathFont(doc: Document): Promise<void>;
21
+ /**
22
+ * Renders a formula to an SVG image (MathML in `foreignObject`) sized from a live layout in `doc`.
23
+ * Call {@link ensureMathFont} first so measurement uses the final font.
24
+ */
25
+ export declare function createFormulaImage(input: MathDocument | string, doc: Document, options?: FormulaImageOptions): FormulaImage;
26
+ /** Base64 SVG data URI (`saveMode: 'base64'`). */
27
+ export declare function toBase64DataUri(svg: string): string;
28
+ /** Rasterizes a formula image to a PNG data URI at `scale` × CSS pixels. */
29
+ export declare function rasterizeFormulaImage(image: FormulaImage, doc: Document, scale?: number): Promise<string>;
@@ -0,0 +1,22 @@
1
+ import { type MathDocument } from '../math-core/index';
2
+ export { applyMathVariant, hasUnicodeVariant } from './alphanumerics.js';
3
+ export { normalizeLength, sanitizeStyle } from './attributes.js';
4
+ export { type BuildOptions, PLACEHOLDER_CLASS, buildCoreTree } from './core.js';
5
+ export * from './image.js';
6
+ export { type Box, caretBox, caretFromPoint, selectionBoxes } from './layout.js';
7
+ export * from './styles.js';
8
+ export * from './view.js';
9
+ export * from './vnode.js';
10
+ /** MathML (any dialect the parser accepts) → MathML Core markup for display. */
11
+ export declare function toCoreMathML(input: MathDocument | string): string;
12
+ export interface RenderElementOptions {
13
+ /** Show empty slots as placeholder boxes (toolbar icons). */
14
+ placeholders?: boolean;
15
+ }
16
+ /** Read-only `<math>` element for display in `doc`. */
17
+ export declare function renderMathElement(input: MathDocument | string, doc: Document, options?: RenderElementOptions): Element;
18
+ /**
19
+ * Viewer for saved content (INT-003): replaces each `<math>` under `root` with its MathML Core render,
20
+ * so MathType markup such as `mfenced` or `menclose` displays without a server. Returns the count.
21
+ */
22
+ export declare function upgradeMathElements(root: Element | Document | DocumentFragment): number;
@@ -0,0 +1,9 @@
1
+ var ne=Object.defineProperty;var re=(n,t,e)=>t in n?ne(n,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):n[t]=e;var b=(n,t,e)=>re(n,typeof t!="symbol"?t+"":t,e);import{parseMathML as Gn}from"../math-core/index.js";var oe={B:"\u212C",E:"\u2130",F:"\u2131",H:"\u210B",I:"\u2110",L:"\u2112",M:"\u2133",R:"\u211B",e:"\u212F",g:"\u210A",o:"\u2134"},ie={C:"\u212D",H:"\u210C",I:"\u2111",R:"\u211C",Z:"\u2128"},se={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},ut={bold:{upper:119808,lower:119834,digits:120782,greekUpper:120488,greekLower:120514},italic:{upper:119860,lower:119886,greekUpper:120546,greekLower:120572,exceptions:{h:"\u210E"}},"bold-italic":{upper:119912,lower:119938,greekUpper:120604,greekLower:120630},script:{upper:119964,lower:119990,exceptions:oe},"bold-script":{upper:120016,lower:120042},fraktur:{upper:120068,lower:120094,exceptions:ie},"double-struck":{upper:120120,lower:120146,digits:120792,exceptions:se},"bold-fraktur":{upper:120172,lower:120198},"sans-serif":{upper:120224,lower:120250,digits:120802},"bold-sans-serif":{upper:120276,lower:120302,digits:120812,greekUpper:120662,greekLower:120688},"sans-serif-italic":{upper:120328,lower:120354},"sans-serif-bold-italic":{upper:120380,lower:120406,greekUpper:120720,greekLower:120746},monospace:{upper:120432,lower:120458,digits:120822}},at=65,ae=90,lt=97,le=122,ct=48,ce=57,dt=913,de=937,mt=945,me=969;function ue(n,t){let e=t.exceptions?.[n];if(e)return e;let r=n.codePointAt(0)??0;return r>=at&&r<=ae&&t.upper!==void 0?String.fromCodePoint(t.upper+r-at):r>=lt&&r<=le&&t.lower!==void 0?String.fromCodePoint(t.lower+r-lt):r>=ct&&r<=ce&&t.digits!==void 0?String.fromCodePoint(t.digits+r-ct):r>=dt&&r<=de&&t.greekUpper!==void 0?String.fromCodePoint(t.greekUpper+r-dt):r>=mt&&r<=me&&t.greekLower!==void 0?String.fromCodePoint(t.greekLower+r-mt):n}function H(n,t){let e=ut[t];return e?[...n].map(r=>ue(r,e)).join(""):null}function X(n){return n in ut}var pe=["dir","mathcolor","mathbackground","mathsize","displaystyle","scriptlevel"],he={math:["display"],mo:["form","fence","separator","lspace","rspace","stretchy","symmetric","maxsize","minsize","largeop","movablelimits"],mfrac:["linethickness"],mover:["accent"],munder:["accentunder"],munderover:["accent","accentunder"],mspace:["width","height","depth"],mpadded:["width","height","depth","lspace","voffset"],mtd:["rowspan","columnspan"]},fe=new Set(["lspace","rspace","width","height","depth","voffset","maxsize","minsize"]),ge=18,Ee={veryverythinmathspace:1,verythinmathspace:2,thinmathspace:3,mediummathspace:4,thickmathspace:5,verythickmathspace:6,veryverythickmathspace:7},be={small:"80%",normal:"100%",big:"125%"},xe={thin:"0.04em",medium:"0.066em",thick:"0.12em"},Re=.066,ye=100,q=/^-?\d*\.?\d+$/,we=/^[\w\s#().,%+-]*$/,Se=/^[\w\s,"'-]+$/,Ce=new Set(["color","background-color","font-family","font-size","font-weight","font-style","text-decoration"]);function C(n){let t=n.trim(),e=t.startsWith("negative"),r=e?t.slice(8):t,o=Ee[r];return o!==void 0?`${e?"-":""}${(o/ge).toFixed(4)}em`:q.test(t)&&t!=="0"?`${t}em`:t}function Ae(n){let t=n.trim(),e=be[t];return e||(q.test(t)?`${Number(t)*ye}%`:t)}function _e(n){let t=n.trim(),e=xe[t];return e||(q.test(t)&&t!=="0"?`${Number(t)*Re}em`:t)}function pt(n){return we.test(n)&&!/url\s*\(|expression/i.test(n)}function ht(n){if(!n)return null;let t=[];for(let e of n.split(";")){let r=e.indexOf(":");if(r<=0)continue;let o=e.slice(0,r).trim().toLowerCase(),i=e.slice(r+1).trim();if(!Ce.has(o)||i==="")continue;(o==="font-family"?Se.test(i):pt(i))&&t.push(`${o}:${i}`)}return t.length>0?t.join(";"):null}function E(n,t){let e={},r=[...pe,...he[n]??[]];for(let i of r){let s=t[i];s!==void 0&&(i==="mathsize"?e[i]=Ae(s):i==="linethickness"?e[i]=_e(s):fe.has(i)?e[i]=C(s):pt(s)&&(e[i]=s))}let o=ht(t.style);return o&&(e.style=o),e}function R(n,t){if(t.length===0)return;let e=n.style;n.style=e?`${e};${t.join(";")}`:t.join(";")}import{MATHML_NS as gt,escapeXml as ft}from"../math-core/index.js";var Ne="data-sw-id",ve="data-sw-row",I="data-sw-line";function c(n,t={},e=[]){return{tag:n,attrs:t,children:e}}function A(n,t,e){let r=t.createElementNS(gt,n.tag);for(let[o,i]of Object.entries(n.attrs))r.setAttribute(o,i);n.nodeId!==void 0&&(r.setAttribute(Ne,String(n.nodeId)),e?.atoms.set(n.nodeId,r)),n.rowId!==void 0&&(r.setAttribute(ve,String(n.rowId)),e?.rows.set(n.rowId,r)),n.line&&r.setAttribute(I,"");for(let o of n.children)r.appendChild(typeof o=="string"?t.createTextNode(o):A(o,t,e));return r}function $(n,t=!0){let e=Object.entries(n.attrs).map(([i,s])=>` ${i}="${ft(s,!0)}"`).join(""),r=t?` xmlns="${gt}"`:"",o=n.children.map(i=>typeof i=="string"?ft(i,!1):$(i,!1)).join("");return`<${n.tag}${e}${r}>${o}</${n.tag}>`}var vt="sw-placeholder",Z={width:"0.6em",height:"0.75em",depth:"0.15em"},Le=new Set(["mfrac","mroot","msqrt","msub","msup","msubsup","munder","mover","munderover","mmultiscripts","mstyle","mphantom","mpadded","merror"]),v="1px solid currentColor",Lt=.1,Tt=.2,W=.6,Te="0",Me=.5,j="padding:0",U="padding:0.1em 0",ke="1",Oe="(",De=")",Et='"',Ie="-",$e="\u2212",Fe=new Map([["\u2229","\u22C2"],["\u222A","\u22C3"],["\u2293","\u2A05"],["\u2294","\u2A06"]]),Mt=new Set(["\u2211","\u220F","\u2210","\u22C0","\u22C1","\u22C2","\u22C3","\u2A00","\u2A01","\u2A02","\u2A04","\u2A05","\u2A06"]),kt=new Set(["munder","mover","munderover"]),Be=new Set([...kt,"msub","msup","msubsup"]),_="font-family:",Ve=new Set(["bold","italic","bold-italic"]),Pe="italic",Ge=new Set([...Mt,"\u222B","\u222C","\u222D","\u222E","\u222F","\u2230","\u2A0C"]),He=new Set(["\xAF","\u203E","_","\u0332","^","\u02C6","\u02C7","\u02D8","\u02D9","\u02DA","\xA8","~","\u02DC","\xB4","`","\u23B4","\u23B5","\u23DC","\u23DD","\u23DE","\u23DF","\u2190","\u2192","\u2194","\u21BC","\u21BD","\u21C0","\u21C1","\u21D0","\u21D2","\u21D4"]),Ue={mover:[[1,"accent"]],munder:[[1,"accentunder"]],munderover:[[1,"accentunder"],[2,"accent"]]};function Ot(n){if(n?.kind!=="row"||n.children.length!==1)return;let t=n.children[0];return t?.kind==="token"&&t.tag==="mo"?t.text:void 0}function ze(n){if(!kt.has(n.tag))return!1;let t=Dt(n);return t!==void 0&&(t.attrs.largeop==="true"||Mt.has(t.text))}function Dt(n){let t=n.children[0],e=t?.kind==="row"&&t.children.length===1?t.children[0]:t;return e?.kind==="token"&&e.tag==="mo"?e:void 0}function bt(n){return n?.tag==="mo"&&(n.attrs.largeop==="true"||Ge.has(n.text))}function We(n){return He.has(Ot(n)??"")}var xt="0.9em",Rt="0",Ye="0.15em",Ke=new Map([["\u23DC",Rt],["\u23DD",Rt],["\u23DE",xt],["\u23DF",xt]]),Xe={mover:["accent","height"],munder:["accentunder","depth"]};function qe(n){let t=Ke.get(Ot(n.children[1])??""),e=Xe[n.tag];return t===void 0||e===void 0?void 0:{tag:n.tag,attrs:e,minWidth:t}}function Ze(n,{tag:t,attrs:[e,r],minWidth:o}){return c(t,{[e]:"true"},[n,c("mspace",{width:o,[r]:Ye})])}var je={mover:[void 0,"over"],munder:[void 0,"under"],munderover:[void 0,"under","over"]},Qe=[[8592,8703],[10224,10239],[10496,10623]],k="1em";function Je(n){if(n?.kind!=="row"||n.children.length!==1)return!1;let t=n.children[0];if(t?.kind!=="token"||t.tag!=="mo"||t.attrs.stretchy==="false"||[...t.text].length!==1)return!1;let e=t.text.codePointAt(0)??0;return Qe.some(([r,o])=>e>=r&&e<=o)}function tn(n,t){let e=t==="over"?`padding-bottom:${k};margin-top:-${k}`:`padding-top:${k};margin-bottom:-${k}`;return c("mpadded",{voffset:t==="over"?`-${k}`:k,style:e},[n])}var Q={left:"left",center:"center",right:"right",decimalpoint:"right"},en={top:"top",bottom:"bottom",center:"middle",baseline:"baseline",axis:"middle"},yt="3px double currentColor",wt={"|":v,"\u2223":v,"\u2016":yt,"\u2225":yt},St="0.2em",nn="padding-block:0.1em",rn=new Set(["stackedrightright","mediumstackedrightright","shortstackedrightright"]),on=")",Ct="padding-left:0.2em",sn="padding-right:0.3em",an="padding:0 0 0.1em",ln="padding-top:0.1em";function J(n){return[`text-align:${n}`,`text-align:-webkit-${n}`]}var It="text-align:start",$t={height:"0.8em",depth:"0.2em"},cn={height:$t.height,depth:"0"},dn="padding:0.45em 0 0",mn="math-style:inherit";function At(n){return n.length===0?[]:[c("mrow",{style:It},[...n])]}function z(n){let t=`calc(50% - ${W}px)`,e=`calc(50% + ${W}px)`;return`linear-gradient(${n}, transparent ${t}, currentColor ${t}, currentColor ${e}, transparent ${e})`}var un={box:["border"],roundedbox:["border"],circle:["border"],left:["border-left"],right:["border-right"],top:["border-top"],bottom:["border-bottom"],actuarial:["border-top","border-right"],madruwb:["border-bottom","border-right"],longdiv:["border-top"],phasorangle:["border-bottom"]},pn={roundedbox:"0.4em",circle:"50%"},hn={circle:"padding:0.3em 0.4em",roundedbox:"padding:0.1em",longdiv:"padding:0.2em 0 0.2em 0.35em"},fn=`radial-gradient(0.55em 60% at -0.3em 50%, transparent calc(100% - ${2*W}px), currentColor calc(100% - ${2*W}px), currentColor 100%, transparent 100%)`,Ft=.25,gn=.35,_t={image:z("to bottom right"),inline:0,block:Ft},En={horizontalstrike:{image:z("to bottom"),inline:Tt,block:Lt},verticalstrike:{image:z("to right"),inline:0,block:gn},updiagonalstrike:_t,updiagonalarrow:_t,downdiagonalstrike:{image:z("to top right"),inline:0,block:Ft}};function Nt(n){return n===0?"0":`${n}em`}function bn(n,t){let e=n.has("border")||n.size===0&&t.length===0,r=Math.max(0,...t.map(s=>s.inline)),o=s=>Nt(Math.max(r,e||n.has(s)?Tt:0)),i=Nt(Math.max(Lt,...t.map(s=>s.block)));return`padding:${i} ${o("border-right")} ${i} ${o("border-left")}`}function N(n,t){if(!n)return;let e=n.trim().split(/\s+/);return e[Math.min(t,e.length-1)]}function xn(n){return n.kind==="leaf"&&n.tag==="mspace"&&n.attrs.linebreak==="newline"}function Rn(n){return n.tag==="mo"&&n.text!==""&&n.text.trim()===""}var yn=new Set([",",":",";","%","*",".","?","@","/","-","^","\xB7","\u2022","\u2043","\u2305","\u2306","\u2145","\u2146"]),wn=/^\p{Sm}$/u,Sn=[[8592,8703],[10224,10239],[10496,10623],[11008,11263]];function Cn(n){let t=[...n],e=t[0];if(t.length!==1||e===void 0||wn.test(e)||yn.has(e))return!1;let r=e.codePointAt(0)??0;return!Sn.some(([o,i])=>r>=o&&r<=i)}function An({atoms:n,first:t}){let e=n[0];t?.kind==="token"&&t.tag==="mo"&&t.attrs.lspace===void 0&&e&&(e.attrs.lspace="0")}var tt=class{constructor(t){b(this,"options",t);b(this,"lineAlign","left");b(this,"textFamily",null)}document(t){let{mathsize:e,...r}=t.attrs,o=E("math",r),i=o.style?.split(";")??[],s=i.find(u=>u.startsWith(_))?.slice(_.length),l=this.options.fallbackFonts,a=s===void 0?null:l?`${s}, ${l}`:s;this.textFamily=a,a!==null&&(o.style=i.map(u=>u.startsWith(_)?`${_}${a}`:u).join(";")),this.lineAlign=Q[t.attrs.indentalign??"left"]??"left";let d=this.row(t.root);return c("math",o,[e===void 0?d:c("mstyle",E("mstyle",{mathsize:e}),[d])])}row(t){let e=this.splitLines(t.children),r;if(e.length>1){let o=e.map((i,s)=>{let{atoms:l,empty:a}=i;An(i);let d={};R(d,[...J(this.lineAlign),s===0?"padding:0":dn]);let u=c("mspace",{...a?cn:$t}),m=c("mrow",{style:It},[u,...l]);return m.line=!0,c("mtr",{},[c("mtd",d,[m])])});r=c("mtable",{style:mn},o)}else{let o=e[0]?.atoms??[];o.length===0&&(this.options.placeholders??this.options.editable)&&o.push(this.placeholder()),r=c("mrow",{},o)}return this.options.editable&&(r.rowId=t.id),r}splitLines(t){let e=[{atoms:[],empty:!0}];for(let r of t){let o=e[e.length-1];o&&(o.first??(o.first=r),o.atoms.push(this.atom(r)),xn(r)?e.push({atoms:[],empty:!0}):o.empty=!1)}return e}placeholder(){return c("mspace",{class:vt,...Z})}atom(t){let e;return t.kind==="token"?e=this.token(t):t.kind==="leaf"?e=this.leaf(t):e=this.element(t),this.options.editable&&(e.nodeId=t.id),e}child(t){return t.kind==="row"?this.row(t):t.kind==="leaf"?this.leaf(t):this.element(t)}token(t){if(t.tag==="ms"){let s=t.attrs.lquote??Et,l=t.attrs.rquote??Et;return c("mtext",E("mtext",t.attrs),[`${s}${t.text}${l}`])}let e=E(t.tag,t.attrs),r=t.attrs.mathvariant,o=t.text;if(r==="normal")e.mathvariant="normal";else if(!r&&this.textFamily!==null&&t.tag==="mi"&&[...t.text].length===1&&H(t.text,Pe)!==t.text)e.mathvariant="normal",R(e,["font-style:italic"]);else if(r&&X(r)&&(o=this.textFamily!==null&&Ve.has(r)?t.text:H(t.text,r)??t.text,t.tag==="mi"&&(e.mathvariant="normal"),[...t.text].some((l,a)=>l.trim()!==""&&[...o][a]===l))){let l=[];r.includes("bold")&&l.push("font-weight:bold"),r.includes("italic")&&l.push("font-style:italic"),R(e,l)}(Rn(t)||t.tag==="mo"&&Cn(t.text))&&(e.lspace??(e.lspace="0"),e.rspace??(e.rspace="0")),t.tag==="mo"&&o===Ie&&(o=$e),t.tag==="mo"&&t.attrs.largeop==="true"&&(o=Fe.get(o)??o);let i=this.options.fallbackFonts;return this.textFamily!==null&&i&&bt(t)&&R(e,[`${_}${i}`]),c(t.tag,e,o?[o]:[])}leaf(t){switch(t.tag){case"mspace":return c("mspace",E("mspace",t.attrs));case"mprescripts":return c("mprescripts");case"mglyph":return c("mtext",{},t.attrs.alt?[t.attrs.alt]:[]);case"none":return c("mrow");default:return c("mspace",{width:"0"})}}element(t){switch(t.tag){case"mfrac":return t.attrs.bevelled==="true"?this.bevelled(t):this.generic(t);case"mfenced":return this.fenced(t);case"menclose":return this.enclose(t);case"mtable":return this.table(t);case"mstack":return this.stack(t);case"mlongdiv":return this.longdiv(t);case"maction":{let e=t.children[0];return c("mrow",{},e?[this.child(e)]:[])}default:return Le.has(t.tag)?this.generic(t):c("mrow",E("mrow",t.attrs),t.children.map(e=>this.child(e)))}}generic(t){let e=E(t.tag,t.attrs);for(let[a,d]of Ue[t.tag]??[])e[d]===void 0&&We(t.children[a])&&(e[d]="true");let r=Je(t.children[0])?je[t.tag]:void 0,o=qe(t),i=ze(t),s=t.children.map((a,d)=>{let u=r?.[d];return u?tn(this.child(a),u):d===0&&i?c("mstyle",{displaystyle:"true"},[this.child(a)]):o?d===0?Ze(this.child(a),o):a.kind==="row"?this.operatorRow(a):this.child(a):this.child(a)}),l=this.largeOperatorFonts(t);if(l){R(e,[`${_}${l.element}`]);for(let a of s.slice(1))R(a.attrs,[`${_}${l.scripts}`])}return c(t.tag,e,s)}largeOperatorFonts(t){let e=this.options.fallbackFonts;return this.textFamily===null||!e||!Be.has(t.tag)||!bt(Dt(t))?null:{element:e,scripts:this.textFamily}}operatorRow(t){let[e]=t.children;if(!e)return this.row(t);let r=this.atom(e);return this.options.editable&&(r.rowId=t.id),r}bevelled(t){let[e,r]=t.children,o=i=>c("mstyle",{scriptlevel:Te},i?[this.child(i)]:[]);return c("mrow",E("mrow",t.attrs),[c("msup",{},[c("mrow"),o(e)]),c("mo",{stretchy:"false",lspace:"0",rspace:"0"},["/"]),c("msub",{},[c("mrow"),o(r)])])}fenced(t){let e=t.attrs.open??Oe,r=t.attrs.close??De,o=[],i=[],s=wt[e],l=wt[r];s?i.push(`border-inline-start:${s}`,`padding-inline-start:${St}`):e&&o.push(c("mo",{fence:"true",form:"prefix"},[e]));for(let d of t.children)o.push(this.child(d));l?i.push(`border-inline-end:${l}`,`padding-inline-end:${St}`):r&&o.push(c("mo",{fence:"true",form:"postfix"},[r]));let a=E("mrow",t.attrs);return i.length>0&&R(a,[...i,nn]),c("mrow",a,o)}enclose(t){let e=(t.attrs.notation??"longdiv").trim().split(/[\s,]+/).filter(Boolean),r=t.children.map(m=>this.child(m));e.includes("radical")&&(r=[c("msqrt",{},r)]);let o=E("mrow",t.attrs),i=[],s=[],l=new Set,a;for(let m of e){for(let h of un[m]??[])i.push(`${h}:${v}`),l.add(h);a=pn[m]??a;let p=En[m];p&&s.push(p)}a&&i.push(`border-radius:${a}`);let d=[...e.includes("longdiv")?[fn]:[],...s.map(m=>m.image)];d.length>0&&i.push(`background-image:${d.join(",")}`);let u=e.map(m=>hn[m]).find(m=>m!==void 0);return i.push(u??bn(l,s)),R(o,i),(l.size>0||s.length>0)&&r.push(c("mspace",{height:Z.height,depth:Z.depth})),c("mrow",o,r)}table(t){let e=t.children.filter(l=>l.kind==="element"),r=E("mtable",t.attrs),o=t.attrs.frame;(o==="solid"||o==="dashed")&&R(r,[`border:1px ${o} currentColor`]);let i=e.length,s=e.map((l,a)=>{let d=l.children.filter(h=>h.kind==="element"),u=d.length,m=l.attrs.rowalign??N(t.attrs.rowalign,a);return c("mtr",{},d.map((h,f)=>{let x=E("mtd",h.attrs),g=[],y=h.attrs.columnalign??N(l.attrs.columnalign,f)??N(t.attrs.columnalign,f),T=y?Q[y]:void 0;T&&g.push(...J(T));let P=h.attrs.rowalign??m,G=P?en[P]:void 0;G&&g.push(`vertical-align:${G}`);let O=N(t.attrs.columnlines,f);f<u-1&&(O==="solid"||O==="dashed")&&g.push(`border-right:1px ${O} currentColor`);let D=N(t.attrs.rowlines,a);a<i-1&&(D==="solid"||D==="dashed")&&g.push(`border-bottom:1px ${D} currentColor`);let M=N(t.attrs.columnspacing,f);M&&g.push(`padding-left:calc(${C(M)} / 2)`,`padding-right:calc(${C(M)} / 2)`);let K=N(t.attrs.rowspacing,a);K&&g.push(`padding-top:calc(${C(K)} / 2)`,`padding-bottom:calc(${C(K)} / 2)`),R(x,g);let st=h.children.map(ee=>this.child(ee));return c("mtd",x,T?At(st):st)}))});return c("mtable",r,s)}stackCells(t,e,r){let o=[],i=e;for(let s of t){if(s.kind==="element"&&s.tag==="msgroup"){let l=i+Number(s.attrs.position??0);o.push(...this.stackCells(s.children,l,Number(s.attrs.shift??0)))}else if(s.kind==="leaf"&&s.tag==="msline")o.push({css:[j,`border-top:${v}`],content:[]});else if(s.kind==="element"&&s.tag==="mscarries"){let l=s.children.map(a=>this.child(a));o.push({css:[j],content:[c("mstyle",{scriptlevel:ke},l)]})}else{let l=i+Number(s.kind==="row"?s.attrs.position??0:0),a=[U];l!==0&&a.push(`padding-right:${l*Me}em`),o.push({css:a,content:[this.child(s)]})}i+=r}return o}stackAlign(t){return Q[t.attrs.stackalign??"decimalpoint"]??"right"}stackCell(t,e,r=[]){let o=[...t?.css??[j],...J(e),...r];return c("mtd",{style:o.join(";")},At(t?.content??[]))}slotCell(t){return{css:[U],content:t?[this.child(t)]:[]}}stack(t){let e=this.stackAlign(t),r=this.stackCells(t.children,0,0).map(o=>c("mtr",{},[this.stackCell(o,e)]));return c("mtable",E("mtable",t.attrs),r)}longdiv(t){let[e,r,...o]=t.children,i=this.stackAlign(t),[s,...l]=this.stackCells(o,0,0),a=()=>this.stackCell(void 0,i),d;if(rn.has(t.attrs.longdivstyle??"")){let[u,...m]=l,p=h=>this.stackCell(h,i,[sn]);d=[[p(s),this.stackCell(this.slotCell(e),"left",[`border-left:${v}`,`border-bottom:${v}`,Ct])],[p(u),this.stackCell(this.slotCell(r),"left",[Ct])],...m.map(h=>[p(h),a()])]}else d=[[a(),this.bracketCell(this.slotCell(r),i,!1)],[this.stackCell(this.slotCell(e),"right"),this.bracketCell(s,i,!0)],...l.map(u=>[a(),this.bracketCell(u,i,!1)])];return c("mtable",E("mtable",t.attrs),d.map(u=>c("mtr",{},u)))}bracketCell(t,e,r){let o=c("mo",{lspace:"0",rspace:"0"},[on]),i=t?.content??[];if(!r)return this.stackCell({css:t?.css??[U],content:[c("mrow",{},[c("mphantom",{},[o]),...i])]},e);let s=[an,...(t?.css??[]).filter(l=>l!==U),`border-top:${v}`];return this.stackCell({css:s,content:[c("mrow",{},[o,c("mrow",{style:ln},[...i])])]},e)}};function w(n,t){return new tt(t).document(n)}var F="FormulaComposer Math",et=`@font-face{font-family:"${F}";src:local("STIX Two Math"),local("STIXTwoMath-Regular"),local("Cambria Math"),local("Latin Modern Math"),local("LatinModernMath-Regular");}`,B=`"${F}", math`,nt=`"STIX Two Math", "${F}", "Cambria Math", "Latin Modern Math", math`,Bt="formula-composer-renderer-styles",_n=`${et}
2
+ .sw-canvas{position:relative;outline:none;cursor:text;}
3
+ .sw-canvas math{font-family:${nt};math-style:normal;}
4
+ .sw-placeholder{outline:1px solid var(--sw-placeholder,#3f9b46);outline-offset:-1px;}
5
+ .sw-caret{position:absolute;width:0;border-left:1.5px solid currentColor;pointer-events:none;animation:sw-blink 1.06s steps(1) infinite;}
6
+ .sw-canvas:not(.sw-focused) .sw-caret{display:none;}
7
+ .sw-selection-box{position:absolute;background:rgba(51,128,240,0.28);pointer-events:none;}
8
+ @keyframes sw-blink{50%{opacity:0;}}
9
+ @media (prefers-reduced-motion:reduce){.sw-caret{animation:none;}}`;function L(n){if(n.getElementById(Bt))return;let t=n.createElement("style");t.id=Bt,t.textContent=_n,(n.head??n.documentElement).appendChild(t)}import{parseMathML as Nn}from"../math-core/index.js";var Wt=16,vn="#000000",V=1,Vt=1,Ln=-1e5,Tn="http://www.w3.org/2000/svg",Mn="http://www.w3.org/1999/xhtml",kn=/^(#[0-9a-fA-F]{3,8}|[a-zA-Z]+|rgba?\([\d\s.,%]+\))$/,Pt="math-style:normal",On="math:not([displaystyle])",Gt=new WeakMap;function sr(n){let t=Gt.get(n);if(t)return t;L(n);let e=n.fonts,r=e?e.load(`${Wt}px "${F}"`).then(()=>{},()=>{}):Promise.resolve();return Gt.set(n,r),r}var Ht=100;function Ut(n){return Math.round(n*Ht)/Ht}function Dn(n){let t=n.getBoundingClientRect(),e={left:t.left,top:t.top,right:t.right,bottom:t.bottom};for(let r of n.querySelectorAll("*")){let o=r.getBoundingClientRect();o.width===0&&o.height===0||(e.left=Math.min(e.left,o.left),e.top=Math.min(e.top,o.top),e.right=Math.max(e.right,o.right),e.bottom=Math.max(e.bottom,o.bottom))}return e}function zt(n,t){return n&&kn.test(n)?n:t}function ar(n,t,e={}){let r=typeof n=="string"?Nn(n).doc:n,o=w(r,{editable:!1,fallbackFonts:B}),i=e.fontSize??Wt,s=zt(e.color,vn),l=e.backgroundColor?zt(e.backgroundColor,"transparent"):"transparent";L(t);let a=t.createElement("div");a.setAttribute("aria-hidden","true"),a.style.cssText=`position:absolute;left:${Ln}px;top:0;visibility:hidden;white-space:nowrap;line-height:normal;font-size:${i}px;`;let d=A(o,t),u=d.getAttribute("style"),m=d.hasAttribute("displaystyle")?`font-family:${B}`:`font-family:${B};${Pt}`;d.setAttribute("style",u?`${m};${u}`:m);let p=t.createElement("span");p.style.cssText="display:inline-block;width:0;height:0;vertical-align:baseline;",a.append(d,p),(t.body??t.documentElement).appendChild(a);let h=a.getBoundingClientRect(),f=Dn(d),x=p.getBoundingClientRect();a.remove();let g=Math.max(Vt,Math.ceil(f.right-f.left)+2*V),y=Math.max(Vt,Math.ceil(f.bottom-f.top)+2*V),T=Math.round(x.top-f.top)+V,P=-(y-T),G=Ut(h.left-f.left+V),O=Ut(h.top-f.top+V),D=`${et}math{font-family:${B};}${On}{${Pt};}`,M=`<svg xmlns="${Tn}" width="${g}" height="${y}" viewBox="0 0 ${g} ${y}"><foreignObject x="0" y="0" width="${g}" height="${y}"><div xmlns="${Mn}" style="position:relative;overflow:hidden;width:${g}px;height:${y}px;background:${l};"><div style="position:absolute;left:${G}px;top:${O}px;font-size:${i}px;line-height:normal;white-space:nowrap;color:${s};"><style>${D}</style>${$(o)}</div></div></foreignObject></svg>`;return{svg:M,dataUri:`data:image/svg+xml;charset=utf8,${encodeURIComponent(M)}`,width:g,height:y,baseline:T,verticalAlign:P}}function lr(n){let t="";for(let e of new TextEncoder().encode(n))t+=String.fromCharCode(e);return`data:image/svg+xml;base64,${btoa(t)}`}function cr(n,t,e=2){return new Promise((r,o)=>{let i=t.createElement("img");i.onload=()=>{let s=t.createElement("canvas");s.width=Math.ceil(n.width*e),s.height=Math.ceil(n.height*e);let l=s.getContext("2d");if(!l){o(new Error("Canvas 2D context unavailable"));return}l.scale(e,e),l.drawImage(i,0,0,n.width,n.height);try{r(s.toDataURL("image/png"))}catch(a){o(a instanceof Error?a:new Error("Canvas export failed"))}},i.onerror=()=>o(new Error("Formula image failed to load")),i.src=n.dataUri})}var Y=2;function In(n){let t=n.ownerDocument.defaultView;return t?t.getComputedStyle(n).direction==="rtl":!1}function Kt(n,t){if(n===t)return t.getBoundingClientRect();let e=n.parentElement;for(;e&&e!==t;){if(e.hasAttribute(I))return e.getBoundingClientRect();e=e.parentElement}return t.getBoundingClientRect()}function Yt(n,t){let e=n.children[t];return e?.kind==="leaf"&&e.attrs.linebreak==="newline"}function $n(n){return n.closest(`[${I}]`)?.parentElement?.parentElement?.nextElementSibling?.querySelector(`[${I}]`)??null}function Xt(n,t){let e=t.rows.get(n.id);if(!e)return[];let r=e.getBoundingClientRect();if(n.children.length===0)return[{offset:0,x:r.left+r.width/2,line:r}];let o=In(e),i=[];for(let s=0;s<=n.children.length;s+=1){let l=s>0&&!Yt(n,s-1),a=n.children[l?s-1:s],d=a?t.atoms.get(a.id):void 0;if(!d){let p=s===n.children.length?n.children[s-1]:void 0,h=p&&Yt(n,s-1)?t.atoms.get(p.id):void 0,f=h?$n(h):null;if(f){let x=f.getBoundingClientRect();i.push({offset:s,x:o?x.right:x.left,line:x})}continue}let u=d.getBoundingClientRect(),m=l!==o;i.push({offset:s,x:m?u.right:u.left,line:Kt(d,e)})}return i}function qt(n,t){return{left:n.left-t.left,top:n.top-t.top,width:n.width,height:n.height}}function rt(n,t,e,r){let o=t.rows.get(n.rowId);if(!o)return null;let i=Xt(o,e).find(s=>s.offset===n.offset);return i?qt({left:i.x,top:i.line.top,width:0,height:i.line.height},r):null}function ot(n,t,e){let r=t.rows.get(n.row.id);if(!r)return[];let o=new Map;for(let i=n.start;i<n.end;i+=1){let s=n.row.children[i],l=s?t.atoms.get(s.id):void 0;if(!l)continue;let a=l.getBoundingClientRect(),d=Kt(l,r),u=`${d.top}:${d.left}`,m=o.get(u);m?(m.left=Math.min(m.left,a.left),m.right=Math.max(m.right,a.right)):o.set(u,{left:a.left,right:a.right,line:d})}return[...o.values()].map(i=>qt({left:i.left,top:i.line.top,width:i.right-i.left,height:i.line.height},e))}function Fn(n,t,e){return t>=n.left-Y&&t<=n.right+Y&&e>=n.top-Y&&e<=n.bottom+Y}function it(n,t,e,r,o){let i,s=Number.POSITIVE_INFINITY;for(let[p,h]of r.rows){let f=h.getBoundingClientRect();if(!Fn(f,n,t))continue;let x=f.width*f.height;if(x<=s){let g=e.rows.get(p);g&&(i=g,s=x)}}let l=i??e.rows.get(o);if(!l)return null;let a=Xt(l,r),d=a.filter(p=>t>=p.line.top&&t<=p.line.bottom),u=d.length>0?d:a,m;for(let p of u)(!m||Math.abs(p.x-n)<Math.abs(m.x-n))&&(m=p);return m?{rowId:l.id,offset:m.offset}:{rowId:l.id,offset:0}}var Bn="sw-canvas",Vn="sw-focused",Pn="sw-caret",Zt="sw-selection-box",S=8;function jt(n,t){n.style.left=`${t.left}px`,n.style.top=`${t.top}px`,n.style.width=`${t.width}px`,n.style.height=`${t.height}px`}var Qt=class{constructor(t,e,r={}){b(this,"model",e);b(this,"element");b(this,"mathHost");b(this,"overlay");b(this,"caretEl");b(this,"maps",{rows:new Map,atoms:new Map});b(this,"unsubscribe");b(this,"destroyed",!1);b(this,"renderedRevision",-1);let o=t.ownerDocument;L(o),this.element=o.createElement("div"),this.element.className=Bn,r.fontSize&&(this.element.style.fontSize=r.fontSize),this.mathHost=o.createElement("div"),this.overlay=o.createElement("div"),this.overlay.setAttribute("aria-hidden","true"),this.caretEl=o.createElement("div"),this.caretEl.className=Pn,this.overlay.appendChild(this.caretEl),this.element.append(this.mathHost,this.overlay),t.appendChild(this.element),this.unsubscribe=e.onChange(()=>{e.revision!==this.renderedRevision?this.render():this.updateOverlay()}),this.render()}get elementMaps(){return this.maps}get mathElement(){return this.mathHost.firstElementChild}render(){if(this.destroyed)return;let t=this.element.ownerDocument,e={rows:new Map,atoms:new Map},r=A(w(this.model.document,{editable:!0,fallbackFonts:nt}),t,e);this.maps=e,this.renderedRevision=this.model.revision,this.mathHost.replaceChildren(r),this.updateOverlay()}updateOverlay(){if(this.destroyed)return;let t=this.element.getBoundingClientRect();for(let o of this.overlay.querySelectorAll(`.${Zt}`))o.remove();let e=this.model.getSelection();if(e)for(let o of ot(e,this.maps,t)){let i=this.element.ownerDocument.createElement("div");i.className=Zt,jt(i,o),this.overlay.appendChild(i)}let r=rt(this.model.getCaret(),this.model.treeIndex,this.maps,t);this.caretEl.hidden=r===null||e!==null,r&&jt(this.caretEl,r),this.restartBlink()}restartBlink(){this.caretEl.style.animation="none",this.caretEl.offsetWidth,this.caretEl.style.animation=""}setFocused(t){this.element.classList.toggle(Vn,t)}caretFromPoint(t,e){return it(t,e,this.model.treeIndex,this.maps,this.model.document.root.id)}scrollCaretIntoView(t){let e=this.caretEl.getBoundingClientRect(),r=t.getBoundingClientRect();e.right+S>r.right?t.scrollLeft+=e.right+S-r.right:e.left-S<r.left&&(t.scrollLeft-=r.left-e.left+S),e.bottom+S>r.bottom?t.scrollTop+=e.bottom+S-r.bottom:e.top-S<r.top&&(t.scrollTop-=r.top-e.top+S)}destroy(){this.destroyed||(this.destroyed=!0,this.unsubscribe(),this.element.remove())}};function te(n){return typeof n=="string"?Gn(n).doc:n}function Sr(n){return $(w(te(n),{editable:!1}))}function Hn(n,t,e={}){return L(t),A(w(te(n),{editable:!1,placeholders:e.placeholders??!1}),t)}var Jt="data-sw-core",Un=9;function zn(n){return n.nodeType===Un}function Cr(n){let t=zn(n)?n:n.ownerDocument,e=new XMLSerializer,r=0;for(let o of[...n.querySelectorAll("math")]){if(o.hasAttribute(Jt)||o.parentElement?.closest("math"))continue;let i;try{i=Hn(e.serializeToString(o),t)}catch{continue}i.setAttribute(Jt,""),o.replaceWith(i),r+=1}return r}export{Wt as DEFAULT_IMAGE_FONT_SIZE,nt as EDITOR_FONT_STACK,et as FONT_FACE_CSS,F as IMAGE_FONT_FAMILY,B as IMAGE_FONT_STACK,I as LINE_ATTR,Qt as MathView,Ne as NODE_ID_ATTR,vt as PLACEHOLDER_CLASS,_n as RENDERER_CSS,ve as ROW_ID_ATTR,H as applyMathVariant,w as buildCoreTree,rt as caretBox,it as caretFromPoint,ar as createFormulaImage,sr as ensureMathFont,L as ensureRendererStyles,X as hasUnicodeVariant,C as normalizeLength,cr as rasterizeFormulaImage,Hn as renderMathElement,ht as sanitizeStyle,ot as selectionBoxes,lr as toBase64DataUri,Sr as toCoreMathML,A as toDOM,$ as toXML,Cr as upgradeMathElements,c as vel};
@@ -0,0 +1,14 @@
1
+ import type { Caret, SelectionRange, TreeIndex } from '../math-core/index';
2
+ import { type ElementMaps } from './vnode.js';
3
+ export interface Box {
4
+ left: number;
5
+ top: number;
6
+ width: number;
7
+ height: number;
8
+ }
9
+ /** Caret box relative to `origin` (usually the canvas rect). */
10
+ export declare function caretBox(caret: Caret, index: TreeIndex, maps: ElementMaps, origin: DOMRect): Box | null;
11
+ /** Highlight boxes for a selection, one per visual line. */
12
+ export declare function selectionBoxes(range: SelectionRange, maps: ElementMaps, origin: DOMRect): Box[];
13
+ /** Caret position nearest to a client point: deepest row under the point, then nearest stop. */
14
+ export declare function caretFromPoint(x: number, y: number, index: TreeIndex, maps: ElementMaps, rootRowId: number): Caret | null;
@@ -0,0 +1,9 @@
1
+ /** Local-only face so measurement in the page and drawing inside an SVG image resolve to the same font. */
2
+ export declare const IMAGE_FONT_FAMILY = "FormulaComposer Math";
3
+ export declare const FONT_FACE_CSS: string;
4
+ export declare const IMAGE_FONT_STACK = "\"FormulaComposer Math\", math";
5
+ /** Editor stack: a bundled "STIX Two Math" web font wins when the host page provides one. */
6
+ export declare const EDITOR_FONT_STACK = "\"STIX Two Math\", \"FormulaComposer Math\", \"Cambria Math\", \"Latin Modern Math\", math";
7
+ export declare const RENDERER_CSS = "@font-face{font-family:\"FormulaComposer Math\";src:local(\"STIX Two Math\"),local(\"STIXTwoMath-Regular\"),local(\"Cambria Math\"),local(\"Latin Modern Math\"),local(\"LatinModernMath-Regular\");}\n.sw-canvas{position:relative;outline:none;cursor:text;}\n.sw-canvas math{font-family:\"STIX Two Math\", \"FormulaComposer Math\", \"Cambria Math\", \"Latin Modern Math\", math;math-style:normal;}\n.sw-placeholder{outline:1px solid var(--sw-placeholder,#3f9b46);outline-offset:-1px;}\n.sw-caret{position:absolute;width:0;border-left:1.5px solid currentColor;pointer-events:none;animation:sw-blink 1.06s steps(1) infinite;}\n.sw-canvas:not(.sw-focused) .sw-caret{display:none;}\n.sw-selection-box{position:absolute;background:rgba(51,128,240,0.28);pointer-events:none;}\n@keyframes sw-blink{50%{opacity:0;}}\n@media (prefers-reduced-motion:reduce){.sw-caret{animation:none;}}";
8
+ /** Injects renderer styles once per document. */
9
+ export declare function ensureRendererStyles(doc: Document): void;
@@ -0,0 +1,30 @@
1
+ import type { Caret, MathEditorModel } from '../math-core/index';
2
+ import { type ElementMaps } from './vnode.js';
3
+ export interface MathViewOptions {
4
+ /** CSS font size of the formula, e.g. `'24px'`. */
5
+ fontSize?: string;
6
+ }
7
+ /** Live rendering of a {@link MathEditorModel} with caret and selection overlay. */
8
+ export declare class MathView {
9
+ private readonly model;
10
+ readonly element: HTMLDivElement;
11
+ private readonly mathHost;
12
+ private readonly overlay;
13
+ private readonly caretEl;
14
+ private maps;
15
+ private readonly unsubscribe;
16
+ private destroyed;
17
+ private renderedRevision;
18
+ constructor(container: HTMLElement, model: MathEditorModel, options?: MathViewOptions);
19
+ get elementMaps(): ElementMaps;
20
+ /** The rendered `<math>` element. */
21
+ get mathElement(): Element | null;
22
+ render(): void;
23
+ updateOverlay(): void;
24
+ private restartBlink;
25
+ setFocused(focused: boolean): void;
26
+ caretFromPoint(clientX: number, clientY: number): Caret | null;
27
+ /** Scrolls `scroller` so the caret stays visible. */
28
+ scrollCaretIntoView(scroller: HTMLElement): void;
29
+ destroy(): void;
30
+ }
@@ -0,0 +1,25 @@
1
+ /** Render tree node. Every element is in the MathML namespace. */
2
+ export interface VElement {
3
+ tag: string;
4
+ attrs: Record<string, string>;
5
+ children: VChild[];
6
+ /** Model id of the atom this element renders (editable mode only). */
7
+ nodeId?: number;
8
+ /** Model id of the row this element renders (editable mode only). */
9
+ rowId?: number;
10
+ /** Marks a visual line of a multi-line row. */
11
+ line?: boolean;
12
+ }
13
+ export type VChild = VElement | string;
14
+ export interface ElementMaps {
15
+ readonly rows: Map<number, Element>;
16
+ readonly atoms: Map<number, Element>;
17
+ }
18
+ export declare const NODE_ID_ATTR = "data-sw-id";
19
+ export declare const ROW_ID_ATTR = "data-sw-row";
20
+ export declare const LINE_ATTR = "data-sw-line";
21
+ export declare function vel(tag: string, attrs?: Record<string, string>, children?: VChild[]): VElement;
22
+ /** Builds DOM nodes in `doc`, recording atom and row elements in `maps`. */
23
+ export declare function toDOM(node: VElement, doc: Document, maps?: ElementMaps): Element;
24
+ /** Serializes to XML without editor bookkeeping attributes. */
25
+ export declare function toXML(node: VElement, root?: boolean): string;