wysiwygido 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -2,6 +2,17 @@
2
2
 
3
3
  All notable changes to this project are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/). Until 1.0, minor versions may contain breaking changes; they are listed under "Changed" or "Removed".
4
4
 
5
+ ## 0.4.0
6
+
7
+ - Added: colour themes (`Themes` plugin): light, dark, sepia, ocean, forest, rose, solarized, midnight, nord and high-contrast, a View → Themes menu, `colorTheme` / `cycleColorTheme` / `clearColorTheme` commands, your own theme from a handful of colours, and `<wysiwyg-editor theme="sepia">`.
8
+ - Added: the editor emits a `theme` event when Dark Mode or Switch Background changes.
9
+
10
+ ## 0.3.0
11
+
12
+ - Added: change case (UPPER, lower, toggle, snake_case, camelCase, Title, Sentence, PascalCase, kebab-case) with shortcuts, a Home-tab menu and a right-click submenu; `Shift+F3` cycles.
13
+ - Added: cover page (`Cover` plugin, Layout and Insert tabs): a picture over the whole first page, exported to Word anchored to the page.
14
+
15
+
5
16
  ## 0.2.2
6
17
 
7
18
  - Added: right-click menu (`ContextMenu`, in the default set) with table, list, link, picture and text-format items, and a `contextMenu(context)` hook for plugins to add their own.
package/README.md CHANGED
@@ -461,6 +461,45 @@ returns an unsubscribe function, and `editor.emit('my-event', payload)` tells ot
461
461
  `registerIcon(name, svgInner)` adds an icon for ribbon buttons. See `demo/custom-plugin` for a complete third-party plugin, and `src/plugins/` for the built-in ones.
462
462
  Plugins are fixed when the editor is created (the schema cannot change afterwards); commands, toolbar layout and listeners can change at any time.
463
463
 
464
+ ## Change case
465
+
466
+ `TextCase` (in `defaultPlugins`) changes the case of the selection, or of the word at the caret: UPPERCASE (`Ctrl/⌘+Alt+U`), lowercase (`Ctrl/⌘+Alt+L`),
467
+ tOGGLE cASE (`Ctrl/⌘+Alt+G`), snake_case (`Ctrl/⌘+Alt+S`), camelCase (`Ctrl/⌘+Alt+M`), plus Title Case, Sentence case, PascalCase and kebab-case from the menu.
468
+ `Shift+F3` cycles lowercase, UPPERCASE, Title Case and Sentence case like Word. The menu is the **Aa** button in the Home tab's Font group and *Change case*
469
+ in the right-click menu. Upper/lower/toggle/title/sentence keep every bold, link and colour in place; snake/camel/kebab join the words into one
470
+ identifier that takes the formatting of its first letter. From code: `editor.execute('changeCase', 'snake')` or the pure `convertCase(text, 'camel')`.
471
+
472
+ ## Themes
473
+
474
+ Ten colour themes ship with the editor: `light`, `dark`, `sepia`, `ocean`, `forest`, `rose`, `solarized`, `midnight`, `nord` and `high-contrast`. A theme restyles the toolbar, ribbon, panels and the paper, and only inside the editor.
475
+
476
+ ```ts
477
+ import { createEditor, defaultPlugins, Themes } from 'wysiwygido';
478
+
479
+ createEditor({ element, plugins: [...defaultPlugins, Themes({ initial: 'sepia' })] });
480
+ editor.execute('colorTheme', 'midnight');
481
+ editor.execute('cycleColorTheme');
482
+ editor.execute('clearColorTheme'); // back to the stock look
483
+ ```
484
+
485
+ Pick one from **View → Themes** in the ribbon, or use `<wysiwyg-editor theme="nord">`. Dark Mode on its own returns to the stock look.
486
+
487
+ Your own theme is a handful of colours; hover, borders, selection and the rest are derived from them:
488
+
489
+ ```ts
490
+ Themes({ extra: [{ name: 'brand', label: 'Brand', palette: { mode: 'light', bg: '#fff8f0', surface: '#ffeede', fg: '#2a1a10',
491
+ muted: '#7a5a44', border: '#f0d6bf', accent: '#e8590c', workspace: '#f0d2b8', pageBg: '#fff', pageFg: '#2a1a10' } }] });
492
+ ```
493
+
494
+ `editor.extensions.themes` gives `list()`, `current()`, `register(theme)`, `apply(name)` and `clear()`. A theme can also set any `--wy-*` variable through `vars`.
495
+
496
+ ## Cover page
497
+
498
+ `Cover` (in `defaultPlugins`) adds a cover page: one picture that fills the whole first page, edge to edge, with the text starting on page 2. Use
499
+ **Layout → Cover Page** (also under Insert) to upload a picture or give its address; choosing it again replaces the picture, and *Remove cover page* takes it out.
500
+ It goes through your `uploadImage` handler like any picture, is exported to Word as a picture anchored to the page, and is a block named `cover_page` in the document.
501
+ `editor.execute('coverPage', url, alt)` does the same from code. Page numbers count the cover as page 1.
502
+
464
503
  ## Right-click menu
465
504
 
466
505
  `ContextMenu` is in `defaultPlugins`. Right-click shows cut/copy/paste and then what applies at the click: table tools in a table (insert/delete
package/dist/adapter.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as createEditor } from "./src-DFClH3tv.js";
1
+ import { t as createEditor } from "./src-DmooWA6v.js";
2
2
  //#region src/adapter.ts
3
3
  /**
4
4
  * Framework-neutral binding for anything that needs a "value in, value out" control: Angular's `ControlValueAccessor`, Svelte, Solid,
package/dist/docx.js CHANGED
@@ -533,6 +533,15 @@ var imageKey = (attrs) => attrs.crop ? `${attrs.src}|${cropToString(attrs.crop)}
533
533
  function collectImages(doc) {
534
534
  const out = /* @__PURE__ */ new Map();
535
535
  doc.descendants((n) => {
536
+ if (n.type.name === "cover_page") {
537
+ const key = imageKey({ src: n.attrs.src });
538
+ out.set(key, {
539
+ key,
540
+ src: n.attrs.src,
541
+ crop: null
542
+ });
543
+ return;
544
+ }
536
545
  if (n.type.name !== "image") return;
537
546
  const key = imageKey(n.attrs);
538
547
  out.set(key, {
@@ -1014,6 +1023,37 @@ function blocks(node, ctx) {
1014
1023
  color: "999999",
1015
1024
  space: 1
1016
1025
  } } })];
1026
+ case "cover_page": {
1027
+ const img = ctx.images.get(imageKey({ src: node.attrs.src }));
1028
+ const after = new D.Paragraph({ children: [new D.PageBreak()] });
1029
+ if (!img) return [after];
1030
+ const run = new D.ImageRun({
1031
+ type: img.type,
1032
+ data: img.data,
1033
+ transformation: {
1034
+ width: ctx.pageSize.w,
1035
+ height: ctx.pageSize.h
1036
+ },
1037
+ floating: {
1038
+ horizontalPosition: {
1039
+ relative: D.HorizontalPositionRelativeFrom.PAGE,
1040
+ offset: 0
1041
+ },
1042
+ verticalPosition: {
1043
+ relative: D.VerticalPositionRelativeFrom.PAGE,
1044
+ offset: 0
1045
+ },
1046
+ behindDocument: true,
1047
+ allowOverlap: true
1048
+ },
1049
+ altText: {
1050
+ name: "cover",
1051
+ title: "Cover",
1052
+ description: String(node.attrs.alt || "Cover page")
1053
+ }
1054
+ });
1055
+ return [new D.Paragraph({ children: [run] }), after];
1056
+ }
1017
1057
  case "page_break": return [new D.Paragraph({ children: [new D.PageBreak()] })];
1018
1058
  case "toc": return [new D.TableOfContents("Table of Contents", {
1019
1059
  hyperlink: true,
@@ -1098,7 +1138,11 @@ async function buildDocx(editor, options = {}) {
1098
1138
  author: "Author",
1099
1139
  commentIds: new Map(exported.map((t, i) => [t.id, i])),
1100
1140
  referenced: /* @__PURE__ */ new Set(),
1101
- quote: 0
1141
+ quote: 0,
1142
+ pageSize: {
1143
+ w: page?.width ?? 794,
1144
+ h: page?.height ?? 1123
1145
+ }
1102
1146
  };
1103
1147
  const segments = [];
1104
1148
  doc.forEach((n) => {
package/dist/docx.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"docx.js","names":[],"sources":["../src/latex-docx.ts","../src/svg-raster.ts","../src/docx.ts"],"sourcesContent":["import * as D from 'docx';\n\n/** A node of Word's equation tree. */\nexport type MathNode = InstanceType<typeof D.MathRun> | InstanceType<typeof D.MathFraction> | InstanceType<typeof D.MathRadical> | InstanceType<typeof D.MathSuperScript> | InstanceType<typeof D.MathSubScript> | InstanceType<typeof D.MathSubSuperScript> | InstanceType<typeof D.MathSum> | InstanceType<typeof D.MathIntegral> | InstanceType<typeof D.MathRoundBrackets> | InstanceType<typeof D.MathSquareBrackets> | InstanceType<typeof D.MathCurlyBrackets> | InstanceType<typeof D.MathLimitLower>;\n\nconst SYMBOLS: Record<string, string> = {\n alpha: 'α', beta: 'β', gamma: 'γ', delta: 'δ', epsilon: 'ε', varepsilon: 'ε', zeta: 'ζ', eta: 'η', theta: 'θ', vartheta: 'ϑ', iota: 'ι', kappa: 'κ', lambda: 'λ', mu: 'μ', nu: 'ν', xi: 'ξ', pi: 'π', rho: 'ρ', sigma: 'σ', tau: 'τ', upsilon: 'υ', phi: 'φ', varphi: 'φ', chi: 'χ', psi: 'ψ', omega: 'ω',\n Gamma: 'Γ', Delta: 'Δ', Theta: 'Θ', Lambda: 'Λ', Xi: 'Ξ', Pi: 'Π', Sigma: 'Σ', Phi: 'Φ', Psi: 'Ψ', Omega: 'Ω',\n pm: '±', mp: '∓', times: '×', cdot: '·', div: '÷', le: '≤', leq: '≤', ge: '≥', geq: '≥', ne: '≠', neq: '≠', approx: '≈', equiv: '≡', sim: '∼', propto: '∝', infty: '∞', partial: '∂', nabla: '∇',\n to: '→', rightarrow: '→', leftarrow: '←', Rightarrow: '⇒', Leftarrow: '⇐', leftrightarrow: '↔', Leftrightarrow: '⇔', in: '∈', notin: '∉', subset: '⊂', subseteq: '⊆', cup: '∪', cap: '∩', forall: '∀', exists: '∃', emptyset: '∅', ldots: '…', cdots: '⋯', dots: '…', degree: '°',\n prime: '′', angle: '∠', perp: '⊥', parallel: '∥', neg: '¬', land: '∧', lor: '∨', circ: '∘', bullet: '•', star: '⋆', ',': ' ', ';': ' ', ':': ' ', '!': '', quad: ' ', qquad: ' ',\n};\nconst FUNCTIONS = new Set(['sin', 'cos', 'tan', 'cot', 'sec', 'csc', 'arcsin', 'arccos', 'arctan', 'sinh', 'cosh', 'tanh', 'log', 'ln', 'exp', 'det', 'max', 'min', 'gcd', 'lg', 'sup', 'inf', 'lim']);\nconst BLACKBOARD: Record<string, string> = { R: 'ℝ', N: 'ℕ', Z: 'ℤ', Q: 'ℚ', C: 'ℂ', P: 'ℙ' };\n\ntype Tok = { t: 'cmd' | 'ch' | '{' | '}' | '^' | '_' | '[' | ']'; v: string };\nclass Unsupported extends Error {}\n\nfunction tokenize(src: string): Tok[] {\n const out: Tok[] = [];\n for (let i = 0; i < src.length; i++) {\n const c = src[i];\n if (c === '\\\\') {\n const m = /^[A-Za-z]+/.exec(src.slice(i + 1));\n if (m) { out.push({ t: 'cmd', v: m[0] }); i += m[0].length; }\n else if (i + 1 < src.length) { out.push({ t: 'cmd', v: src[i + 1] }); i++; } // \\, \\; \\{ \\} \\\\\n } else if (c === '{' || c === '}' || c === '^' || c === '_' || c === '[' || c === ']') out.push({ t: c as Tok['t'], v: c });\n else if (!/\\s/.test(c)) out.push({ t: 'ch', v: c });\n }\n return out;\n}\n\n/**\n * Convert LaTeX to Word's native equation objects (fractions, roots, scripts, sums, integrals, limits, brackets, Greek letters\n * and common operators). Returns null when the formula uses something outside this subset (matrices, aligned environments,\n * custom macros), so the caller can fall back to the LaTeX text instead of writing a wrong equation.\n */\nexport function latexToDocx(tex: string): MathNode[] | null {\n let toks: Tok[];\n try { toks = tokenize(tex.slice(0, 5000)); } catch { return null; }\n let i = 0;\n let depth = 0; // nesting guard: a hostile formula must not overflow the stack\n const peek = () => toks[i];\n const run = (text: string) => new D.MathRun(text);\n\n const group = (): MathNode[] => {\n if (peek()?.t !== '{') { // a single token: x^2, \\frac12\n const a = atom();\n if (!a) throw new Unsupported(); // \"x^\" with nothing after it\n return [a];\n }\n i++;\n const out = sequence((t) => t.t === '}');\n if (peek()?.t !== '}') throw new Unsupported();\n i++;\n return out;\n };\n const optional = (): MathNode[] | null => {\n if (peek()?.t !== '[') return null;\n i++;\n const out = sequence((t) => t.t === ']');\n if (peek()?.t !== ']') throw new Unsupported();\n i++;\n return out;\n };\n const text = (): string => { // \\text{...}: raw characters up to the closing brace\n if (peek()?.t !== '{') throw new Unsupported();\n i++;\n let s = '';\n while (peek() && peek().t !== '}') { const t = toks[i++]; s += t.t === 'cmd' ? (SYMBOLS[t.v] ?? ` ${t.v}`) : t.v; }\n if (peek()?.t !== '}') throw new Unsupported();\n i++;\n return s;\n };\n\n /** One atom plus any ^ _ that follow it. */\n const withScripts = (base: MathNode[]): MathNode[] => {\n let sub: MathNode[] | null = null;\n let sup: MathNode[] | null = null;\n for (let n = 0; n < 2 && (peek()?.t === '^' || peek()?.t === '_'); n++) {\n const which = toks[i++].t;\n const arg = group();\n if (which === '^') sup = arg; else sub = arg;\n }\n if (sub && sup) return [new D.MathSubSuperScript({ children: base, subScript: sub, superScript: sup })];\n if (sup) return [new D.MathSuperScript({ children: base, superScript: sup })];\n if (sub) return [new D.MathSubScript({ children: base, subScript: sub })];\n return base;\n };\n\n const atom = (): MathNode | null => {\n if (++depth > 60) throw new Unsupported();\n try { return atomInner(); } finally { depth--; }\n };\n const atomInner = (): MathNode | null => {\n const t = toks[i];\n if (!t) return null;\n if (t.t === '{') return (i++, wrap(sequence((x) => x.t === '}', true)));\n if (t.t === 'ch') { i++; return run(t.v); }\n if (t.t === 'cmd') {\n i++;\n const c = t.v;\n if (c === 'frac' || c === 'dfrac' || c === 'tfrac') { const n = group(); const d = group(); return new D.MathFraction({ numerator: n, denominator: d }); }\n if (c === 'sqrt') { const deg = optional(); const body = group(); return new D.MathRadical(deg ? { children: body, degree: deg } : { children: body }); }\n if (c === 'text' || c === 'mathrm' || c === 'operatorname') return run(text());\n if (c === 'mathbb') { const s = text(); return run([...s].map((ch) => BLACKBOARD[ch] ?? ch).join('')); }\n if (c === 'left' || c === 'right') throw new Unsupported(); // handled in sequence()\n if (SYMBOLS[c] !== undefined) return run(SYMBOLS[c]);\n if (FUNCTIONS.has(c)) return run(c);\n if (['{', '}', '#', '%', '&', '$', '_'].includes(c)) return run(c);\n throw new Unsupported(); // \\begin, \\matrix, macros ...\n }\n throw new Unsupported(); // a stray ^ _ ] }\n };\n const wrap = (nodes: MathNode[]): MathNode => (nodes.length === 1 ? nodes[0] : new D.MathRoundBrackets({ children: nodes })); // only used for {…} used as one atom\n\n /** Words after \\sum / \\int / \\lim limits: the operand is the next atom with its scripts. */\n const operand = (): MathNode[] => {\n const a = atom();\n return a ? withScripts([a]) : [];\n };\n\n function sequence(stop: (t: Tok) => boolean, flatten = false): MathNode[] {\n if (++depth > 60) throw new Unsupported();\n try { return sequenceInner(stop, flatten); } finally { depth--; }\n }\n function sequenceInner(stop: (t: Tok) => boolean, flatten: boolean): MathNode[] {\n const out: MathNode[] = [];\n while (peek() && !stop(peek())) {\n const t = peek();\n if (t.t === 'cmd' && (t.v === 'sum' || t.v === 'int' || t.v === 'prod' || t.v === 'lim' || t.v === 'limits')) {\n i++;\n if (t.v === 'limits') continue;\n let sub: MathNode[] | undefined;\n let sup: MathNode[] | undefined;\n for (let n = 0; n < 2 && (peek()?.t === '^' || peek()?.t === '_'); n++) { const w = toks[i++].t; const g = group(); if (w === '^') sup = g; else sub = g; }\n if (t.v === 'lim') { out.push(new D.MathLimitLower({ children: [run('lim')], limit: sub ?? [] })); continue; }\n const body = operand();\n if (t.v === 'int') out.push(new D.MathIntegral({ children: body, subScript: sub, superScript: sup }));\n else out.push(new D.MathSum({ children: body, subScript: sub, superScript: sup })); // \\prod is written as a sum sign when Word lacks a product class\n continue;\n }\n if (t.t === 'cmd' && t.v === 'left') {\n i++;\n const open = toks[i++];\n const inner = sequence((x) => x.t === 'cmd' && x.v === 'right');\n i++; // \\right\n const close = toks[i++];\n if (!open || !close) throw new Unsupported();\n const o = open.v;\n out.push(o === '[' ? new D.MathSquareBrackets({ children: inner }) : o === '{' || (open.t === 'cmd' && open.v === '{') ? new D.MathCurlyBrackets({ children: inner }) : new D.MathRoundBrackets({ children: inner }));\n continue;\n }\n const a = atom();\n if (!a) break;\n out.push(...withScripts([a]));\n }\n return flatten && out.length === 1 ? out : out;\n }\n\n try {\n const result = sequence(() => false);\n return i >= toks.length && result.length ? result : null;\n } catch (e) {\n if (e instanceof Unsupported) return null;\n throw e;\n }\n}\n","/** Draw SVG markup to PNG bytes in the browser (no network, no external references). Null where there is no canvas or the SVG has no size. */\nexport async function rasterizeSVG(svg: string, scale = 2, maxSide = 4000): Promise<{ data: Uint8Array; width: number; height: number } | null> {\n try {\n // real browsers have createImageBitmap; environments without a canvas (tests, servers) skip drawing\n if (typeof document === 'undefined' || typeof createImageBitmap !== 'function') return null;\n const parsed = new DOMParser().parseFromString(svg, 'image/svg+xml');\n const root = parsed.documentElement;\n if (!root || root.nodeName.toLowerCase() !== 'svg' || parsed.querySelector('parsererror')) return null;\n const vb = root.getAttribute('viewBox')?.trim().split(/[\\s,]+/).map(Number);\n const attr = (n: string) => { const v = parseFloat(root.getAttribute(n) ?? ''); return Number.isFinite(v) && !(root.getAttribute(n) ?? '').includes('%') ? v : NaN; };\n let w = vb && vb.length === 4 ? vb[2] : attr('width');\n let h = vb && vb.length === 4 ? vb[3] : attr('height');\n if (!(w > 0) || !(h > 0)) return null;\n const k = Math.min(scale, maxSide / w, maxSide / h);\n root.setAttribute('xmlns', 'http://www.w3.org/2000/svg');\n root.setAttribute('width', String(w));\n root.setAttribute('height', String(h));\n root.removeAttribute('style');\n const xml = new XMLSerializer().serializeToString(root);\n const url = URL.createObjectURL(new Blob([xml], { type: 'image/svg+xml;charset=utf-8' }));\n try {\n const img = new Image();\n await new Promise<void>((ok, fail) => { const t = setTimeout(() => fail(new Error('svg timeout')), 10000); img.onload = () => (clearTimeout(t), ok()); img.onerror = () => (clearTimeout(t), fail(new Error('svg'))); img.src = url; });\n const pw = Math.max(1, Math.round(w * k));\n const ph = Math.max(1, Math.round(h * k));\n const canvas = Object.assign(document.createElement('canvas'), { width: pw, height: ph });\n const ctx = canvas.getContext('2d');\n if (!ctx) return null;\n ctx.fillStyle = '#fff'; // Word pages are white: a transparent background would show dark text on dark in some viewers\n ctx.fillRect(0, 0, pw, ph);\n ctx.drawImage(img, 0, 0, pw, ph);\n const blob = await new Promise<Blob | null>((r) => canvas.toBlob(r, 'image/png'));\n w = pw; h = ph;\n return blob ? { data: new Uint8Array(await blob.arrayBuffer()), width: w, height: h } : null;\n } finally {\n URL.revokeObjectURL(url);\n }\n } catch {\n return null;\n }\n}\n","/**\n * .docx import/export. Lives in its own entry point (`wysiwygido/docx`) so the `docx` and `mammoth`\n * libraries are only loaded by apps that need them.\n */\nimport * as D from 'docx';\nimport type { Mark, Node as PMNode } from 'prosemirror-model';\nimport { cropBytes, cropToString, type Crop } from './crop';\nimport { latexToDocx } from './latex-docx';\nimport { rasterizeSVG } from './svg-raster';\nimport { chartSVG, cleanChart } from './chart';\nimport type { Editor } from './editor';\nimport type { PageSettings } from './plugins/pages';\nimport type { CommentsPlugin, CommentThread } from './plugins/comments';\n\nexport interface ExportOptions {\n /** Include comments (defaults to the editor's Comments plugin store, if installed). */\n comments?: CommentThread[];\n /** Title in the document properties. */\n title?: string;\n /** Fetch remote images to embed them. Default true; failures fall back to the alt text. */\n fetchImages?: boolean;\n}\n\ninterface ImageData { data: Uint8Array; type: 'png' | 'jpg' | 'gif'; width: number; height: number }\n\nconst PX_TO_TWIP = 15;\nconst px = (n: number) => Math.round(n * PX_TO_TWIP);\nconst hex = (c: string) => c.replace('#', '').toUpperCase();\n\n/** Largest image (bytes) the exporter will embed or fetch, and the largest `.docx` the importer will open. */\nconst MAX_IMAGE_BYTES = 15 * 1024 * 1024;\nconst MAX_DOCX_BYTES = 50 * 1024 * 1024;\nconst MAX_DIMENSION = 20000;\n\n/** Read width/height and format from PNG, JPEG or GIF bytes. Null for unknown formats and for zero or absurd sizes. */\nexport function imageInfo(b: Uint8Array): { type: 'png' | 'jpg' | 'gif'; width: number; height: number } | null {\n const info = rawImageInfo(b);\n return info && info.width > 0 && info.height > 0 && info.width <= MAX_DIMENSION && info.height <= MAX_DIMENSION ? info : null;\n}\n\nfunction rawImageInfo(b: Uint8Array): { type: 'png' | 'jpg' | 'gif'; width: number; height: number } | null {\n if (b.length > 24 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) {\n const v = new DataView(b.buffer, b.byteOffset, b.byteLength);\n return { type: 'png', width: v.getUint32(16), height: v.getUint32(20) };\n }\n if (b.length > 10 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46) {\n return { type: 'gif', width: b[6] | (b[7] << 8), height: b[8] | (b[9] << 8) };\n }\n if (b.length > 4 && b[0] === 0xff && b[1] === 0xd8) {\n let i = 2;\n while (i + 9 < b.length) {\n if (b[i] !== 0xff) { i++; continue; }\n const marker = b[i + 1];\n if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {\n return { type: 'jpg', height: (b[i + 5] << 8) | b[i + 6], width: (b[i + 7] << 8) | b[i + 8] };\n }\n i += 2 + ((b[i + 2] << 8) | b[i + 3]);\n }\n }\n return null;\n}\n\n/** Read a response body, giving up (null) as soon as it exceeds `max` bytes, whatever Content-Length claimed. */\nasync function readCapped(res: Response, max: number): Promise<Uint8Array | null> {\n if (!res.body) {\n const buf = new Uint8Array(await res.arrayBuffer());\n return buf.length > max ? null : buf;\n }\n const reader = res.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > max) { await reader.cancel(); return null; }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let at = 0;\n for (const c of chunks) { out.set(c, at); at += c.length; }\n return out;\n}\n\nasync function loadImage(src: string, fetchRemote: boolean): Promise<ImageData | null> {\n try {\n let bytes: Uint8Array;\n if (src.startsWith('data:')) {\n const comma = src.indexOf(',');\n if (comma < 0 || !/;base64$/i.test(src.slice(0, comma))) return null;\n if (src.length - comma > MAX_IMAGE_BYTES * 1.4) return null; // base64 is ~4/3 of the bytes\n const bin = atob(src.slice(comma + 1));\n bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));\n } else if (fetchRemote && /^https?:/i.test(src)) {\n const res = await fetch(src, { signal: AbortSignal.timeout(15000), credentials: 'omit', referrerPolicy: 'no-referrer' });\n if (!res.ok) return null;\n const declared = Number(res.headers.get('content-length'));\n if (declared > MAX_IMAGE_BYTES) return null;\n const body = await readCapped(res, MAX_IMAGE_BYTES);\n if (!body) return null;\n bytes = body;\n } else return null;\n const info = imageInfo(bytes);\n return info ? { data: bytes, ...info } : null;\n } catch {\n return null;\n }\n}\n\nconst imageKey = (attrs: { src: string; crop?: Crop | null }) => (attrs.crop ? `${attrs.src}|${cropToString(attrs.crop)}` : attrs.src);\n\nfunction collectImages(doc: PMNode): { key: string; src: string; crop: Crop | null }[] {\n const out = new Map<string, { key: string; src: string; crop: Crop | null }>();\n doc.descendants((n) => {\n if (n.type.name !== 'image') return;\n const key = imageKey(n.attrs as { src: string; crop?: Crop | null });\n out.set(key, { key, src: n.attrs.src, crop: n.attrs.crop ?? null });\n });\n return [...out.values()];\n}\n\ninterface Ctx {\n images: Map<string, ImageData | null>;\n /** Mermaid diagrams drawn to PNG, by source. */\n diagrams: Map<string, ImageData | null>;\n footnotes: Record<number, { children: D.Paragraph[] }>;\n numbering: D.ILevelsOptions[][];\n numberingRefs: string[];\n revision: number;\n author: string;\n commentIds: Map<string, number>;\n referenced: Set<string>;\n quote: number;\n}\n\nconst ALIGN: Record<string, (typeof D.AlignmentType)[keyof typeof D.AlignmentType]> = {\n left: D.AlignmentType.LEFT,\n center: D.AlignmentType.CENTER,\n right: D.AlignmentType.RIGHT,\n justify: D.AlignmentType.JUSTIFIED,\n};\n\ntype ListFormat = 'decimal' | 'lowerLetter' | 'upperLetter' | 'lowerRoman' | 'upperRoman' | 'bullet';\nconst FORMATS: Record<ListFormat, (typeof D.LevelFormat)[keyof typeof D.LevelFormat]> = { decimal: D.LevelFormat.DECIMAL, lowerLetter: D.LevelFormat.LOWER_LETTER, upperLetter: D.LevelFormat.UPPER_LETTER, lowerRoman: D.LevelFormat.LOWER_ROMAN, upperRoman: D.LevelFormat.UPPER_ROMAN, bullet: D.LevelFormat.BULLET };\nconst TYPE_FORMAT: Record<string, ListFormat> = { '1': 'decimal', a: 'lowerLetter', A: 'upperLetter', i: 'lowerRoman', I: 'upperRoman' };\n\nfunction levels(format: ListFormat, text?: string, start = 1): D.ILevelsOptions[] {\n return Array.from({ length: 9 }, (_, level) => ({\n level,\n format: FORMATS[format],\n start: format === 'bullet' ? undefined : start,\n text: format !== 'bullet' ? `%${level + 1}.` : text ?? (level % 2 ? '◦' : '•'),\n alignment: D.AlignmentType.START,\n style: { paragraph: { indent: { left: 720 * (level + 1), hanging: 360 } } },\n }));\n}\n\nfunction newNumbering(ctx: Ctx, format: ListFormat, text?: string, start = 1): string {\n const ref = `list-${ctx.numberingRefs.length}`;\n ctx.numberingRefs.push(ref);\n ctx.numbering.push(levels(format, text, start));\n return ref;\n}\n\nfunction runOptions(marks: readonly Mark[]) {\n const o: Record<string, unknown> = {};\n let link: string | null = null;\n let revision: 'insertion' | 'deletion' | null = null;\n for (const m of marks) {\n switch (m.type.name) {\n case 'bold': o.bold = true; break;\n case 'italic': o.italics = true; break;\n case 'underline': o.underline = {}; break;\n case 'strike': o.strike = true; break;\n case 'code': o.font = 'Courier New'; o.shading = { type: D.ShadingType.CLEAR, fill: 'F0F0F0', color: 'auto' }; break;\n case 'text_color': o.color = hex(m.attrs.color); break;\n case 'highlight': o.shading = { type: D.ShadingType.CLEAR, fill: hex(m.attrs.color), color: 'auto' }; break;\n case 'font_family': o.font = m.attrs.value; break;\n case 'font_size': o.size = Math.round(Number(m.attrs.value) * 1.5); break; // px -> half-points\n case 'link': link = m.attrs.href; o.color ??= '1D4ED8'; o.underline ??= {}; break;\n case 'insertion': revision = 'insertion'; break;\n case 'deletion': revision = 'deletion'; break;\n }\n }\n return { o, link, revision };\n}\n\nfunction footnoteText(ctx: Ctx, text: string): number {\n const id = Object.keys(ctx.footnotes).length + 1;\n ctx.footnotes[id] = { children: [new D.Paragraph({ children: [new D.TextRun(text)] })] };\n return id;\n}\n\nfunction inlineChildren(node: PMNode, ctx: Ctx): D.ParagraphChild[] {\n const out: D.ParagraphChild[] = [];\n // Comment ranges: open before the first run carrying a comment, close after the last one in this paragraph.\n const lastIndexOf = new Map<string, number>();\n node.forEach((child, _o, i) => child.marks.forEach((m) => m.type.name === 'comment' && lastIndexOf.set(m.attrs.id, i)));\n const open = new Set<string>();\n\n node.forEach((child, _offset, index) => {\n const ids = child.marks.filter((m) => m.type.name === 'comment').map((m) => m.attrs.id as string);\n for (const id of ids) {\n if (!open.has(id) && ctx.commentIds.has(id)) {\n open.add(id);\n out.push(new D.CommentRangeStart(ctx.commentIds.get(id)!));\n }\n }\n\n const { o, link, revision } = runOptions(child.marks);\n let run: D.ParagraphChild | null = null;\n if (child.isText) {\n const text = child.text!;\n if (revision === 'insertion') run = new D.InsertedTextRun({ id: ctx.revision++, author: ctx.author, date: new Date().toISOString(), text, ...o });\n else if (revision === 'deletion') run = new D.DeletedTextRun({ id: ctx.revision++, author: ctx.author, date: new Date().toISOString(), text, ...o });\n else run = new D.TextRun({ text, ...o });\n } else if (child.type.name === 'mention') {\n run = new D.TextRun({ text: `@${child.attrs.label}`, color: '1D4ED8', ...o });\n } else if (child.type.name === 'math_inline') {\n const eq = latexToDocx(child.attrs.tex); // a native Word equation; the LaTeX text when the formula is outside what we convert\n run = eq ? (new D.Math({ children: eq }) as unknown as D.ParagraphChild) : new D.TextRun({ text: child.attrs.tex, font: 'Cambria Math', italics: true, ...o });\n } else if (child.type.name === 'xref') {\n run = new D.TextRun({ text: String(child.attrs.text), ...o });\n } else if (child.type.name === 'form_field') {\n const a = child.attrs;\n run = new D.TextRun({ text: `${a.label ? `${a.label}: ` : ''}${a.kind === 'checkbox' ? (a.value === 'true' ? '☒' : '☐') : a.value || '________'}`, underline: a.kind === 'checkbox' ? undefined : {}, ...o });\n } else if (child.type.name === 'attachment') {\n run = new D.TextRun({ text: `[${child.attrs.name}]`, color: '1D4ED8', ...o });\n } else if (child.type.name === 'hard_break') {\n run = new D.TextRun({ break: 1 });\n } else if (child.type.name === 'footnote') {\n run = new D.FootnoteReferenceRun(footnoteText(ctx, child.attrs.text));\n } else if (child.type.name === 'image') {\n const img = ctx.images.get(imageKey(child.attrs as { src: string; crop?: Crop | null }));\n if (img) {\n const w = child.attrs.width ?? Math.min(img.width, 600);\n run = new D.ImageRun({\n type: img.type,\n data: img.data,\n transformation: { width: w, height: Math.max(1, Math.round((w * img.height) / img.width)) },\n altText: { name: 'image', title: child.attrs.alt ?? 'image', description: child.attrs.alt ?? '' },\n });\n } else run = new D.TextRun({ text: child.attrs.alt ? `[${child.attrs.alt}]` : '[image]', italics: true });\n }\n if (run) out.push(link ? new D.ExternalHyperlink({ link, children: [run as D.TextRun] }) : run);\n\n for (const id of ids) {\n if (open.has(id) && lastIndexOf.get(id) === index) {\n open.delete(id);\n const n = ctx.commentIds.get(id)!;\n out.push(new D.CommentRangeEnd(n));\n if (!ctx.referenced.has(id)) {\n ctx.referenced.add(id);\n out.push(new D.TextRun({ children: [new D.CommentReference(n)] }));\n }\n }\n }\n });\n return out;\n}\n\nfunction paragraphOptions(node: PMNode, ctx: Ctx) {\n const o: Record<string, unknown> = {};\n if (node.attrs.align && ALIGN[node.attrs.align]) o.alignment = ALIGN[node.attrs.align];\n if (node.attrs.lineHeight) o.spacing = { line: Math.round(Number(node.attrs.lineHeight) * 240), lineRule: D.LineRuleType.AUTO };\n if (ctx.quote) {\n o.indent = { left: 720 * ctx.quote };\n o.border = { left: { style: D.BorderStyle.SINGLE, size: 12, color: 'D4D4D4', space: 8 } };\n }\n return o;\n}\n\ntype Block = D.Paragraph | D.Table | D.TableOfContents;\n\nfunction listBlocks(list: PMNode, ctx: Ctx, depth: number): Block[] {\n const out: Block[] = [];\n const name = list.type.name;\n const ref = name === 'ordered_list' ? newNumbering(ctx, TYPE_FORMAT[list.attrs.type] ?? 'decimal', undefined, Math.max(1, Number(list.attrs.order) || 1)) : name === 'bullet_list' ? newNumbering(ctx, 'bullet') : null;\n list.forEach((item) => {\n let first = true;\n const taskRef = name === 'task_list' ? newNumbering(ctx, 'bullet', item.attrs.checked ? '☑' : '☐') : null;\n item.forEach((child) => {\n if (child.type.name === 'paragraph' && first) {\n out.push(new D.Paragraph({ children: inlineChildren(child, ctx), numbering: { reference: (ref ?? taskRef)!, level: depth }, ...paragraphOptions(child, ctx) }));\n } else if (/_list$/.test(child.type.name)) {\n out.push(...listBlocks(child, ctx, depth + 1));\n } else {\n out.push(...blocks(child, ctx).map((b) => b));\n }\n first = false;\n });\n });\n return out;\n}\n\nfunction tableBlock(table: PMNode, ctx: Ctx): D.Table {\n const rows: D.TableRow[] = [];\n table.forEach((row) => {\n const cells: D.TableCell[] = [];\n let header = true;\n row.forEach((cell) => {\n if (cell.type.name !== 'table_header') header = false;\n const children: Block[] = [];\n cell.forEach((c) => children.push(...blocks(c, ctx)));\n if (!children.length) children.push(new D.Paragraph(''));\n const bg = cell.attrs.background as string | null;\n cells.push(\n new D.TableCell({\n children: children as D.Paragraph[],\n columnSpan: cell.attrs.colspan > 1 ? cell.attrs.colspan : undefined,\n rowSpan: cell.attrs.rowspan > 1 ? cell.attrs.rowspan : undefined,\n shading: bg ? { type: D.ShadingType.CLEAR, fill: hex(bg), color: 'auto' } : undefined,\n }),\n );\n });\n rows.push(new D.TableRow({ children: cells, tableHeader: header }));\n });\n return new D.Table({ rows, width: { size: 100, type: D.WidthType.PERCENTAGE } });\n}\n\nfunction blocks(node: PMNode, ctx: Ctx): Block[] {\n switch (node.type.name) {\n case 'paragraph':\n return [new D.Paragraph({ children: inlineChildren(node, ctx), ...paragraphOptions(node, ctx) })];\n case 'heading':\n return [new D.Paragraph({ heading: D.HeadingLevel[`HEADING_${Math.min(6, node.attrs.level)}` as 'HEADING_1'], children: inlineChildren(node, ctx), ...paragraphOptions(node, ctx) })];\n case 'bullet_list':\n case 'ordered_list':\n case 'task_list':\n return listBlocks(node, ctx, 0);\n case 'locked_section':\n case 'editable_region': {\n // Locking is an editing concern; in Word the content is simply part of the document.\n const out: Block[] = [];\n node.forEach((c) => out.push(...blocks(c, ctx)));\n return out;\n }\n case 'blockquote': {\n ctx.quote++;\n const out: Block[] = [];\n node.forEach((c) => out.push(...blocks(c, ctx)));\n ctx.quote--;\n return out;\n }\n case 'code_block':\n return node.textContent.split('\\n').map((line) => new D.Paragraph({ children: [new D.TextRun({ text: line, font: 'Courier New', size: 20 })], shading: { type: D.ShadingType.CLEAR, fill: 'F0F0F0', color: 'auto' } }));\n case 'clip':\n return [new D.Paragraph({ children: [new D.TextRun({ text: `${node.attrs.kind === 'video' ? 'Screen' : 'Audio'} recording: `, color: '6B7280' }), ...(/^https?:/i.test(String(node.attrs.src)) ? [new D.ExternalHyperlink({ link: String(node.attrs.src), children: [new D.TextRun({ text: String(node.attrs.name || node.attrs.src), style: 'Hyperlink', color: '1D4ED8', underline: {} })] })] : [new D.TextRun({ text: String(node.attrs.name || '(embedded in the online document)') })])] })];\n case 'chart': {\n const png = ctx.diagrams.get(`chart:${node.attrs.spec}`);\n const spec = cleanChart(node.attrs.spec);\n if (png) {\n const w = Math.min(png.width / 2, 520);\n return [new D.Paragraph({ alignment: D.AlignmentType.CENTER, spacing: { before: 120, after: 120 }, children: [new D.ImageRun({ type: 'png', data: png.data, transformation: { width: w, height: Math.max(1, Math.round((w * png.height) / png.width)) }, altText: { name: 'chart', title: spec?.title || 'Chart', description: spec ? `${spec.type} chart: ${spec.labels.join(', ')}` : 'Chart' } })] })];\n }\n return spec ? [new D.Paragraph({ children: [new D.TextRun({ text: `Chart: ${spec.title || spec.type}`, italics: true, color: '6B7280' })] })] : [];\n }\n case 'column_break':\n return [new D.Paragraph({ children: [new D.ColumnBreak()] })];\n case 'columns': {\n const out: Block[] = [];\n node.forEach((c) => out.push(...blocks(c, ctx)));\n return out;\n }\n case 'caption': {\n const label = String(node.attrs.kind).replace(/^./, (c: string) => c.toUpperCase());\n return [new D.Paragraph({ spacing: { before: 60, after: 160 }, children: [new D.TextRun({ text: `${label} ${node.attrs.n}. `, bold: true, italics: true, size: 20 }), ...inlineChildren(node, ctx)] })];\n }\n case 'caption_list': {\n let items: { n: number; text: string }[] = [];\n try { items = JSON.parse(node.attrs.items); } catch { /* none */ }\n const label = String(node.attrs.kind).replace(/^./, (c: string) => c.toUpperCase());\n return [new D.Paragraph({ children: [new D.TextRun({ text: `List of ${label.toLowerCase()}s`, bold: true })] }), ...items.map((it) => new D.Paragraph({ children: [new D.TextRun({ text: `${label} ${it.n}. ${it.text}` })] }))];\n }\n case 'embed':\n return [new D.Paragraph({ children: [new D.TextRun({ text: 'Media: ', color: '6B7280' }), new D.ExternalHyperlink({ link: String(node.attrs.url), children: [new D.TextRun({ text: String(node.attrs.url), style: 'Hyperlink', color: '1D4ED8', underline: {} })] })] })];\n case 'math_block': {\n const eq = latexToDocx(node.attrs.tex);\n return [new D.Paragraph({ alignment: D.AlignmentType.CENTER, spacing: { before: 120, after: 120 }, children: eq ? [new D.Math({ children: eq }) as unknown as D.ParagraphChild] : [new D.TextRun({ text: node.attrs.tex, font: 'Cambria Math', italics: true })] })];\n }\n case 'mermaid_diagram': {\n const png = ctx.diagrams.get(node.attrs.code);\n if (png) {\n const w = Math.min(png.width / 2, 600); // drawn at 2x for sharpness\n return [new D.Paragraph({ alignment: D.AlignmentType.CENTER, spacing: { before: 120, after: 120 }, children: [new D.ImageRun({ type: 'png', data: png.data, transformation: { width: w, height: Math.max(1, Math.round((w * png.height) / png.width)) }, altText: { name: 'diagram', title: 'Diagram', description: String(node.attrs.code).slice(0, 200) } })] })];\n }\n // no canvas (or an invalid diagram): keep the source, clearly labelled\n return [\n new D.Paragraph({ children: [new D.TextRun({ text: 'Diagram (Mermaid source)', italics: true, color: '6B7280', size: 18 })] }),\n ...String(node.attrs.code).split('\\n').map((line) => new D.Paragraph({ children: [new D.TextRun({ text: line, font: 'Courier New', size: 20 })], shading: { type: D.ShadingType.CLEAR, fill: 'F0F0F0', color: 'auto' } })),\n ];\n }\n case 'horizontal_rule':\n return [new D.Paragraph({ border: { bottom: { style: D.BorderStyle.SINGLE, size: 6, color: '999999', space: 1 } } })];\n case 'page_break':\n return [new D.Paragraph({ children: [new D.PageBreak()] })];\n case 'toc':\n return [new D.TableOfContents('Table of Contents', { hyperlink: true, headingStyleRange: '1-4' })];\n case 'table':\n return [tableBlock(node, ctx), new D.Paragraph('')]; // Word needs a paragraph after a table\n default:\n return node.isTextblock ? [new D.Paragraph({ children: inlineChildren(node, ctx) })] : [];\n }\n}\n\nfunction headerFooterParagraph(template: string): D.Paragraph {\n const parts = template.split(/(\\{page\\}|\\{pages\\})/);\n const run: (string | (typeof D.PageNumber)[keyof typeof D.PageNumber])[] = parts\n .filter(Boolean)\n .map((p) => (p === '{page}' ? D.PageNumber.CURRENT : p === '{pages}' ? D.PageNumber.TOTAL_PAGES : p));\n return new D.Paragraph({ alignment: D.AlignmentType.CENTER, children: [new D.TextRun({ children: run, color: '9CA3AF', size: 18 })] });\n}\n\n/** Build a docx `Document` from the editor's content, page setup, footnotes, comments and tracked changes. */\nexport async function buildDocx(editor: Editor, options: ExportOptions = {}): Promise<D.Document> {\n const doc = editor.view.state.doc;\n const page = (editor.extensions.pageSettings as (() => PageSettings) | undefined)?.();\n const store = (editor.config.plugins.find((p) => p.name === 'comments') as CommentsPlugin | undefined)?.store;\n const threads = options.comments ?? store?.list() ?? [];\n const used = new Set<string>();\n doc.descendants((n) => void n.marks.forEach((m) => m.type.name === 'comment' && used.add(m.attrs.id)));\n const exported = threads.filter((t) => used.has(t.id));\n\n const images = new Map<string, ImageData | null>();\n await Promise.all(\n collectImages(doc).map(async ({ key, src, crop }) => {\n let img = await loadImage(src, options.fetchImages !== false);\n if (img && crop) {\n // Word needs the cropped pixels; render them with canvas. Without canvas the full image is exported.\n const cropped = await cropBytes(img.data, crop);\n if (cropped) img = { data: cropped.data, type: 'png', width: cropped.width, height: cropped.height };\n }\n images.set(key, img);\n }),\n );\n\n // Diagrams: render each Mermaid source to SVG with the editor's plugin, then to PNG (needs a browser canvas).\n const diagrams = new Map<string, ImageData | null>();\n const renderSVG = (editor.extensions.mermaid as { renderSVG?: (code: string, dark?: boolean) => Promise<string> } | undefined)?.renderSVG;\n const codes = new Set<string>();\n const codesCharts = new Set<string>();\n doc.descendants((n) => void (n.type.name === 'mermaid_diagram' && codes.add(n.attrs.code)));\n if (renderSVG) {\n await Promise.all([...codes].map(async (code) => {\n try {\n const png = await rasterizeSVG(await renderSVG(code, false));\n diagrams.set(code, png ? { data: png.data, type: 'png', width: png.width, height: png.height } : null);\n } catch {\n diagrams.set(code, null); // an invalid diagram: its source is written instead\n }\n }));\n }\n\n // Charts: the SVG is drawn from the data here, then rasterised like a diagram\n doc.descendants((n) => {\n if (n.type.name === 'chart') codesCharts.add(String(n.attrs.spec));\n });\n await Promise.all([...codesCharts].map(async (raw) => {\n const spec = cleanChart(raw);\n const png = spec ? await rasterizeSVG(chartSVG(spec)) : null;\n diagrams.set(`chart:${raw}`, png ? { data: png.data, type: 'png', width: png.width, height: png.height } : null);\n }));\n\n const ctx: Ctx = {\n images,\n diagrams,\n footnotes: {},\n numbering: [],\n numberingRefs: [],\n revision: 1,\n author: 'Author',\n commentIds: new Map(exported.map((t, i) => [t.id, i])),\n referenced: new Set(),\n quote: 0,\n };\n // Top-level `columns` blocks become their own continuous Word sections with the right column count; the text around them is single-column.\n type Segment = { count: number; gap: number; rule: boolean; children: Block[] };\n const segments: Segment[] = [];\n doc.forEach((n) => {\n if (n.type.name === 'columns') {\n const kids: Block[] = [];\n n.forEach((c) => kids.push(...blocks(c, ctx)));\n if (kids.length) segments.push({ count: Number(n.attrs.count) || 2, gap: Number(n.attrs.gap) || 28, rule: n.attrs.rule === 'solid', children: kids });\n return;\n }\n const last = segments[segments.length - 1];\n const out = blocks(n, ctx);\n if (last && last.count === 1) last.children.push(...out);\n else segments.push({ count: 1, gap: 0, rule: false, children: out });\n });\n if (!segments.some((s) => s.children.length)) segments.splice(0, segments.length, { count: 1, gap: 0, rule: false, children: [new D.Paragraph('')] });\n\n const w = page?.width ?? 794;\n const h = page?.height ?? 1123;\n const landscape = page?.orientation === 'landscape';\n const m = page?.margins ?? { top: 96, right: 96, bottom: 96, left: 96 };\n const headerTpl = page?.header ?? '';\n const footerTpl = page ? page.footer : '';\n\n return new D.Document({\n creator: 'wysiwygido',\n title: options.title,\n features: { updateFields: doc.content.content.some((n) => n.type.name === 'toc') },\n numbering: { config: ctx.numbering.map((lv, i) => ({ reference: ctx.numberingRefs[i], levels: lv })) },\n footnotes: ctx.footnotes,\n comments: {\n children: exported.map((t, i) => ({\n id: i,\n author: t.author,\n date: new Date(t.createdAt),\n children: [t.text, ...t.replies.map((r) => `${r.author}: ${r.text}`)].map((text) => new D.Paragraph(text)),\n })),\n },\n sections: segments.map((seg, i) => ({\n properties: {\n ...(i === 0 ? { titlePage: page?.differentFirstPage } : { type: D.SectionType.CONTINUOUS }),\n ...(seg.count > 1 ? { column: { count: seg.count, space: seg.gap * 15, separate: seg.rule, equalWidth: true } } : {}),\n page: {\n size: { width: px(Math.min(w, h)), height: px(Math.max(w, h)), orientation: landscape ? D.PageOrientation.LANDSCAPE : D.PageOrientation.PORTRAIT },\n margin: { top: px(m.top), right: px(m.right), bottom: px(m.bottom), left: px(m.left) },\n },\n },\n // headers and footers belong to the first section; later continuous sections carry on with them\n ...(i === 0\n ? {\n headers: {\n default: new D.Header({ children: [headerFooterParagraph(headerTpl)] }),\n ...(page?.differentFirstPage ? { first: new D.Header({ children: [headerFooterParagraph(page.firstHeader)] }) } : {}),\n },\n footers: {\n default: new D.Footer({ children: [headerFooterParagraph(footerTpl)] }),\n ...(page?.differentFirstPage ? { first: new D.Footer({ children: [headerFooterParagraph(page.firstFooter)] }) } : {}),\n },\n }\n : {}),\n children: (seg.children.length ? seg.children : [new D.Paragraph('')]) as D.Paragraph[],\n })),\n });\n}\n\n/** Export the document as a .docx `Blob`. */\nexport async function exportDocx(editor: Editor, options: ExportOptions = {}): Promise<Blob> {\n return D.Packer.toBlob(await buildDocx(editor, options));\n}\n\nfunction blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {\n if (typeof blob.arrayBuffer === 'function') return blob.arrayBuffer();\n return new Promise((resolve, reject) => {\n const r = new FileReader();\n r.onload = () => resolve(r.result as ArrayBuffer);\n r.onerror = () => reject(r.error);\n r.readAsArrayBuffer(blob);\n });\n}\n\n/** Replace the editor content with a .docx file's content (undoable). Returns mammoth's conversion warnings. */\nexport async function importDocx(editor: Editor, source: Blob | ArrayBuffer): Promise<string[]> {\n const mammoth = (await import('mammoth')).default ?? (await import('mammoth'));\n const size = source instanceof ArrayBuffer ? source.byteLength : source.size;\n if (size > MAX_DOCX_BYTES) throw new Error(`The .docx file is too large (${Math.round(size / 1048576)} MB; the limit is ${MAX_DOCX_BYTES / 1048576} MB).`);\n const arrayBuffer = source instanceof ArrayBuffer ? source : await blobToArrayBuffer(source);\n // mammoth's browser build reads `arrayBuffer`, its Node build reads `buffer`; pass what the runtime has.\n const input = { arrayBuffer, ...(typeof Buffer !== 'undefined' ? { buffer: Buffer.from(arrayBuffer) } : {}) };\n const result = await mammoth.convertToHtml(\n input as { arrayBuffer: ArrayBuffer },\n { styleMap: ['u => u', 'strike => s', \"p[style-name='Quote'] => blockquote:fresh\"] },\n );\n editor.replaceHTML(result.value);\n return result.messages.map((m: { message: string }) => m.message);\n}\n"],"mappings":";;;AAKA,IAAM,UAAkC;CACtC,OAAO;CAAK,MAAM;CAAK,OAAO;CAAK,OAAO;CAAK,SAAS;CAAK,YAAY;CAAK,MAAM;CAAK,KAAK;CAAK,OAAO;CAAK,UAAU;CAAK,MAAM;CAAK,OAAO;CAAK,QAAQ;CAAK,IAAI;CAAK,IAAI;CAAK,IAAI;CAAK,IAAI;CAAK,KAAK;CAAK,OAAO;CAAK,KAAK;CAAK,SAAS;CAAK,KAAK;CAAK,QAAQ;CAAK,KAAK;CAAK,KAAK;CAAK,OAAO;CACtS,OAAO;CAAK,OAAO;CAAK,OAAO;CAAK,QAAQ;CAAK,IAAI;CAAK,IAAI;CAAK,OAAO;CAAK,KAAK;CAAK,KAAK;CAAK,OAAO;CAC1G,IAAI;CAAK,IAAI;CAAK,OAAO;CAAK,MAAM;CAAK,KAAK;CAAK,IAAI;CAAK,KAAK;CAAK,IAAI;CAAK,KAAK;CAAK,IAAI;CAAK,KAAK;CAAK,QAAQ;CAAK,OAAO;CAAK,KAAK;CAAK,QAAQ;CAAK,OAAO;CAAK,SAAS;CAAK,OAAO;CAC7L,IAAI;CAAK,YAAY;CAAK,WAAW;CAAK,YAAY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,QAAgB,UAAyB,CAAC,GAAkB;CAC3F,OAAO,EAAE,OAAO,OAAO,MAAM,UAAU,QAAQ,OAAO,CAAC;AACzD;AAEA,SAAS,kBAAkB,MAAkC;CAC3D,IAAI,OAAO,KAAK,gBAAgB,YAAY,OAAO,KAAK,YAAY;CACpE,OAAO,IAAI,SAAS,SAAS,WAAW;EACtC,MAAM,IAAI,IAAI,WAAW;EACzB,EAAE,eAAe,QAAQ,EAAE,MAAqB;EAChD,EAAE,gBAAgB,OAAO,EAAE,KAAK;EAChC,EAAE,kBAAkB,IAAI;CAC1B,CAAC;AACH;;AAGA,eAAsB,WAAW,QAAgB,QAA+C;CAC9F,MAAM,WAAW,MAAM,OAAO,WAAA,CAAY,WAAY,MAAM,OAAO;CACnE,MAAM,OAAO,kBAAkB,cAAc,OAAO,aAAa,OAAO;CACxE,IAAI,OAAO,gBAAgB,MAAM,IAAI,MAAM,gCAAgC,KAAK,MAAM,OAAO,OAAO,EAAE,oBAAoB,iBAAiB,QAAQ,MAAM;CACzJ,MAAM,cAAc,kBAAkB,cAAc,SAAS,MAAM,kBAAkB,MAAM;CAE3F,MAAM,QAAQ;EAAE;EAAa,GAAI,OAAO,WAAW,cAAc,EAAE,QAAQ,OAAO,KAAK,WAAW,EAAE,IAAI,CAAC;CAAG;CAC5G,MAAM,SAAS,MAAM,QAAQ,cAC3B,OACA,EAAE,UAAU;EAAC;EAAU;EAAe;CAA2C,EAAE,CACrF;CACA,OAAO,YAAY,OAAO,KAAK;CAC/B,OAAO,OAAO,SAAS,KAAK,MAA2B,EAAE,OAAO;AAClE"}
1
+ {"version":3,"file":"docx.js","names":[],"sources":["../src/latex-docx.ts","../src/svg-raster.ts","../src/docx.ts"],"sourcesContent":["import * as D from 'docx';\n\n/** A node of Word's equation tree. */\nexport type MathNode = InstanceType<typeof D.MathRun> | InstanceType<typeof D.MathFraction> | InstanceType<typeof D.MathRadical> | InstanceType<typeof D.MathSuperScript> | InstanceType<typeof D.MathSubScript> | InstanceType<typeof D.MathSubSuperScript> | InstanceType<typeof D.MathSum> | InstanceType<typeof D.MathIntegral> | InstanceType<typeof D.MathRoundBrackets> | InstanceType<typeof D.MathSquareBrackets> | InstanceType<typeof D.MathCurlyBrackets> | InstanceType<typeof D.MathLimitLower>;\n\nconst SYMBOLS: Record<string, string> = {\n alpha: 'α', beta: 'β', gamma: 'γ', delta: 'δ', epsilon: 'ε', varepsilon: 'ε', zeta: 'ζ', eta: 'η', theta: 'θ', vartheta: 'ϑ', iota: 'ι', kappa: 'κ', lambda: 'λ', mu: 'μ', nu: 'ν', xi: 'ξ', pi: 'π', rho: 'ρ', sigma: 'σ', tau: 'τ', upsilon: 'υ', phi: 'φ', varphi: 'φ', chi: 'χ', psi: 'ψ', omega: 'ω',\n Gamma: 'Γ', Delta: 'Δ', Theta: 'Θ', Lambda: 'Λ', Xi: 'Ξ', Pi: 'Π', Sigma: 'Σ', Phi: 'Φ', Psi: 'Ψ', Omega: 'Ω',\n pm: '±', mp: '∓', times: '×', cdot: '·', div: '÷', le: '≤', leq: '≤', ge: '≥', geq: '≥', ne: '≠', neq: '≠', approx: '≈', equiv: '≡', sim: '∼', propto: '∝', infty: '∞', partial: '∂', nabla: '∇',\n to: '→', rightarrow: '→', leftarrow: '←', Rightarrow: '⇒', Leftarrow: '⇐', leftrightarrow: '↔', Leftrightarrow: '⇔', in: '∈', notin: '∉', subset: '⊂', subseteq: '⊆', cup: '∪', cap: '∩', forall: '∀', exists: '∃', emptyset: '∅', ldots: '…', cdots: '⋯', dots: '…', degree: '°',\n prime: '′', angle: '∠', perp: '⊥', parallel: '∥', neg: '¬', land: '∧', lor: '∨', circ: '∘', bullet: '•', star: '⋆', ',': ' ', ';': ' ', ':': ' ', '!': '', quad: ' ', qquad: ' ',\n};\nconst FUNCTIONS = new Set(['sin', 'cos', 'tan', 'cot', 'sec', 'csc', 'arcsin', 'arccos', 'arctan', 'sinh', 'cosh', 'tanh', 'log', 'ln', 'exp', 'det', 'max', 'min', 'gcd', 'lg', 'sup', 'inf', 'lim']);\nconst BLACKBOARD: Record<string, string> = { R: 'ℝ', N: 'ℕ', Z: 'ℤ', Q: 'ℚ', C: 'ℂ', P: 'ℙ' };\n\ntype Tok = { t: 'cmd' | 'ch' | '{' | '}' | '^' | '_' | '[' | ']'; v: string };\nclass Unsupported extends Error {}\n\nfunction tokenize(src: string): Tok[] {\n const out: Tok[] = [];\n for (let i = 0; i < src.length; i++) {\n const c = src[i];\n if (c === '\\\\') {\n const m = /^[A-Za-z]+/.exec(src.slice(i + 1));\n if (m) { out.push({ t: 'cmd', v: m[0] }); i += m[0].length; }\n else if (i + 1 < src.length) { out.push({ t: 'cmd', v: src[i + 1] }); i++; } // \\, \\; \\{ \\} \\\\\n } else if (c === '{' || c === '}' || c === '^' || c === '_' || c === '[' || c === ']') out.push({ t: c as Tok['t'], v: c });\n else if (!/\\s/.test(c)) out.push({ t: 'ch', v: c });\n }\n return out;\n}\n\n/**\n * Convert LaTeX to Word's native equation objects (fractions, roots, scripts, sums, integrals, limits, brackets, Greek letters\n * and common operators). Returns null when the formula uses something outside this subset (matrices, aligned environments,\n * custom macros), so the caller can fall back to the LaTeX text instead of writing a wrong equation.\n */\nexport function latexToDocx(tex: string): MathNode[] | null {\n let toks: Tok[];\n try { toks = tokenize(tex.slice(0, 5000)); } catch { return null; }\n let i = 0;\n let depth = 0; // nesting guard: a hostile formula must not overflow the stack\n const peek = () => toks[i];\n const run = (text: string) => new D.MathRun(text);\n\n const group = (): MathNode[] => {\n if (peek()?.t !== '{') { // a single token: x^2, \\frac12\n const a = atom();\n if (!a) throw new Unsupported(); // \"x^\" with nothing after it\n return [a];\n }\n i++;\n const out = sequence((t) => t.t === '}');\n if (peek()?.t !== '}') throw new Unsupported();\n i++;\n return out;\n };\n const optional = (): MathNode[] | null => {\n if (peek()?.t !== '[') return null;\n i++;\n const out = sequence((t) => t.t === ']');\n if (peek()?.t !== ']') throw new Unsupported();\n i++;\n return out;\n };\n const text = (): string => { // \\text{...}: raw characters up to the closing brace\n if (peek()?.t !== '{') throw new Unsupported();\n i++;\n let s = '';\n while (peek() && peek().t !== '}') { const t = toks[i++]; s += t.t === 'cmd' ? (SYMBOLS[t.v] ?? ` ${t.v}`) : t.v; }\n if (peek()?.t !== '}') throw new Unsupported();\n i++;\n return s;\n };\n\n /** One atom plus any ^ _ that follow it. */\n const withScripts = (base: MathNode[]): MathNode[] => {\n let sub: MathNode[] | null = null;\n let sup: MathNode[] | null = null;\n for (let n = 0; n < 2 && (peek()?.t === '^' || peek()?.t === '_'); n++) {\n const which = toks[i++].t;\n const arg = group();\n if (which === '^') sup = arg; else sub = arg;\n }\n if (sub && sup) return [new D.MathSubSuperScript({ children: base, subScript: sub, superScript: sup })];\n if (sup) return [new D.MathSuperScript({ children: base, superScript: sup })];\n if (sub) return [new D.MathSubScript({ children: base, subScript: sub })];\n return base;\n };\n\n const atom = (): MathNode | null => {\n if (++depth > 60) throw new Unsupported();\n try { return atomInner(); } finally { depth--; }\n };\n const atomInner = (): MathNode | null => {\n const t = toks[i];\n if (!t) return null;\n if (t.t === '{') return (i++, wrap(sequence((x) => x.t === '}', true)));\n if (t.t === 'ch') { i++; return run(t.v); }\n if (t.t === 'cmd') {\n i++;\n const c = t.v;\n if (c === 'frac' || c === 'dfrac' || c === 'tfrac') { const n = group(); const d = group(); return new D.MathFraction({ numerator: n, denominator: d }); }\n if (c === 'sqrt') { const deg = optional(); const body = group(); return new D.MathRadical(deg ? { children: body, degree: deg } : { children: body }); }\n if (c === 'text' || c === 'mathrm' || c === 'operatorname') return run(text());\n if (c === 'mathbb') { const s = text(); return run([...s].map((ch) => BLACKBOARD[ch] ?? ch).join('')); }\n if (c === 'left' || c === 'right') throw new Unsupported(); // handled in sequence()\n if (SYMBOLS[c] !== undefined) return run(SYMBOLS[c]);\n if (FUNCTIONS.has(c)) return run(c);\n if (['{', '}', '#', '%', '&', '$', '_'].includes(c)) return run(c);\n throw new Unsupported(); // \\begin, \\matrix, macros ...\n }\n throw new Unsupported(); // a stray ^ _ ] }\n };\n const wrap = (nodes: MathNode[]): MathNode => (nodes.length === 1 ? nodes[0] : new D.MathRoundBrackets({ children: nodes })); // only used for {…} used as one atom\n\n /** Words after \\sum / \\int / \\lim limits: the operand is the next atom with its scripts. */\n const operand = (): MathNode[] => {\n const a = atom();\n return a ? withScripts([a]) : [];\n };\n\n function sequence(stop: (t: Tok) => boolean, flatten = false): MathNode[] {\n if (++depth > 60) throw new Unsupported();\n try { return sequenceInner(stop, flatten); } finally { depth--; }\n }\n function sequenceInner(stop: (t: Tok) => boolean, flatten: boolean): MathNode[] {\n const out: MathNode[] = [];\n while (peek() && !stop(peek())) {\n const t = peek();\n if (t.t === 'cmd' && (t.v === 'sum' || t.v === 'int' || t.v === 'prod' || t.v === 'lim' || t.v === 'limits')) {\n i++;\n if (t.v === 'limits') continue;\n let sub: MathNode[] | undefined;\n let sup: MathNode[] | undefined;\n for (let n = 0; n < 2 && (peek()?.t === '^' || peek()?.t === '_'); n++) { const w = toks[i++].t; const g = group(); if (w === '^') sup = g; else sub = g; }\n if (t.v === 'lim') { out.push(new D.MathLimitLower({ children: [run('lim')], limit: sub ?? [] })); continue; }\n const body = operand();\n if (t.v === 'int') out.push(new D.MathIntegral({ children: body, subScript: sub, superScript: sup }));\n else out.push(new D.MathSum({ children: body, subScript: sub, superScript: sup })); // \\prod is written as a sum sign when Word lacks a product class\n continue;\n }\n if (t.t === 'cmd' && t.v === 'left') {\n i++;\n const open = toks[i++];\n const inner = sequence((x) => x.t === 'cmd' && x.v === 'right');\n i++; // \\right\n const close = toks[i++];\n if (!open || !close) throw new Unsupported();\n const o = open.v;\n out.push(o === '[' ? new D.MathSquareBrackets({ children: inner }) : o === '{' || (open.t === 'cmd' && open.v === '{') ? new D.MathCurlyBrackets({ children: inner }) : new D.MathRoundBrackets({ children: inner }));\n continue;\n }\n const a = atom();\n if (!a) break;\n out.push(...withScripts([a]));\n }\n return flatten && out.length === 1 ? out : out;\n }\n\n try {\n const result = sequence(() => false);\n return i >= toks.length && result.length ? result : null;\n } catch (e) {\n if (e instanceof Unsupported) return null;\n throw e;\n }\n}\n","/** Draw SVG markup to PNG bytes in the browser (no network, no external references). Null where there is no canvas or the SVG has no size. */\nexport async function rasterizeSVG(svg: string, scale = 2, maxSide = 4000): Promise<{ data: Uint8Array; width: number; height: number } | null> {\n try {\n // real browsers have createImageBitmap; environments without a canvas (tests, servers) skip drawing\n if (typeof document === 'undefined' || typeof createImageBitmap !== 'function') return null;\n const parsed = new DOMParser().parseFromString(svg, 'image/svg+xml');\n const root = parsed.documentElement;\n if (!root || root.nodeName.toLowerCase() !== 'svg' || parsed.querySelector('parsererror')) return null;\n const vb = root.getAttribute('viewBox')?.trim().split(/[\\s,]+/).map(Number);\n const attr = (n: string) => { const v = parseFloat(root.getAttribute(n) ?? ''); return Number.isFinite(v) && !(root.getAttribute(n) ?? '').includes('%') ? v : NaN; };\n let w = vb && vb.length === 4 ? vb[2] : attr('width');\n let h = vb && vb.length === 4 ? vb[3] : attr('height');\n if (!(w > 0) || !(h > 0)) return null;\n const k = Math.min(scale, maxSide / w, maxSide / h);\n root.setAttribute('xmlns', 'http://www.w3.org/2000/svg');\n root.setAttribute('width', String(w));\n root.setAttribute('height', String(h));\n root.removeAttribute('style');\n const xml = new XMLSerializer().serializeToString(root);\n const url = URL.createObjectURL(new Blob([xml], { type: 'image/svg+xml;charset=utf-8' }));\n try {\n const img = new Image();\n await new Promise<void>((ok, fail) => { const t = setTimeout(() => fail(new Error('svg timeout')), 10000); img.onload = () => (clearTimeout(t), ok()); img.onerror = () => (clearTimeout(t), fail(new Error('svg'))); img.src = url; });\n const pw = Math.max(1, Math.round(w * k));\n const ph = Math.max(1, Math.round(h * k));\n const canvas = Object.assign(document.createElement('canvas'), { width: pw, height: ph });\n const ctx = canvas.getContext('2d');\n if (!ctx) return null;\n ctx.fillStyle = '#fff'; // Word pages are white: a transparent background would show dark text on dark in some viewers\n ctx.fillRect(0, 0, pw, ph);\n ctx.drawImage(img, 0, 0, pw, ph);\n const blob = await new Promise<Blob | null>((r) => canvas.toBlob(r, 'image/png'));\n w = pw; h = ph;\n return blob ? { data: new Uint8Array(await blob.arrayBuffer()), width: w, height: h } : null;\n } finally {\n URL.revokeObjectURL(url);\n }\n } catch {\n return null;\n }\n}\n","/**\n * .docx import/export. Lives in its own entry point (`wysiwygido/docx`) so the `docx` and `mammoth`\n * libraries are only loaded by apps that need them.\n */\nimport * as D from 'docx';\nimport type { Mark, Node as PMNode } from 'prosemirror-model';\nimport { cropBytes, cropToString, type Crop } from './crop';\nimport { latexToDocx } from './latex-docx';\nimport { rasterizeSVG } from './svg-raster';\nimport { chartSVG, cleanChart } from './chart';\nimport type { Editor } from './editor';\nimport type { PageSettings } from './plugins/pages';\nimport type { CommentsPlugin, CommentThread } from './plugins/comments';\n\nexport interface ExportOptions {\n /** Include comments (defaults to the editor's Comments plugin store, if installed). */\n comments?: CommentThread[];\n /** Title in the document properties. */\n title?: string;\n /** Fetch remote images to embed them. Default true; failures fall back to the alt text. */\n fetchImages?: boolean;\n}\n\ninterface ImageData { data: Uint8Array; type: 'png' | 'jpg' | 'gif'; width: number; height: number }\n\nconst PX_TO_TWIP = 15;\nconst px = (n: number) => Math.round(n * PX_TO_TWIP);\nconst hex = (c: string) => c.replace('#', '').toUpperCase();\n\n/** Largest image (bytes) the exporter will embed or fetch, and the largest `.docx` the importer will open. */\nconst MAX_IMAGE_BYTES = 15 * 1024 * 1024;\nconst MAX_DOCX_BYTES = 50 * 1024 * 1024;\nconst MAX_DIMENSION = 20000;\n\n/** Read width/height and format from PNG, JPEG or GIF bytes. Null for unknown formats and for zero or absurd sizes. */\nexport function imageInfo(b: Uint8Array): { type: 'png' | 'jpg' | 'gif'; width: number; height: number } | null {\n const info = rawImageInfo(b);\n return info && info.width > 0 && info.height > 0 && info.width <= MAX_DIMENSION && info.height <= MAX_DIMENSION ? info : null;\n}\n\nfunction rawImageInfo(b: Uint8Array): { type: 'png' | 'jpg' | 'gif'; width: number; height: number } | null {\n if (b.length > 24 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) {\n const v = new DataView(b.buffer, b.byteOffset, b.byteLength);\n return { type: 'png', width: v.getUint32(16), height: v.getUint32(20) };\n }\n if (b.length > 10 && b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46) {\n return { type: 'gif', width: b[6] | (b[7] << 8), height: b[8] | (b[9] << 8) };\n }\n if (b.length > 4 && b[0] === 0xff && b[1] === 0xd8) {\n let i = 2;\n while (i + 9 < b.length) {\n if (b[i] !== 0xff) { i++; continue; }\n const marker = b[i + 1];\n if (marker >= 0xc0 && marker <= 0xcf && ![0xc4, 0xc8, 0xcc].includes(marker)) {\n return { type: 'jpg', height: (b[i + 5] << 8) | b[i + 6], width: (b[i + 7] << 8) | b[i + 8] };\n }\n i += 2 + ((b[i + 2] << 8) | b[i + 3]);\n }\n }\n return null;\n}\n\n/** Read a response body, giving up (null) as soon as it exceeds `max` bytes, whatever Content-Length claimed. */\nasync function readCapped(res: Response, max: number): Promise<Uint8Array | null> {\n if (!res.body) {\n const buf = new Uint8Array(await res.arrayBuffer());\n return buf.length > max ? null : buf;\n }\n const reader = res.body.getReader();\n const chunks: Uint8Array[] = [];\n let total = 0;\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n total += value.length;\n if (total > max) { await reader.cancel(); return null; }\n chunks.push(value);\n }\n const out = new Uint8Array(total);\n let at = 0;\n for (const c of chunks) { out.set(c, at); at += c.length; }\n return out;\n}\n\nasync function loadImage(src: string, fetchRemote: boolean): Promise<ImageData | null> {\n try {\n let bytes: Uint8Array;\n if (src.startsWith('data:')) {\n const comma = src.indexOf(',');\n if (comma < 0 || !/;base64$/i.test(src.slice(0, comma))) return null;\n if (src.length - comma > MAX_IMAGE_BYTES * 1.4) return null; // base64 is ~4/3 of the bytes\n const bin = atob(src.slice(comma + 1));\n bytes = Uint8Array.from(bin, (c) => c.charCodeAt(0));\n } else if (fetchRemote && /^https?:/i.test(src)) {\n const res = await fetch(src, { signal: AbortSignal.timeout(15000), credentials: 'omit', referrerPolicy: 'no-referrer' });\n if (!res.ok) return null;\n const declared = Number(res.headers.get('content-length'));\n if (declared > MAX_IMAGE_BYTES) return null;\n const body = await readCapped(res, MAX_IMAGE_BYTES);\n if (!body) return null;\n bytes = body;\n } else return null;\n const info = imageInfo(bytes);\n return info ? { data: bytes, ...info } : null;\n } catch {\n return null;\n }\n}\n\nconst imageKey = (attrs: { src: string; crop?: Crop | null }) => (attrs.crop ? `${attrs.src}|${cropToString(attrs.crop)}` : attrs.src);\n\nfunction collectImages(doc: PMNode): { key: string; src: string; crop: Crop | null }[] {\n const out = new Map<string, { key: string; src: string; crop: Crop | null }>();\n doc.descendants((n) => {\n if (n.type.name === 'cover_page') {\n const key = imageKey({ src: n.attrs.src });\n out.set(key, { key, src: n.attrs.src, crop: null });\n return;\n }\n if (n.type.name !== 'image') return;\n const key = imageKey(n.attrs as { src: string; crop?: Crop | null });\n out.set(key, { key, src: n.attrs.src, crop: n.attrs.crop ?? null });\n });\n return [...out.values()];\n}\n\ninterface Ctx {\n images: Map<string, ImageData | null>;\n /** Mermaid diagrams drawn to PNG, by source. */\n diagrams: Map<string, ImageData | null>;\n footnotes: Record<number, { children: D.Paragraph[] }>;\n numbering: D.ILevelsOptions[][];\n numberingRefs: string[];\n revision: number;\n author: string;\n commentIds: Map<string, number>;\n referenced: Set<string>;\n quote: number;\n /** Page size in px, for the cover picture. */\n pageSize: { w: number; h: number };\n}\n\nconst ALIGN: Record<string, (typeof D.AlignmentType)[keyof typeof D.AlignmentType]> = {\n left: D.AlignmentType.LEFT,\n center: D.AlignmentType.CENTER,\n right: D.AlignmentType.RIGHT,\n justify: D.AlignmentType.JUSTIFIED,\n};\n\ntype ListFormat = 'decimal' | 'lowerLetter' | 'upperLetter' | 'lowerRoman' | 'upperRoman' | 'bullet';\nconst FORMATS: Record<ListFormat, (typeof D.LevelFormat)[keyof typeof D.LevelFormat]> = { decimal: D.LevelFormat.DECIMAL, lowerLetter: D.LevelFormat.LOWER_LETTER, upperLetter: D.LevelFormat.UPPER_LETTER, lowerRoman: D.LevelFormat.LOWER_ROMAN, upperRoman: D.LevelFormat.UPPER_ROMAN, bullet: D.LevelFormat.BULLET };\nconst TYPE_FORMAT: Record<string, ListFormat> = { '1': 'decimal', a: 'lowerLetter', A: 'upperLetter', i: 'lowerRoman', I: 'upperRoman' };\n\nfunction levels(format: ListFormat, text?: string, start = 1): D.ILevelsOptions[] {\n return Array.from({ length: 9 }, (_, level) => ({\n level,\n format: FORMATS[format],\n start: format === 'bullet' ? undefined : start,\n text: format !== 'bullet' ? `%${level + 1}.` : text ?? (level % 2 ? '◦' : '•'),\n alignment: D.AlignmentType.START,\n style: { paragraph: { indent: { left: 720 * (level + 1), hanging: 360 } } },\n }));\n}\n\nfunction newNumbering(ctx: Ctx, format: ListFormat, text?: string, start = 1): string {\n const ref = `list-${ctx.numberingRefs.length}`;\n ctx.numberingRefs.push(ref);\n ctx.numbering.push(levels(format, text, start));\n return ref;\n}\n\nfunction runOptions(marks: readonly Mark[]) {\n const o: Record<string, unknown> = {};\n let link: string | null = null;\n let revision: 'insertion' | 'deletion' | null = null;\n for (const m of marks) {\n switch (m.type.name) {\n case 'bold': o.bold = true; break;\n case 'italic': o.italics = true; break;\n case 'underline': o.underline = {}; break;\n case 'strike': o.strike = true; break;\n case 'code': o.font = 'Courier New'; o.shading = { type: D.ShadingType.CLEAR, fill: 'F0F0F0', color: 'auto' }; break;\n case 'text_color': o.color = hex(m.attrs.color); break;\n case 'highlight': o.shading = { type: D.ShadingType.CLEAR, fill: hex(m.attrs.color), color: 'auto' }; break;\n case 'font_family': o.font = m.attrs.value; break;\n case 'font_size': o.size = Math.round(Number(m.attrs.value) * 1.5); break; // px -> half-points\n case 'link': link = m.attrs.href; o.color ??= '1D4ED8'; o.underline ??= {}; break;\n case 'insertion': revision = 'insertion'; break;\n case 'deletion': revision = 'deletion'; break;\n }\n }\n return { o, link, revision };\n}\n\nfunction footnoteText(ctx: Ctx, text: string): number {\n const id = Object.keys(ctx.footnotes).length + 1;\n ctx.footnotes[id] = { children: [new D.Paragraph({ children: [new D.TextRun(text)] })] };\n return id;\n}\n\nfunction inlineChildren(node: PMNode, ctx: Ctx): D.ParagraphChild[] {\n const out: D.ParagraphChild[] = [];\n // Comment ranges: open before the first run carrying a comment, close after the last one in this paragraph.\n const lastIndexOf = new Map<string, number>();\n node.forEach((child, _o, i) => child.marks.forEach((m) => m.type.name === 'comment' && lastIndexOf.set(m.attrs.id, i)));\n const open = new Set<string>();\n\n node.forEach((child, _offset, index) => {\n const ids = child.marks.filter((m) => m.type.name === 'comment').map((m) => m.attrs.id as string);\n for (const id of ids) {\n if (!open.has(id) && ctx.commentIds.has(id)) {\n open.add(id);\n out.push(new D.CommentRangeStart(ctx.commentIds.get(id)!));\n }\n }\n\n const { o, link, revision } = runOptions(child.marks);\n let run: D.ParagraphChild | null = null;\n if (child.isText) {\n const text = child.text!;\n if (revision === 'insertion') run = new D.InsertedTextRun({ id: ctx.revision++, author: ctx.author, date: new Date().toISOString(), text, ...o });\n else if (revision === 'deletion') run = new D.DeletedTextRun({ id: ctx.revision++, author: ctx.author, date: new Date().toISOString(), text, ...o });\n else run = new D.TextRun({ text, ...o });\n } else if (child.type.name === 'mention') {\n run = new D.TextRun({ text: `@${child.attrs.label}`, color: '1D4ED8', ...o });\n } else if (child.type.name === 'math_inline') {\n const eq = latexToDocx(child.attrs.tex); // a native Word equation; the LaTeX text when the formula is outside what we convert\n run = eq ? (new D.Math({ children: eq }) as unknown as D.ParagraphChild) : new D.TextRun({ text: child.attrs.tex, font: 'Cambria Math', italics: true, ...o });\n } else if (child.type.name === 'xref') {\n run = new D.TextRun({ text: String(child.attrs.text), ...o });\n } else if (child.type.name === 'form_field') {\n const a = child.attrs;\n run = new D.TextRun({ text: `${a.label ? `${a.label}: ` : ''}${a.kind === 'checkbox' ? (a.value === 'true' ? '☒' : '☐') : a.value || '________'}`, underline: a.kind === 'checkbox' ? undefined : {}, ...o });\n } else if (child.type.name === 'attachment') {\n run = new D.TextRun({ text: `[${child.attrs.name}]`, color: '1D4ED8', ...o });\n } else if (child.type.name === 'hard_break') {\n run = new D.TextRun({ break: 1 });\n } else if (child.type.name === 'footnote') {\n run = new D.FootnoteReferenceRun(footnoteText(ctx, child.attrs.text));\n } else if (child.type.name === 'image') {\n const img = ctx.images.get(imageKey(child.attrs as { src: string; crop?: Crop | null }));\n if (img) {\n const w = child.attrs.width ?? Math.min(img.width, 600);\n run = new D.ImageRun({\n type: img.type,\n data: img.data,\n transformation: { width: w, height: Math.max(1, Math.round((w * img.height) / img.width)) },\n altText: { name: 'image', title: child.attrs.alt ?? 'image', description: child.attrs.alt ?? '' },\n });\n } else run = new D.TextRun({ text: child.attrs.alt ? `[${child.attrs.alt}]` : '[image]', italics: true });\n }\n if (run) out.push(link ? new D.ExternalHyperlink({ link, children: [run as D.TextRun] }) : run);\n\n for (const id of ids) {\n if (open.has(id) && lastIndexOf.get(id) === index) {\n open.delete(id);\n const n = ctx.commentIds.get(id)!;\n out.push(new D.CommentRangeEnd(n));\n if (!ctx.referenced.has(id)) {\n ctx.referenced.add(id);\n out.push(new D.TextRun({ children: [new D.CommentReference(n)] }));\n }\n }\n }\n });\n return out;\n}\n\nfunction paragraphOptions(node: PMNode, ctx: Ctx) {\n const o: Record<string, unknown> = {};\n if (node.attrs.align && ALIGN[node.attrs.align]) o.alignment = ALIGN[node.attrs.align];\n if (node.attrs.lineHeight) o.spacing = { line: Math.round(Number(node.attrs.lineHeight) * 240), lineRule: D.LineRuleType.AUTO };\n if (ctx.quote) {\n o.indent = { left: 720 * ctx.quote };\n o.border = { left: { style: D.BorderStyle.SINGLE, size: 12, color: 'D4D4D4', space: 8 } };\n }\n return o;\n}\n\ntype Block = D.Paragraph | D.Table | D.TableOfContents;\n\nfunction listBlocks(list: PMNode, ctx: Ctx, depth: number): Block[] {\n const out: Block[] = [];\n const name = list.type.name;\n const ref = name === 'ordered_list' ? newNumbering(ctx, TYPE_FORMAT[list.attrs.type] ?? 'decimal', undefined, Math.max(1, Number(list.attrs.order) || 1)) : name === 'bullet_list' ? newNumbering(ctx, 'bullet') : null;\n list.forEach((item) => {\n let first = true;\n const taskRef = name === 'task_list' ? newNumbering(ctx, 'bullet', item.attrs.checked ? '☑' : '☐') : null;\n item.forEach((child) => {\n if (child.type.name === 'paragraph' && first) {\n out.push(new D.Paragraph({ children: inlineChildren(child, ctx), numbering: { reference: (ref ?? taskRef)!, level: depth }, ...paragraphOptions(child, ctx) }));\n } else if (/_list$/.test(child.type.name)) {\n out.push(...listBlocks(child, ctx, depth + 1));\n } else {\n out.push(...blocks(child, ctx).map((b) => b));\n }\n first = false;\n });\n });\n return out;\n}\n\nfunction tableBlock(table: PMNode, ctx: Ctx): D.Table {\n const rows: D.TableRow[] = [];\n table.forEach((row) => {\n const cells: D.TableCell[] = [];\n let header = true;\n row.forEach((cell) => {\n if (cell.type.name !== 'table_header') header = false;\n const children: Block[] = [];\n cell.forEach((c) => children.push(...blocks(c, ctx)));\n if (!children.length) children.push(new D.Paragraph(''));\n const bg = cell.attrs.background as string | null;\n cells.push(\n new D.TableCell({\n children: children as D.Paragraph[],\n columnSpan: cell.attrs.colspan > 1 ? cell.attrs.colspan : undefined,\n rowSpan: cell.attrs.rowspan > 1 ? cell.attrs.rowspan : undefined,\n shading: bg ? { type: D.ShadingType.CLEAR, fill: hex(bg), color: 'auto' } : undefined,\n }),\n );\n });\n rows.push(new D.TableRow({ children: cells, tableHeader: header }));\n });\n return new D.Table({ rows, width: { size: 100, type: D.WidthType.PERCENTAGE } });\n}\n\nfunction blocks(node: PMNode, ctx: Ctx): Block[] {\n switch (node.type.name) {\n case 'paragraph':\n return [new D.Paragraph({ children: inlineChildren(node, ctx), ...paragraphOptions(node, ctx) })];\n case 'heading':\n return [new D.Paragraph({ heading: D.HeadingLevel[`HEADING_${Math.min(6, node.attrs.level)}` as 'HEADING_1'], children: inlineChildren(node, ctx), ...paragraphOptions(node, ctx) })];\n case 'bullet_list':\n case 'ordered_list':\n case 'task_list':\n return listBlocks(node, ctx, 0);\n case 'locked_section':\n case 'editable_region': {\n // Locking is an editing concern; in Word the content is simply part of the document.\n const out: Block[] = [];\n node.forEach((c) => out.push(...blocks(c, ctx)));\n return out;\n }\n case 'blockquote': {\n ctx.quote++;\n const out: Block[] = [];\n node.forEach((c) => out.push(...blocks(c, ctx)));\n ctx.quote--;\n return out;\n }\n case 'code_block':\n return node.textContent.split('\\n').map((line) => new D.Paragraph({ children: [new D.TextRun({ text: line, font: 'Courier New', size: 20 })], shading: { type: D.ShadingType.CLEAR, fill: 'F0F0F0', color: 'auto' } }));\n case 'clip':\n return [new D.Paragraph({ children: [new D.TextRun({ text: `${node.attrs.kind === 'video' ? 'Screen' : 'Audio'} recording: `, color: '6B7280' }), ...(/^https?:/i.test(String(node.attrs.src)) ? [new D.ExternalHyperlink({ link: String(node.attrs.src), children: [new D.TextRun({ text: String(node.attrs.name || node.attrs.src), style: 'Hyperlink', color: '1D4ED8', underline: {} })] })] : [new D.TextRun({ text: String(node.attrs.name || '(embedded in the online document)') })])] })];\n case 'chart': {\n const png = ctx.diagrams.get(`chart:${node.attrs.spec}`);\n const spec = cleanChart(node.attrs.spec);\n if (png) {\n const w = Math.min(png.width / 2, 520);\n return [new D.Paragraph({ alignment: D.AlignmentType.CENTER, spacing: { before: 120, after: 120 }, children: [new D.ImageRun({ type: 'png', data: png.data, transformation: { width: w, height: Math.max(1, Math.round((w * png.height) / png.width)) }, altText: { name: 'chart', title: spec?.title || 'Chart', description: spec ? `${spec.type} chart: ${spec.labels.join(', ')}` : 'Chart' } })] })];\n }\n return spec ? [new D.Paragraph({ children: [new D.TextRun({ text: `Chart: ${spec.title || spec.type}`, italics: true, color: '6B7280' })] })] : [];\n }\n case 'column_break':\n return [new D.Paragraph({ children: [new D.ColumnBreak()] })];\n case 'columns': {\n const out: Block[] = [];\n node.forEach((c) => out.push(...blocks(c, ctx)));\n return out;\n }\n case 'caption': {\n const label = String(node.attrs.kind).replace(/^./, (c: string) => c.toUpperCase());\n return [new D.Paragraph({ spacing: { before: 60, after: 160 }, children: [new D.TextRun({ text: `${label} ${node.attrs.n}. `, bold: true, italics: true, size: 20 }), ...inlineChildren(node, ctx)] })];\n }\n case 'caption_list': {\n let items: { n: number; text: string }[] = [];\n try { items = JSON.parse(node.attrs.items); } catch { /* none */ }\n const label = String(node.attrs.kind).replace(/^./, (c: string) => c.toUpperCase());\n return [new D.Paragraph({ children: [new D.TextRun({ text: `List of ${label.toLowerCase()}s`, bold: true })] }), ...items.map((it) => new D.Paragraph({ children: [new D.TextRun({ text: `${label} ${it.n}. ${it.text}` })] }))];\n }\n case 'embed':\n return [new D.Paragraph({ children: [new D.TextRun({ text: 'Media: ', color: '6B7280' }), new D.ExternalHyperlink({ link: String(node.attrs.url), children: [new D.TextRun({ text: String(node.attrs.url), style: 'Hyperlink', color: '1D4ED8', underline: {} })] })] })];\n case 'math_block': {\n const eq = latexToDocx(node.attrs.tex);\n return [new D.Paragraph({ alignment: D.AlignmentType.CENTER, spacing: { before: 120, after: 120 }, children: eq ? [new D.Math({ children: eq }) as unknown as D.ParagraphChild] : [new D.TextRun({ text: node.attrs.tex, font: 'Cambria Math', italics: true })] })];\n }\n case 'mermaid_diagram': {\n const png = ctx.diagrams.get(node.attrs.code);\n if (png) {\n const w = Math.min(png.width / 2, 600); // drawn at 2x for sharpness\n return [new D.Paragraph({ alignment: D.AlignmentType.CENTER, spacing: { before: 120, after: 120 }, children: [new D.ImageRun({ type: 'png', data: png.data, transformation: { width: w, height: Math.max(1, Math.round((w * png.height) / png.width)) }, altText: { name: 'diagram', title: 'Diagram', description: String(node.attrs.code).slice(0, 200) } })] })];\n }\n // no canvas (or an invalid diagram): keep the source, clearly labelled\n return [\n new D.Paragraph({ children: [new D.TextRun({ text: 'Diagram (Mermaid source)', italics: true, color: '6B7280', size: 18 })] }),\n ...String(node.attrs.code).split('\\n').map((line) => new D.Paragraph({ children: [new D.TextRun({ text: line, font: 'Courier New', size: 20 })], shading: { type: D.ShadingType.CLEAR, fill: 'F0F0F0', color: 'auto' } })),\n ];\n }\n case 'horizontal_rule':\n return [new D.Paragraph({ border: { bottom: { style: D.BorderStyle.SINGLE, size: 6, color: '999999', space: 1 } } })];\n case 'cover_page': {\n const img = ctx.images.get(imageKey({ src: node.attrs.src }));\n const after = new D.Paragraph({ children: [new D.PageBreak()] });\n if (!img) return [after];\n // anchored to the page itself, so the picture runs edge to edge whatever the margins are\n const run = new D.ImageRun({\n type: img.type,\n data: img.data,\n transformation: { width: ctx.pageSize.w, height: ctx.pageSize.h },\n floating: { horizontalPosition: { relative: D.HorizontalPositionRelativeFrom.PAGE, offset: 0 }, verticalPosition: { relative: D.VerticalPositionRelativeFrom.PAGE, offset: 0 }, behindDocument: true, allowOverlap: true },\n altText: { name: 'cover', title: 'Cover', description: String(node.attrs.alt || 'Cover page') },\n });\n return [new D.Paragraph({ children: [run] }), after];\n }\n case 'page_break':\n return [new D.Paragraph({ children: [new D.PageBreak()] })];\n case 'toc':\n return [new D.TableOfContents('Table of Contents', { hyperlink: true, headingStyleRange: '1-4' })];\n case 'table':\n return [tableBlock(node, ctx), new D.Paragraph('')]; // Word needs a paragraph after a table\n default:\n return node.isTextblock ? [new D.Paragraph({ children: inlineChildren(node, ctx) })] : [];\n }\n}\n\nfunction headerFooterParagraph(template: string): D.Paragraph {\n const parts = template.split(/(\\{page\\}|\\{pages\\})/);\n const run: (string | (typeof D.PageNumber)[keyof typeof D.PageNumber])[] = parts\n .filter(Boolean)\n .map((p) => (p === '{page}' ? D.PageNumber.CURRENT : p === '{pages}' ? D.PageNumber.TOTAL_PAGES : p));\n return new D.Paragraph({ alignment: D.AlignmentType.CENTER, children: [new D.TextRun({ children: run, color: '9CA3AF', size: 18 })] });\n}\n\n/** Build a docx `Document` from the editor's content, page setup, footnotes, comments and tracked changes. */\nexport async function buildDocx(editor: Editor, options: ExportOptions = {}): Promise<D.Document> {\n const doc = editor.view.state.doc;\n const page = (editor.extensions.pageSettings as (() => PageSettings) | undefined)?.();\n const store = (editor.config.plugins.find((p) => p.name === 'comments') as CommentsPlugin | undefined)?.store;\n const threads = options.comments ?? store?.list() ?? [];\n const used = new Set<string>();\n doc.descendants((n) => void n.marks.forEach((m) => m.type.name === 'comment' && used.add(m.attrs.id)));\n const exported = threads.filter((t) => used.has(t.id));\n\n const images = new Map<string, ImageData | null>();\n await Promise.all(\n collectImages(doc).map(async ({ key, src, crop }) => {\n let img = await loadImage(src, options.fetchImages !== false);\n if (img && crop) {\n // Word needs the cropped pixels; render them with canvas. Without canvas the full image is exported.\n const cropped = await cropBytes(img.data, crop);\n if (cropped) img = { data: cropped.data, type: 'png', width: cropped.width, height: cropped.height };\n }\n images.set(key, img);\n }),\n );\n\n // Diagrams: render each Mermaid source to SVG with the editor's plugin, then to PNG (needs a browser canvas).\n const diagrams = new Map<string, ImageData | null>();\n const renderSVG = (editor.extensions.mermaid as { renderSVG?: (code: string, dark?: boolean) => Promise<string> } | undefined)?.renderSVG;\n const codes = new Set<string>();\n const codesCharts = new Set<string>();\n doc.descendants((n) => void (n.type.name === 'mermaid_diagram' && codes.add(n.attrs.code)));\n if (renderSVG) {\n await Promise.all([...codes].map(async (code) => {\n try {\n const png = await rasterizeSVG(await renderSVG(code, false));\n diagrams.set(code, png ? { data: png.data, type: 'png', width: png.width, height: png.height } : null);\n } catch {\n diagrams.set(code, null); // an invalid diagram: its source is written instead\n }\n }));\n }\n\n // Charts: the SVG is drawn from the data here, then rasterised like a diagram\n doc.descendants((n) => {\n if (n.type.name === 'chart') codesCharts.add(String(n.attrs.spec));\n });\n await Promise.all([...codesCharts].map(async (raw) => {\n const spec = cleanChart(raw);\n const png = spec ? await rasterizeSVG(chartSVG(spec)) : null;\n diagrams.set(`chart:${raw}`, png ? { data: png.data, type: 'png', width: png.width, height: png.height } : null);\n }));\n\n const ctx: Ctx = {\n images,\n diagrams,\n footnotes: {},\n numbering: [],\n numberingRefs: [],\n revision: 1,\n author: 'Author',\n commentIds: new Map(exported.map((t, i) => [t.id, i])),\n referenced: new Set(),\n quote: 0,\n pageSize: { w: page?.width ?? 794, h: page?.height ?? 1123 },\n };\n // Top-level `columns` blocks become their own continuous Word sections with the right column count; the text around them is single-column.\n type Segment = { count: number; gap: number; rule: boolean; children: Block[] };\n const segments: Segment[] = [];\n doc.forEach((n) => {\n if (n.type.name === 'columns') {\n const kids: Block[] = [];\n n.forEach((c) => kids.push(...blocks(c, ctx)));\n if (kids.length) segments.push({ count: Number(n.attrs.count) || 2, gap: Number(n.attrs.gap) || 28, rule: n.attrs.rule === 'solid', children: kids });\n return;\n }\n const last = segments[segments.length - 1];\n const out = blocks(n, ctx);\n if (last && last.count === 1) last.children.push(...out);\n else segments.push({ count: 1, gap: 0, rule: false, children: out });\n });\n if (!segments.some((s) => s.children.length)) segments.splice(0, segments.length, { count: 1, gap: 0, rule: false, children: [new D.Paragraph('')] });\n\n const w = page?.width ?? 794;\n const h = page?.height ?? 1123;\n const landscape = page?.orientation === 'landscape';\n const m = page?.margins ?? { top: 96, right: 96, bottom: 96, left: 96 };\n const headerTpl = page?.header ?? '';\n const footerTpl = page ? page.footer : '';\n\n return new D.Document({\n creator: 'wysiwygido',\n title: options.title,\n features: { updateFields: doc.content.content.some((n) => n.type.name === 'toc') },\n numbering: { config: ctx.numbering.map((lv, i) => ({ reference: ctx.numberingRefs[i], levels: lv })) },\n footnotes: ctx.footnotes,\n comments: {\n children: exported.map((t, i) => ({\n id: i,\n author: t.author,\n date: new Date(t.createdAt),\n children: [t.text, ...t.replies.map((r) => `${r.author}: ${r.text}`)].map((text) => new D.Paragraph(text)),\n })),\n },\n sections: segments.map((seg, i) => ({\n properties: {\n ...(i === 0 ? { titlePage: page?.differentFirstPage } : { type: D.SectionType.CONTINUOUS }),\n ...(seg.count > 1 ? { column: { count: seg.count, space: seg.gap * 15, separate: seg.rule, equalWidth: true } } : {}),\n page: {\n size: { width: px(Math.min(w, h)), height: px(Math.max(w, h)), orientation: landscape ? D.PageOrientation.LANDSCAPE : D.PageOrientation.PORTRAIT },\n margin: { top: px(m.top), right: px(m.right), bottom: px(m.bottom), left: px(m.left) },\n },\n },\n // headers and footers belong to the first section; later continuous sections carry on with them\n ...(i === 0\n ? {\n headers: {\n default: new D.Header({ children: [headerFooterParagraph(headerTpl)] }),\n ...(page?.differentFirstPage ? { first: new D.Header({ children: [headerFooterParagraph(page.firstHeader)] }) } : {}),\n },\n footers: {\n default: new D.Footer({ children: [headerFooterParagraph(footerTpl)] }),\n ...(page?.differentFirstPage ? { first: new D.Footer({ children: [headerFooterParagraph(page.firstFooter)] }) } : {}),\n },\n }\n : {}),\n children: (seg.children.length ? seg.children : [new D.Paragraph('')]) as D.Paragraph[],\n })),\n });\n}\n\n/** Export the document as a .docx `Blob`. */\nexport async function exportDocx(editor: Editor, options: ExportOptions = {}): Promise<Blob> {\n return D.Packer.toBlob(await buildDocx(editor, options));\n}\n\nfunction blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {\n if (typeof blob.arrayBuffer === 'function') return blob.arrayBuffer();\n return new Promise((resolve, reject) => {\n const r = new FileReader();\n r.onload = () => resolve(r.result as ArrayBuffer);\n r.onerror = () => reject(r.error);\n r.readAsArrayBuffer(blob);\n });\n}\n\n/** Replace the editor content with a .docx file's content (undoable). Returns mammoth's conversion warnings. */\nexport async function importDocx(editor: Editor, source: Blob | ArrayBuffer): Promise<string[]> {\n const mammoth = (await import('mammoth')).default ?? (await import('mammoth'));\n const size = source instanceof ArrayBuffer ? source.byteLength : source.size;\n if (size > MAX_DOCX_BYTES) throw new Error(`The .docx file is too large (${Math.round(size / 1048576)} MB; the limit is ${MAX_DOCX_BYTES / 1048576} MB).`);\n const arrayBuffer = source instanceof ArrayBuffer ? source : await blobToArrayBuffer(source);\n // mammoth's browser build reads `arrayBuffer`, its Node build reads `buffer`; pass what the runtime has.\n const input = { arrayBuffer, ...(typeof Buffer !== 'undefined' ? { buffer: Buffer.from(arrayBuffer) } : {}) };\n const result = await mammoth.convertToHtml(\n input as { arrayBuffer: ArrayBuffer },\n { styleMap: ['u => u', 'strike => s', \"p[style-name='Quote'] => blockquote:fresh\"] },\n );\n editor.replaceHTML(result.value);\n return result.messages.map((m: { message: string }) => m.message);\n}\n"],"mappings":";;;AAKA,IAAM,UAAkC;CACtC,OAAO;CAAK,MAAM;CAAK,OAAO;CAAK,OAAO;CAAK,SAAS;CAAK,YAAY;CAAK,MAAM;CAAK,KAAK;CAAK,OAAO;CAAK,UAAU;CAAK,MAAM;CAAK,OAAO;CAAK,QAAQ;CAAK,IAAI;CAAK,IAAI;CAAK,IAAI;CAAK,IAAI;CAAK,KAAK;CAAK,OAAO;CAAK,KAAK;CAAK,SAAS;CAAK,KAAK;CAAK,QAAQ;CAAK,KAAK;CAAK,KAAK;CAAK,OAAO;CACtS,OAAO;CAAK,OAAO;CAAK,OAAO;CAAK,QAAQ;CAAK,IAAI;CAAK,IAAI;CAAK,OAAO;CAAK,KAAK;CAAK,KAAK;CAAK,OAAO;CAC1G,IAAI;CAAK,IAAI;CAAK,OAAO;CAAK,MAAM;CAAK,KAAK;CAAK,IAAI;CAAK,KAAK;CAAK,IAAI;CAAK,KAAK;CAAK,IAAI;CAAK,KAAK;CAAK,QAAQ;CAAK,OAAO;CAAK,KAAK;CAAK,QAAQ;CAAK,OAAO;CAAK,SAAS;CAAK,OAAO;CAC7L,IAAI;CAAK,YAAY;CAAK,WAAW;CAAK,YAAY;CAAK,WAAW;CAAK,gBAAgB;CAAK,gBAAgB;CAAK,IAAI;CAAK,OAAO;CAAK,QAAQ;CAAK,UAAU;CAAK,KAAK;CAAK,KAAK;CAAK,QAAQ;CAAK,QAAQ;CAAK,UAAU;CAAK,OAAO;CAAK,OAAO;CAAK,MAAM;CAAK,QAAQ;CAC9Q,OAAO;CAAK,OAAO;CAAK,MAAM;CAAK,UAAU;CAAK,KAAK;CAAK,MAAM;CAAK,KAAK;CAAK,MAAM;CAA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AM,gCAAgC,KAAK,MAAM,OAAO,OAAO,EAAE,oBAAoB,iBAAiB,QAAQ,MAAM;CACzJ,MAAM,cAAc,kBAAkB,cAAc,SAAS,MAAM,kBAAkB,MAAM;CAE3F,MAAM,QAAQ;EAAE;EAAa,GAAI,OAAO,WAAW,cAAc,EAAE,QAAQ,OAAO,KAAK,WAAW,EAAE,IAAI,CAAC;CAAG;CAC5G,MAAM,SAAS,MAAM,QAAQ,cAC3B,OACA,EAAE,UAAU;EAAC;EAAU;EAAe;CAA2C,EAAE,CACrF;CACA,OAAO,YAAY,OAAO,KAAK;CAC/B,OAAO,OAAO,SAAS,KAAK,MAA2B,EAAE,OAAO;AAClE"}
package/dist/element.d.ts CHANGED
@@ -16,7 +16,7 @@ export interface WysiwygElement extends HTMLElement {
16
16
  *
17
17
  * <wysiwyg-editor value="<p>Hello</p>" ribbon paged theme="dark" name="body"></wysiwyg-editor>
18
18
  *
19
- * Attributes: `value`, `readonly`, `theme` (light | dark | auto), `placeholder`, `locale`, `ribbon`, `paged` (A4 pages with a ruler),
19
+ * Attributes: `value`, `readonly`, `theme` (light | dark | auto, or the name of a colour theme such as sepia), `placeholder`, `locale`, `ribbon`, `paged` (A4 pages with a ruler),
20
20
  * `outline`, `name` (the HTML is submitted with a surrounding form under this name). Properties: `value`, `readOnly`, `plugins`, `config`,
21
21
  * `editor`. Events: `editor-ready` and `editor-change` (`detail.html`). Load the stylesheet (`wysiwygido/style.css`) in the page:
22
22
  * the element renders in the light DOM so the document can be styled and printed like any other content.
@@ -0,0 +1,6 @@
1
+ import type { EditorPlugin } from '../types.js';
2
+ /**
3
+ * A cover page: one picture that fills the whole first page, edge to edge, followed by a page break. Add it from the Layout or Insert
4
+ * tab (Cover Page), by uploading a picture or giving its address. There is at most one, and it is always the first thing in the document.
5
+ */
6
+ export declare const Cover: EditorPlugin;
@@ -5,6 +5,9 @@ export { List } from './list.js';
5
5
  export { Blocks } from './blocks.js';
6
6
  export { Link } from './link.js';
7
7
  export { Image } from './image.js';
8
+ export { Cover } from './cover.js';
9
+ export { TextCase, applyCase, convertCase, CASE_ITEMS } from './text-case.js';
10
+ export type { CaseKind } from './text-case.js';
8
11
  export { ContextMenu, buildContextMenu, tidyEntries } from './context-menu.js';
9
12
  export type { ContextMenuOptions } from './context-menu.js';
10
13
  export { Table } from './table.js';
@@ -89,3 +92,5 @@ export { Recording, isSafeClip } from './recording.js';
89
92
  export type { RecordingOptions } from './recording.js';
90
93
  export { PdfEpub } from './pdf-epub.js';
91
94
  export type { PdfEpubOptions } from './pdf-epub.js';
95
+ export { Themes, defaultThemes, themeVars } from './themes.js';
96
+ export type { Theme, ThemePalette, ThemesOptions, ThemeApi } from './themes.js';
@@ -0,0 +1,16 @@
1
+ import { type EditorState, type Transaction } from 'prosemirror-state';
2
+ import type { EditorPlugin } from '../types.js';
3
+ export type CaseKind = 'upper' | 'lower' | 'title' | 'sentence' | 'toggle' | 'snake' | 'camel' | 'pascal' | 'kebab';
4
+ /** Convert a piece of text. Pure, so it is easy to test and reuse. */
5
+ export declare function convertCase(text: string, kind: CaseKind): string;
6
+ /** Change the case of the selected text (or of the word at the caret). Returns false when there is nothing to change. */
7
+ export declare function applyCase(state: EditorState, kind: CaseKind): Transaction | null;
8
+ export declare const CASE_ITEMS: {
9
+ kind: CaseKind;
10
+ command: string;
11
+ label: string;
12
+ key?: string;
13
+ sample: string;
14
+ }[];
15
+ /** Change case: UPPERCASE, lowercase, Title Case, Sentence case, tOGGLE, snake_case, camelCase, PascalCase and kebab-case. Shift+F3 cycles through the first four, as in Word. */
16
+ export declare const TextCase: EditorPlugin;
@@ -0,0 +1,54 @@
1
+ import type { EditorPlugin } from '../types.js';
2
+ /** A colour theme in a few colours. The rest of the interface colours are derived from these. */
3
+ export interface ThemePalette {
4
+ /** Decides the browser's own controls (scrollbars, form fields) and the `light` / `dark` state of the editor. */
5
+ mode: 'light' | 'dark';
6
+ /** Toolbar, ribbon and panels. */
7
+ bg: string;
8
+ surface: string;
9
+ fg: string;
10
+ muted: string;
11
+ border: string;
12
+ /** Buttons, selections, focus. */
13
+ accent: string;
14
+ /** Area around the pages. */
15
+ workspace: string;
16
+ /** The paper and its text. */
17
+ pageBg: string;
18
+ pageFg: string;
19
+ /** Links in the document. Default: the accent. */
20
+ link?: string;
21
+ }
22
+ export interface Theme {
23
+ /** Id used by `editor.execute('colorTheme', id)`. */
24
+ name: string;
25
+ label: string;
26
+ palette: ThemePalette;
27
+ /** Any further `--wy-*` variables to set, with or without the leading dashes. */
28
+ vars?: Record<string, string>;
29
+ }
30
+ /** Expands a palette into the editor's CSS variables. */
31
+ export declare function themeVars(p: ThemePalette): Record<string, string>;
32
+ /** The themes that come with the editor. `light` and `dark` are the stock look. */
33
+ export declare const defaultThemes: Theme[];
34
+ export interface ThemesOptions {
35
+ /** Theme applied on start. Default: leave the editor's own `theme` option as it is. */
36
+ initial?: string;
37
+ /** Replace the built-in list. */
38
+ themes?: Theme[];
39
+ /** Add to the built-in list (same name replaces). */
40
+ extra?: Theme[];
41
+ }
42
+ /** The API stored on `editor.extensions.themes`. */
43
+ export interface ThemeApi {
44
+ list(): Theme[];
45
+ current(): string | null;
46
+ register(theme: Theme): void;
47
+ apply(name: string): boolean;
48
+ clear(): void;
49
+ }
50
+ /**
51
+ * Colour themes: `editor.execute('colorTheme', 'sepia')`, the View → Themes menu, or `editor.extensions.themes`.
52
+ * A theme sets the CSS variables on the editor element, so it never leaks outside it. Switching Dark Mode afterwards returns to the stock look.
53
+ */
54
+ export declare function Themes(options?: ThemesOptions): EditorPlugin;
package/dist/react.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as createEditor } from "./src-DFClH3tv.js";
1
+ import { t as createEditor } from "./src-DmooWA6v.js";
2
2
  import { createElement, forwardRef, useEffect, useImperativeHandle, useLayoutEffect, useRef } from "react";
3
3
  //#region src/react.ts
4
4
  /** React wrapper (needs the optional `react` peer dependency). */