Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion core/htmlblocks.js
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
7 changes: 5 additions & 2 deletions docs/GETTING_STARTED.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
96 changes: 7 additions & 89 deletions exporters/confluence-word.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -35,29 +35,15 @@ const CALLOUT = {
error: { fill: 'FFEBE6', border: 'DE350B' },
};

function runXml(text, { bold, italic, strike, code, link } = {}) {
const rpr = [
link ? '<w:rStyle w:val="Hyperlink"/>' : '',
code ? '<w:rFonts w:ascii="Courier New" w:hAnsi="Courier New" w:cs="Courier New"/>' : '',
bold ? '<w:b/>' : '',
italic ? '<w:i/>' : '',
strike ? '<w:strike/>' : '',
].join('');
return String(text).split('\n').map((line, i) => (
`${i ? '<w:r><w:br/></w:r>' : ''}<w:r>${rpr ? `<w:rPr>${rpr}</w:rPr>` : ''}<w:t xml:space="preserve">${escapeXml(line)}</w:t></w:r>`
)).join('');
}

function paragraph(content, props = '') {
return `<w:p>${props ? `<w:pPr>${props}</w:pPr>` : ''}${content}</w:p>`;
}

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;
}
Expand All @@ -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 `<w:hyperlink w:anchor="${this.anchorFor(target)}">${runXml(r.text, { ...r, link: true })}</w:hyperlink>`;
}
if (r.href && /^(https?:|mailto:)/i.test(r.href)) {
return `<w:hyperlink r:id="${this.rel('hyperlink', r.href, true)}">${runXml(r.text, { ...r, link: true })}</w:hyperlink>`;
}
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('', '<w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="C1C7D0"/></w:pBdr>'));
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), `<w:pStyle w:val="ListParagraph"/><w:ind w:left="${720 * (lvl + 1)}"/>`)
: paragraph(this.runs(block.runs), `<w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="${lvl}"/><w:numId w:val="${list.id}"/></w:numPr>`));
continue;
}
if (/^h[1-4]$/.test(block.type)) {
out.push(paragraph(this.runs(block.runs), '<w:pStyle w:val="Heading4"/>'));
} else if (block.type === 'blockquote') {
out.push(paragraph(this.runs(block.runs), '<w:pStyle w:val="Quote"/>'));
} else {
out.push(paragraph(this.runs(block.runs)));
}
}
endTable();
return out.join('');
return this.rich.richText(html);
}

callout(tb) {
Expand Down Expand Up @@ -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: `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
Expand Down Expand Up @@ -314,20 +246,6 @@ ${style('Code', 'Code', { ppr: '<w:shd w:val="clear" w:color="auto" w:fill="F4F5
${style('Hyperlink', 'Hyperlink', { type: 'character', basedOn: null, rpr: '<w:color w:val="0052CC"/><w:u w:val="single"/>' })}
</w:styles>`;

function numberingXml(nums) {
const level = (ilvl, fmt, text) => `<w:lvl w:ilvl="${ilvl}"><w:start w:val="1"/><w:numFmt w:val="${fmt}"/>`
+ `<w:lvlText w:val="${text}"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720 * (ilvl + 1)}" w:hanging="360"/></w:pPr>`
+ `${fmt === 'bullet' ? '<w:rPr><w:rFonts w:ascii="Symbol" w:hAnsi="Symbol" w:hint="default"/></w:rPr>' : ''}</w:lvl>`;
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 `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:numbering xmlns:w="${W_NS}">
<w:abstractNum w:abstractNumId="0"><w:multiLevelType w:val="hybridMultilevel"/>${bullet}</w:abstractNum>
<w:abstractNum w:abstractNumId="1"><w:multiLevelType w:val="hybridMultilevel"/>${decimal}</w:abstractNum>
${nums.map((n) => `<w:num w:numId="${n.id}"><w:abstractNumId w:val="${n.abstractId}"/>${n.abstractId === 1 ? '<w:lvlOverride w:ilvl="0"><w:startOverride w:val="1"/></w:lvlOverride>' : ''}</w:num>`).join('\n')}
</w:numbering>`;
}

/** Build the .docx bytes for a guide. */
function buildConfluenceWord(ast, images, tpl = { includeImages: true }) {
return new WordDocument(ast).build(images, tpl);
Expand Down
61 changes: 54 additions & 7 deletions exporters/docx.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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(/<w:br\b[^>]*\/>/g, '\n')
return xml.replace(/<w:br\b[^>]*\/>/g, '\n').replace(/<\/w:p>(?=.)/g, '\n')
.replace(/<[^>]*>/g, '').replace(/&lt;/g, '<').replace(/&gt;/g, '>')
.replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&');
}
Expand All @@ -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('<w:p>')) return xml;
const paras = xml.includes('<w:tbl>') ? [xml] : xml.split(/(?=<w:p>)/);
// 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(/^<w:p>(?:<w:pPr>([\s\S]*?)<\/w:pPr>)?/);
const props = (match[1] || '').replace(/<w:keep(?:Next|Lines)\b[^>]*\/>/g, '');
const style = props.match(/<w:pStyle\b[^>]*\/>/)?.[0] || '';
Expand Down Expand Up @@ -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(`<Relationship Id="rId${relId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/${type}" Target="${escapeXml(target)}"${external ? ' TargetMode="External"' : ''}/>`);
return `rId${relId}`;
},
});

const body = [];
// Under a flowchart picture: its shapes' step links (Word can't link parts of a picture).
const chartLinkParagraph = (chart) => {
Expand Down Expand Up @@ -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}<w:spacing w:before="120" w:after="240"/>`)
: p(run(ast.guide.title, { bold: true, size: 48 }),
`<w:pBdr><w:bottom w:val="single" w:sz="24" w:space="12" w:color="${primary}"/></w:pBdr>${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' })));

Expand All @@ -468,13 +500,21 @@ function exportDocx(ast, outDir, template = {}) {
const shots = screenshotOptions(ast);
const alignProps = shots.align === 'left' ? '' : `<w:jc w:val="${shots.align}"/>`;

// 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 }) : ''}`,
`<w:shd w:val="clear" w:fill="${style.fill}"/><w:pBdr><w:left w:val="single" w:sz="24" w:space="4" w:color="${style.color}"/></w:pBdr>`
));
const box = {
pBdr: `<w:pBdr><w:left w:val="single" w:sz="24" w:space="4" w:color="${style.color}"/></w:pBdr>`,
shd: `<w:shd w:val="clear" w:fill="${style.fill}"/>`,
spacing: '<w:spacing w:before="0" w:after="0"/>',
};
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)}<w:spacing w:before="0" w:after="160"/>${xml.slice(last + box.spacing.length)}`);
};

const parentIds = new Set(ast.steps.map((step) => step.parentStepId).filter(Boolean));
Expand Down Expand Up @@ -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`;
Expand Down Expand Up @@ -602,6 +642,13 @@ function exportDocx(ast, outDir, template = {}) {
+ `<w:footerReference w:type="default" r:id="${footer}"/><w:footerReference w:type="first" r:id="${firstFooter}"/>`;
}

// Lists in descriptions and callouts need a numbering part.
if (rich.nums.length) {
const relId = ++relCounter;
rels.push(`<Relationship Id="rId${relId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/>`);
parts.push({ name: 'word/numbering.xml', data: rich.numberingXml(), kind: 'numbering', rels: [] });
}

const documentXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"
xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing"
Expand Down
105 changes: 105 additions & 0 deletions exporters/pptx-text.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
'use strict';

const { htmlToBlocks } = require('../core/htmlblocks');

/**
* Step text for slides: sanitized description HTML as paragraphs of
* formatted runs, ready to measure and split.
*
* Each paragraph is { text, runs, list, quote, heading }:
* runs: [{ text, bold, italic, strike, code, href }]
* text: the runs' text joined, whitespace collapsed to single spaces and
* trimmed, so it wraps and splits the same way it's measured
* list: { ordered, n, level } for a list item, else null
* quote: true inside a block quote; heading: true for a heading
* A line break inside a paragraph starts a new paragraph (a list item's
* continuation keeps its indent, without a bullet). Table rows come out as
* { rows } groups, in place.
*/

/** Runs with whitespace collapsed across them, leading and trailing space dropped. */
function normalizeRuns(runs) {
const out = [];
let prevSpace = true;
for (const run of runs) {
let text = '';
for (const ch of run.text.replace(/\s/g, ' ')) {
if (ch === ' ' && prevSpace) continue;
text += ch;
prevSpace = ch === ' ';
}
if (text) out.push({ ...run, text });
}
// Trailing space.
while (out.length && out[out.length - 1].text.endsWith(' ')) {
const last = out[out.length - 1];
last.text = last.text.slice(0, -1);
if (!last.text) out.pop();
}
return out;
}

/** Split runs at line breaks into one run list per line. */
function splitLines(runs) {
const lines = [[]];
for (const run of runs) {
run.text.split('\n').forEach((part, i) => {
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 joinRuns = (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: 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),
});
});
}
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, joinRuns, normalizeRuns, markedText };
Loading
Loading