diff --git a/src/lib/export/docx.ts b/src/lib/export/docx.ts
index 50f4a6f..f6fb555 100644
--- a/src/lib/export/docx.ts
+++ b/src/lib/export/docx.ts
@@ -612,6 +612,7 @@ function inlineToRuns(content: TiptapNode[] = [], force: TextProps = {}): Inline
}
}
closeComment();
+ flush(); // a bookmark still open at the paragraph's end would drop its runs
return out;
}
@@ -791,6 +792,11 @@ function txbxRunPropsXml(marks: TiptapNode['marks'] = []): string {
const line = wordUnderline(u.attrs);
parts.push(``);
}
+ // Visible hyperlink styling, as runPropsFromMarks paints it for the body.
+ if (marks.some((m) => m.type === 'link' && !m.attrs?.plain)) {
+ if (!col) parts.push('');
+ if (!u) parts.push('');
+ }
const hl = marks.find((m) => m.type === 'highlight');
if (hl?.attrs?.color) {
const h = hexColor(String(hl.attrs.color));
@@ -807,7 +813,11 @@ function txbxRunPropsXml(marks: TiptapNode['marks'] = []): string {
type TxbxParts = {
media: { path: string; bytes: Uint8Array; rid: string; type: string }[];
nums: { id: number; levels: string[] }[];
+ // External hyperlink targets of box runs, each a relationship to mint.
+ links: { rid: string; href: string }[];
nextRid: () => string;
+ // w:bookmarkStart ids minted for box content — offset clear of the package's own.
+ nextBookmarkId: () => number;
};
// One picture inside a box, as an as-char drawing.
@@ -829,27 +839,82 @@ function txbxImageXml(node: TiptapNode, parts: TxbxParts): string {
`` +
`` +
`` +
- `` +
+ `` +
`` +
``
);
}
+// The box paragraph's own formatting, hand-serialized in CT_PPr child order
+// (pBdr, shd, bidi, spacing, ind, jc) — mirrors what paragraphToDocx hands the package.
+function txbxPPrXml(attrs: TiptapNode['attrs'], indentTwip: number): string {
+ const out: string[] = [];
+ const borders = paraBordersOf(attrs);
+ if (borders) {
+ const side = (name: string, b?: IBorderOptions) =>
+ b ? `` : '';
+ out.push(`${side('top', borders.top)}${side('left', borders.left)}${side('bottom', borders.bottom)}${side('right', borders.right)}`);
+ }
+ const shd = paraShadingOf(attrs);
+ if (shd) out.push(``);
+ if (attrs?.dir === 'rtl') out.push('');
+ const s = spacingOf(attrs);
+ if (s) {
+ out.push(``);
+ }
+ const ind: string[] = [];
+ if (typeof attrs?.indent === 'number' && attrs.indent > 0) ind.push(` w:left="${cmToTwip(attrs.indent)}"`);
+ else if (indentTwip) ind.push(` w:left="${indentTwip}"`);
+ if (typeof attrs?.indentRight === 'number' && attrs.indentRight > 0) ind.push(` w:right="${cmToTwip(attrs.indentRight)}"`);
+ if (typeof attrs?.indentFirst === 'number' && attrs.indentFirst !== 0) {
+ ind.push(attrs.indentFirst < 0 ? ` w:hanging="${cmToTwip(-attrs.indentFirst)}"` : ` w:firstLine="${cmToTwip(attrs.indentFirst)}"`);
+ }
+ if (ind.length) out.push(``);
+ const ta = attrs?.textAlign;
+ const jc = ta === 'center' ? 'center' : ta === 'right' ? 'right' : ta === 'justify' ? 'both' : '';
+ if (jc) out.push(``);
+ return out.join('');
+}
+
// One paragraph/heading of a text box. `numPr` makes it a list item of one of the
// numbering definitions minted for the box.
function txbxParagraphXml(node: TiptapNode, parts: TxbxParts, indentTwip = 0, numPr = ''): string {
const attrs = node.attrs ?? {};
- const pPr: string[] = [numPr];
+ const pPr: string[] = [];
if (node.type === 'heading') {
const lvl = Math.min(MAX_HEADING_LEVEL, Math.max(1, Number(attrs.level) || 1));
pPr.push(``);
}
- if (indentTwip) pPr.push(``);
- const ta = attrs.textAlign;
- const jc = ta === 'center' ? 'center' : ta === 'right' ? 'right' : ta === 'justify' ? 'both' : '';
- if (jc) pPr.push(``);
+ pPr.push(numPr, txbxPPrXml(attrs, indentTwip));
let runs = '';
+ // Comment ranges and bookmarks bracket consecutive runs sharing the mark, as
+ // inlineToRuns does for the body; the reference run is what Word draws the bubble from.
+ let openComment: number | null = null;
+ const closeComment = () => {
+ if (openComment === null) return;
+ runs += ``;
+ openComment = null;
+ };
+ let openBookmarkName: string | null = null;
+ let openBookmarkId = 0;
+ const closeBookmark = () => {
+ if (openBookmarkName === null) return;
+ runs += ``;
+ openBookmarkName = null;
+ };
for (const child of node.content ?? []) {
+ const cid = commentIdOf(child);
+ if (cid !== openComment) { closeBookmark(); closeComment(); }
+ const bm = bookmarkNameOf(child);
+ if (bm !== openBookmarkName) closeBookmark();
+ if (cid !== null && cid !== openComment) { runs += ``; openComment = cid; }
+ if (bm && openBookmarkName === null) {
+ openBookmarkName = bm;
+ openBookmarkId = parts.nextBookmarkId();
+ runs += ``;
+ }
if (child.type === 'image') {
const drawing = txbxImageXml(child, parts);
if (drawing) runs += `${drawing}`;
@@ -858,6 +923,20 @@ function txbxParagraphXml(node: TiptapNode, parts: TxbxParts, indentTwip = 0, nu
const { instr, text } = sequenceFieldParts(child);
runs += `` +
`${txbxRunPropsXml(child.marks)}${escapeXml(text)}`;
+ } else if (child.type === 'crossRef') {
+ const verb = child.attrs?.format === 'page' ? 'PAGEREF' : 'REF';
+ runs += `` +
+ `${escapeXml(String(child.attrs?.text ?? ''))}`;
+ } else if (child.type === 'formula') {
+ // A sentinel run, resolved by applyFormulasDocx — it runs after the boxes are packed.
+ const latex = typeof child.attrs?.latex === 'string' ? child.attrs.latex : '';
+ if (latex) {
+ docFormulas.push({ latex, display: child.attrs?.display === true });
+ runs += `${MTH}${docFormulas.length - 1}${MTH}`;
+ }
+ } else if (child.type === 'ruby') {
+ docRubies.push({ base: String(child.attrs?.base ?? ''), text: String(child.attrs?.text ?? '') });
+ runs += `${RBY}${docRubies.length - 1}${RBY}`;
} else if (child.type === 'text' && child.text) {
const rPr = txbxRunPropsXml(child.marks);
let inner = '';
@@ -865,11 +944,24 @@ function txbxParagraphXml(node: TiptapNode, parts: TxbxParts, indentTwip = 0, nu
if (i > 0) inner += '';
if (seg) inner += `${escapeXml(seg)}`;
});
- runs += `${rPr}${inner}`;
+ const run = `${rPr}${inner}`;
+ const href = child.marks?.find((m) => m.type === 'link')?.attrs?.href;
+ const link = href ? String(href) : '';
+ if (link.startsWith('#')) {
+ runs += `${run}`;
+ } else if (link) {
+ const rid = parts.nextRid();
+ parts.links.push({ rid, href: link });
+ runs += `${run}`;
+ } else {
+ runs += run;
+ }
} else if (child.type === 'hardBreak') {
runs += `${txbxRunPropsXml(child.marks)}`;
}
}
+ closeBookmark();
+ closeComment();
return `${pPr.length ? `${pPr.join('')}` : ''}${runs}`;
}
@@ -1026,7 +1118,8 @@ function applyTextBoxesDocx(bytes: Uint8Array, boxes: TextBoxDocx[]): Uint8Array
const relsPath = 'word/_rels/document.xml.rels';
const rels = files[relsPath] ? strFromU8(files[relsPath]) : '';
let nextRid = maxIdIn(rels, /Id="rId(\d+)"/g);
- const parts: TxbxParts = { media: [], nums: [], nextRid: () => `rId${++nextRid}` };
+ let nextBm = 8000;
+ const parts: TxbxParts = { media: [], nums: [], links: [], nextRid: () => `rId${++nextRid}`, nextBookmarkId: () => ++nextBm };
xml = xml.replace(
new RegExp(`]*?>(?:(?!)[\\s\\S])*?${TBX}(\\d+)${TBX}(?:(?!)[\\s\\S])*?`, 'g'),
@@ -1055,10 +1148,12 @@ function applyTextBoxesDocx(bytes: Uint8Array, boxes: TextBoxDocx[]): Uint8Array
xml = xml.replace(new RegExp(`${TXBX_NUM}(\\d+)${TXBX_NUM}`, 'g'), (_m, i: string) => String(base + Number(i)));
}
- if (parts.media.length && rels) {
+ if ((parts.media.length || parts.links.length) && rels) {
for (const m of parts.media) files[m.path] = m.bytes as Uint8Array;
files[relsPath] = strToU8(rels.replace('', parts.media.map((m) =>
``).join('') +
+ parts.links.map((l) =>
+ ``).join('') +
''));
}
@@ -1148,9 +1243,11 @@ function applyFormulasDocx(bytes: Uint8Array, formulas: FormulaDocx[]): Uint8Arr
const docBytes = files['word/document.xml'];
if (!docBytes) return bytes;
let xml = strFromU8(docBytes);
- // Tempered pattern: the match stays inside the one run that holds the sentinel.
+ // Tempered pattern: the match stays inside the one run that holds the sentinel — it
+ // may cross neither nor a nested (a box's drawing run wraps whole
+ // paragraphs, so matching from it would swallow the box preamble).
xml = xml.replace(
- new RegExp(`]*?>(?:(?!)[\\s\\S])*?${MTH}(\\d+)${MTH}(?:(?!)[\\s\\S])*?`, 'g'),
+ new RegExp(`]*?>(?:(?!?w:r[\\s>])[\\s\\S])*?${MTH}(\\d+)${MTH}(?:(?!?w:r[\\s>])[\\s\\S])*?`, 'g'),
(_m, idx: string) => {
const f = formulas[Number(idx)];
if (!f) return '';
@@ -1173,8 +1270,10 @@ function applyRubyDocx(bytes: Uint8Array, rubies: RubyDocx[]): Uint8Array {
const docBytes = files['word/document.xml'];
if (!docBytes) return bytes;
let xml = strFromU8(docBytes);
+ // Tempered like the formula pass: crossing a nested would let a match starting
+ // at a box's drawing run swallow the box preamble.
xml = xml.replace(
- new RegExp(`]*?>(?:(?!)[\\s\\S])*?${RBY}(\\d+)${RBY}(?:(?!)[\\s\\S])*?`, 'g'),
+ new RegExp(`]*?>(?:(?!?w:r[\\s>])[\\s\\S])*?${RBY}(\\d+)${RBY}(?:(?!?w:r[\\s>])[\\s\\S])*?`, 'g'),
(_m, idx: string) => {
const r = rubies[Number(idx)];
if (!r) return '';