From 3d9311edf57c39b606cc088274a282c79c35cd2f Mon Sep 17 00:00:00 2001 From: Twest2 Date: Tue, 17 Nov 2026 10:29:17 -0600 Subject: [PATCH 1/2] Keep step text formatting in Word and PowerPoint exports MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Word and PowerPoint built step descriptions and callouts from the plain-text version, so bold, italics, inline code, links and lists were lost: a numbered list came out as bullets, and a quote ran into the next sentence. - exporters/word-rich.js: the Confluence exporter's rich-text renderer, moved out so Word uses it too. Confluence's output is byte-for-byte unchanged. In Word (no list or link styles), formatting is written on each run: bold, italic, strikethrough, code, links to web pages and to other steps' headings, real numbered and bulleted lists (a plain "•" any font has), quotes, tables. - Word callouts: label and text are paragraphs sharing one border and shading; their lists are unindented "•" and "1." lines, since an indent moves a paragraph's border and would break the box. - Word pagination keeps a block's paragraphs together (each keeps with the next) when it fits a page; a block too tall to keep may break between them. - exporters/pptx-text.js: description HTML as paragraphs of formatted runs. Slides show bold, italic, strikethrough, inline code, real bullets and numbers, quotes and tables; web links open their page and links to another step jump to its slide. Text split onto a "(continued)" slide keeps its formatting on both sides. --- docs/GETTING_STARTED.md | 7 +- exporters/confluence-word.js | 96 ++------------ exporters/docx.js | 61 +++++++-- exporters/pptx-text.js | 105 ++++++++++++++++ exporters/pptx-xml.js | 25 ++-- exporters/pptx.js | 121 +++++++++++++++--- exporters/word-rich.js | 179 +++++++++++++++++++++++++++ tests/unit/branding.test.js | 5 +- tests/unit/docx-pagination.test.js | 17 +-- tests/unit/exporters-binary.test.js | 4 +- tests/unit/pptx-layout.test.js | 10 +- tests/unit/rich-text-exports.test.js | 149 ++++++++++++++++++++++ 12 files changed, 643 insertions(+), 136 deletions(-) create mode 100644 exporters/pptx-text.js create mode 100644 exporters/word-rich.js create mode 100644 tests/unit/rich-text-exports.test.js diff --git a/docs/GETTING_STARTED.md b/docs/GETTING_STARTED.md index 7afde0bd..593a72ec 100644 --- a/docs/GETTING_STARTED.md +++ b/docs/GETTING_STARTED.md @@ -142,8 +142,11 @@ exports and accepts Markdown: `**bold**`, `*italic*`, `` `code` ``, `[links](https://example.com)`, lists that start with `-` or `1.` (indent an item by two spaces to nest it), `~~strikethrough~~`, `#` headings (`#` to `####`), `>` quotes, `---` dividers, and tables (`| A | B |` with a -`| --- | --- |` line under the header). Word, PowerPoint and GIF exports show -the description as plain text. +`| --- | --- |` line under the header). GIF and PowerPoint exports leave it +off their title card and title slide. Step descriptions and +callouts keep their formatting in PDF, Word, PowerPoint, HTML, Markdown and +wiki exports: bold, italics, code, links (a link to another step jumps to +it), lists and quotes. **Working with many steps at once:** choose **Select**, click one step, then **Shift-click** another to select everything in between, including substeps. diff --git a/exporters/confluence-word.js b/exporters/confluence-word.js index a921d1f2..ee6edada 100644 --- a/exporters/confluence-word.js +++ b/exporters/confluence-word.js @@ -3,7 +3,7 @@ const { zipSync } = require('../core/zip'); const { escapeXml } = require('../core/util'); const { encodePng } = require('../core/png'); -const { htmlToBlocks } = require('../core/htmlblocks'); +const { WordRichText, runXml, paragraph } = require('./word-rich'); const { levelLabel, stepContentGroups, codeBlockText, wordCodeRuns, wordCodeShading, flowchartImageKey, flowchartAlt, chartLinksHtml } = require('./common'); const { highlightCode } = require('../core/code-highlight'); const { guideMetaLines, stepCount } = require('./document-layout'); @@ -35,29 +35,15 @@ const CALLOUT = { error: { fill: 'FFEBE6', border: 'DE350B' }, }; -function runXml(text, { bold, italic, strike, code, link } = {}) { - const rpr = [ - link ? '' : '', - code ? '' : '', - bold ? '' : '', - italic ? '' : '', - strike ? '' : '', - ].join(''); - return String(text).split('\n').map((line, i) => ( - `${i ? '' : ''}${rpr ? `${rpr}` : ''}${escapeXml(line)}` - )).join(''); -} - -function paragraph(content, props = '') { - return `${props ? `${props}` : ''}${content}`; -} - class WordDocument { constructor(ast) { this.ast = ast; this.rels = []; this.media = []; - this.nums = []; // numbering instances: { id, abstractId } + // Descriptions and callouts: real lists, links, quotes (exporters/word-rich.js). + this.rich = new WordRichText({ + ast, rel: (...args) => this.rel(...args), anchorFor: (step) => this.anchorFor(step), table: (rows) => this.table(rows), + }); this.nextRel = 3; // rId1 styles, rId2 numbering this.nextBookmark = 1; } @@ -68,67 +54,13 @@ class WordDocument { return id; } - newList(ordered) { - const id = this.nums.length + 1; - this.nums.push({ id, abstractId: ordered ? 1 : 0 }); - return id; - } - anchorFor(step) { return `step_${String(step.number).replace(/\./g, '_')}`; } - runs(runs) { - return runs.map((r) => { - if (r.href && r.href.startsWith('step:')) { - const target = this.ast.steps.find((s) => s.stepId === r.href.slice(5)); - if (!target) return runXml(r.text, r); - return `${runXml(r.text, { ...r, link: true })}`; - } - if (r.href && /^(https?:|mailto:)/i.test(r.href)) { - return `${runXml(r.text, { ...r, link: true })}`; - } - return runXml(r.text, r); - }).join(''); - } - /** Rich description HTML -> Word paragraphs, with real lists. */ richText(html) { - const out = []; - let list = null; // { ordered, id } - let rows = []; // consecutive table rows, written as one Word table - const endTable = () => { if (rows.length) out.push(this.table(rows)); rows = []; }; - for (const block of htmlToBlocks(html || '')) { - if (block.type === 'tr') { list = null; rows.push(block.cells); continue; } - endTable(); - const isList = block.type === 'li' || block.type === 'oli'; - const ordered = block.type === 'oli'; - if (!isList) list = null; - if (block.type === 'hr') { - out.push(paragraph('', '')); - continue; - } - if (isList) { - if (!list || list.ordered !== ordered || (ordered && block.n === 1 && block.indent <= 1 && !block.cont)) { - list = { ordered, id: this.newList(ordered) }; - } - const lvl = Math.min(2, Math.max(0, block.indent - 1)); - // A line after a break in the item continues it: same indent, no new number. - out.push(block.cont - ? paragraph(this.runs(block.runs), ``) - : paragraph(this.runs(block.runs), ``)); - continue; - } - if (/^h[1-4]$/.test(block.type)) { - out.push(paragraph(this.runs(block.runs), '')); - } else if (block.type === 'blockquote') { - out.push(paragraph(this.runs(block.runs), '')); - } else { - out.push(paragraph(this.runs(block.runs))); - } - } - endTable(); - return out.join(''); + return this.rich.richText(html); } callout(tb) { @@ -254,7 +186,7 @@ class WordDocument { { name: 'docProps/core.xml', data: coreProps(ast.guide.title || t('Untitled guide')) }, { name: 'word/document.xml', data: documentXml }, { name: 'word/styles.xml', data: STYLES }, - { name: 'word/numbering.xml', data: numberingXml(this.nums) }, + { name: 'word/numbering.xml', data: this.rich.numberingXml() }, { name: 'word/_rels/document.xml.rels', data: ` @@ -314,20 +246,6 @@ ${style('Code', 'Code', { ppr: '' })} `; -function numberingXml(nums) { - const level = (ilvl, fmt, text) => `` - + `` - + `${fmt === 'bullet' ? '' : ''}`; - const bullet = [0, 1, 2].map((l) => level(l, 'bullet', '')).join(''); - const decimal = [0, 1, 2].map((l) => level(l, ['decimal', 'lowerLetter', 'lowerRoman'][l], `%${l + 1}.`)).join(''); - return ` - -${bullet} -${decimal} -${nums.map((n) => `${n.abstractId === 1 ? '' : ''}`).join('\n')} -`; -} - /** Build the .docx bytes for a guide. */ function buildConfluenceWord(ast, images, tpl = { includeImages: true }) { return new WordDocument(ast).build(images, tpl); diff --git a/exporters/docx.js b/exporters/docx.js index 602d1cb9..f4c2e6da 100644 --- a/exporters/docx.js +++ b/exporters/docx.js @@ -10,6 +10,7 @@ const { exportText } = require('../core/export-text'); const { highlightCode } = require('../core/code-highlight'); const { guideMetaLines, guideSummary, tocEntries } = require('./document-layout'); const { fitSize, textOn, screenshotOptions } = require('./branding'); +const { WordRichText } = require('./word-rich'); /** * DOCX exporter: WordprocessingML built directly (no dependency), one @@ -51,7 +52,7 @@ const PRINTABLE_WIDTH_TWIPS = 11906 - 1134 * 2; const STEP_KEEP_BUDGET = PRINTABLE_HEIGHT_TWIPS - 720; function paragraphText(xml) { - return xml.replace(/]*\/>/g, '\n') + return xml.replace(/]*\/>/g, '\n').replace(/<\/w:p>(?=.)/g, '\n') .replace(/<[^>]*>/g, '').replace(/</g, '<').replace(/>/g, '>') .replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, '&'); } @@ -78,8 +79,21 @@ function blockHeight(xml, width = PRINTABLE_WIDTH_TWIPS) { + (heading ? 480 : 160); } +/** + * Keep settings for an emitted block. A block of several paragraphs (a + * callout's label and text, a description) that fits a page is kept + * together: each paragraph keeps with the next, and the last takes `next`. + * A block holding a table sets only its first paragraph. + */ function paragraphKeeps(xml, next, lines) { if (!xml.startsWith('')) return xml; + const paras = xml.includes('') ? [xml] : xml.split(/(?=)/); + // A block too tall to keep together (lines off) may break between its paragraphs. + if (paras.length > 1) return paras.map((para, i) => keepOne(para, i < paras.length - 1 ? lines : next, lines)).join(''); + return keepOne(xml, next, lines); +} + +function keepOne(xml, next, lines) { const match = xml.match(/^(?:([\s\S]*?)<\/w:pPr>)?/); const props = (match[1] || '').replace(/]*\/>/g, ''); const style = props.match(/]*\/>/)?.[0] || ''; @@ -419,6 +433,24 @@ function exportDocx(ast, outDir, template = {}) { return relId; }; + // Descriptions and callouts keep their formatting: bold, italic, inline + // code, links (to web pages and other steps), real lists, quotes, tables. + const rich = new WordRichText({ + ast, + styled: false, + size: 20, + color: ink, + linkColor: primary, + bullet: '\u2022', + anchorFor: bookmarkName, + table, + rel: (type, target, external) => { + const relId = ++relCounter; + rels.push(``); + return `rId${relId}`; + }, + }); + const body = []; // Under a flowchart picture: its shapes' step links (Word can't link parts of a picture). const chartLinkParagraph = (chart) => { @@ -449,7 +481,7 @@ function exportDocx(ast, outDir, template = {}) { ? p(run(ast.guide.title, { bold: true, size: 48, color: textOn(brand.colors.primary).slice(1) }), `${band}`) : p(run(ast.guide.title, { bold: true, size: 48 }), `${jc}`)); - if (ast.guide.descriptionText) body.push(p(run(ast.guide.descriptionText, { size: 22, color: '444444' }))); + if (ast.guide.descriptionHtml) body.push(rich.richText(ast.guide.descriptionHtml, { rpr: { size: 22, color: '444444' } })); for (const line of guideMetaLines(ast)) body.push(p(run(line, { size: 20, color: '6B7280' }))); body.push(p(run(guideSummary(ast), { size: 18, color: '888888' }))); @@ -468,13 +500,21 @@ function exportDocx(ast, outDir, template = {}) { const shots = screenshotOptions(ast); const alignProps = shots.align === 'left' ? '' : ``; + // A callout: its label, then its text with formatting, as paragraphs that + // share one border and shading, so Word draws them as a single box. const emitTextBlock = (tb) => { const style = LEVEL_STYLE[tb.level] || LEVEL_STYLE.info; const label = calloutLabel(tb, ast); - body.push(p( - `${run(label, { bold: true, size: 20, color: style.color })}${tb.descriptionText ? run('\n' + tb.descriptionText, { size: 20, color: ink }) : ''}`, - `` - )); + const box = { + pBdr: ``, + shd: ``, + spacing: '', + }; + const text = tb.descriptionHtml ? rich.richText(tb.descriptionHtml, { ppr: box, flatLists: true }) : ''; + const xml = p(run(label, { bold: true, size: 20, color: style.color }), `${box.pBdr}${box.shd}${box.spacing}`) + text; + // Space after the box, not between its paragraphs. + const last = xml.lastIndexOf(box.spacing); + body.push(`${xml.slice(0, last)}${xml.slice(last + box.spacing.length)}`); }; const parentIds = new Set(ast.steps.map((step) => step.parentStepId).filter(Boolean)); @@ -515,7 +555,7 @@ function exportDocx(ast, outDir, template = {}) { )); for (const tb of afterTitle) emit(tb); const img = images.get(step.stepId); - const description = step.descriptionText ? p(run(step.descriptionText, { size: 20, color: ink })) : ''; + const description = step.descriptionHtml ? rich.richText(step.descriptionHtml) : ''; const screenshot = (maxTwips) => { const relId = ++relCounter; const name = `image${relCounter}.png`; @@ -602,6 +642,13 @@ function exportDocx(ast, outDir, template = {}) { + ``; } + // Lists in descriptions and callouts need a numbering part. + if (rich.nums.length) { + const relId = ++relCounter; + rels.push(``); + parts.push({ name: 'word/numbering.xml', data: rich.numberingXml(), kind: 'numbering', rels: [] }); + } + const documentXml = ` { + if (i) lines.push([]); + if (part) lines[lines.length - 1].push({ ...run, text: part }); + }); + } + return lines; +} + +/** The runs between character offsets `start` and `end` of their joined text. */ +function sliceRuns(runs, start, end = Infinity) { + const out = []; + let at = 0; + for (const run of runs) { + const from = Math.max(start, at); + const to = Math.min(end, at + run.text.length); + if (to > from) out.push({ ...run, text: run.text.slice(from - at, to - at) }); + at += run.text.length; + } + return normalizeRuns(out); +} + +const joined = (runs) => runs.map((r) => r.text).join(''); + +function richParagraphs(html) { + const out = []; + let table = null; + for (const block of htmlToBlocks(html || '')) { + if (block.type === 'tr') { + if (!table) { table = { rows: [] }; out.push(table); } + table.rows.push(block.cells.map((c) => String(c ?? ''))); + continue; + } + table = null; + if (block.type === 'hr') continue; + const isList = block.type === 'li' || block.type === 'oli'; + splitLines(block.runs).forEach((lineRuns, i) => { + const runs = normalizeRuns(lineRuns); + if (!runs.length) return; + const continued = block.cont || i > 0; + out.push({ + runs, + text: joined(runs), + list: isList ? { ordered: block.type === 'oli', n: block.n || 1, level: Math.max(0, (block.indent || 1) - 1), continued } : null, + quote: block.type === 'blockquote', + heading: /^h[1-4]$/.test(block.type), + }); + }); + } + return out; +} + +/** Plain text for a paragraph with its list marker: "• item", "2. item". */ +function markedText(para) { + if (!para.list) return para.text; + const indent = ' '.repeat(para.list.level); + if (para.list.continued) return `${indent} ${para.text}`; + return `${indent}${para.list.ordered ? `${para.list.n}.` : '•'} ${para.text}`; +} + +module.exports = { richParagraphs, sliceRuns, normalizeRuns, markedText }; diff --git a/exporters/pptx-xml.js b/exporters/pptx-xml.js index ca32b8fa..7e6a271a 100644 --- a/exporters/pptx-xml.js +++ b/exporters/pptx-xml.js @@ -60,20 +60,31 @@ const SHADOW = '${solidFill(color)}` - + `` + const attrs = `${italic ? ' i="1"' : ''}${underline || link ? ' u="sng"' : ''}${strike ? ' strike="sngStrike"' : ''}`; + const click = link ? `` : ''; + return `${solidFill(color)}` + + `${click}` + `${escapeXml(t)}`; } -/** A paragraph of runs; `spaceAfter` and `spaceBefore` in points. */ -function paragraph(runs, { align = 'l', spaceAfter = 0, spaceBefore = 0, endSize = 0 } = {}) { +/** + * A paragraph of runs; `spaceAfter` and `spaceBefore` in points. `marL` + * (EMU) indents it; a `bullet` ({ char } or { number: startAt }) hangs in + * that margin. + */ +function paragraph(runs, { align = 'l', spaceAfter = 0, spaceBefore = 0, endSize = 0, marL = 0, bullet = null } = {}) { const spacing = (spaceBefore ? `` : '') + (spaceAfter ? `` : ''); - const pPr = `${spacing}`; + const indent = marL ? ` marL="${int(marL)}" indent="${bullet ? -int(Math.min(marL, 285750)) : 0}"` : ''; + let bu = ''; + if (bullet?.char) bu = ``; + else if (bullet?.number) bu = ` 1 ? ` startAt="${int(bullet.number)}"` : ''}/>`; + const pPr = `${spacing}${bu}`; const end = endSize ? `` : ''; return `${pPr}${Array.isArray(runs) ? runs.join('') : runs}${end}`; } diff --git a/exporters/pptx.js b/exporters/pptx.js index 49a5bb9a..4fef3854 100644 --- a/exporters/pptx.js +++ b/exporters/pptx.js @@ -12,6 +12,7 @@ const { tocEntries, guideMetaLines, guideSummary } = require('./document-layout' const { SLIDE_SCREENSHOT_POSITIONS } = require('../core/branding'); const { withBrand, fitSize, textOn, brandRaster, hexToRgb } = require('./branding'); const metrics = require('./text-metrics'); +const { richParagraphs, sliceRuns, markedText } = require('./pptx-text'); const X = require('./pptx-xml'); /** @@ -74,6 +75,9 @@ const ACCENT_BAR_H = Math.round(0.07 * IN); const HEADER_GAP = Math.round(0.24 * IN); // header → body const GAP = Math.round(0.16 * IN); // between blocks const PARA_GAP = Math.round(0.09 * IN); // between description paragraphs +const LIST_GAP = Math.round(0.04 * IN); // between list items +const LIST_INDENT = Math.round(0.3 * IN); // per list level; the bullet hangs in it +const QUOTE_INDENT = Math.round(0.25 * IN); const COLUMN_GAP = Math.round(0.4 * IN); const BADGE = Math.round(0.5 * IN); const BADGE_GAP = Math.round(0.18 * IN); @@ -139,9 +143,21 @@ function stepItems(step) { const groups = Object.fromEntries(Object.entries(stepContentGroups(step)) // A flowchart block sits beside the screenshot on its slide, wherever it goes elsewhere. .map(([group, list]) => [group, list.filter((block) => block.kind !== 'flowchart')])); - const callouts = (list, after = false) => list.map((tb) => ({ kind: 'callout', tb, label: null, body: tb.descriptionText || '', after })); - const description = String(step.descriptionText || '').split('\n').map((s) => s.trim()).filter(Boolean) - .map((text) => ({ kind: 'para', text, after: false })); + const callouts = (list, after = false) => list.map((tb) => { + // A callout's text keeps its formatting; its lists and tables become lines. + const paras = tb.descriptionHtml ? richParagraphs(tb.descriptionHtml).flatMap((p) => (p.rows + ? p.rows.map((row) => ({ runs: [{ text: row.join(' | ') }], text: row.join(' | '), list: null })) + : [p])) : null; + const body = paras ? paras.map(markedText).join('\n') : (tb.descriptionText || ''); + return { kind: 'callout', tb, label: null, body, paras, after }; + }); + // The description keeps its formatting: bold, italic, code, links, lists, quotes, tables. + const description = step.descriptionHtml + ? richParagraphs(step.descriptionHtml).map((p) => (p.rows + ? { kind: 'table', rows: p.rows, after: false } + : { kind: 'para', ...p, after: false })) + : String(step.descriptionText || '').split('\n').map((s) => s.trim()).filter(Boolean) + .map((text) => ({ kind: 'para', text, runs: [{ text }], list: null, after: false })); const rest = groups.rest.map((block) => { if (block.kind === 'code') return { kind: 'code', code: codeBlockText(block), language: block.language, after: true }; if (block.kind === 'table' && block.rows?.length) return { kind: 'table', rows: block.rows.map((r) => r.map((c) => String(c ?? ''))), header: true, after: true }; @@ -188,7 +204,7 @@ function tableRowHeights(ctx, rows, colWidths, scale) { function itemHeight(ctx, item, width, scale) { switch (item.kind) { case 'para': - return metrics.textHeight(item.text, width, measure(ctx, 'body', SIZE.body * scale)); + return metrics.textHeight(item.text, width - paraIndent(item), measure(ctx, 'body', SIZE.body * scale, paraBold(item))); case 'callout': { const { label, body } = calloutParts(ctx, item); const inner = width - CALLOUT_BAR - CALLOUT_PAD_X * 2; @@ -208,7 +224,21 @@ function itemHeight(ctx, item, width, scale) { } function gapBetween(prev, next) { - return prev.kind === 'para' && next.kind === 'para' ? PARA_GAP : GAP; + if (prev.kind === 'para' && next.kind === 'para') return prev.list && next.list ? LIST_GAP : PARA_GAP; + return GAP; +} + +/** How far a paragraph is indented: list items by level, quotes a little. */ +function paraIndent(item) { + if (item.list) return LIST_INDENT * (item.list.level + 1); + return item.quote ? QUOTE_INDENT : 0; +} + +/** Whether to measure a paragraph as bold: a heading, or mostly bold text. */ +function paraBold(item) { + if (item.heading) return true; + const bold = (item.runs || []).reduce((n, r) => n + (r.bold ? r.text.length : 0), 0); + return bold > item.text.length * 0.3; } function stackHeight(ctx, items, width, scale) { @@ -236,9 +266,16 @@ function splitText(text, lines, fit) { */ function splitItem(ctx, item, width, scale, maxH) { if (item.kind === 'para') { - const m = measure(ctx, 'body', SIZE.body * scale); - const parts = splitText(item.text, metrics.wrapText(item.text, width, m).flat(), Math.floor(maxH / pt(m.lineHeight))); - return parts && [{ ...item, text: parts[0] }, { ...item, text: parts[1] }]; + const m = measure(ctx, 'body', SIZE.body * scale, paraBold(item)); + const parts = splitText(item.text, metrics.wrapText(item.text, width - paraIndent(item), m).flat(), Math.floor(maxH / pt(m.lineHeight))); + if (!parts) return null; + // Both halves keep their formatting; the second continues a list item without a new bullet. + const head = sliceRuns(item.runs, 0, parts[0].length); + const tail = sliceRuns(item.runs, item.text.length - parts[1].length); + return [ + { ...item, runs: head, text: parts[0] }, + { ...item, runs: tail, text: parts[1], list: item.list && { ...item.list, continued: true } }, + ]; } if (item.kind === 'code') { const lines = item.code.split('\n'); @@ -254,7 +291,7 @@ function splitItem(ctx, item, width, scale, maxH) { const m = measure(ctx, 'body', SIZE.callout * scale); const fit = Math.floor((maxH - labelH - pt(3) - CALLOUT_PAD_Y * 2) / pt(m.lineHeight)); const parts = splitText(body, metrics.wrapText(body, inner, m).flat(), fit); - return parts && [{ ...item, label, body: parts[0] }, { ...item, label, body: parts[1] }]; + return parts && [{ ...item, label, body: parts[0], paras: null }, { ...item, label, body: parts[1], paras: null }]; } if (item.kind === 'table') { const cols = tableColumns(ctx, item.rows, width, scale); @@ -446,19 +483,29 @@ function itemXml(ctx, nextId, item, box, scale) { const ink = 'scheme:tx1'; const lang = ctx.lang; switch (item.kind) { - case 'para': + case 'para': { + const size = SIZE.body * scale; + const list = item.list; + const marL = paraIndent(item); + const bullet = list && !list.continued ? (list.ordered ? { number: list.n } : { char: '\u2022' }) : null; + const style = { size, color: item.quote ? '475569' : ink, lang, bold: item.heading, italic: item.quote }; return X.shape(nextId, { name: 'Text', box, - paras: X.paragraphs(item.text, { size: SIZE.body * scale, color: ink, lang }), + paras: [X.paragraph(richRuns(ctx, item.runs, style), { marL, bullet })], text: { inset: 0 }, }); + } case 'callout': { const style = CALLOUT_STYLE[item.tb.level] || CALLOUT_STYLE.info; const { label, body } = calloutParts(ctx, item); const paras = [ ...(label ? X.paragraphs(label, { size: SIZE.callout * scale, bold: true, color: style.color, lang }) : []), - ...(body ? X.paragraphs(body, { size: SIZE.callout * scale, color: '1F2937', lang }, { spaceBefore: label ? 3 : 0 }) : []), + ...(item.paras + // Formatted text; list items start with their marker. + ? item.paras.map((p, i) => X.paragraph(richRuns(ctx, p.list ? [{ text: markedText({ ...p, text: '' }) }, ...p.runs] : p.runs, + { size: SIZE.callout * scale, color: '1F2937', lang }), { spaceBefore: i === 0 && label ? 3 : 0 })) + : (body ? X.paragraphs(body, { size: SIZE.callout * scale, color: '1F2937', lang }, { spaceBefore: label ? 3 : 0 }) : [])), ]; return X.shape(nextId, { name: 'Callout', box, fill: style.fill }) + X.shape(nextId, { name: 'Callout bar', box: { x: box.x, y: box.y, w: CALLOUT_BAR, h: box.h }, fill: style.accent }) @@ -505,6 +552,28 @@ function itemXml(ctx, nextId, item, box, scale) { } } +/** + * Formatted runs as slide runs: bold, italic, strikethrough, inline code in + * the code font, and links. A web link goes to its page; a link to another + * step jumps to that step's slide (resolved when the deck is put together). + */ +function richRuns(ctx, runs, base) { + return runs.map((r) => { + let link = null; + if (r.href && /^(https?:|mailto:)/i.test(r.href)) link = ctx.addLink({ href: r.href }); + else if (r.href && r.href.startsWith('step:') && ctx.ast.steps.some((s) => s.stepId === r.href.slice(5))) link = ctx.addLink({ stepId: r.href.slice(5) }); + return X.run(r.text, { + ...base, + bold: base.bold || r.bold, + italic: base.italic || r.italic, + strike: r.strike, + font: r.code ? CODE_FONT : (base.font || '+mn-lt'), + color: link ? 'scheme:hlink' : base.color, + link, + }); + }).join(''); +} + /** Draw items stacked down a column from `y`; returns the xml and the bottom. */ function columnXml(ctx, nextId, items, { x, y, w }, scale) { let xml = ''; @@ -552,7 +621,7 @@ function accentBar(ctx, nextId) { function notesText(ctx, step, items) { const lines = [`${step.number}. ${step.title || ctx.t('Untitled step')}`]; for (const item of items) { - if (item.kind === 'para') lines.push(item.text); + if (item.kind === 'para') lines.push(markedText(item)); else if (item.kind === 'callout') { const { label, body } = calloutParts(ctx, item); lines.push([label, body].filter(Boolean).join(' — ')); @@ -895,6 +964,7 @@ function stepSlides(ctx, step, tpl) { const notes = tpl.speakerNotes || plan.first.mode === 'full' ? notesText(ctx, step, items) : ''; // The first slide. { + ctx.slideLinks = []; const nextId = X.ids(); const p = plan.first; let xml = accentBar(ctx, nextId) + headerXml(ctx, nextId, header); @@ -927,7 +997,7 @@ function stepSlides(ctx, step, tpl) { xml += columnXml(ctx, nextId, p.below, { x: area.x, y: picTop + p.fit.h + GAP, w: area.w }, p.scale).xml; } } - slides.push({ xml: X.slideXml(xml), rels, media, notes }); + slides.push({ xml: X.slideXml(xml), rels, media, notes, links: ctx.slideLinks }); } // The rest of the text, on as many slides as it needs. const queue = plan.rest.slice(); @@ -937,10 +1007,11 @@ function stepSlides(ctx, step, tpl) { let guard = 0; while (queue.length && guard++ < 200) { const scale = SCALES[0]; + ctx.slideLinks = []; const taken = takeFitting(ctx, queue, contArea.w, scale, contArea.h, { force: true }); const nextId = X.ids(); const xml = accentBar(ctx, nextId) + headerXml(ctx, nextId, contHeader) + columnXml(ctx, nextId, taken, contArea, scale).xml; - slides.push({ xml: X.slideXml(xml), rels: [], media: [], notes: '' }); + slides.push({ xml: X.slideXml(xml), rels: [], media: [], notes: '', links: ctx.slideLinks }); } return slides; } @@ -1004,13 +1075,26 @@ function exportPptx(ast, outDir, template = {}) { titleRight: logoAt && logoPosition === 'top-right' ? logoAt.x - Math.round(0.25 * IN) : SLIDE_W - MARGIN_X, bottomLimit, nextMedia: () => ++mediaCounter, + // Links on the slide being drawn: { id, href } or { id, stepId }, as rId100 and up. + slideLinks: [], + addLink(target) { + const same = this.slideLinks.find((l) => (target.href ? l.href === target.href : l.stepId === target.stepId)); + const link = same || { id: `rId${100 + this.slideLinks.length}`, ...target }; + if (!same) this.slideLinks.push(link); + return { id: link.id, slide: Boolean(link.stepId) }; + }, }; const slides = []; // { xml, rels: [{ id, name }], media: [{ name, data }], notes } if (tpl.titleSlide) slides.push(titleSlide(ctx)); const toc = tpl.includeToc && ast.steps.length > 1 ? tocEntries(ast) : []; if (toc.length) slides.push(...tocSlides(ctx, toc)); - for (const step of ast.steps) slides.push(...stepSlides(ctx, step, tpl)); + // Each step's first slide (1-based), for links that jump to it. + const stepSlide = new Map(); + for (const step of ast.steps) { + stepSlide.set(step.stepId, slides.length + 1); + slides.push(...stepSlides(ctx, step, tpl)); + } const withNotes = slides.some((s) => s.notes); const entries = []; @@ -1026,10 +1110,13 @@ function exportPptx(ast, outDir, template = {}) { const slideRels = [ ``, ...slide.rels.map((r) => ``), + ...(slide.links || []).map((l) => (l.href + ? `` + : ``)), ]; if (slide.notes) { notesCount += 1; - const notesId = Math.max(1, ...slide.rels.map((r) => r.id)) + 1; + const notesId = Math.max(1, ...slide.rels.map((r) => r.id), ...(slide.links || []).map((l) => Number(l.id.slice(3)))) + 1; slideRels.push(``); entries.push( { name: `ppt/notesSlides/notesSlide${notesCount}.xml`, data: X.notesXml(slide.notes) }, diff --git a/exporters/word-rich.js b/exporters/word-rich.js new file mode 100644 index 00000000..3a17b934 --- /dev/null +++ b/exporters/word-rich.js @@ -0,0 +1,179 @@ +'use strict'; + +const { escapeXml } = require('../core/util'); +const { htmlToBlocks } = require('../core/htmlblocks'); + +/** + * Rich text (sanitized description HTML) as WordprocessingML paragraphs: + * bold, italic, strikethrough, inline code, links to web pages and to other + * steps, real bulleted and numbered lists, quotes, headings, tables and + * rules. Shared by the Word and Confluence exports. + * + * `styled` documents (Confluence) define List Paragraph, Quote, Heading 4 + * and Hyperlink styles and refer to them. Otherwise (Word) the formatting + * is written out on each paragraph and run, on top of `rpr` (size, color) + * and `ppr` (a callout's shading and border) for every paragraph. + * + * Lists need a numbering part: `numberingXml()` once the document is built, + * when `nums` isn't empty. `bullet` is the bullet character: the Symbol + * font's (Word's own default) or a plain "•" that any font has. + */ + +const W_NS = 'http://schemas.openxmlformats.org/wordprocessingml/2006/main'; + +/** Run properties in schema order: style, font, b, i, strike, color, size, underline. */ +function runProps({ bold, italic, strike, code, link } = {}, { styled = true, size = 0, color = '', linkColor = '0563C1', codeFont = 'Courier New' } = {}) { + return [ + link && styled ? '' : '', + code ? `` : '', + bold ? '' : '', + italic ? '' : '', + strike ? '' : '', + link && !styled ? `` : (color ? `` : ''), + size ? `` : '', + link && !styled ? '' : '', + ].join(''); +} + +/** One run per line of `text`, with a line break between them. */ +function runXml(text, format = {}, options = {}) { + const rpr = runProps(format, options); + return String(text).split('\n').map((line, i) => ( + `${i ? '' : ''}${rpr ? `${rpr}` : ''}${escapeXml(line)}` + )).join(''); +} + +/** + * Paragraph properties in schema order. `parts` holds the pieces a paragraph + * needs: style, numPr, pBdr (whole element), shd, spacing, ind. + */ +function paragraphProps({ style = '', numPr = '', pBdr = '', shd = '', spacing = '', ind = '' } = {}) { + return [style ? `` : '', numPr, pBdr, shd, spacing, ind].join(''); +} + +function paragraph(content, props = '') { + return `${props ? `${props}` : ''}${content}`; +} + +class WordRichText { + /** + * `rel(type, target, external)` adds a relationship and returns its id; + * `anchorFor(step)` is the bookmark a step's heading carries; `table(rows)` + * writes a description's table rows (arrays of cell text). + */ + constructor({ ast, rel, anchorFor, table, styled = true, size = 0, color = '', linkColor = '0563C1', bullet = SYMBOL_BULLET }) { + this.ast = ast; + this.rel = rel; + this.anchorFor = anchorFor; + this.tableXml = table; + this.styled = styled; + this.runOptions = { styled, size, color, linkColor }; + this.bullet = bullet; + this.nums = []; // numbering instances: { id, abstractId } + } + + newList(ordered) { + const id = this.nums.length + 1; + this.nums.push({ id, abstractId: ordered ? 1 : 0 }); + return id; + } + + /** Runs with links: to another step's heading (a bookmark), or to a web page. */ + runs(runs, options = this.runOptions) { + return runs.map((r) => { + if (r.href && r.href.startsWith('step:')) { + const target = this.ast.steps.find((s) => s.stepId === r.href.slice(5)); + if (!target) return runXml(r.text, r, options); + return `${runXml(r.text, { ...r, link: true }, options)}`; + } + if (r.href && /^(https?:|mailto:)/i.test(r.href)) { + return `${runXml(r.text, { ...r, link: true }, options)}`; + } + return runXml(r.text, r, options); + }).join(''); + } + + /** + * Description HTML as paragraphs. `ppr` adds properties to every paragraph + * ({ pBdr, shd } for a callout's box); `rpr` overrides run size or color. + * `flatLists` writes list items as "•" and "1." lines without indenting + * them: a paragraph's border follows its indent, so a real list would + * break a callout's box. + */ + richText(html, { ppr = {}, rpr = {}, flatLists = false } = {}) { + const options = { ...this.runOptions, ...rpr }; + const styled = this.styled; + const out = []; + let list = null; // { ordered, id } + let rows = []; // consecutive table rows, written as one Word table + const endTable = () => { if (rows.length) out.push(this.tableXml(rows)); rows = []; }; + const props = (own) => paragraphProps({ ...ppr, ...own }); + for (const block of htmlToBlocks(html || '')) { + if (block.type === 'tr') { list = null; rows.push(block.cells); continue; } + endTable(); + const isList = block.type === 'li' || block.type === 'oli'; + const ordered = block.type === 'oli'; + if (!isList) list = null; + if (block.type === 'hr') { + out.push(paragraph('', props({ pBdr: '' }))); + continue; + } + if (isList && flatLists) { + const nested = '\u2003'.repeat(Math.max(0, block.indent - 1)); + const marker = block.cont ? '\u2003' : (ordered ? `${block.n}.` : '\u2022'); + out.push(paragraph(runXml(`${nested}${marker}\u2002`, {}, options) + this.runs(block.runs, options), props())); + continue; + } + if (isList) { + if (!list || list.ordered !== ordered || (ordered && block.n === 1 && block.indent <= 1 && !block.cont)) { + list = { ordered, id: this.newList(ordered) }; + } + const lvl = Math.min(2, Math.max(0, block.indent - 1)); + const style = styled ? 'ListParagraph' : ''; + const spacing = styled ? '' : ''; + // A line after a break in the item continues it: same indent, no new number. + out.push(block.cont + ? paragraph(this.runs(block.runs, options), props({ style, spacing, ind: `` })) + : paragraph(this.runs(block.runs, options), props({ style, spacing, numPr: `` }))); + continue; + } + if (/^h[1-4]$/.test(block.type)) { + out.push(styled + ? paragraph(this.runs(block.runs, options), props({ style: 'Heading4' })) + : paragraph(this.runs(block.runs.map((r) => ({ ...r, bold: true })), options), props({ spacing: '' }))); + } else if (block.type === 'blockquote') { + out.push(styled + ? paragraph(this.runs(block.runs, options), props({ style: 'Quote' })) + : paragraph(this.runs(block.runs.map((r) => ({ ...r, italic: true })), { ...options, color: '505F79' }), + props({ ind: `` }))); + } else { + out.push(paragraph(this.runs(block.runs, options), props())); + } + } + endTable(); + return out.join(''); + } + + /** The numbering part for the lists written so far. */ + numberingXml() { + return numberingXml(this.nums, { bullet: this.bullet }); + } +} + +const SYMBOL_BULLET = '\uF0B7'; + +function numberingXml(nums, { bullet: mark = SYMBOL_BULLET } = {}) { + const level = (ilvl, fmt, text) => `` + + `` + + `${fmt === 'bullet' && mark === SYMBOL_BULLET ? '' : ''}`; + const bullet = [0, 1, 2].map((l) => level(l, 'bullet', mark)).join(''); + const decimal = [0, 1, 2].map((l) => level(l, ['decimal', 'lowerLetter', 'lowerRoman'][l], `%${l + 1}.`)).join(''); + return ` + +${bullet} +${decimal} +${nums.map((n) => `${n.abstractId === 1 ? '' : ''}`).join('\n')} +`; +} + +module.exports = { WordRichText, runXml, paragraph, numberingXml }; diff --git a/tests/unit/branding.test.js b/tests/unit/branding.test.js index cc174ff3..3ab4bde0 100644 --- a/tests/unit/branding.test.js +++ b/tests/unit/branding.test.js @@ -437,7 +437,7 @@ test('branding: Word gets brand styles, the logo on the cover, and a header and assert.ok(z.has('word/media/brand-logo.png') && z.has('word/media/brand-banner.png')); assert.match(z.get('[Content_Types].xml'), /PartName="\/word\/footer1.xml" ContentType="[^"]+footer\+xml"/); const rels = z.get('word/_rels/document.xml.rels'); - for (const m of rels.matchAll(/Target="([^"]+)"/g)) assert.ok(z.has(`word/${m[1]}`), `${m[1]} exists`); + for (const m of rels.matchAll(/Target="([^"]+)"(?! TargetMode="External")/g)) assert.ok(z.has(`word/${m[1]}`), `${m[1]} exists`); const p = zipEntries(exportDocx(plain, path.join(root, 'plain')).file); assert.ok(!p.has('word/header1.xml')); @@ -468,7 +468,8 @@ test('branding: PowerPoint gets a brand theme, logo, footer and slide numbers on for (const [name, xml] of z) { if (!name.endsWith('.rels')) continue; const base = path.posix.dirname(path.posix.dirname(name)); - for (const m of xml.matchAll(/Target="([^"]+)"/g)) assert.ok(z.has(path.posix.normalize(path.posix.join(base, m[1]))), `${name} → ${m[1]}`); + // Web links point outside the package. + for (const m of xml.matchAll(/Target="([^"]+)"(?! TargetMode="External")/g)) assert.ok(z.has(path.posix.normalize(path.posix.join(base, m[1]))), `${name} → ${m[1]}`); } const p = zipEntries(exportPptx(plain, path.join(root, 'plain')).file); diff --git a/tests/unit/docx-pagination.test.js b/tests/unit/docx-pagination.test.js index 6f2170ef..9fcf07fa 100644 --- a/tests/unit/docx-pagination.test.js +++ b/tests/unit/docx-pagination.test.js @@ -50,10 +50,11 @@ test('DOCX pagination: process headings attach to their first child, not all sib test('DOCX pagination: a short caption ends its own picture chain', t => { const { paragraphs: p } = exported(t, fixtures.caption); - assert.equal(p.length, 4); + // Heading, instructions, screenshot, then the caption callout's label and text. + assert.equal(p.length, 5); p.slice(0, -1).forEach(xml => assert.ok(kept(xml))); - assert.ok(ended(p[3]) && linesKept(p[3])); - assert.match(p[3], /This example is illustrative; your setup may differ/); + assert.ok(ended(p[4]) && linesKept(p[4])); + assert.match(p[4], /This example is illustrative; your setup may differ/); }); test('DOCX pagination: intervening callouts remain attached to the picture', t => { @@ -64,7 +65,8 @@ test('DOCX pagination: intervening callouts remain attached to the picture', t = // after the cover's explicit page break, including that leading callout. const body = r.xml.split('')[1]; const p = body.match(/[\s\S]*?<\/w:p>/g); - assert.equal(p.length, 8); + // Five callouts of two paragraphs (label, text), the heading, instructions and screenshot. + assert.equal(p.length, 13); p.slice(0, -1).forEach(xml => assert.ok(kept(xml) && linesKept(xml))); assert.ok(ended(p.at(-1))); }); @@ -80,7 +82,8 @@ test('DOCX pagination: oversized instructions can split before a fitting image/c assert.ok(kept(p[0])); assert.ok(ended(p[1])); assert.match(props(p[1]), //); - assert.ok(kept(p[2]) && ended(p[3])); + // The screenshot keeps with the callout after it: its label, then its text. + assert.ok(kept(p[2]) && kept(p[3]) && ended(p[4])); }); test('DOCX pagination: long trailing commentary is not made into a picture caption', t => { @@ -109,8 +112,8 @@ test('DOCX pagination: a forced-page step starts with its before-title callout', const p = body.match(/[\s\S]*?<\/w:p>/g); assert.match(props(p[0]), //); assert.doesNotMatch(props(p[1]), //); - // CT_PPr order: keepLines, pageBreakBefore, then the callout's border/shading. - assert.match(props(p[0]), /[\s\S]*<\/w:pBdr> { diff --git a/tests/unit/exporters-binary.test.js b/tests/unit/exporters-binary.test.js index 33191f5a..d4d598d5 100644 --- a/tests/unit/exporters-binary.test.js +++ b/tests/unit/exporters-binary.test.js @@ -432,8 +432,10 @@ test('DOCX export: valid OPC package, well-formed XML, resolvable image rels', ( // Every relationship target exists in the package, every embed has a rel. const relsXml = entries.get('word/_rels/document.xml.rels').toString('utf8'); - const relTargets = [...relsXml.matchAll(/Target="([^"]+)"/g)].map((m) => m[1]); + const relTargets = [...relsXml.matchAll(/Target="([^"]+)"(?! TargetMode="External")/g)].map((m) => m[1]); assert.equal(relTargets.length, 4); + // The description's web link is a hyperlink relationship, outside the package. + assert.match(relsXml, /Type="[^"]+\/hyperlink" Target="https:\/\/docs\.example\.com" TargetMode="External"/); assert.ok(relTargets.includes('settings.xml')); assert.ok(relTargets.includes('styles.xml')); diff --git a/tests/unit/pptx-layout.test.js b/tests/unit/pptx-layout.test.js index 9e0c745f..97077c4a 100644 --- a/tests/unit/pptx-layout.test.js +++ b/tests/unit/pptx-layout.test.js @@ -88,8 +88,8 @@ function blocks(xml) { const overlaps = (a, b) => a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h; -/** All the text on a slide, runs joined with spaces. */ -const slideText = (xml) => [...xml.matchAll(/([^<]*)<\/a:t>/g)].map((m) => m[1]).join(' ').replace(/'/g, '\'').replace(/"/g, '"').replace(/\s+/g, ' '); +/** All the text on a slide: a paragraph's runs joined as written, paragraphs with spaces. */ +const slideText = (xml) => [...xml.matchAll(/([\s\S]*?)<\/a:p>/g)].map((p) => [...p[1].matchAll(/([^<]*)<\/a:t>/g)].map((m) => m[1]).join('')).join(' ').replace(/'/g, '\'').replace(/"/g, '"').replace(/\s+/g, ' '); /** The step slides whose title starts with `title` (the first, then any "(continued)"). */ const stepSlides = (slides, title) => slides.filter((xml) => xml.includes('name="Step number"') && new RegExp(`[\\s\\S]*?${title}`).test(xml)); @@ -118,7 +118,8 @@ test('PPTX layout: no text is cut; long steps carry on to "(continued)" slides', const { slides } = deck(ast, path.join(root, 'out')); const all = slides.map(slideText).join(' '); for (const step of ast.steps) { - for (const para of step.descriptionText.split('\n')) assert.ok(all.includes(para.trim()), `"${para.slice(0, 40)}…" is on a slide`); + // List items are real bullets on the slide, not "•" in the text. + for (const para of step.descriptionText.split('\n')) assert.ok(all.includes(para.replace(/^• /, '').trim()), `"${para.slice(0, 40)}…" is on a slide`); } assert.ok(all.includes('Do not reset service accounts') && all.includes('Service accounts break integrations')); const long = stepSlides(slides, 'If the reset email never arrives'); @@ -179,7 +180,8 @@ test('PPTX layout: speaker notes hold each step’s full text, and can be left o for (const [name, xml] of z) { if (!name.endsWith('.rels')) continue; const base = path.posix.dirname(path.posix.dirname(name)); - for (const m of xml.matchAll(/Target="([^"]+)"/g)) assert.ok(z.has(path.posix.normalize(path.posix.join(base, m[1]))), `${name} → ${m[1]}`); + // Web links point outside the package. + for (const m of xml.matchAll(/Target="([^"]+)"(?! TargetMode="External")/g)) assert.ok(z.has(path.posix.normalize(path.posix.join(base, m[1]))), `${name} → ${m[1]}`); } const none = deck(ast, path.join(root, 'none'), { speakerNotes: false }).z; diff --git a/tests/unit/rich-text-exports.test.js b/tests/unit/rich-text-exports.test.js new file mode 100644 index 00000000..02dc4bda --- /dev/null +++ b/tests/unit/rich-text-exports.test.js @@ -0,0 +1,149 @@ +'use strict'; + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const { GuideStore } = require('../../core/store'); +const { buildRenderAst } = require('../../core/renderast'); +const { exportDocx } = require('../../exporters/docx'); +const { exportPptx } = require('../../exporters/pptx'); +const { richParagraphs, sliceRuns, markedText } = require('../../exporters/pptx-text'); +const { WordRichText } = require('../../exporters/word-rich'); +const { unzipSync } = require('../../core/zip'); +const { encodePng } = require('../../core/png'); +const raster = require('../../core/raster'); +const { makeTmpDir, rmrf } = require('./helpers'); + +const LONG = 'Check the account name and email carefully before you continue. The reset signs the user out of every device. '.repeat(30); + +/** A guide whose steps use every kind of formatting a description can hold. */ +function richGuide(t) { + const root = makeTmpDir('rich-text'); + t.after(() => rmrf(root)); + const store = new GuideStore(path.join(root, 'data')); + const guide = store.createGuide({ title: 'Rich text', descriptionHtml: '

For the service desk.

' }); + const png = encodePng(raster.createImage(640, 380, [240, 242, 245, 255])); + const first = store.addStep(guide.guideId, { + title: 'Open the Users page', + descriptionHtml: '

Select Users. See the Users guide for bulk changes and old notes.

', + }, png, { width: 640, height: 380 }); + store.addStep(guide.guideId, { + title: 'Reset the password', + descriptionHtml: `

Run adminctl unlock first:

  1. Pick Email a link.
  2. Choose Send.
` + + `
  • works anywhere
The old password stops working.

Go back to the Users page.

`, + textBlocks: [{ position: 'after-description', level: 'success', title: 'Shortcut', descriptionHtml: '

Press Ctrl+R:

  • works in every browser
' }], + }, png, { width: 640, height: 380 }); + store.addStep(guide.guideId, { kind: 'empty', title: 'A long one', descriptionHtml: `

Start with ${LONG} and ${LONG}

` }); + return { root, ast: buildRenderAst(store, guide.guideId), firstId: first.stepId }; +} + +const unzip = (file) => new Map(unzipSync(fs.readFileSync(file)).map((e) => [e.name, e.data.toString('utf8')])); + +test('Word keeps description formatting: bold, italic, strikethrough, code, links, real lists and quotes', (t) => { + const { root, ast } = richGuide(t); + const z = unzip(exportDocx(ast, path.join(root, 'docx')).file); + const doc = z.get('word/document.xml'); + const rels = z.get('word/_rels/document.xml.rels'); + assert.match(doc, /<\/w:rPr>Users<\/w:t><\/w:r>/, 'bold'); + assert.match(doc, /[^]*?bulk<\/w:t>/, 'italic'); + assert.match(doc, /[^]*?old<\/w:t>/, 'strikethrough'); + assert.match(doc, /]*\/>[^]*?adminctl unlock<\/w:t>/, 'inline code'); + // A web link is a hyperlink relationship; a link to a step goes to its heading's bookmark. + const id = doc.match(/[^]*?<\/w:rPr>Users guide<\/w:t>/)[1]; + assert.match(rels, new RegExp(`Id="${id}" Type="[^"]+/hyperlink" Target="https://docs.example.com/users" TargetMode="External"`)); + const anchor = doc.match(/[^]*?the Users page/)[1]; + assert.match(doc, new RegExp(`[^]*?Open the Users page`)); + // Real numbered and bulleted lists, with a numbering part. + const items = [...doc.matchAll(/<\/w:numPr>[^]*?([^<]+) [m[1], m[2]]); + assert.deepEqual(items.map(([, text]) => text), ['Pick ', 'Choose ', 'works anywhere']); + assert.equal(items[0][0], items[1][0], 'one numbered list'); + assert.notEqual(items[1][0], items[2][0], 'then a separate bulleted one'); + const numbering = z.get('word/numbering.xml'); + assert.match(numbering, //); + assert.match(numbering, //, 'a bullet any font has'); + assert.match(rels, /Type="[^"]+\/numbering" Target="numbering.xml"/); + assert.match(z.get('[Content_Types].xml'), /PartName="\/word\/numbering.xml" ContentType="[^"]+numbering\+xml"/); + assert.match(doc, /[^]*?The old password stops working\./, 'quote'); + // The guide's description on the cover keeps its formatting too. + assert.match(doc, /<\/w:rPr>service desk { + const { root, ast } = richGuide(t); + const doc = unzip(exportDocx(ast, path.join(root, 'docx')).file).get('word/document.xml'); + const box = ''; + const paras = [...doc.matchAll(/([^]*?)<\/w:pPr>([^]*?)<\/w:p>/g)].filter((m) => m[1].includes(box)); + assert.equal(paras.length, 3, 'label, text and list item share the border and shading'); + assert.match(paras[0][2], /Tip: Shortcut/); + assert.match(paras[1][2], /[^]*?Ctrl\+R/); + assert.match(paras[2][2], /• <\/w:t>[^]*?works in /); + assert.ok(paras.every((m) => !m[1].includes('') && !m[1].includes('/, 'space after the box, not inside it'); +}); + +test('PowerPoint keeps description formatting, real bullets and numbers, and links', (t) => { + const { root, ast } = richGuide(t); + const { file, slideCount } = exportPptx(ast, path.join(root, 'pptx')); + const z = unzip(file); + const slides = Array.from({ length: slideCount }, (_, i) => z.get(`ppt/slides/slide${i + 1}.xml`)); + const slideOf = (title) => slides.findIndex((xml) => xml.includes('name="Step number"') && xml.includes(`${title}`)) + 1; + const first = slideOf('Open the Users page'); + const second = slideOf('Reset the password'); + const s1 = z.get(`ppt/slides/slide${first}.xml`); + const s2 = z.get(`ppt/slides/slide${second}.xml`); + assert.match(s1, /[^]*?Users<\/a:t>/, 'bold'); + assert.match(s1, /i="1"[^>]*>[^]*?bulk<\/a:t>/, 'italic'); + assert.match(s1, /strike="sngStrike"[^>]*>[^]*?old<\/a:t>/, 'strikethrough'); + assert.match(s2, /<\/a:rPr>adminctl unlock<\/a:t>/, 'inline code'); + assert.match(s2, /<\/a:pPr>[^]*?Pick <\/a:pPr>[^]*?Choose <\/a:pPr>[^]*?works anywhere<\/a:t>/, 'a bulleted list'); + assert.match(s2, /i="1"[^>]*>[^]*?The old password stops working\.<\/a:t>/, 'quote'); + // The web link points at its page; the step link jumps to that step's slide. + const web = s1.match(/<\/a:rPr>Users guide<\/a:t>/)[1]; + assert.match(z.get(`ppt/slides/_rels/slide${first}.xml.rels`), new RegExp(`Id="${web}" Type="[^"]+/hyperlink" Target="https://docs.example.com/users" TargetMode="External"`)); + const jump = s2.match(/<\/a:rPr>the Users page<\/a:t>/)[1]; + assert.match(z.get(`ppt/slides/_rels/slide${second}.xml.rels`), new RegExp(`Id="${jump}" Type="[^"]+/slide" Target="slide${first}.xml"`)); + // A callout's text keeps its formatting, its list items marked. + assert.match(s2, /Tip: Shortcut<\/a:t>[^]*?b="1"[^>]*>[^]*?Ctrl\+R<\/a:t>[^]*?• <\/a:t>[^]*?works in <\/a:t>/); +}); + +test('PowerPoint keeps formatting on both sides of a split onto a "(continued)" slide', (t) => { + const { root, ast } = richGuide(t); + const { file, slideCount } = exportPptx(ast, path.join(root, 'pptx')); + const z = unzip(file); + const slides = Array.from({ length: slideCount }, (_, i) => z.get(`ppt/slides/slide${i + 1}.xml`)).filter((xml) => xml.includes('A long one')); + assert.ok(slides.length >= 2, 'the long step continues'); + const runs = (xml) => [...xml.matchAll(/]*?b="(\d)"(?: i="1")?[^>]*>[^]*?([^<]*)<\/a:t>/g)]; + // Bold text stays bold and italic text stays italic on every slide it reaches. + for (const xml of slides) { + for (const m of [...xml.matchAll(/]*)>(?:(?!<\/a:rPr>)[^])*<\/a:rPr>([^<]*)<\/a:t>/g)]) { + if (m[2].startsWith('Check the account') && !m[1].includes('sz="2800"')) assert.ok(m[1].includes('b="1"') || m[1].includes('i="1"'), `"${m[2].slice(0, 30)}" keeps its style`); + } + } + assert.ok(runs(slides[0]).length > 0); +}); + +test('slide text helpers: paragraphs, list markers and splitting runs', () => { + const paras = richParagraphs('

A bold word
next line

  1. one
  2. two
AB
12
'); + assert.deepEqual(paras.slice(0, 2).map((p) => p.text), ['A bold word', 'next line']); + assert.deepEqual(paras[0].runs.map((r) => [r.text, Boolean(r.bold)]), [['A ', false], ['bold', true], [' word', false]]); + assert.deepEqual(paras.slice(2, 4).map(markedText), ['1. one', '2. two']); + assert.deepEqual(paras[4].rows, [['A', 'B'], ['1', '2']]); + const runs = paras[0].runs; + assert.deepEqual(sliceRuns(runs, 0, 4).map((r) => r.text), ['A ', 'bo']); + assert.deepEqual(sliceRuns(runs, 6).map((r) => [r.text, Boolean(r.bold)]), [['word', false]], 'leading space dropped'); +}); + +test('Word rich text: the Confluence (styled) form refers to styles and keeps the Symbol bullet', () => { + const rels = []; + const rich = new WordRichText({ ast: { steps: [] }, rel: (type, target) => { rels.push(target); return 'rId9'; }, anchorFor: () => 'x', table: () => '' }); + const xml = rich.richText('
  • one
q

l

'); + assert.match(xml, //); + assert.match(xml, //); + assert.match(xml, //); + assert.deepEqual(rels, ['https://example.com']); + assert.match(rich.numberingXml(), /[^]*? Date: Tue, 17 Nov 2026 13:38:14 -0600 Subject: [PATCH 2/2] Keep nested list depth, link query strings and split text intact in Word and PowerPoint - Lists: the parser's list depth is already zero-based, so a nested item was flattened to its parent's level. Word now also keeps one list per depth, so an outer numbered list keeps counting after a nested one. - Links: decode entities in href, so "?a=1&b=2" links to "?a=1&b=2" instead of "?a=1&amp;b=2". - Slides: split a long paragraph at an offset in its own text. Rejoining wrapped lines with spaces put the cut in the wrong place for long unbroken text, repeating characters across the two slides. --- core/htmlblocks.js | 3 +- exporters/pptx-text.js | 8 ++--- exporters/pptx.js | 45 ++++++++++++++++-------- exporters/word-rich.js | 20 ++++++----- tests/unit/rich-text-exports.test.js | 52 ++++++++++++++++++++++++++++ 5 files changed, 100 insertions(+), 28 deletions(-) diff --git a/core/htmlblocks.js b/core/htmlblocks.js index a20a72c2..7bf39716 100644 --- a/core/htmlblocks.js +++ b/core/htmlblocks.js @@ -147,7 +147,8 @@ function htmlToBlocks(html) { if (closing) styleStack.pop(); else { const hrefM = HREF_RE.exec(rawAttrs); - styleStack.push({ ...currentStyle(), href: hrefM ? (hrefM[1] ?? hrefM[2]) : undefined }); + // Decoded like text: "?a=1&b=2" is the link "?a=1&b=2". + styleStack.push({ ...currentStyle(), href: hrefM ? decodeEntities(hrefM[1] ?? hrefM[2]) : undefined }); } break; default: diff --git a/exporters/pptx-text.js b/exporters/pptx-text.js index 2e862d07..8060de96 100644 --- a/exporters/pptx-text.js +++ b/exporters/pptx-text.js @@ -64,7 +64,7 @@ function sliceRuns(runs, start, end = Infinity) { return normalizeRuns(out); } -const joined = (runs) => runs.map((r) => r.text).join(''); +const joinRuns = (runs) => runs.map((r) => r.text).join(''); function richParagraphs(html) { const out = []; @@ -84,8 +84,8 @@ function richParagraphs(html) { const continued = block.cont || i > 0; out.push({ runs, - text: joined(runs), - list: isList ? { ordered: block.type === 'oli', n: block.n || 1, level: Math.max(0, (block.indent || 1) - 1), continued } : null, + text: joinRuns(runs), + list: isList ? { ordered: block.type === 'oli', n: block.n || 1, level: block.indent || 0, continued } : null, quote: block.type === 'blockquote', heading: /^h[1-4]$/.test(block.type), }); @@ -102,4 +102,4 @@ function markedText(para) { return `${indent}${para.list.ordered ? `${para.list.n}.` : '•'} ${para.text}`; } -module.exports = { richParagraphs, sliceRuns, normalizeRuns, markedText }; +module.exports = { richParagraphs, sliceRuns, joinRuns, normalizeRuns, markedText }; diff --git a/exporters/pptx.js b/exporters/pptx.js index 4fef3854..7c545ea8 100644 --- a/exporters/pptx.js +++ b/exporters/pptx.js @@ -12,7 +12,7 @@ const { tocEntries, guideMetaLines, guideSummary } = require('./document-layout' const { SLIDE_SCREENSHOT_POSITIONS } = require('../core/branding'); const { withBrand, fitSize, textOn, brandRaster, hexToRgb } = require('./branding'); const metrics = require('./text-metrics'); -const { richParagraphs, sliceRuns, markedText } = require('./pptx-text'); +const { richParagraphs, sliceRuns, joinRuns, markedText } = require('./pptx-text'); const X = require('./pptx-xml'); /** @@ -245,18 +245,33 @@ function stackHeight(ctx, items, width, scale) { return items.reduce((sum, item, i) => sum + (i ? gapBetween(items[i - 1], item) : 0) + itemHeight(ctx, item, width, scale), 0); } +/** + * Where `text` ends after its first `count` wrapped `lines`. Lines are the + * text with whitespace collapsed and a long word broken between characters, + * so walk both together rather than rejoining the lines. + */ +function offsetAfterLines(text, lines, count) { + let at = 0; + for (const line of lines.slice(0, count)) { + for (const ch of line) { + if (/\s/.test(ch)) continue; + while (at < text.length && /\s/.test(text[at])) at += 1; + at += ch.length; + } + } + return at; +} + /** * Split wrapped text after its first `fit` lines, at the end of a sentence - * when one ends in the second half of them. Null when fewer than two lines - * fit or everything does. + * when one ends in the second half of them. Returns the character offset in + * `text` to cut at, or null when fewer than two lines fit or everything does. */ function splitText(text, lines, fit) { if (fit < 2 || fit >= lines.length) return null; - const head = lines.slice(0, fit).join(' '); + const head = text.slice(0, offsetAfterLines(text, lines, fit)); const sentence = [...head.matchAll(/[.!?。!?](?=\s|$)/g)].map((m) => m.index + 1).filter((i) => i > head.length / 2).pop(); - const cut = sentence || head.length; - const flat = lines.join(' '); - return [flat.slice(0, cut).trim(), flat.slice(cut).trim()]; + return sentence || head.length; } /** @@ -267,14 +282,14 @@ function splitText(text, lines, fit) { function splitItem(ctx, item, width, scale, maxH) { if (item.kind === 'para') { const m = measure(ctx, 'body', SIZE.body * scale, paraBold(item)); - const parts = splitText(item.text, metrics.wrapText(item.text, width - paraIndent(item), m).flat(), Math.floor(maxH / pt(m.lineHeight))); - if (!parts) return null; + const cut = splitText(item.text, metrics.wrapText(item.text, width - paraIndent(item), m).flat(), Math.floor(maxH / pt(m.lineHeight))); + if (cut == null) return null; // Both halves keep their formatting; the second continues a list item without a new bullet. - const head = sliceRuns(item.runs, 0, parts[0].length); - const tail = sliceRuns(item.runs, item.text.length - parts[1].length); + const head = sliceRuns(item.runs, 0, cut); + const tail = sliceRuns(item.runs, cut); return [ - { ...item, runs: head, text: parts[0] }, - { ...item, runs: tail, text: parts[1], list: item.list && { ...item.list, continued: true } }, + { ...item, runs: head, text: joinRuns(head) }, + { ...item, runs: tail, text: joinRuns(tail), list: item.list && { ...item.list, continued: true } }, ]; } if (item.kind === 'code') { @@ -290,8 +305,8 @@ function splitItem(ctx, item, width, scale, maxH) { const labelH = label ? metrics.textHeight(label, inner, measure(ctx, 'body', SIZE.callout * scale, true)) : 0; const m = measure(ctx, 'body', SIZE.callout * scale); const fit = Math.floor((maxH - labelH - pt(3) - CALLOUT_PAD_Y * 2) / pt(m.lineHeight)); - const parts = splitText(body, metrics.wrapText(body, inner, m).flat(), fit); - return parts && [{ ...item, label, body: parts[0], paras: null }, { ...item, label, body: parts[1], paras: null }]; + const cut = splitText(body, metrics.wrapText(body, inner, m).flat(), fit); + return cut == null ? null : [{ ...item, label, body: body.slice(0, cut).trim(), paras: null }, { ...item, label, body: body.slice(cut).trim(), paras: null }]; } if (item.kind === 'table') { const cols = tableColumns(ctx, item.rows, width, scale); diff --git a/exporters/word-rich.js b/exporters/word-rich.js index 3a17b934..7a27d2cd 100644 --- a/exporters/word-rich.js +++ b/exporters/word-rich.js @@ -104,31 +104,35 @@ class WordRichText { const options = { ...this.runOptions, ...rpr }; const styled = this.styled; const out = []; - let list = null; // { ordered, id } + const lists = []; // the open list at each depth: { ordered, id } let rows = []; // consecutive table rows, written as one Word table const endTable = () => { if (rows.length) out.push(this.tableXml(rows)); rows = []; }; const props = (own) => paragraphProps({ ...ppr, ...own }); for (const block of htmlToBlocks(html || '')) { - if (block.type === 'tr') { list = null; rows.push(block.cells); continue; } + if (block.type === 'tr') { lists.length = 0; rows.push(block.cells); continue; } endTable(); const isList = block.type === 'li' || block.type === 'oli'; const ordered = block.type === 'oli'; - if (!isList) list = null; + if (!isList) lists.length = 0; if (block.type === 'hr') { out.push(paragraph('', props({ pBdr: '' }))); continue; } if (isList && flatLists) { - const nested = '\u2003'.repeat(Math.max(0, block.indent - 1)); + const nested = '\u2003'.repeat(block.indent || 0); const marker = block.cont ? '\u2003' : (ordered ? `${block.n}.` : '\u2022'); out.push(paragraph(runXml(`${nested}${marker}\u2002`, {}, options) + this.runs(block.runs, options), props())); continue; } if (isList) { - if (!list || list.ordered !== ordered || (ordered && block.n === 1 && block.indent <= 1 && !block.cont)) { - list = { ordered, id: this.newList(ordered) }; + // One list per nesting depth (zero-based), so a parent list keeps + // counting after a nested list of either kind ends. + const lvl = Math.min(2, block.indent || 0); + lists.length = Math.min(lists.length, lvl + 1); + let list = lists[lvl]; + if (!list || list.ordered !== ordered || (ordered && block.n === 1 && !block.cont)) { + list = lists[lvl] = { ordered, id: this.newList(ordered) }; } - const lvl = Math.min(2, Math.max(0, block.indent - 1)); const style = styled ? 'ListParagraph' : ''; const spacing = styled ? '' : ''; // A line after a break in the item continues it: same indent, no new number. @@ -172,7 +176,7 @@ function numberingXml(nums, { bullet: mark = SYMBOL_BULLET } = {}) { ${bullet} ${decimal} -${nums.map((n) => `${n.abstractId === 1 ? '' : ''}`).join('\n')} +${nums.map((n) => `${n.abstractId === 1 ? [0, 1, 2].map((l) => ``).join('') : ''}`).join('\n')} `; } diff --git a/tests/unit/rich-text-exports.test.js b/tests/unit/rich-text-exports.test.js index 02dc4bda..24938c64 100644 --- a/tests/unit/rich-text-exports.test.js +++ b/tests/unit/rich-text-exports.test.js @@ -147,3 +147,55 @@ test('Word rich text: the Confluence (styled) form refers to styles and keeps th assert.deepEqual(rels, ['https://example.com']); assert.match(rich.numberingXml(), /[^]*? rmrf(root)); + const store = new GuideStore(path.join(root, 'data')); + const guide = store.createGuide({ title: 'One step' }); + store.addStep(guide.guideId, { kind: 'empty', title: 'The step', descriptionHtml }); + return { root, ast: buildRenderAst(store, guide.guideId) }; +} + +const NESTED = '
  1. Parent
    • Child
      1. Grandchild
  2. Next
'; + +test('nested lists keep their depth on slides and in Word, and the outer list keeps counting', (t) => { + assert.deepEqual(richParagraphs(NESTED).map((p) => [p.text, p.list.level]), [['Parent', 0], ['Child', 1], ['Grandchild', 2], ['Next', 0]]); + assert.deepEqual(richParagraphs(NESTED).map(markedText), ['1. Parent', ' • Child', ' 1. Grandchild', '2. Next']); + + const { root, ast } = oneStepGuide(t, NESTED); + const doc = unzip(exportDocx(ast, path.join(root, 'docx')).file).get('word/document.xml'); + const items = [...doc.matchAll(/[^]*?([^<]*)<\/w:t>/g)] + .map((m) => ({ text: m[3], lvl: Number(m[1]), num: m[2] })); + assert.deepEqual(items.map((i) => [i.text, i.lvl]), [['Parent', 0], ['Child', 1], ['Grandchild', 2], ['Next', 0]]); + assert.equal(items[3].num, items[0].num, '"Next" continues the outer numbered list, so it is numbered 2'); +}); + +test('links with several query parameters keep their "&" in Word and PowerPoint', (t) => { + const { root, ast } = oneStepGuide(t, '

See the page.

'); + const docxRels = unzip(exportDocx(ast, path.join(root, 'docx')).file).get('word/_rels/document.xml.rels'); + assert.match(docxRels, /Target="https:\/\/example\.com\/\?a=1&b=2" TargetMode="External"/); + const pptx = unzip(exportPptx(ast, path.join(root, 'pptx')).file); + const slideRels = [...pptx].filter(([name]) => /^ppt\/slides\/_rels\/slide\d+\.xml\.rels$/.test(name)).map(([, xml]) => xml).join(''); + assert.match(slideRels, /Target="https:\/\/example\.com\/\?a=1&b=2" TargetMode="External"/); + assert.doesNotMatch(docxRels + slideRels, /&amp;/); +}); + +test('PowerPoint splits long unbroken text onto "(continued)" slides without repeating or losing any of it', (t) => { + // No spaces to wrap at, so lines break between characters. + const bold = '粗'.repeat(1500); + const plain = '文'.repeat(1500); + const { root, ast } = oneStepGuide(t, `

${bold}${plain}

`); + const { file, slideCount } = exportPptx(ast, path.join(root, 'pptx')); + const z = unzip(file); + const slides = Array.from({ length: slideCount }, (_, i) => z.get(`ppt/slides/slide${i + 1}.xml`)).filter((xml) => xml.includes('The step')); + assert.ok(slides.length >= 2, 'the step continues'); + const runs = slides.flatMap((xml) => [...xml.matchAll(/]*)>(?:(?!<\/a:rPr>)[^])*<\/a:rPr>([^<]*)<\/a:t>/g)]); + const count = (ch) => runs.reduce((n, m) => n + [...m[2]].filter((c) => c === ch).length, 0); + assert.equal(count('粗'), 1500); + assert.equal(count('文'), 1500); + for (const m of runs) { + if (m[2].includes('粗')) assert.ok(m[1].includes('b="1"') && !m[2].includes('文'), 'bold text stays bold and apart from plain text'); + } +});