import {
  DEFAULT_FORMULAX_LOCALE,
  createLegacyBaseComponent,
  getFormulaXRuntimeMessage,
  kityAssetManifest,
  legacyBaseUtils,
  legacyBoxType,
  legacyEleType,
  legacyEventListener,
  legacyGroupType,
  legacyInputFilter,
  legacyItemType,
  legacyKfEvent,
  legacyKfExtDef,
  legacyOtherPosition,
  legacySysconf,
  legacyUiDef,
  legacyUiUtils,
  normalizeFormulaXLocale,
  setToolbarAssetUrls,
  utils_default
} from "./chunk-OCSSWPUX.js";

// src/index.ts
import { Node } from "@tiptap/core";

// ../kity-runtime/src/vendor/char-position.ts
var legacyCharPosition = {
  "\\pm": {
    "x": 5,
    "y": 0
  },
  "\\infty": {
    "x": 42,
    "y": 0
  },
  "=": {
    "x": 79,
    "y": 0
  },
  "\\sim": {
    "x": 116,
    "y": 0
  },
  "\\times": {
    "x": 153,
    "y": 0
  },
  "\\div": {
    "x": 190,
    "y": 0
  },
  "!": {
    "x": 227,
    "y": 0
  },
  "<": {
    "x": 264,
    "y": 0
  },
  "\\ll": {
    "x": 301,
    "y": 0
  },
  ">": {
    "x": 338,
    "y": 0
  },
  "\\gg": {
    "x": 375,
    "y": 0
  },
  "\\leq": {
    "x": 412,
    "y": 0
  },
  "\\geq": {
    "x": 449,
    "y": 0
  },
  "\\mp": {
    "x": 486,
    "y": 0
  },
  "\\cong": {
    "x": 523,
    "y": 0
  },
  "\\equiv": {
    "x": 560,
    "y": 0
  },
  "\\propto": {
    "x": 597,
    "y": 0
  },
  "\\approx": {
    "x": 634,
    "y": 0
  },
  "\\forall": {
    "x": 671,
    "y": 0
  },
  "\\partial": {
    "x": 708,
    "y": 0
  },
  "\\surd": {
    "x": 745,
    "y": 0
  },
  "\\cup": {
    "x": 782,
    "y": 0
  },
  "\\cap": {
    "x": 819,
    "y": 0
  },
  "\\varnothing": {
    "x": 856,
    "y": 0
  },
  "%": {
    "x": 893,
    "y": 0
  },
  "\\circ": {
    "x": 930,
    "y": 0
  },
  "\\exists": {
    "x": 967,
    "y": 0
  },
  "\\nexists": {
    "x": 1004,
    "y": 0
  },
  "\\in": {
    "x": 1041,
    "y": 0
  },
  "\\ni": {
    "x": 1078,
    "y": 0
  },
  "\\gets": {
    "x": 5,
    "y": 37
  },
  "\\uparrow": {
    "x": 42,
    "y": 37
  },
  "\\to": {
    "x": 79,
    "y": 37
  },
  "\\downarrow": {
    "x": 116,
    "y": 37
  },
  "\\leftrightarrow": {
    "x": 153,
    "y": 37
  },
  "\\therefore": {
    "x": 190,
    "y": 37
  },
  "\\because": {
    "x": 227,
    "y": 37
  },
  "+": {
    "x": 264,
    "y": 37
  },
  "-": {
    "x": 301,
    "y": 37
  },
  "\\neg": {
    "x": 338,
    "y": 37
  },
  "\\ast": {
    "x": 375,
    "y": 37
  },
  "\\cdot": {
    "x": 412,
    "y": 37
  },
  "\\vdots": {
    "x": 449,
    "y": 37
  },
  "\\ddots": {
    "x": 486,
    "y": 37
  },
  "\\aleph": {
    "x": 523,
    "y": 37
  },
  "\\beth": {
    "x": 560,
    "y": 37
  },
  "\\blacksquare": {
    "x": 597,
    "y": 37
  },
  "\\alpha": {
    "x": 634,
    "y": 37
  },
  "\\beta": {
    "x": 671,
    "y": 37
  },
  "\\gamma": {
    "x": 708,
    "y": 37
  },
  "\\delta": {
    "x": 745,
    "y": 37
  },
  "\\epsilon": {
    "x": 782,
    "y": 37
  },
  "\\zeta": {
    "x": 819,
    "y": 37
  },
  "\\eta": {
    "x": 856,
    "y": 37
  },
  "\\theta": {
    "x": 893,
    "y": 37
  },
  "\\iota": {
    "x": 930,
    "y": 37
  },
  "\\kappa": {
    "x": 967,
    "y": 37
  },
  "\\lambda": {
    "x": 1004,
    "y": 37
  },
  "\\mu": {
    "x": 1041,
    "y": 37
  },
  "\\nu": {
    "x": 1078,
    "y": 37
  },
  "\\xi": {
    "x": 5,
    "y": 74
  },
  "\\omicron": {
    "x": 42,
    "y": 74
  },
  "\\pi": {
    "x": 79,
    "y": 74
  },
  "\\rho": {
    "x": 116,
    "y": 74
  },
  "\\sigma": {
    "x": 153,
    "y": 74
  },
  "\\tau": {
    "x": 190,
    "y": 74
  },
  "\\upsilon": {
    "x": 227,
    "y": 74
  },
  "\\phi": {
    "x": 264,
    "y": 74
  },
  "\\chi": {
    "x": 301,
    "y": 74
  },
  "\\psi": {
    "x": 338,
    "y": 74
  },
  "\\omega": {
    "x": 375,
    "y": 74
  },
  "\\Alpha": {
    "x": 412,
    "y": 74
  },
  "\\Beta": {
    "x": 449,
    "y": 74
  },
  "\\Gamma": {
    "x": 486,
    "y": 74
  },
  "\\Delta": {
    "x": 523,
    "y": 74
  },
  "\\Epsilon": {
    "x": 560,
    "y": 74
  },
  "\\Zeta": {
    "x": 597,
    "y": 74
  },
  "\\Eta": {
    "x": 634,
    "y": 74
  },
  "\\Theta": {
    "x": 671,
    "y": 74
  },
  "\\Iota": {
    "x": 708,
    "y": 74
  },
  "\\Kappa": {
    "x": 745,
    "y": 74
  },
  "\\Lambda": {
    "x": 782,
    "y": 74
  },
  "\\Mu": {
    "x": 819,
    "y": 74
  },
  "\\Nu": {
    "x": 856,
    "y": 74
  },
  "\\Xi": {
    "x": 893,
    "y": 74
  },
  "\\Omicron": {
    "x": 930,
    "y": 74
  },
  "\\Pi": {
    "x": 967,
    "y": 74
  },
  "\\Rho": {
    "x": 1004,
    "y": 74
  },
  "\\Sigma": {
    "x": 1041,
    "y": 74
  },
  "\\Tau": {
    "x": 1078,
    "y": 74
  },
  "\\Upsilon": {
    "x": 5,
    "y": 111
  },
  "\\Phi": {
    "x": 42,
    "y": 111
  },
  "\\Chi": {
    "x": 79,
    "y": 111
  },
  "\\Psi": {
    "x": 116,
    "y": 111
  },
  "\\Omega": {
    "x": 153,
    "y": 111
  },
  "\\digamma": {
    "x": 190,
    "y": 111
  },
  "\\varepsilon": {
    "x": 227,
    "y": 111
  },
  "\\varkappa": {
    "x": 264,
    "y": 111
  },
  "\\varphi": {
    "x": 301,
    "y": 111
  },
  "\\varpi": {
    "x": 338,
    "y": 111
  },
  "\\varrho": {
    "x": 375,
    "y": 111
  },
  "\\varsigma": {
    "x": 412,
    "y": 111
  },
  "\\vartheta": {
    "x": 449,
    "y": 111
  },
  "\\neq": {
    "x": 486,
    "y": 111
  },
  "\\nless": {
    "x": 523,
    "y": 111
  },
  "\\ngtr": {
    "x": 560,
    "y": 111
  },
  "\\nleq": {
    "x": 597,
    "y": 111
  },
  "\\ngeq": {
    "x": 634,
    "y": 111
  },
  "\\nsim": {
    "x": 671,
    "y": 111
  },
  "\\lneqq": {
    "x": 708,
    "y": 111
  },
  "\\gneqq": {
    "x": 745,
    "y": 111
  },
  "\\nprec": {
    "x": 782,
    "y": 111
  },
  "\\nsucc": {
    "x": 819,
    "y": 111
  },
  "\\notin": {
    "x": 856,
    "y": 111
  },
  "\\nsubseteq": {
    "x": 893,
    "y": 111
  },
  "\\nsupseteq": {
    "x": 930,
    "y": 111
  },
  "\\subsetneq": {
    "x": 967,
    "y": 111
  },
  "\\supsetneq": {
    "x": 1004,
    "y": 111
  },
  "\\lnsim": {
    "x": 1041,
    "y": 111
  },
  "\\gnsim": {
    "x": 1078,
    "y": 111
  },
  "\\precnsim": {
    "x": 5,
    "y": 148
  },
  "\\succnsim": {
    "x": 42,
    "y": 148
  },
  "\\ntriangleleft": {
    "x": 79,
    "y": 148
  },
  "\\ntriangleright": {
    "x": 116,
    "y": 148
  },
  "\\ntrianglelefteq": {
    "x": 153,
    "y": 148
  },
  "\\ntrianglerighteq": {
    "x": 190,
    "y": 148
  },
  "\\nmid": {
    "x": 227,
    "y": 148
  },
  "\\nparallel": {
    "x": 264,
    "y": 148
  },
  "\\nvdash": {
    "x": 301,
    "y": 148
  },
  "\\nVdash": {
    "x": 338,
    "y": 148
  },
  "\\nvDash": {
    "x": 375,
    "y": 148
  },
  "\\nVDash": {
    "x": 412,
    "y": 148
  },
  "\\daleth": {
    "x": 449,
    "y": 148
  },
  "\\gimel": {
    "x": 486,
    "y": 148
  },
  "\\complement": {
    "x": 523,
    "y": 148
  },
  "\\ell": {
    "x": 560,
    "y": 148
  },
  "\\eth": {
    "x": 597,
    "y": 148
  },
  "\\hbar": {
    "x": 634,
    "y": 148
  },
  "\\hslash": {
    "x": 671,
    "y": 148
  },
  "\\mho": {
    "x": 708,
    "y": 148
  },
  "\\wp": {
    "x": 745,
    "y": 148
  },
  "\\circledS": {
    "x": 782,
    "y": 148
  },
  "\\Bbbk": {
    "x": 819,
    "y": 148
  },
  "\\Finv": {
    "x": 856,
    "y": 148
  },
  "\\Game": {
    "x": 893,
    "y": 148
  },
  "\\Im": {
    "x": 930,
    "y": 148
  },
  "\\Re": {
    "x": 967,
    "y": 148
  },
  "\\updownarrow": {
    "x": 1004,
    "y": 148
  },
  "\\Leftarrow": {
    "x": 1041,
    "y": 148
  },
  "\\Rightarrow": {
    "x": 1078,
    "y": 148
  },
  "\\Uparrow": {
    "x": 5,
    "y": 185
  },
  "\\Downarrow": {
    "x": 42,
    "y": 185
  },
  "\\Leftrightarrow": {
    "x": 79,
    "y": 185
  },
  "\\Updownarrow": {
    "x": 116,
    "y": 185
  },
  "\\longleftarrow": {
    "x": 153,
    "y": 185
  },
  "\\longrightarrow": {
    "x": 190,
    "y": 185
  },
  "\\longleftrightarrow": {
    "x": 227,
    "y": 185
  },
  "\\Longleftarrow": {
    "x": 264,
    "y": 185
  },
  "\\Longrightarrow": {
    "x": 301,
    "y": 185
  },
  "\\Longleftrightarrow": {
    "x": 338,
    "y": 185
  },
  "\\nearrow": {
    "x": 375,
    "y": 185
  },
  "\\nwarrow": {
    "x": 412,
    "y": 185
  },
  "\\searrow": {
    "x": 449,
    "y": 185
  },
  "\\swarrow": {
    "x": 486,
    "y": 185
  },
  "\\nleftarrow": {
    "x": 523,
    "y": 185
  },
  "\\nrightarrow": {
    "x": 560,
    "y": 185
  },
  "\\nLeftarrow": {
    "x": 597,
    "y": 185
  },
  "\\nRightarrow": {
    "x": 634,
    "y": 185
  },
  "\\nLeftrightarrow": {
    "x": 671,
    "y": 185
  },
  "\\leftharpoonup": {
    "x": 708,
    "y": 185
  },
  "\\leftharpoondown": {
    "x": 745,
    "y": 185
  },
  "\\rightharpoonup": {
    "x": 782,
    "y": 185
  },
  "\\rightharpoondown": {
    "x": 819,
    "y": 185
  },
  "\\upharpoonleft": {
    "x": 856,
    "y": 185
  },
  "\\upharpoonright": {
    "x": 893,
    "y": 185
  },
  "\\downharpoonleft": {
    "x": 930,
    "y": 185
  },
  "\\downharpoonright": {
    "x": 967,
    "y": 185
  },
  "\\leftrightharpoons": {
    "x": 1004,
    "y": 185
  },
  "\\rightleftharpoons": {
    "x": 1041,
    "y": 185
  },
  "\\leftleftarrows": {
    "x": 1078,
    "y": 185
  },
  "\\rightrightarrows": {
    "x": 5,
    "y": 222
  },
  "\\upuparrows": {
    "x": 42,
    "y": 222
  },
  "\\downdownarrows": {
    "x": 79,
    "y": 222
  },
  "\\leftrightarrows": {
    "x": 116,
    "y": 222
  },
  "\\rightleftarrows": {
    "x": 153,
    "y": 222
  },
  "\\looparrowleft": {
    "x": 190,
    "y": 222
  },
  "\\looparrowright": {
    "x": 227,
    "y": 222
  },
  "\\leftarrowtail": {
    "x": 264,
    "y": 222
  },
  "\\rightarrowtail": {
    "x": 301,
    "y": 222
  },
  "\\Lsh": {
    "x": 338,
    "y": 222
  },
  "\\Rsh": {
    "x": 375,
    "y": 222
  },
  "\\Lleftarrow": {
    "x": 412,
    "y": 222
  },
  "\\Rrightarrow": {
    "x": 449,
    "y": 222
  },
  "\\curvearrowleft": {
    "x": 486,
    "y": 222
  },
  "\\curvearrowright": {
    "x": 523,
    "y": 222
  },
  "\\circlearrowleft": {
    "x": 560,
    "y": 222
  },
  "\\circlearrowright": {
    "x": 597,
    "y": 222
  },
  "\\multimap": {
    "x": 634,
    "y": 222
  },
  "\\leftrightsquigarrow": {
    "x": 671,
    "y": 222
  },
  "\\twoheadleftarrow": {
    "x": 708,
    "y": 222
  },
  "\\twoheadrightarrow": {
    "x": 745,
    "y": 222
  },
  "\\rightsquigarrow": {
    "x": 782,
    "y": 222
  },
  "\\mathcal{A}": {
    "x": 819,
    "y": 222
  },
  "\\mathcal{B}": {
    "x": 856,
    "y": 222
  },
  "\\mathcal{C}": {
    "x": 893,
    "y": 222
  },
  "\\mathcal{D}": {
    "x": 930,
    "y": 222
  },
  "\\mathcal{E}": {
    "x": 967,
    "y": 222
  },
  "\\mathcal{F}": {
    "x": 1004,
    "y": 222
  },
  "\\mathcal{G}": {
    "x": 1041,
    "y": 222
  },
  "\\mathcal{H}": {
    "x": 1078,
    "y": 222
  },
  "\\mathcal{I}": {
    "x": 5,
    "y": 259
  },
  "\\mathcal{J}": {
    "x": 42,
    "y": 259
  },
  "\\mathcal{K}": {
    "x": 79,
    "y": 259
  },
  "\\mathcal{L}": {
    "x": 116,
    "y": 259
  },
  "\\mathcal{M}": {
    "x": 153,
    "y": 259
  },
  "\\mathcal{N}": {
    "x": 190,
    "y": 259
  },
  "\\mathcal{O}": {
    "x": 227,
    "y": 259
  },
  "\\mathcal{P}": {
    "x": 264,
    "y": 259
  },
  "\\mathcal{Q}": {
    "x": 301,
    "y": 259
  },
  "\\mathcal{R}": {
    "x": 338,
    "y": 259
  },
  "\\mathcal{S}": {
    "x": 375,
    "y": 259
  },
  "\\mathcal{T}": {
    "x": 412,
    "y": 259
  },
  "\\mathcal{U}": {
    "x": 449,
    "y": 259
  },
  "\\mathcal{V}": {
    "x": 486,
    "y": 259
  },
  "\\mathcal{W}": {
    "x": 523,
    "y": 259
  },
  "\\mathcal{X}": {
    "x": 560,
    "y": 259
  },
  "\\mathcal{Y}": {
    "x": 597,
    "y": 259
  },
  "\\mathcal{Z}": {
    "x": 634,
    "y": 259
  },
  "\\mathfrak{A}": {
    "x": 671,
    "y": 259
  },
  "\\mathfrak{B}": {
    "x": 708,
    "y": 259
  },
  "\\mathfrak{C}": {
    "x": 745,
    "y": 259
  },
  "\\mathfrak{D}": {
    "x": 782,
    "y": 259
  },
  "\\mathfrak{E}": {
    "x": 819,
    "y": 259
  },
  "\\mathfrak{F}": {
    "x": 856,
    "y": 259
  },
  "\\mathfrak{G}": {
    "x": 893,
    "y": 259
  },
  "\\mathfrak{H}": {
    "x": 930,
    "y": 259
  },
  "\\mathfrak{I}": {
    "x": 967,
    "y": 259
  },
  "\\mathfrak{J}": {
    "x": 1004,
    "y": 259
  },
  "\\mathfrak{K}": {
    "x": 1041,
    "y": 259
  },
  "\\mathfrak{L}": {
    "x": 1078,
    "y": 259
  },
  "\\mathfrak{M}": {
    "x": 5,
    "y": 296
  },
  "\\mathfrak{N}": {
    "x": 42,
    "y": 296
  },
  "\\mathfrak{O}": {
    "x": 79,
    "y": 296
  },
  "\\mathfrak{P}": {
    "x": 116,
    "y": 296
  },
  "\\mathfrak{Q}": {
    "x": 153,
    "y": 296
  },
  "\\mathfrak{R}": {
    "x": 190,
    "y": 296
  },
  "\\mathfrak{S}": {
    "x": 227,
    "y": 296
  },
  "\\mathfrak{T}": {
    "x": 264,
    "y": 296
  },
  "\\mathfrak{U}": {
    "x": 301,
    "y": 296
  },
  "\\mathfrak{V}": {
    "x": 338,
    "y": 296
  },
  "\\mathfrak{W}": {
    "x": 375,
    "y": 296
  },
  "\\mathfrak{X}": {
    "x": 412,
    "y": 296
  },
  "\\mathfrak{Y}": {
    "x": 449,
    "y": 296
  },
  "\\mathfrak{Z}": {
    "x": 486,
    "y": 296
  },
  "\\mathfrak{a}": {
    "x": 523,
    "y": 296
  },
  "\\mathfrak{b}": {
    "x": 560,
    "y": 296
  },
  "\\mathfrak{c}": {
    "x": 597,
    "y": 296
  },
  "\\mathfrak{d}": {
    "x": 634,
    "y": 296
  },
  "\\mathfrak{e}": {
    "x": 671,
    "y": 296
  },
  "\\mathfrak{f}": {
    "x": 708,
    "y": 296
  },
  "\\mathfrak{g}": {
    "x": 745,
    "y": 296
  },
  "\\mathfrak{h}": {
    "x": 782,
    "y": 296
  },
  "\\mathfrak{i}": {
    "x": 819,
    "y": 296
  },
  "\\mathfrak{j}": {
    "x": 856,
    "y": 296
  },
  "\\mathfrak{k}": {
    "x": 893,
    "y": 296
  },
  "\\mathfrak{l}": {
    "x": 930,
    "y": 296
  },
  "\\mathfrak{m}": {
    "x": 967,
    "y": 296
  },
  "\\mathfrak{n}": {
    "x": 1004,
    "y": 296
  },
  "\\mathfrak{o}": {
    "x": 1041,
    "y": 296
  },
  "\\mathfrak{p}": {
    "x": 1078,
    "y": 296
  },
  "\\mathfrak{q}": {
    "x": 5,
    "y": 333
  },
  "\\mathfrak{r}": {
    "x": 42,
    "y": 333
  },
  "\\mathfrak{s}": {
    "x": 79,
    "y": 333
  },
  "\\mathfrak{t}": {
    "x": 116,
    "y": 333
  },
  "\\mathfrak{u}": {
    "x": 153,
    "y": 333
  },
  "\\mathfrak{v}": {
    "x": 190,
    "y": 333
  },
  "\\mathfrak{w}": {
    "x": 227,
    "y": 333
  },
  "\\mathfrak{x}": {
    "x": 264,
    "y": 333
  },
  "\\mathfrak{y}": {
    "x": 301,
    "y": 333
  },
  "\\mathfrak{z}": {
    "x": 338,
    "y": 333
  },
  "\\mathbb{A}": {
    "x": 375,
    "y": 333
  },
  "\\mathbb{B}": {
    "x": 412,
    "y": 333
  },
  "\\mathbb{C}": {
    "x": 449,
    "y": 333
  },
  "\\mathbb{D}": {
    "x": 486,
    "y": 333
  },
  "\\mathbb{E}": {
    "x": 523,
    "y": 333
  },
  "\\mathbb{F}": {
    "x": 560,
    "y": 333
  },
  "\\mathbb{G}": {
    "x": 597,
    "y": 333
  },
  "\\mathbb{H}": {
    "x": 634,
    "y": 333
  },
  "\\mathbb{I}": {
    "x": 671,
    "y": 333
  },
  "\\mathbb{J}": {
    "x": 708,
    "y": 333
  },
  "\\mathbb{K}": {
    "x": 745,
    "y": 333
  },
  "\\mathbb{L}": {
    "x": 782,
    "y": 333
  },
  "\\mathbb{M}": {
    "x": 819,
    "y": 333
  },
  "\\mathbb{N}": {
    "x": 856,
    "y": 333
  },
  "\\mathbb{O}": {
    "x": 893,
    "y": 333
  },
  "\\mathbb{P}": {
    "x": 930,
    "y": 333
  },
  "\\mathbb{Q}": {
    "x": 967,
    "y": 333
  },
  "\\mathbb{R}": {
    "x": 1004,
    "y": 333
  },
  "\\mathbb{S}": {
    "x": 1041,
    "y": 333
  },
  "\\mathbb{T}": {
    "x": 1078,
    "y": 333
  },
  "\\mathbb{U}": {
    "x": 5,
    "y": 370
  },
  "\\mathbb{V}": {
    "x": 42,
    "y": 370
  },
  "\\mathbb{W}": {
    "x": 79,
    "y": 370
  },
  "\\mathbb{X}": {
    "x": 116,
    "y": 370
  },
  "\\mathbb{Y}": {
    "x": 153,
    "y": 370
  },
  "\\mathbb{Z}": {
    "x": 190,
    "y": 370
  },
  "\\mathrm{A}": {
    "x": 227,
    "y": 370
  },
  "\\mathrm{B}": {
    "x": 264,
    "y": 370
  },
  "\\mathrm{C}": {
    "x": 301,
    "y": 370
  },
  "\\mathrm{D}": {
    "x": 338,
    "y": 370
  },
  "\\mathrm{E}": {
    "x": 375,
    "y": 370
  },
  "\\mathrm{F}": {
    "x": 412,
    "y": 370
  },
  "\\mathrm{G}": {
    "x": 449,
    "y": 370
  },
  "\\mathrm{H}": {
    "x": 486,
    "y": 370
  },
  "\\mathrm{I}": {
    "x": 523,
    "y": 370
  },
  "\\mathrm{J}": {
    "x": 560,
    "y": 370
  },
  "\\mathrm{K}": {
    "x": 597,
    "y": 370
  },
  "\\mathrm{L}": {
    "x": 634,
    "y": 370
  },
  "\\mathrm{M}": {
    "x": 671,
    "y": 370
  },
  "\\mathrm{N}": {
    "x": 708,
    "y": 370
  },
  "\\mathrm{O}": {
    "x": 745,
    "y": 370
  },
  "\\mathrm{P}": {
    "x": 782,
    "y": 370
  },
  "\\mathrm{Q}": {
    "x": 819,
    "y": 370
  },
  "\\mathrm{R}": {
    "x": 856,
    "y": 370
  },
  "\\mathrm{S}": {
    "x": 893,
    "y": 370
  },
  "\\mathrm{T}": {
    "x": 930,
    "y": 370
  },
  "\\mathrm{U}": {
    "x": 967,
    "y": 370
  },
  "\\mathrm{V}": {
    "x": 1004,
    "y": 370
  },
  "\\mathrm{W}": {
    "x": 1041,
    "y": 370
  },
  "\\mathrm{X}": {
    "x": 1078,
    "y": 370
  },
  "\\mathrm{Y}": {
    "x": 5,
    "y": 407
  },
  "\\mathrm{Z}": {
    "x": 42,
    "y": 407
  },
  "\\mathrm{a}": {
    "x": 79,
    "y": 407
  },
  "\\mathrm{b}": {
    "x": 116,
    "y": 407
  },
  "\\mathrm{c}": {
    "x": 153,
    "y": 407
  },
  "\\mathrm{d}": {
    "x": 190,
    "y": 407
  },
  "\\mathrm{e}": {
    "x": 227,
    "y": 407
  },
  "\\mathrm{f}": {
    "x": 264,
    "y": 407
  },
  "\\mathrm{g}": {
    "x": 301,
    "y": 407
  },
  "\\mathrm{h}": {
    "x": 338,
    "y": 407
  },
  "\\mathrm{i}": {
    "x": 375,
    "y": 407
  },
  "\\mathrm{j}": {
    "x": 412,
    "y": 407
  },
  "\\mathrm{k}": {
    "x": 449,
    "y": 407
  },
  "\\mathrm{l}": {
    "x": 486,
    "y": 407
  },
  "\\mathrm{m}": {
    "x": 523,
    "y": 407
  },
  "\\mathrm{n}": {
    "x": 560,
    "y": 407
  },
  "\\mathrm{o}": {
    "x": 597,
    "y": 407
  },
  "\\mathrm{p}": {
    "x": 634,
    "y": 407
  },
  "\\mathrm{q}": {
    "x": 671,
    "y": 407
  },
  "\\mathrm{r}": {
    "x": 708,
    "y": 407
  },
  "\\mathrm{s}": {
    "x": 745,
    "y": 407
  },
  "\\mathrm{t}": {
    "x": 782,
    "y": 407
  },
  "\\mathrm{u}": {
    "x": 819,
    "y": 407
  },
  "\\mathrm{v}": {
    "x": 856,
    "y": 407
  },
  "\\mathrm{w}": {
    "x": 893,
    "y": 407
  },
  "\\mathrm{x}": {
    "x": 930,
    "y": 407
  },
  "\\mathrm{y}": {
    "x": 967,
    "y": 407
  },
  "\\mathrm{z}": {
    "x": 1004,
    "y": 407
  }
};

// ../kity-runtime/src/vendor/legacy-common.ts
var legacyCommonUtils = {
  contains: legacyBaseUtils.contains,
  getRect: legacyBaseUtils.getRect
};

// ../kity-runtime/src/kity/class-system.ts
function Class() {
}
var ClassProto = Class.prototype;
ClassProto.base = function(name) {
  const stack = this.__kityCallStack__;
  const info = stack[stack.length - 1];
  const method = info.cls.__KityBaseClass.prototype[name];
  return method.apply(this, Array.prototype.slice.call(arguments, 1));
};
ClassProto.callBase = function() {
  const stack = this.__kityCallStack__;
  const info = stack[stack.length - 1];
  const method = info.cls.__KityBaseClass.prototype[info.methodName];
  return method.apply(this, arguments);
};
ClassProto.mixin = function(name) {
  const stack = this.__kityCallStack__;
  const info = stack[stack.length - 1];
  const mixins = info.cls.__KityMixins;
  if (!mixins) return this;
  return mixins[name].apply(this, Array.prototype.slice.call(arguments, 1));
};
ClassProto.callMixin = function() {
  const stack = this.__kityCallStack__;
  const info = stack[stack.length - 1];
  const methodName = info.methodName;
  const mixins = info.cls.__KityMixins;
  if (!mixins) return this;
  const method = mixins[methodName];
  if (methodName === "constructor") {
    for (let i = 0; i < method.length; i++) method[i].call(this);
    return this;
  }
  return method.apply(this, arguments);
};
ClassProto.pipe = function(fn) {
  if (typeof fn === "function") fn.call(this, this);
  return this;
};
ClassProto.getType = function() {
  return this.__KityClassName;
};
ClassProto.getClass = function() {
  return this.constructor;
};
function wrapMethod(cls, methodName, originalMethod) {
  const wrapped = function() {
    this.__kityCallStack__ = this.__kityCallStack__ || [];
    this.__kityCallStack__.push({ cls, methodName });
    try {
      return originalMethod.apply(this, arguments);
    } finally {
      this.__kityCallStack__.pop();
    }
  };
  wrapped.__KityMethodClass = cls;
  wrapped.__KityMethodName = methodName;
  return wrapped;
}
function inherit(constructor, BaseClass) {
  const KityClass = function() {
    const meta2 = KityClass;
    meta2.__KityConstructor.apply(this, arguments);
  };
  const meta = KityClass;
  meta.__KityConstructor = constructor;
  KityClass.prototype = Object.create(BaseClass.prototype);
  for (const methodName in BaseClass.prototype) {
    if (Object.prototype.hasOwnProperty.call(BaseClass.prototype, methodName) && methodName.indexOf("__Kity") !== 0) {
      KityClass.prototype[methodName] = BaseClass.prototype[methodName];
    }
  }
  KityClass.prototype.constructor = KityClass;
  return KityClass;
}
function legacyMixin(NewClass, mixins) {
  if (!(mixins instanceof Array)) return NewClass;
  const meta = NewClass;
  meta.__KityMixins = { constructor: [] };
  for (let i = 0; i < mixins.length; i++) {
    const proto = mixins[i].prototype;
    for (const method in proto) {
      if (!Object.prototype.hasOwnProperty.call(proto, method)) continue;
      if (method === "constructor") {
        meta.__KityMixins["constructor"].push(proto[method]);
      } else {
        NewClass.prototype[method] = meta.__KityMixins[method] = proto[method];
      }
    }
  }
  return NewClass;
}
function extend(BaseClass, extension) {
  for (const methodName in extension) {
    if (Object.prototype.hasOwnProperty.call(extension, methodName) && methodName !== "constructor" && methodName.indexOf("__Kity") !== 0) {
      BaseClass.prototype[methodName] = wrapMethod(
        BaseClass,
        methodName,
        extension[methodName]
      );
    }
  }
  return BaseClass;
}
function checkBaseConstructorCall(targetClass, classname) {
  if (!/this\.callBase/.test(targetClass.toString())) {
    throw new Error(
      `${classname}: the constructor must call the base constructor for compatibility with the legacy kity class system.`
    );
  }
}
function createClass(classname, defines) {
  let constructor;
  let NewClass;
  let BaseClass;
  if (arguments.length === 1) {
    defines = arguments[0];
    classname = "AnonymousClass";
  }
  defines = defines || {};
  BaseClass = defines.base || Class;
  if (Object.prototype.hasOwnProperty.call(defines, "constructor")) {
    constructor = defines.constructor;
    if (BaseClass !== Class) {
      checkBaseConstructorCall(constructor, classname);
    }
  } else {
    constructor = function() {
      this.callBase.apply(this, arguments);
      this.callMixin.apply(this, arguments);
    };
  }
  const originalConstructor = constructor;
  constructor = function() {
    this.__kityCallStack__ = this.__kityCallStack__ || [];
    this.__kityCallStack__.push({
      cls: NewClass,
      methodName: "constructor"
    });
    try {
      return originalConstructor.apply(this, arguments);
    } finally {
      this.__kityCallStack__.pop();
    }
  };
  NewClass = inherit(constructor, BaseClass);
  NewClass = legacyMixin(NewClass, defines.mixins || []);
  const meta = NewClass;
  meta.__KityClassName = constructor.__KityClassName = classname;
  meta.__KityBaseClass = constructor.__KityBaseClass = BaseClass;
  constructor.__KityMethodName = "constructor";
  constructor.__KityMethodClass = NewClass;
  delete defines.mixins;
  delete defines.constructor;
  delete defines.base;
  NewClass = extend(NewClass, defines);
  return NewClass;
}
function extendClass(clazz, extension) {
  return extend(clazz, extension);
}

// ../kity-runtime/src/kity/geometry.ts
var Box = createClass("Box", {
  constructor(x, y, width, height) {
    const box = arguments[0];
    if (box && typeof box === "object" && ("x" in box || "left" in box)) {
      x = box.x ?? box.left;
      y = box.y ?? box.top;
      width = box.width;
      height = box.height;
    }
    const w = width ?? 0;
    const h = height ?? 0;
    if (w < 0) {
      x = x - (width = -w);
    }
    if (h < 0) {
      y = y - (height = -h);
    }
    this.x = x || 0;
    this.y = y || 0;
    this.width = width || 0;
    this.height = height || 0;
    this.left = this.x;
    this.right = this.x + this.width;
    this.top = this.y;
    this.bottom = this.y + this.height;
    this.cx = this.x + this.width / 2;
    this.cy = this.y + this.height / 2;
  },
  getRangeX() {
    return [this.left, this.right];
  },
  getRangeY() {
    return [this.top, this.bottom];
  },
  merge(another) {
    if (this.isEmpty()) return new Box(another.x, another.y, another.width, another.height);
    const left = Math.min(this.left, another.left);
    const right = Math.max(this.right, another.right);
    const top = Math.min(this.top, another.top);
    const bottom = Math.max(this.bottom, another.bottom);
    return new Box(left, top, right - left, bottom - top);
  },
  intersect(another) {
    if (!(another instanceof Box) || this.isEmpty() || another.isEmpty()) return new Box();
    if (this.right <= another.left || another.right <= this.left || this.bottom <= another.top || another.bottom <= this.top)
      return new Box();
    const x = Math.max(this.left, another.left), y = Math.max(this.top, another.top);
    return new Box(
      x,
      y,
      Math.min(this.right, another.right) - x,
      Math.min(this.bottom, another.bottom) - y
    );
  },
  expand(top, right, bottom, left) {
    if (arguments.length < 4) {
      right = top;
      bottom = top;
      left = top;
    }
    return new Box(
      this.x - left,
      this.y - top,
      this.width + right + left,
      this.height + top + bottom
    );
  },
  valueOf() {
    return [this.x, this.y, this.width, this.height];
  },
  toString() {
    return this.valueOf().join(" ");
  },
  isEmpty() {
    return !this.width || !this.height;
  }
});
Box.parse = function(unknown) {
  if (!unknown) return new Box();
  if (unknown instanceof Box) return unknown;
  if (typeof unknown === "string") return Box.parse(unknown.split(/\s*[\s,]\s*/));
  if ("0" in unknown && "1" in unknown && "2" in unknown && "3" in unknown)
    return new Box(unknown[0], unknown[1], unknown[2], unknown[3]);
  return new Box();
};
var Point = createClass("Point", {
  constructor(x, y) {
    this.x = x || 0;
    this.y = y || 0;
  },
  offset(dx, dy) {
    if (arguments.length === 1) {
      dy = dx.y;
      dx = dx.x;
    }
    return new Point(this.x + dx, this.y + dy);
  },
  valueOf() {
    return [this.x, this.y];
  },
  toString() {
    return this.valueOf().join(" ");
  },
  spof() {
    return new Point((this.x | 0) + 0.5, (this.y | 0) + 0.5);
  },
  round() {
    return new Point(this.x | 0, this.y | 0);
  },
  isOrigin() {
    return this.x === 0 && this.y === 0;
  }
});
Point.fromPolar = function(radius, angle, unit) {
  if (unit !== "rad") angle = angle / 180 * Math.PI;
  return new Point(radius * Math.cos(angle), radius * Math.sin(angle));
};
Point.parse = function(unknown) {
  if (!unknown) return new Point();
  if (unknown instanceof Point) return unknown;
  if (typeof unknown === "string") return Point.parse(unknown.split(/\s*[\s,]\s*/));
  if ("0" in unknown && "1" in unknown) return new Point(unknown[0], unknown[1]);
  return new Point();
};
var g = {};
g.pathToString = function(pathSegment) {
  pathSegment = pathSegment || this;
  if (typeof pathSegment === "string") return pathSegment;
  if (pathSegment instanceof Array)
    return utils_default.flatten(pathSegment).join(",").replace(/,?([achlmqrstvxz]),?/gi, "$1");
  return "";
};
function d2r(deg) {
  return deg * Math.PI / 180;
}
function mergeMatrixData(m2, m1) {
  return {
    a: m1.a * m2.a + m1.c * m2.b,
    b: m1.b * m2.a + m1.d * m2.b,
    c: m1.a * m2.c + m1.c * m2.d,
    d: m1.b * m2.c + m1.d * m2.d,
    e: m1.a * m2.e + m1.c * m2.f + m1.e,
    f: m1.b * m2.e + m1.d * m2.f + m1.f
  };
}
var mPattern = /matrix\s*\((.+)\)/i;
var Matrix = createClass("Matrix", {
  constructor(..._args) {
    if (arguments.length) {
      this.setMatrix.apply(this, arguments);
    } else {
      this.setMatrix(1, 0, 0, 1, 0, 0);
    }
  },
  translate(x, y) {
    this.m = mergeMatrixData(this.m, {
      a: 1,
      c: 0,
      e: x,
      b: 0,
      d: 1,
      f: y
    });
    return this;
  },
  rotate(deg) {
    const r = d2r(deg), s = Math.sin(r), c = Math.cos(r);
    this.m = mergeMatrixData(this.m, {
      a: c,
      c: -s,
      e: 0,
      b: s,
      d: c,
      f: 0
    });
    return this;
  },
  scale(sx, sy) {
    if (sy === void 0) sy = sx;
    this.m = mergeMatrixData(this.m, {
      a: sx,
      c: 0,
      e: 0,
      b: 0,
      d: sy,
      f: 0
    });
    return this;
  },
  skew(degX, degY) {
    if (degY === void 0) degY = degX;
    this.m = mergeMatrixData(this.m, {
      a: 1,
      c: Math.tan(d2r(degX)),
      e: 0,
      b: Math.tan(d2r(degY)),
      d: 1,
      f: 0
    });
    return this;
  },
  inverse() {
    const m = this.m, k = m.a * m.d - m.b * m.c;
    return new Matrix(
      m.d / k,
      -m.b / k,
      -m.c / k,
      m.a / k,
      (m.c * m.f - m.e * m.d) / k,
      (m.b * m.e - m.a * m.f) / k
    );
  },
  setMatrix(a, b, c, d, e, f) {
    if (arguments.length === 1) {
      this.m = utils_default.clone(arguments[0]);
    } else {
      this.m = {
        a,
        b,
        c,
        d,
        e,
        f
      };
    }
    return this;
  },
  getMatrix() {
    return utils_default.clone(this.m);
  },
  getTranslate() {
    const m = this.m;
    return { x: m.e / m.a, y: m.f / m.d };
  },
  mergeMatrix(matrix) {
    return new Matrix(mergeMatrixData(this.m, matrix.m));
  },
  merge(matrix) {
    return this.mergeMatrix(matrix);
  },
  toString() {
    return this.valueOf().join(" ");
  },
  valueOf() {
    const m = this.m;
    return [m.a, m.b, m.c, m.d, m.e, m.f];
  },
  equals(matrix) {
    const m1 = this.m, m2 = matrix.m;
    return m1.a === m2.a && m1.b === m2.b && m1.c === m2.c && m1.d === m2.d && m1.e === m2.e && m1.f === m2.f;
  },
  transformPoint() {
    return Matrix.transformPoint.apply(
      null,
      [].slice.call(arguments).concat([this.m])
    );
  },
  transformBox(box) {
    return Matrix.transformBox(box, this.m);
  },
  clone() {
    return new Matrix(this.m);
  },
  reverse() {
    return this.inverse();
  }
});
Matrix.parse = function(str) {
  const f = parseFloat;
  if (str instanceof Array)
    return new Matrix({
      a: f(str[0]),
      b: f(str[1]),
      c: f(str[2]),
      d: f(str[3]),
      e: f(str[4]),
      f: f(str[5])
    });
  const match = mPattern.exec(str);
  if (match) {
    let values = match[1].split(",");
    if (values.length !== 6) values = match[1].split(" ");
    return new Matrix({
      a: f(values[0]),
      b: f(values[1]),
      c: f(values[2]),
      d: f(values[3]),
      e: f(values[4]),
      f: f(values[5])
    });
  }
  return new Matrix();
};
Matrix.transformPoint = function(x, y, m) {
  if (arguments.length === 2) {
    m = y;
    y = x.y;
    x = x.x;
  }
  return new Point(
    m.a * x + m.c * y + m.e,
    m.b * x + m.d * y + m.f
  );
};
Matrix.transformBox = function(box, matrix) {
  let xMin = Number.MAX_VALUE, xMax = -Number.MAX_VALUE, yMin = Number.MAX_VALUE, yMax = -Number.MAX_VALUE;
  const bps = [
    [box.x, box.y],
    [box.x + box.width, box.y],
    [box.x, box.y + box.height],
    [box.x + box.width, box.y + box.height]
  ];
  const rps = [];
  let bp;
  while (bp = bps.pop()) {
    const rp = Matrix.transformPoint(bp[0], bp[1], matrix);
    rps.push(rp);
    xMin = Math.min(xMin, rp.x);
    xMax = Math.max(xMax, rp.x);
    yMin = Math.min(yMin, rp.y);
    yMax = Math.max(yMax, rp.y);
  }
  const result = new Box({
    x: xMin,
    y: yMin,
    width: xMax - xMin,
    height: yMax - yMin
  });
  utils_default.extend(result, { closurePoints: rps });
  return result;
};
function getTransformToElement(target, source) {
  try {
    return source.getScreenCTM().inverse().multiply(target.getScreenCTM());
  } catch {
    throw new Error("Unable to invert the source element's transformation matrix.");
  }
}
Matrix.getCTM = function(target, refer) {
  let ctm = {
    a: 1,
    b: 0,
    c: 0,
    d: 1,
    e: 0,
    f: 0
  };
  const node = target.shapeNode || target.node;
  refer = refer || "parent";
  switch (refer) {
    case "screen":
      ctm = node.getScreenCTM();
      break;
    case "doc":
    case "paper":
      ctm = node.getCTM();
      break;
    case "view":
    case "top":
      if (target.getPaper()) {
        ctm = getTransformToElement(node, target.getPaper().shapeNode);
      }
      break;
    case "parent":
      if (target.node.parentNode) {
        ctm = getTransformToElement(node, target.node.parentNode);
      }
      break;
    default:
      if (refer && refer.node) {
        ctm = getTransformToElement(node, refer.shapeNode || refer.node);
      }
  }
  return new Matrix(ctm.a, ctm.b, ctm.c, ctm.d, ctm.e, ctm.f);
};

// ../kity-runtime/src/kity/graphics.ts
var pc = Point;
var mc = Matrix;
var _svgId = { id: 0 };
var svg = {
  ns: "http://www.w3.org/2000/svg",
  xlink: "http://www.w3.org/1999/xlink",
  defaults: {
    stroke: "none",
    fill: "none"
  },
  createNode(name) {
    const node = document.createElementNS(svg.ns, name);
    node.id = "kity_" + name + "_" + _svgId.id++;
    return node;
  }
};
var INNER_HANDLER_CACHE = {};
var USER_HANDLER_CACHE = {};
var _guid = 0;
function getEventUid(target) {
  const eventUid = target._EVENT_UID ?? target._EVNET_UID;
  if (eventUid === void 0) {
    throw new Error("Event handler instance is missing an event uid.");
  }
  return eventUid;
}
function setLegacyEventUid(target, eventUid) {
  target._EVENT_UID = eventUid;
  if (Object.prototype.hasOwnProperty.call(target, "_EVNET_UID")) {
    target._EVNET_UID = eventUid;
    return;
  }
  Object.defineProperty(target, "_EVNET_UID", {
    configurable: true,
    enumerable: true,
    get() {
      return target._EVENT_UID;
    },
    set(value) {
      target._EVENT_UID = value;
    }
  });
}
function bindDomEvent(node, type, handler) {
  node.addEventListener(type, handler, false);
}
function deleteDomEvent(node, type, handler) {
  node.removeEventListener(type, handler, false);
}
function sendMessage(messageObj, type, msg) {
  const handlers = INNER_HANDLER_CACHE[getEventUid(messageObj)];
  if (!handlers) {
    return;
  }
  const handler = handlers[type];
  if (!handler) {
    return;
  }
  const event = utils_default.extend({ type, target: messageObj }, msg || {});
  handler.call(messageObj, event);
}
function listen(node, type, handler, isOnce, targetObject) {
  const eid = getEventUid(targetObject);
  if (!INNER_HANDLER_CACHE[eid]) {
    INNER_HANDLER_CACHE[eid] = {};
  }
  if (!INNER_HANDLER_CACHE[eid][type]) {
    INNER_HANDLER_CACHE[eid][type] = function kityEventHandler(e) {
      e = new ShapeEvent(e || window.event);
      const list = USER_HANDLER_CACHE[eid][type];
      if (!list) {
        return;
      }
      for (let i = 0; i < list.length; i++) {
        const fn = list[i];
        if (fn) {
          const result = fn.call(targetObject, e);
          if (isOnce) {
            targetObject.off(type, fn);
          }
          if (result === false) {
            return false;
          }
        }
      }
      return;
    };
  }
  if (!USER_HANDLER_CACHE[eid]) {
    USER_HANDLER_CACHE[eid] = {};
  }
  if (!USER_HANDLER_CACHE[eid][type]) {
    USER_HANDLER_CACHE[eid][type] = [handler];
    if (!!node && "on" + type in node) {
      bindDomEvent(node, type, INNER_HANDLER_CACHE[eid][type]);
    }
  } else {
    USER_HANDLER_CACHE[eid][type].push(handler);
  }
}
function _addEvent(type, handler, isOnce) {
  isOnce = !!isOnce;
  if (utils_default.isString(type)) {
    type = type.match(/\S+/g) || [];
  }
  utils_default.each(type, (currentType) => {
    listen(this.node, currentType, handler, isOnce, this);
  });
  return this;
}
function _removeEvent(type, handler) {
  const eventId = String(getEventUid(this));
  const userHandlerList = USER_HANDLER_CACHE[eventId][type];
  let isRemoveAll = handler === void 0;
  if (!isRemoveAll && userHandlerList) {
    isRemoveAll = true;
    utils_default.each(userHandlerList, (fn, index) => {
      if (fn === handler) {
        delete userHandlerList[index];
      } else {
        isRemoveAll = false;
      }
    });
  }
  if (isRemoveAll) {
    deleteDomEvent(this.node, type, INNER_HANDLER_CACHE[eventId][type]);
    delete USER_HANDLER_CACHE[eventId][type];
    delete INNER_HANDLER_CACHE[eventId][type];
  }
  return this;
}
var EventHandler = createClass("EventHandler", {
  constructor() {
    setLegacyEventUid(this, ++_guid);
  },
  addEventListener(type, handler) {
    return _addEvent.call(this, type, handler, false);
  },
  addOnceEventListener(type, handler) {
    return _addEvent.call(this, type, handler, true);
  },
  removeEventListener(type, handler) {
    return _removeEvent.call(this, type, handler);
  },
  on(type, handler) {
    return this.addEventListener(type, handler);
  },
  once(type, handler) {
    return this.addOnceEventListener(type, handler);
  },
  off(type, handler) {
    return this.removeEventListener(type, handler);
  },
  fire(type, params) {
    return this.trigger(type, params);
  },
  trigger(type, params) {
    sendMessage(this, type, params);
    return this;
  }
});
var ShapeEvent = createClass("ShapeEvent", {
  constructor(event) {
    let target = null;
    if (!utils_default.isObject(event.target)) {
      this.type = event.type;
      target = event.target;
      if (target.correspondingUseElement) {
        target = target.correspondingUseElement;
      }
      this.originEvent = event;
      this.targetShape = target.shape || target.paper || event.currentTarget && (event.currentTarget.shape || event.currentTarget.paper);
      if (event._kityParam) {
        utils_default.extend(this, event._kityParam);
      }
    } else {
      utils_default.extend(this, event);
    }
  },
  preventDefault() {
    const evt = this.originEvent;
    if (!evt) {
      return true;
    }
    evt.preventDefault();
    return evt.cancelable;
  },
  getPosition(refer, touchIndex) {
    if (!this.originEvent) {
      return null;
    }
    const eventClient = this.originEvent.touches ? this.originEvent.touches[touchIndex || 0] : this.originEvent;
    const target = this.targetShape;
    const targetNode = target.shapeNode || target.node;
    const pScreen = new pc(
      eventClient && eventClient.clientX || 0,
      eventClient && eventClient.clientY || 0
    );
    const pTarget = mc.transformPoint(pScreen, targetNode.getScreenCTM().inverse());
    const pRefer = mc.getCTM(target, refer || "view").transformPoint(pTarget);
    return pRefer;
  },
  stopPropagation() {
    const evt = this.originEvent;
    if (!evt) {
      return true;
    }
    evt.stopPropagation();
  }
});
var _ClassListProto = {
  constructor(node) {
    this._node = node;
    this._list = node.className.toString().split(" ");
  },
  _update() {
    this._node.className = this._list.join(" ");
  },
  add(name) {
    this._list.push(name);
    this._update();
  },
  remove(name) {
    const index = this._list.indexOf(name);
    if (~index) {
      this._list.splice(index, 1);
    }
    this._update();
  },
  contains(name) {
    return !!~this._list.indexOf(name);
  }
};
function _getClassList(node) {
  if (!node.classList) {
    node.classList = new (createClass("ClassList", _ClassListProto))(node);
  }
  return node.classList;
}
var Styled = createClass("Styled", {
  addClass(name) {
    _getClassList(this.node).add(name);
    return this;
  },
  removeClass(name) {
    _getClassList(this.node).remove(name);
    return this;
  },
  hasClass(name) {
    return _getClassList(this.node).contains(name);
  },
  setStyle(styleOrName, value) {
    if (arguments.length === 2 && typeof styleOrName === "string") {
      this.node.style[styleOrName] = value;
      return this;
    }
    if (typeof styleOrName === "object") {
      for (const name in styleOrName) {
        if (Object.prototype.hasOwnProperty.call(styleOrName, name)) {
          this.node.style[name] = styleOrName[name];
        }
      }
    }
    return this;
  }
});
var Data = createClass("Data", {
  constructor() {
    this._data = {};
  },
  setData(name, value) {
    this._data[name] = value;
    return this;
  },
  getData(name) {
    return this._data[name];
  },
  removeData(name) {
    delete this._data[name];
    return this;
  }
});
function itemRemove() {
  this.container.removeItem(this);
  return this;
}
var Container = createClass("Container", {
  getItems() {
    return this.items || (this.items = []);
  },
  getItem(index) {
    return this.getItems()[index];
  },
  getFirstItem() {
    return this.getItem(0);
  },
  getLastItem() {
    return this.getItem(this.getItems().length - 1);
  },
  indexOf(item) {
    return this.getItems().indexOf(item);
  },
  eachItem(fn) {
    const items = this.getItems();
    for (let i = 0; i < items.length; i++) {
      fn.call(this, i, items[i]);
    }
    return this;
  },
  addItem(item, pos, noEvent) {
    const items = this.getItems();
    const length = items.length;
    if (~items.indexOf(item)) {
      return this;
    }
    if (!(pos >= 0 && pos < length)) {
      pos = length;
    }
    items.splice(pos, 0, item);
    if (typeof item === "object") {
      item.container = this;
      item.remove = itemRemove;
    }
    this.handleAdd(item, pos);
    if (!noEvent) {
      this.onContainerChanged("add", [item]);
    }
    return this;
  },
  addItems(items) {
    for (let i = 0, l = items.length; i < l; i++) {
      this.addItem(items[i], -1, true);
    }
    this.onContainerChanged("add", items);
    return this;
  },
  setItems(items) {
    return this.clear().addItems(items);
  },
  appendItem(item) {
    return this.addItem(item);
  },
  prependItem(item) {
    return this.addItem(item, 0);
  },
  removeItem(pos, noEvent) {
    if (typeof pos !== "number") {
      return this.removeItem(this.indexOf(pos));
    }
    const items = this.getItems();
    const item = items[pos];
    if (item === void 0) {
      return this;
    }
    items.splice(pos, 1);
    if (item.container) {
      delete item.container;
    }
    if (item.remove) {
      delete item.remove;
    }
    this.handleRemove(item, pos);
    if (!noEvent) {
      this.onContainerChanged("remove", [item]);
    }
    return this;
  },
  clear() {
    const removed = [];
    let item;
    while ((item = this.getFirstItem()) !== void 0) {
      removed.push(item);
      this.removeItem(0, true);
    }
    this.onContainerChanged("remove", removed);
    return this;
  },
  onContainerChanged(_type, _items) {
  },
  handleAdd(_item, _index) {
  },
  handleRemove(_item, _index) {
  }
});
var Shape = createClass("Shape", {
  mixins: [EventHandler, Styled, Data],
  constructor(tagName) {
    this.node = svg.createNode(tagName);
    this.node.shape = this;
    this.transform = {
      translate: null,
      rotate: null,
      scale: null,
      matrix: null
    };
    this.callMixin();
  },
  getId() {
    return this.node.id;
  },
  setId(id) {
    this.node.id = id;
    return this;
  },
  getNode() {
    return this.node;
  },
  getBoundaryBox() {
    let box;
    try {
      box = this.node.getBBox();
    } catch {
      box = {
        x: this.node.clientLeft,
        y: this.node.clientTop,
        width: this.node.clientWidth,
        height: this.node.clientHeight
      };
    }
    return new Box(box);
  },
  getRenderBox(refer) {
    const box = this.getBoundaryBox();
    const matrix = this.getTransform(refer);
    return matrix.transformBox(box);
  },
  getWidth() {
    return this.getRenderBox().width;
  },
  getHeight() {
    return this.getRenderBox().height;
  },
  getSize() {
    const box = this.getRenderBox();
    delete box.x;
    delete box.y;
    return box;
  },
  setOpacity(value) {
    this.node.setAttribute("opacity", String(value));
    return this;
  },
  getOpacity() {
    const opacity = this.node.getAttribute("opacity");
    return opacity ? +opacity : 1;
  },
  setVisible(value) {
    if (value) {
      this.node.removeAttribute("display");
    } else {
      this.node.setAttribute("display", "none");
    }
    return this;
  },
  getVisible() {
    this.node.getAttribute("display");
  },
  hasAncestor(node) {
    let parent = this.container;
    while (parent) {
      if (parent === node) {
        return true;
      }
      parent = parent.container;
    }
    return false;
  },
  getTransform(refer) {
    return mc.getCTM(this, refer);
  },
  clearTransform() {
    this.node.removeAttribute("transform");
    this.transform = {
      translate: null,
      rotate: null,
      scale: null,
      matrix: null
    };
    this.trigger("shapeupdate", {
      type: "transform"
    });
    return this;
  },
  _applyTransform() {
    const t = this.transform;
    const result = [];
    if (t.translate) {
      result.push(["translate(", t.translate, ")"]);
    }
    if (t.rotate) {
      result.push(["rotate(", t.rotate, ")"]);
    }
    if (t.scale) {
      result.push(["scale(", t.scale, ")"]);
    }
    if (t.matrix) {
      result.push(["matrix(", t.matrix, ")"]);
    }
    this.node.setAttribute("transform", utils_default.flatten(result).join(" "));
    return this;
  },
  setMatrix(m) {
    this.transform.matrix = m;
    return this._applyTransform();
  },
  setTranslate(t) {
    this.transform.translate = t !== null && [].slice.call(arguments) || null;
    return this._applyTransform();
  },
  setRotate(r) {
    this.transform.rotate = r !== null && [].slice.call(arguments) || null;
    return this._applyTransform();
  },
  setScale(s) {
    this.transform.scale = s !== null && [].slice.call(arguments) || null;
    return this._applyTransform();
  },
  translate(dx, dy) {
    let m = this.transform.matrix || new mc();
    if (dy === void 0) {
      dy = 0;
    }
    this.transform.matrix = m.translate(dx, dy);
    return this._applyTransform();
  },
  rotate(deg) {
    let m = this.transform.matrix || new mc();
    this.transform.matrix = m.rotate(deg);
    return this._applyTransform();
  },
  scale(sx, sy) {
    let m = this.transform.matrix || new mc();
    if (sy === void 0) {
      sy = sx;
    }
    this.transform.matrix = m.scale(sx, sy);
    return this._applyTransform();
  },
  skew(sx, sy) {
    let m = this.transform.matrix || new mc();
    if (sy === void 0) {
      sy = sx;
    }
    this.transform.matrix = m.skew(sx, sy);
    return this._applyTransform();
  },
  stroke(pen, width) {
    if (pen && pen.stroke) {
      pen.stroke(this);
    } else if (pen) {
      this.node.setAttribute("stroke", pen.toString());
      if (width) {
        this.node.setAttribute("stroke-width", String(width));
      }
    } else if (pen === null) {
      this.node.removeAttribute("stroke");
    }
    return this;
  },
  fill(brush) {
    if (brush) {
      this.node.setAttribute("fill", brush.toString());
    }
    if (brush === null) {
      this.node.removeAttribute("fill");
    }
    return this;
  },
  setAttr(a, v) {
    if (utils_default.isObject(a)) {
      utils_default.each(a, (val, key) => {
        this.setAttr(key, val);
      });
      return this;
    }
    if (v === void 0 || v === null || v === "") {
      this.node.removeAttribute(a);
    } else {
      this.node.setAttribute(a, v);
    }
    return this;
  },
  getAttr(a) {
    return this.node.getAttribute(a);
  }
});
var ShapeContainer = createClass("ShapeContainer", {
  base: Container,
  isShapeContainer: true,
  handleAdd(shape, index) {
    const parent = this.getShapeNode();
    parent.insertBefore(shape.node, parent.childNodes[index] || null);
    shape.trigger("add", { container: this });
    if (shape.notifyTreeModification) {
      shape.notifyTreeModification("treeadd", this);
    }
  },
  handleRemove(shape, _index) {
    const parent = this.getShapeNode();
    parent.removeChild(shape.node);
    shape.trigger("remove", {
      container: this
    });
    if (shape.notifyTreeModification) {
      shape.notifyTreeModification("treeremove", this);
    }
  },
  notifyTreeModification(type, container) {
    this.eachItem((_index, shape) => {
      if (shape.notifyTreeModification) {
        shape.notifyTreeModification(type, container);
      }
      shape.trigger(type, { container });
    });
  },
  getShape(index) {
    return this.getItem(index);
  },
  addShape(shape, index) {
    return this.addItem(shape, index);
  },
  put(shape) {
    this.addShape(shape);
    return shape;
  },
  appendShape(shape) {
    return this.addShape(shape);
  },
  prependShape(shape) {
    return this.addShape(shape, 0);
  },
  replaceShape(replacer, origin) {
    const index = this.indexOf(origin);
    if (index === -1) {
      return;
    }
    this.removeShape(index);
    this.addShape(replacer, index);
    return this;
  },
  addShapeBefore(shape, refer) {
    const index = this.indexOf(refer);
    return this.addShape(shape, index);
  },
  addShapeAfter(shape, refer) {
    const index = this.indexOf(refer);
    return this.addShape(shape, index === -1 ? void 0 : index + 1);
  },
  addShapes(shapes) {
    return this.addItems(shapes);
  },
  removeShape(index) {
    return this.removeItem(index);
  },
  getShapes() {
    return this.getItems();
  },
  getShapesByType(name) {
    const shapes = [];
    const getShapes = (shape) => {
      if (name.toLowerCase() === shape.getType().toLowerCase()) {
        shapes.push(shape);
      }
      if (shape.isShapeContainer) {
        utils_default.each(shape.getShapes(), (n) => {
          getShapes(n);
        });
      }
    };
    getShapes(this);
    return shapes;
  },
  getShapeById(id) {
    return this.getShapeNode().getElementById(id).shape;
  },
  arrangeShape(shape, index) {
    return this.removeShape(shape).addShape(shape, index);
  },
  getShapeNode() {
    return this.shapeNode || this.node;
  }
});
extendClass(Shape, {
  bringTo(index) {
    this.container.arrangeShape(this, index);
    return this;
  },
  bringFront() {
    return this.bringTo(this.container.indexOf(this) + 1);
  },
  bringBack() {
    return this.bringTo(this.container.indexOf(this) - 1);
  },
  bringTop() {
    this.container.removeShape(this).addShape(this);
    return this;
  },
  bringRear() {
    return this.bringTo(0);
  },
  bringRefer(referShape, offset) {
    if (referShape.container) {
      if (this.remove) {
        this.remove();
      }
      referShape.container.addShape(this, referShape.container.indexOf(referShape) + (offset || 0));
    }
    return this;
  },
  bringAbove(referShape) {
    return this.bringRefer(referShape);
  },
  bringBelow(referShape) {
    return this.bringRefer(referShape, 1);
  },
  replaceBy(newShape) {
    if (this.container) {
      newShape.bringAbove(this);
      this.remove();
    }
    return this;
  }
});
var ViewBox = createClass("ViewBox", {
  getViewBox() {
    const attr = this.node.getAttribute("viewBox");
    if (attr === null) {
      return {
        x: 0,
        y: 0,
        width: this.node.clientWidth || this.node.parentNode?.clientWidth || 0,
        height: this.node.clientHeight || this.node.parentNode?.clientHeight || 0
      };
    } else {
      const parts = attr.split(" ");
      return {
        x: +parts[0],
        y: +parts[1],
        width: +parts[2],
        height: +parts[3]
      };
    }
  },
  setViewBox(x, y, width, height) {
    this.node.setAttribute("viewBox", [x, y, width, height].join(" "));
    return this;
  }
});
var TextContent = createClass("TextContent", {
  base: Shape,
  constructor(nodeType) {
    this.callBase(nodeType);
    this.shapeNode = this.shapeNode || this.node;
    this.shapeNode.setAttribute("text-rendering", "geometricPrecision");
  },
  clearContent() {
    while (this.shapeNode.firstChild) {
      this.shapeNode.removeChild(this.shapeNode.firstChild);
    }
    return this;
  },
  setContent(content) {
    this.shapeNode.textContent = content;
    return this;
  },
  getContent() {
    return this.shapeNode.textContent;
  },
  appendContent(content) {
    this.shapeNode.textContent += content;
    return this;
  },
  setSize(value) {
    return this.setFontSize(value);
  },
  setFontSize(value) {
    return this.setFont({
      size: value
    });
  },
  setFontFamily(value) {
    return this.setFont({
      family: value
    });
  },
  setFontBold(bold) {
    return this.setFont({
      weight: bold ? "bold" : "normal"
    });
  },
  setFontItalic(italic) {
    return this.setFont({
      style: italic ? "italic" : "normal"
    });
  },
  setFont(font) {
    const node = this.node;
    ["family", "size", "weight", "style"].forEach((section) => {
      if (font[section] === null) {
        node.removeAttribute("font-" + section);
      } else if (font[section]) {
        node.setAttribute("font-" + section, font[section]);
      }
    });
    return this;
  },
  getExtentOfChar(index) {
    return this.node.getExtentOfChar(index);
  },
  getRotationOfChar(index) {
    return this.node.getRotationOfChar(index);
  },
  getCharNumAtPosition(x, y) {
    return this.node.getCharNumAtPosition({ x, y });
  }
});
var _offsetHash = {};
function _getTextBoundOffset(text) {
  const font = text._cachedFontHash;
  if (_offsetHash[font]) {
    return _offsetHash[font];
  }
  const textContent = text.getContent();
  text.setContent("\u767E\u5EA6Fex");
  const bbox = text.getBoundaryBox();
  const y = text.getY();
  if (!bbox.height) {
    return { top: 0, bottom: 0, middle: 0 };
  }
  const topOffset = y - bbox.y + +text.node.getAttribute("dy");
  const bottomOffset = topOffset - bbox.height;
  text.setContent(textContent);
  _offsetHash[font] = {
    top: topOffset,
    bottom: bottomOffset,
    middle: (topOffset + bottomOffset) / 2
  };
  return _offsetHash[font];
}
var Text = createClass("Text", {
  base: TextContent,
  mixins: [ShapeContainer],
  constructor(content) {
    this.callBase("text");
    if (content !== void 0) {
      this.setContent(content);
    }
    this._buildFontHash();
  },
  fixPosition() {
    if (!this.__fixedPosition) {
      this.setVerticalAlign(this.getVerticalAlign());
    }
  },
  _buildFontHash() {
    const style = window.getComputedStyle(this.node);
    this._cachedFontHash = [
      style.fontFamily,
      style.fontSize,
      style.fontStretch,
      style.fontStyle,
      style.fontVariant,
      style.fontWeight
    ].join("-");
  },
  _fontChanged(font) {
    const last = this._lastFont;
    const current = utils_default.extend({}, last, font);
    if (!last) {
      this._lastFont = font;
      return true;
    }
    const changed = last.family !== current.family || last.size !== current.size || last.style !== current.style || last.weight !== current.weight;
    this._lastFont = current;
    return changed;
  },
  setX(x) {
    this.node.setAttribute("x", String(x));
    return this;
  },
  setPosition(x, y) {
    return this.setX(x).setY(y);
  },
  setY(y) {
    this.node.setAttribute("y", String(y));
    return this;
  },
  getX() {
    return +(this.node.getAttribute("x") || "0");
  },
  getY() {
    return +(this.node.getAttribute("y") || "0");
  },
  setFont(font) {
    this.callBase(font);
    if (this._fontChanged(font)) {
      this._buildFontHash();
      this.setVerticalAlign(this.getVerticalAlign());
    }
    return this;
  },
  setTextAnchor(anchor) {
    this.node.setAttribute("text-anchor", anchor);
    return this;
  },
  getTextAnchor() {
    return this.node.getAttribute("text-anchor") || "start";
  },
  setVerticalAlign(align) {
    this.whenPaperReady(() => {
      let dy;
      switch (align) {
        case "top":
          dy = _getTextBoundOffset(this).top;
          break;
        case "bottom":
          dy = _getTextBoundOffset(this).bottom;
          break;
        case "middle":
          dy = _getTextBoundOffset(this).middle;
          break;
        default:
          dy = 0;
      }
      if (dy) {
        this.__fixedPosition = true;
      }
      this.node.setAttribute("dy", dy);
    });
    this.verticalAlign = align;
    return this;
  },
  getVerticalAlign() {
    return this.verticalAlign || "baseline";
  },
  setStartOffset(offset) {
    if (this.shapeNode !== this.node) {
      this.shapeNode.setAttribute("startOffset", offset * 100 + "%");
    }
  },
  addSpan(span) {
    this.addShape(span);
    return this;
  },
  setPath(path) {
    let textpath = this.shapeNode;
    if (this.shapeNode === this.node) {
      textpath = this.shapeNode = svg.createNode("textPath");
      while (this.node.firstChild) {
        this.shapeNode.appendChild(this.node.firstChild);
      }
      this.node.appendChild(textpath);
    }
    textpath.setAttributeNS(svg.xlink, "xlink:href", "#" + path.node.id);
    this.setTextAnchor(this.getTextAnchor());
    return this;
  }
});
var PathDrawer = createClass("PathDrawer", {
  constructor(path) {
    this.segment = [];
    this.path = path;
    this.__clear = false;
  },
  getPath() {
    return this.path;
  },
  redraw() {
    this._transation = this._transation || [];
    return this.clear();
  },
  done() {
    const transation = this._transation;
    this._transation = null;
    this.push(transation);
    return this;
  },
  clear() {
    if (this._transation) {
      this._transation = [];
    } else {
      this.path.setPathData("M 0 0");
    }
    this._clear = true;
    return this;
  },
  push() {
    const segment = [].slice.call(arguments);
    let originData;
    if (this._transation) {
      this._transation.push(segment);
      return this;
    }
    if (this._clear) {
      originData = "";
      this._clear = false;
    } else {
      originData = this.path.getPathData();
    }
    originData = originData || "";
    this.path.setPathData(originData + g.pathToString(segment));
    return this;
  },
  moveTo(_x, _y) {
    return this.push("M", [].slice.call(arguments));
  },
  moveBy(_dx, _dy) {
    return this.push("m", [].slice.call(arguments));
  },
  lineTo(_x, _y) {
    return this.push("L", [].slice.call(arguments));
  },
  lineBy(_dx, _dy) {
    return this.push("l", [].slice.call(arguments));
  },
  arcTo(_rx, _ry, _xr, _laf, _sf, _x, _y) {
    return this.push("A", [].slice.call(arguments));
  },
  arcBy(_rx, _ry, _xr, _laf, _sf, _dx, _dy) {
    return this.push("a", arguments);
  },
  carcTo(r, _laf, _sf, _x, _y) {
    return this.push("A", [r, r, 0].concat([].slice.call(arguments, 1)));
  },
  carcBy(r, _laf, _sf, _dx, _dy) {
    return this.push("a", [r, r, 0].concat([].slice.call(arguments, 1)));
  },
  bezierTo(_x1, _y1, _x2, _y2, _x, _y) {
    return this.push("C", [].slice.call(arguments));
  },
  bezierBy(_dx1, _dy1, _dx2, _dy2, _dx, _dy) {
    return this.push("c", [].slice.call(arguments));
  },
  close() {
    return this.push("z");
  }
});
var Path = createClass("Path", {
  base: Shape,
  constructor(data) {
    this.callBase("path");
    if (data) {
      this.setPathData(data);
    }
    this.node.setAttribute("fill", svg.defaults.fill);
    this.node.setAttribute("stroke", svg.defaults.stroke);
  },
  setPathData(data) {
    data = data || "M0,0";
    this.pathdata = g.pathToString(data);
    this.node.setAttribute("d", this.pathdata);
    this.trigger("shapeupdate", {
      type: "pathdata"
    });
    return this;
  },
  getPathData() {
    return this.pathdata || "";
  },
  getDrawer() {
    return new PathDrawer(this);
  },
  isClosed() {
    const data = this.getPathData();
    return !!~data.indexOf("z") || !!~data.indexOf("Z");
  }
});
var RectUtils = {
  formatRadius(width, height, radius) {
    const minValue = Math.floor(Math.min(width / 2, height / 2));
    return Math.min(minValue, radius);
  }
};
var Rect = createClass("Rect", {
  base: Path,
  constructor(width, height, x, y, radius) {
    this.callBase();
    this.x = x || 0;
    this.y = y || 0;
    this.width = width || 0;
    this.height = height || 0;
    this.radius = RectUtils.formatRadius(this.width, this.height, radius || 0);
    this.update();
  },
  update() {
    const x = this.x, y = this.y, w = this.width, h = this.height, r = this.radius;
    const drawer = this.getDrawer().redraw();
    if (!r) {
      drawer.push("M", x, y);
      drawer.push("h", w);
      drawer.push("v", h);
      drawer.push("h", -w);
      drawer.push("z");
    } else {
      const w2 = w - 2 * r;
      const h2 = h - 2 * r;
      drawer.push("M", x + r, y);
      drawer.push("h", w2);
      drawer.push("a", r, r, 0, 0, 1, r, r);
      drawer.push("v", h2);
      drawer.push("a", r, r, 0, 0, 1, -r, r);
      drawer.push("h", -w2);
      drawer.push("a", r, r, 0, 0, 1, -r, -r);
      drawer.push("v", -h2);
      drawer.push("a", r, r, 0, 0, 1, r, -r);
      drawer.push("z");
    }
    drawer.done();
    return this;
  },
  setWidth(width) {
    this.width = width;
    return this.update();
  },
  setHeight(height) {
    this.height = height;
    return this.update();
  },
  setSize(width, height) {
    this.width = width;
    this.height = height;
    return this.update();
  },
  setBox(box) {
    this.x = box.x;
    this.y = box.y;
    this.width = box.width;
    this.height = box.height;
    return this.update();
  },
  getBox() {
    return new Box(this.x, this.y, this.width, this.height);
  },
  getRadius() {
    return this.radius;
  },
  setRadius(radius) {
    this.radius = RectUtils.formatRadius(this.width, this.height, radius || 0);
    return this.update();
  },
  getPosition() {
    return new pc(this.x, this.y);
  },
  setPosition(xOrP, y) {
    if (arguments.length === 1) {
      const p = pc.parse(arguments[0]);
      y = p.y;
      xOrP = p.x;
    }
    this.x = xOrP;
    this.y = y;
    return this.update();
  },
  getWidth() {
    return this.width;
  },
  getHeight() {
    return this.height;
  },
  getPositionX() {
    return this.x;
  },
  getPositionY() {
    return this.y;
  },
  setPositionX(x) {
    this.x = x;
    return this.update();
  },
  setPositionY(y) {
    this.y = y;
    return this.update();
  }
});
var Group = createClass("Group", {
  mixins: [ShapeContainer],
  base: Shape,
  constructor() {
    this.callBase("g");
  }
});
var Use = createClass("Use", {
  base: Shape,
  constructor(shape) {
    this.callBase("use");
    this.ref(shape);
  },
  ref(shape) {
    if (!shape) {
      this.node.removeAttributeNS(svg.xlink, "xlink:href");
      return this;
    }
    const shapeId = shape.getId();
    if (shapeId) {
      this.node.setAttributeNS(svg.xlink, "xlink:href", "#" + shapeId);
    }
    if (shape.node.getAttribute("fill") === "none") {
      shape.node.removeAttribute("fill");
    }
    if (shape.node.getAttribute("stroke") === "none") {
      shape.node.removeAttribute("stroke");
    }
    return this;
  }
});
extendClass(Shape, {
  use() {
    return new Use(this);
  }
});
var Paper = createClass("Paper", {
  mixins: [ShapeContainer, EventHandler, Styled, ViewBox],
  constructor(container) {
    this.callBase();
    this.node = this.createSVGNode();
    this.node.paper = this;
    this.node.appendChild(this.resourceNode = svg.createNode("defs"));
    this.node.appendChild(this.shapeNode = svg.createNode("g"));
    this.resources = new Container();
    this.setWidth("100%").setHeight("100%");
    if (container) {
      this.renderTo(container);
    }
    this.callMixin();
  },
  renderTo(container) {
    if (utils_default.isString(container)) {
      container = document.getElementById(container);
    }
    this.container = container;
    container.appendChild(this.node);
  },
  createSVGNode() {
    const node = svg.createNode("svg");
    node.setAttribute("xmlns", "http://www.w3.org/2000/svg");
    node.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink");
    node.setAttribute("version", "1.1");
    return node;
  },
  getNode() {
    return this.node;
  },
  getContainer() {
    return this.container;
  },
  getWidth() {
    return this.node.clientWidth;
  },
  setWidth(width) {
    this.node.setAttribute("width", String(width));
    return this;
  },
  getHeight() {
    return this.node.clientHeight;
  },
  setHeight(height) {
    this.node.setAttribute("height", String(height));
    return this;
  },
  setViewPort(cx, cy, zoom) {
    let viewport, box;
    if (arguments.length === 1) {
      viewport = arguments[0];
      cx = viewport.center.x;
      cy = viewport.center.y;
      zoom = viewport.zoom;
    }
    zoom = zoom || 1;
    box = this.getViewBox();
    const matrix = new mc();
    const dx = box.x + box.width / 2 - cx;
    const dy = box.y + box.height / 2 - cy;
    matrix.translate(-cx, -cy);
    matrix.scale(zoom);
    matrix.translate(cx, cy);
    matrix.translate(dx, dy);
    this.shapeNode.setAttribute("transform", "matrix(" + matrix + ")");
    this.viewport = {
      center: { x: cx, y: cy },
      offset: { x: dx, y: dy },
      zoom
    };
    return this;
  },
  getViewPort() {
    if (!this.viewport) {
      const box = this.getViewBox();
      return {
        zoom: 1,
        center: {
          x: box.x + box.width / 2,
          y: box.y + box.height / 2
        },
        offset: { x: 0, y: 0 }
      };
    }
    return this.viewport;
  },
  getViewPortMatrix() {
    return mc.parse(this.shapeNode.getAttribute("transform"));
  },
  getViewPortTransform() {
    const m = this.shapeNode.getCTM();
    return new mc(m.a, m.b, m.c, m.d, m.e, m.f);
  },
  getTransform() {
    return this.getViewPortTransform().reverse();
  },
  addResource(resource) {
    this.resources.appendItem(resource);
    if (resource.node) {
      this.resourceNode.appendChild(resource.node);
    }
    return this;
  },
  removeResource(resource) {
    if (resource.remove) {
      resource.remove();
    }
    if (resource.node) {
      this.resourceNode.removeChild(resource.node);
    }
    return this;
  },
  getPaper() {
    return this;
  }
});
extendClass(Shape, {
  getPaper() {
    let parent = this.container;
    while (parent && parent instanceof Paper === false) {
      parent = parent.container;
    }
    return parent;
  },
  isAttached() {
    return !!this.getPaper();
  },
  whenPaperReady(fn) {
    const me = this;
    function check() {
      const paper = me.getPaper();
      if (paper && fn) {
        fn.call(me, paper);
      }
      return paper;
    }
    if (!check()) {
      this.on("add treeadd", function listen2() {
        if (check()) {
          me.off("add", listen2);
          me.off("treeadd", listen2);
        }
      });
    }
    return this;
  }
});

// ../kity-runtime/src/kity/index.ts
var kity = {
  version: "2.0.5",
  createClass,
  extendClass,
  Utils: utils_default,
  Class,
  Box,
  Point,
  Matrix,
  g,
  Container,
  Shape,
  ShapeContainer,
  Group,
  Rect,
  Path,
  Text,
  Paper,
  Use,
  ViewBox,
  EventHandler,
  Styled,
  Data,
  PathDrawer,
  svg
};
function installKityRuntime(targetWindow = window) {
  if (targetWindow.kity) {
    return;
  }
  targetWindow.kity = kity;
}

// ../kity-runtime/src/perf.ts
function getPerfHost() {
  return globalThis;
}
function getPerfState() {
  const host = getPerfHost();
  host.__FORMULAX_PERF_STATE__ ??= {
    reportedMeasureCount: 0,
    reportScheduled: false
  };
  return host.__FORMULAX_PERF_STATE__;
}
function hasPerfSupport() {
  return typeof performance !== "undefined" && typeof performance.mark === "function" && typeof performance.measure === "function" && typeof performance.getEntriesByType === "function";
}
function isPerfDebugEnabled() {
  return getPerfHost().__FORMULAX_PERF__ === true;
}
function schedulePerfReport() {
  if (!hasPerfSupport() || !isPerfDebugEnabled()) {
    return;
  }
  const state = getPerfState();
  if (state.reportScheduled) {
    return;
  }
  state.reportScheduled = true;
  queueMicrotask(() => {
    state.reportScheduled = false;
    const entries = performance.getEntriesByType("measure").filter((entry) => entry.name.startsWith("fx:")).sort((left, right) => left.startTime - right.startTime);
    const nextEntries = entries.slice(state.reportedMeasureCount);
    state.reportedMeasureCount = entries.length;
    if (!nextEntries.length) {
      return;
    }
    console.table(nextEntries.map((entry) => ({
      name: entry.name,
      duration: Number(entry.duration.toFixed(2)),
      startTime: Number(entry.startTime.toFixed(2))
    })));
  });
}
function markFormulaXPerf(name) {
  if (!hasPerfSupport()) {
    return null;
  }
  const markName = `${name}::${Date.now()}::${Math.random().toString(36).slice(2, 8)}`;
  performance.mark(markName);
  return markName;
}
function measureFormulaXPerf(name, startMark, endMark) {
  if (!hasPerfSupport() || !startMark) {
    return null;
  }
  const resolvedEndMark = endMark ?? markFormulaXPerf(`${name}:end`);
  if (!resolvedEndMark) {
    return null;
  }
  performance.measure(name, startMark, resolvedEndMark);
  schedulePerfReport();
  return resolvedEndMark;
}
function clearFormulaXPerfMarks(...marks) {
  if (!hasPerfSupport()) {
    return;
  }
  for (const mark of marks) {
    if (!mark) {
      continue;
    }
    performance.clearMarks(mark);
  }
}

// ../kity-runtime/src/create-editor.ts
var DEFAULT_LATEX = "x=\\frac{-b\\pm\\sqrt{b^2-4ac}}{2a}";
var DEFAULT_EDITOR_HEIGHT = "auto";
var KITY_STYLE_ID = "formulax-kity-editor-styles";
var runtimePromise = null;
function resolveContainer(el) {
  if (typeof el === "string") {
    const element = document.querySelector(el);
    if (!(element instanceof HTMLElement)) {
      throw new Error(`Kity editor mount target not found: ${el}`);
    }
    return element;
  }
  return el;
}
function normalizeCssSize(value, fallback) {
  if (typeof value === "number") {
    return `${value}px`;
  }
  return value ?? fallback;
}
function resolveEditorAssets(assets) {
  return {
    fonts: {
      ...kityAssetManifest.fonts,
      ...assets?.fonts
    },
    toolbar: {
      ...kityAssetManifest.toolbar,
      ...assets?.toolbar
    },
    styles: {
      ...kityAssetManifest.styles,
      ...assets?.styles
    }
  };
}
function ensureKityStylesheet(doc, href) {
  if (doc.getElementById(KITY_STYLE_ID)) {
    return false;
  }
  const link = doc.createElement("link");
  link.id = KITY_STYLE_ID;
  link.rel = "stylesheet";
  link.href = href;
  doc.head.appendChild(link);
  return true;
}
function hydrateLegacyKf(runtimeWindow) {
  const requireFormula = runtimeWindow.__kityFormulaRequire__;
  if (!requireFormula) {
    return;
  }
  runtimeWindow.kf = {
    ...runtimeWindow.kf ?? {},
    ResourceManager: requireFormula("resource-manager"),
    Operator: requireFormula("operator/operator"),
    Expression: requireFormula("expression/expression"),
    CompoundExpression: requireFormula("expression/compound"),
    TextExpression: requireFormula("expression/text"),
    EmptyExpression: requireFormula("expression/empty"),
    CombinationExpression: requireFormula("expression/compound-exp/combination"),
    FunctionExpression: requireFormula("expression/compound-exp/func"),
    FractionExpression: requireFormula("expression/compound-exp/fraction"),
    IntegrationExpression: requireFormula("expression/compound-exp/integration"),
    RadicalExpression: requireFormula("expression/compound-exp/radical"),
    ScriptExpression: requireFormula("expression/compound-exp/script"),
    SuperscriptExpression: requireFormula("expression/compound-exp/binary-exp/superscript"),
    SubscriptExpression: requireFormula("expression/compound-exp/binary-exp/subscript"),
    SummationExpression: requireFormula("expression/compound-exp/summation"),
    BracketsExpression: requireFormula("expression/compound-exp/brackets")
  };
}
function installLegacyRuntime(runtimeWindow) {
  runtimeWindow.__FORMULAX_KITY_RUNTIME__ = {
    baseComponent: runtimeWindow.kity ? createLegacyBaseComponent(
      runtimeWindow.kity
    ) : void 0,
    baseUtils: legacyBaseUtils,
    boxType: legacyBoxType,
    sysconf: legacySysconf,
    charPosition: legacyCharPosition,
    commonUtils: legacyCommonUtils,
    eleType: legacyEleType,
    eventListener: legacyEventListener,
    groupType: legacyGroupType,
    inputFilter: legacyInputFilter,
    itemType: legacyItemType,
    kf: runtimeWindow.kf,
    kfExtDef: legacyKfExtDef,
    kfEvent: legacyKfEvent,
    kity: runtimeWindow.kity,
    otherPosition: legacyOtherPosition,
    uiDef: legacyUiDef,
    uiUtils: legacyUiUtils
  };
}
async function ensureKityRuntime() {
  if (runtimePromise) {
    return runtimePromise;
  }
  runtimePromise = (async () => {
    const runtimeTotalStart = markFormulaXPerf("fx:kity-runtime:total");
    const runtimeWindow = window;
    runtimeWindow.kf = runtimeWindow.kf ?? {};
    installKityRuntime(runtimeWindow);
    try {
      const formulaImportStart = markFormulaXPerf("fx:kity-runtime:formula-import");
      const { installLegacyKityFormulaRuntime } = await import("./install-XGCSWTLU.js");
      const formulaImportEnd = markFormulaXPerf("fx:kity-runtime:formula-import:end");
      measureFormulaXPerf("fx:kity-runtime:formula-import", formulaImportStart, formulaImportEnd);
      clearFormulaXPerfMarks(formulaImportStart, formulaImportEnd);
      const formulaInstallStart = markFormulaXPerf("fx:kity-runtime:formula-install");
      installLegacyKityFormulaRuntime(runtimeWindow);
      hydrateLegacyKf(runtimeWindow);
      const formulaInstallEnd = markFormulaXPerf("fx:kity-runtime:formula-install:end");
      measureFormulaXPerf("fx:kity-runtime:formula-install", formulaInstallStart, formulaInstallEnd);
      clearFormulaXPerfMarks(formulaInstallStart, formulaInstallEnd);
      const parserImportStart = markFormulaXPerf("fx:kity-runtime:parser-import");
      const { installLegacyParserRuntime } = await import("./install-XVTKACEN.js");
      const parserImportEnd = markFormulaXPerf("fx:kity-runtime:parser-import:end");
      measureFormulaXPerf("fx:kity-runtime:parser-import", parserImportStart, parserImportEnd);
      clearFormulaXPerfMarks(parserImportStart, parserImportEnd);
      const parserInstallStart = markFormulaXPerf("fx:kity-runtime:parser-install");
      installLegacyParserRuntime(runtimeWindow);
      const parserInstallEnd = markFormulaXPerf("fx:kity-runtime:parser-install:end");
      measureFormulaXPerf("fx:kity-runtime:parser-install", parserInstallStart, parserInstallEnd);
      clearFormulaXPerfMarks(parserInstallStart, parserInstallEnd);
      installLegacyRuntime(runtimeWindow);
      const bootImportStart = markFormulaXPerf("fx:kity-runtime:boot-import");
      const { installKityEditorStart } = await import("./start-MBLTNR2Q.js");
      const bootImportEnd = markFormulaXPerf("fx:kity-runtime:boot-import:end");
      measureFormulaXPerf("fx:kity-runtime:boot-import", bootImportStart, bootImportEnd);
      clearFormulaXPerfMarks(bootImportStart, bootImportEnd);
      const bootInstallStart = markFormulaXPerf("fx:kity-runtime:boot-install");
      installKityEditorStart(runtimeWindow);
      const bootInstallEnd = markFormulaXPerf("fx:kity-runtime:boot-install:end");
      measureFormulaXPerf("fx:kity-runtime:boot-install", bootInstallStart, bootInstallEnd);
      clearFormulaXPerfMarks(bootInstallStart, bootInstallEnd);
    } finally {
      const runtimeTotalEnd = markFormulaXPerf("fx:kity-runtime:total:end");
      measureFormulaXPerf("fx:kity-runtime:total", runtimeTotalStart, runtimeTotalEnd);
      clearFormulaXPerfMarks(runtimeTotalStart, runtimeTotalEnd);
    }
  })();
  return runtimePromise;
}
async function createKityEditor(container, options = {}) {
  const createEditorStart = markFormulaXPerf("fx:create-kity-editor:total");
  const fontsize = options.render?.fontsize ?? 40;
  const editorHeight = normalizeCssSize(options.height, DEFAULT_EDITOR_HEIGHT);
  const locale = normalizeFormulaXLocale(options.locale ?? DEFAULT_FORMULAX_LOCALE);
  const assets = resolveEditorAssets(options.assets);
  try {
    legacySysconf.rootPlaceholder.content = getFormulaXRuntimeMessage("editor.placeholder.root", locale);
    const stylesheetInserted = ensureKityStylesheet(document, assets.styles.editor);
    if (stylesheetInserted) {
      const stylesheetInsertedMark = markFormulaXPerf("fx:kity-css:link-inserted");
      measureFormulaXPerf("fx:kity-css:link-inserted", createEditorStart, stylesheetInsertedMark);
      clearFormulaXPerfMarks(stylesheetInsertedMark);
    }
    setToolbarAssetUrls(assets.toolbar);
    await ensureKityRuntime();
    const runtimeReadyMark = markFormulaXPerf("fx:kity-runtime:ready-for-editor");
    measureFormulaXPerf("fx:kity-runtime:ready-for-editor", createEditorStart, runtimeReadyMark);
    clearFormulaXPerfMarks(runtimeReadyMark);
    const runtimeWindow = window;
    if (!runtimeWindow.kf?.EditorFactory) {
      throw new Error("Kity editor runtime did not initialize");
    }
    container.innerHTML = "";
    const host = document.createElement("div");
    host.className = "kf-editor";
    host.style.width = "100%";
    host.style.height = editorHeight;
    container.appendChild(host);
    const factoryCreateStart = markFormulaXPerf("fx:kity-editor-factory:create");
    const factory = runtimeWindow.kf.EditorFactory.create(host, {
      render: {
        fontsize
      },
      ui: {
        locale
      },
      resource: {
        path: "",
        fonts: assets.fonts
      }
    });
    const factoryCreateEnd = markFormulaXPerf("fx:kity-editor-factory:create:end");
    measureFormulaXPerf("fx:kity-editor-factory:create", factoryCreateStart, factoryCreateEnd);
    clearFormulaXPerfMarks(factoryCreateStart, factoryCreateEnd);
    return {
      ready: factory.ready.bind(factory),
      execCommand(name, value) {
        factory.ready(function execWhenReady() {
          this.execCommand(name, value);
        });
      },
      focus() {
        factory.ready(function focusWhenReady() {
          this.execCommand("focus");
        });
      },
      destroy() {
        container.innerHTML = "";
      },
      host,
      raw: factory
    };
  } finally {
    const createEditorEnd = markFormulaXPerf("fx:create-kity-editor:total:end");
    measureFormulaXPerf("fx:create-kity-editor:total", createEditorStart, createEditorEnd);
    clearFormulaXPerfMarks(createEditorStart, createEditorEnd);
  }
}
async function mountKityEditor(container, options = {}) {
  const editor = await createKityEditor(container, options);
  const initialLatex = options.initialLatex ?? DEFAULT_LATEX;
  const shouldFocus = options.autofocus ?? true;
  editor.ready(function ready() {
    this.execCommand("render", initialLatex);
    if (shouldFocus) {
      this.execCommand("focus");
    }
  });
  return editor;
}
var FormulaXEditor = class {
  container;
  options;
  handlePromise;
  constructor(options) {
    const { el, ...editorOptions } = options;
    this.container = resolveContainer(el);
    this.options = editorOptions;
    this.handlePromise = mountKityEditor(this.container, this.options);
  }
  ready(callback) {
    void this.handlePromise.then((handle) => handle.ready(callback));
    return this;
  }
  async execCommand(name, value) {
    const handle = await this.handlePromise;
    handle.execCommand(name, value);
    return this;
  }
  async focus() {
    const handle = await this.handlePromise;
    handle.focus();
    return this;
  }
  async destroy() {
    const handle = await this.handlePromise;
    handle.destroy();
  }
  async getHandle() {
    return this.handlePromise;
  }
};
if (typeof window !== "undefined") {
  window.FormulaXEditor = FormulaXEditor;
}

// src/index.ts
import { parseLatex, serializeLatex } from "@formulaxjs/core";
import {
  createFormulaElement,
  DEFAULT_FORMULA_ATTRIBUTE,
  DEFAULT_FORMULA_CLASS,
  ensureFormulaXBaseStyles,
  getFormulaLatexFromElement
} from "@formulaxjs/renderer";
import { createKityFormulaRenderer } from "@formulaxjs/renderer-kity";
import {
  ensureFormulaXModalStyles as ensureFormulaXModalStyles2,
  getFormulaXEditorMessage,
  scheduleFormulaXEditorPreload
} from "@formulaxjs/editor";

// src/modal.ts
import {
  clearFormulaXPerfMarks as clearFormulaXPerfMarks2,
  ensureFormulaXModalStyles,
  markFormulaXPerf as markFormulaXPerf2,
  measureFormulaXPerf as measureFormulaXPerf2,
  mountFormulaXEditor,
  recordFormulaXPerfPoint,
  renderFormulaXEditorLoadingState,
  waitForFormulaXAnimationFrame
} from "@formulaxjs/editor";
import {
  escapeAttribute,
  escapeHtml
} from "@formulaxjs/renderer";
function openFormulaXTiptapModal(input) {
  recordFormulaXPerfPoint("fx:modal:open:start");
  const modalOpenStart = markFormulaXPerf2("fx:modal:open:start:scope");
  ensureFormulaXModalStyles(document);
  const root = document.createElement("div");
  root.className = "fx-formula-modal-root";
  root.setAttribute("data-formulax-modal", "true");
  const submitText = input.isUpdate ? input.options.modal.updateText : input.options.modal.insertText;
  root.innerHTML = `
    <div class="fx-formula-modal-backdrop" data-action="backdrop"></div>
    <div class="fx-formula-modal" role="dialog" aria-modal="true" aria-label="${escapeAttribute(input.options.modal.title)}">
      <header class="fx-formula-modal__header">
        <h2 class="fx-formula-modal__title">${escapeHtml(input.options.modal.title)}</h2>
        <button class="fx-formula-modal__close" type="button" data-action="close" aria-label="Close">\xD7</button>
      </header>
      <section class="fx-formula-modal__body">
        <div class="fx-formula-editor-host"></div>
      </section>
      <footer class="fx-formula-modal__footer">
        <button class="fx-formula-modal__button" type="button" data-action="cancel">${escapeHtml(input.options.modal.cancelText)}</button>
        <button class="fx-formula-modal__button fx-formula-modal__button--primary" type="button" data-action="submit">${escapeHtml(submitText)}</button>
      </footer>
    </div>
  `;
  document.body.appendChild(root);
  document.body.classList.add("fx-formula-modal-open");
  const modalDomReadyMark = markFormulaXPerf2("fx:modal:dom-ready");
  measureFormulaXPerf2("fx:modal:dom-ready", modalOpenStart, modalDomReadyMark);
  clearFormulaXPerfMarks2(modalDomReadyMark);
  const host = root.querySelector(".fx-formula-editor-host");
  if (!host) {
    root.remove();
    clearFormulaXPerfMarks2(modalOpenStart);
    return Promise.reject(new Error("[FormulaX] Tiptap modal host not found."));
  }
  renderFormulaXEditorLoadingState(host);
  let closed = false;
  let mounted = null;
  const mountedPromise = waitForFormulaXAnimationFrame().then(() => {
    if (closed) {
      clearFormulaXPerfMarks2(modalOpenStart);
      return null;
    }
    const mountStartMark = markFormulaXPerf2("fx:modal:editor-mount-start");
    measureFormulaXPerf2("fx:modal:editor-mount-start", modalOpenStart, mountStartMark);
    clearFormulaXPerfMarks2(mountStartMark);
    const nextMounted = mountFormulaXEditor(host, {
      initialLatex: input.initialLatex,
      height: input.options.editor.height,
      autofocus: input.options.editor.autofocus,
      locale: input.options.editor.locale,
      assets: input.options.editor.assets,
      render: {
        fontsize: input.options.editor.render.fontsize
      }
    });
    mounted = nextMounted;
    const mountedMark = markFormulaXPerf2("fx:modal:editor-mounted");
    measureFormulaXPerf2("fx:modal:editor-mounted", modalOpenStart, mountedMark);
    clearFormulaXPerfMarks2(mountedMark, modalOpenStart);
    queueMicrotask(() => {
      if (!closed) {
        nextMounted.root.focus();
      }
    });
    return nextMounted;
  }).catch((error) => {
    clearFormulaXPerfMarks2(modalOpenStart);
    throw error;
  });
  return new Promise((resolve) => {
    const close = (payload) => {
      if (closed) {
        return;
      }
      closed = true;
      mounted?.destroy();
      root.removeEventListener("click", onClick);
      document.removeEventListener("keydown", onKeydown, true);
      root.remove();
      document.body.classList.remove("fx-formula-modal-open");
      resolve(payload);
    };
    const submit = async () => {
      try {
        const activeMounted = mounted ?? await mountedPromise;
        if (!activeMounted) {
          return;
        }
        const latex = await activeMounted.getLatex();
        close({ latex });
      } catch (error) {
        host.innerHTML = `
          <div class="fx-formula-editor-error">
            Failed to read FormulaX editor content.
            <pre>${escapeHtml(error instanceof Error ? error.message : String(error))}</pre>
          </div>
        `;
      }
    };
    function onClick(event) {
      const action = event.target.closest("[data-action]")?.dataset.action;
      if (!action) {
        return;
      }
      if (action === "submit") {
        void submit();
        return;
      }
      if (action === "cancel" || action === "close") {
        close(null);
        return;
      }
      if (action === "backdrop" && input.options.modal.closeOnBackdrop) {
        close(null);
      }
    }
    function onKeydown(event) {
      if (event.key === "Escape") {
        event.preventDefault();
        close(null);
      }
    }
    root.addEventListener("click", onClick);
    document.addEventListener("keydown", onKeydown, true);
  });
}

// src/index.ts
var FORMULAX_NODE_NAME = "formulaX";
function resolveOptions(options = {}) {
  const locale = options.editor?.locale ?? DEFAULT_FORMULAX_LOCALE;
  return {
    name: options.name ?? FORMULAX_NODE_NAME,
    formulaClassName: options.formulaClassName ?? DEFAULT_FORMULA_CLASS,
    formulaAttributeName: options.formulaAttributeName ?? DEFAULT_FORMULA_ATTRIBUTE,
    cursorStyle: options.cursorStyle ?? "pointer",
    initialLatex: options.initialLatex ?? "",
    renderer: options.renderer ?? createKityFormulaRenderer({
      fontSize: options.editor?.render?.fontsize ?? 40,
      height: options.editor?.height ?? "100%",
      assets: options.editor?.assets ?? {}
    }),
    preload: options.preload ?? "idle",
    modal: {
      title: options.modal?.title ?? getFormulaXEditorMessage("modal.title", locale),
      insertText: options.modal?.insertText ?? getFormulaXEditorMessage("modal.insert", locale),
      updateText: options.modal?.updateText ?? getFormulaXEditorMessage("modal.update", locale),
      cancelText: options.modal?.cancelText ?? getFormulaXEditorMessage("modal.cancel", locale),
      closeOnBackdrop: options.modal?.closeOnBackdrop ?? true
    },
    editor: {
      height: options.editor?.height ?? "100%",
      autofocus: options.editor?.autofocus ?? true,
      locale,
      assets: options.editor?.assets ?? {},
      render: {
        fontsize: options.editor?.render?.fontsize ?? 40
      }
    }
  };
}
function warnDuplicateNodeName(extension) {
  const extensions = extension.editor?.extensionManager?.extensions ?? [];
  const duplicates = extensions.filter((item) => item?.name === extension.name);
  if (duplicates.length > 1) {
    console.warn(
      `[FormulaX] TipTap node name "${extension.name}" is already registered. Pass a unique "name" option to avoid schema collisions.`
    );
  }
}
function createFormulaXNodeConfig(options) {
  return {
    name: options.name,
    group: "inline",
    inline: true,
    atom: true,
    selectable: true,
    addOptions() {
      return options;
    },
    addStorage() {
      return {
        preloadCleanup: null
      };
    },
    onCreate() {
      warnDuplicateNodeName(this);
      if (typeof document !== "undefined") {
        ensureFormulaXBaseStyles(document);
        ensureFormulaXModalStyles2(document);
      }
      const preloadCleanup = scheduleFormulaXEditorPreload(
        options.preload,
        this.editor?.view?.dom ?? null
      );
      if (this.storage) {
        this.storage.preloadCleanup = preloadCleanup;
      }
    },
    onDestroy() {
      this.storage?.preloadCleanup?.();
      if (this.storage) {
        this.storage.preloadCleanup = null;
      }
    },
    addAttributes() {
      return {
        latex: {
          default: ""
        }
      };
    },
    parseHTML() {
      return [{
        tag: "span[data-formulax]",
        getAttrs: (element) => {
          if (!(element instanceof HTMLElement)) {
            return false;
          }
          return {
            latex: getFormulaLatexFromElement(element, this.options.formulaAttributeName)
          };
        }
      }];
    },
    renderHTML({ node }) {
      if (typeof document === "undefined") {
        return [
          "span",
          {
            "data-formulax": "true",
            [this.options.formulaAttributeName]: node.attrs.latex,
            "data-latex": node.attrs.latex
          },
          node.attrs.latex || "\\square"
        ];
      }
      return createFormulaDomElement(document, node.attrs, this.options);
    },
    addCommands() {
      return {
        openFormulaX: () => () => {
          const selectedFormula = getSelectedFormula(this.editor, this.name);
          const initialLatex = selectedFormula?.attrs.latex ?? this.options.initialLatex;
          void openFormulaXTiptapModal({
            initialLatex,
            isUpdate: Boolean(selectedFormula),
            options: this.options
          }).then((payload) => {
            if (!payload) {
              return;
            }
            applyFormulaPayload(this.editor, payload, selectedFormula, this.name);
            this.editor.commands.focus();
          });
          return true;
        }
      };
    },
    addKeyboardShortcuts() {
      return {
        Enter: () => {
          if (!getSelectedFormula(this.editor, this.name)) {
            return false;
          }
          return this.editor.commands.openFormulaX();
        },
        Space: () => {
          if (!getSelectedFormula(this.editor, this.name)) {
            return false;
          }
          return this.editor.commands.openFormulaX();
        }
      };
    },
    addNodeView() {
      return ({ editor, getPos, node }) => {
        const dom = createFormulaDomElement(document, node.attrs, this.options) ?? document.createElement("span");
        dom.classList.add("formulax-math--interactive");
        void renderFormulaIntoElement(dom, node.attrs, this.options);
        const selectNode = () => {
          const position = getPos();
          if (typeof position !== "number") {
            return;
          }
          editor.commands.setNodeSelection?.(position);
        };
        dom.addEventListener("click", (event) => {
          event.preventDefault();
          selectNode();
        });
        dom.addEventListener("dblclick", (event) => {
          event.preventDefault();
          event.stopPropagation();
          selectNode();
          editor.commands.openFormulaX();
        });
        return {
          dom,
          update: (updatedNode) => {
            if (updatedNode.type.name !== this.name) {
              return false;
            }
            syncFormulaDomElement(dom, updatedNode.attrs, this.options);
            void renderFormulaIntoElement(dom, updatedNode.attrs, this.options);
            return true;
          },
          selectNode: () => {
            dom.classList.add("ProseMirror-selectednode");
          },
          deselectNode: () => {
            dom.classList.remove("ProseMirror-selectednode");
          }
        };
      };
    }
  };
}
function createFormulaXNode(nodeFactory = Node, options) {
  return nodeFactory.create(createFormulaXNodeConfig(resolveOptions(options)));
}
var FormulaXNode = createFormulaXNode();
var createFormulaXPayload = (latex) => parseLatex(latex);
var serializeFormulaXPayload = (doc) => serializeLatex(doc);
function applyFormulaPayload(editor, payload, selectedFormula, nodeName) {
  const latex = payload.latex.trim();
  if (selectedFormula) {
    if (!latex) {
      editor.chain().focus().deleteRange({
        from: selectedFormula.from,
        to: selectedFormula.to
      }).run();
      return;
    }
    editor.chain().focus().insertContentAt(
      {
        from: selectedFormula.from,
        to: selectedFormula.to
      },
      createFormulaNodeContent(payload, nodeName)
    ).run();
    return;
  }
  if (!latex) {
    return;
  }
  editor.chain().focus().insertContent(createFormulaNodeContent(payload, nodeName)).run();
}
function getSelectedFormula(editor, nodeName) {
  const { selection } = editor.state;
  const node = selection.node;
  if (node?.type?.name !== nodeName) {
    return null;
  }
  return {
    from: selection.from,
    to: selection.to,
    attrs: {
      latex: node.attrs?.latex ?? ""
    }
  };
}
function createFormulaNodeContent(payload, nodeName = FORMULAX_NODE_NAME) {
  return {
    type: nodeName,
    attrs: {
      latex: payload.latex
    }
  };
}
function createFormulaDomElement(ownerDocument, attrs, options) {
  return createFormulaElement(ownerDocument, attrs.latex, {
    attributeName: options.formulaAttributeName,
    className: options.formulaClassName,
    cursorStyle: options.cursorStyle
  });
}
function syncFormulaDomElement(dom, attrs, options) {
  const next = createFormulaDomElement(dom.ownerDocument ?? document, attrs, options);
  if (!next) {
    return;
  }
  dom.replaceChildren(...Array.from(next.childNodes));
  Array.from(dom.attributes).forEach((attribute) => {
    if (attribute.name === "class") {
      return;
    }
    dom.removeAttribute(attribute.name);
  });
  Array.from(next.attributes).forEach((attribute) => {
    dom.setAttribute(attribute.name, attribute.value);
  });
}
async function renderFormulaIntoElement(dom, attrs, options) {
  const latex = attrs.latex.trim();
  const renderToken = `${latex}::${Date.now()}::${Math.random().toString(36).slice(2, 8)}`;
  dom.dataset.renderToken = renderToken;
  if (!latex) {
    const placeholder = dom.querySelector(`.${options.formulaClassName}__render`);
    if (placeholder) {
      placeholder.textContent = "\\square";
    }
    return;
  }
  try {
    const result = await options.renderer.renderLatex(latex, {
      fontSize: options.editor.render.fontsize,
      className: options.formulaClassName
    });
    if (dom.dataset.renderToken !== renderToken) {
      return;
    }
    dom.innerHTML = result.html;
  } catch (error) {
    if (dom.dataset.renderToken !== renderToken) {
      return;
    }
    console.error("[FormulaX] Failed to render Tiptap formula node:", error);
    const placeholder = dom.querySelector(`.${options.formulaClassName}__render`);
    if (placeholder) {
      placeholder.textContent = latex;
    }
  }
}
export {
  FORMULAX_NODE_NAME,
  FormulaXNode,
  createFormulaXNode,
  createFormulaXPayload,
  openFormulaXTiptapModal,
  resolveOptions,
  serializeFormulaXPayload
};
//# sourceMappingURL=index.js.map