Something went wrong. Try again.
A free, open-source, self-hosted place to write a novel.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499import { strToU8, zipSync } from 'fflate';import { canonicalMark, sanitiseBody, type SafeNode as DocNode } from '#lib/body.ts';import { orderedBookChapters } from '#lib/matter.ts';import type { ManuscriptJson } from './export.ts';import { buildReadingManuscript } from './export-manuscript.ts';import type { ContentScope } from './scope.ts';
export type DocxExportPreset = { font: string; fontSizeHalfPoints: number; lineSpacingTwips: number; firstLineIndentTwips: number; marginTwips: number; pageBreakPerChapter: boolean; sceneSeparator: string; runningHeader?: { authorSurname: string; shortTitle: string; };};
export const SUBMISSION_PRESET: DocxExportPreset = { font: 'Times New Roman', fontSizeHalfPoints: 24, // 12 pt lineSpacingTwips: 480, // Double spacing firstLineIndentTwips: 720, // 0.5 inch marginTwips: 1440, // 1 inch pageBreakPerChapter: true, sceneSeparator: '#'};
function escapeXml(str: string): string { return str .replace(/&/g, '&') .replace(/</g, '<') .replace(/>/g, '>') .replace(/"/g, '"') .replace(/'/g, ''');}
/** Block-level node types, not inline runs. */const BLOCK_TYPES = new Set([ 'paragraph', 'heading', 'blockquote', 'bulletList', 'orderedList', 'listItem', 'codeBlock', 'horizontalRule']);
/** Word defines five list levels, so anything deeper shares the last one. */const LIST_DEPTH_LIMIT = 4;const LIST_NUM_ID = { bullet: 1, decimal: 2 } as const;const BULLET_GLYPHS = ['•', '◦', '▪', '•', '◦'];
function listLevels(kind: 'bullet' | 'decimal'): string { const levels: string[] = [];
for (let level = 0; level <= LIST_DEPTH_LIMIT; level += 1) { const text = kind === 'bullet' ? BULLET_GLYPHS[level] : `%${level + 1}.`; const format = kind === 'bullet' ? 'bullet' : 'decimal'; levels.push( `<w:lvl w:ilvl="${level}"><w:start w:val="1"/><w:numFmt w:val="${format}"/><w:lvlText w:val="${text}"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="${720 * (level + 1)}" w:hanging="360"/></w:pPr></w:lvl>` ); }
return levels.join('');}
function inlineToRuns(nodes: DocNode[] = []): string { let out = ''; for (const node of nodes) { if (node.type === 'hardBreak') { out += '<w:r><w:br/></w:r>'; continue; } if (node.type !== 'text' || !node.text) continue;
const marks = node.marks ?? []; /* * Stored bodies say `bold` and `italic`, the TipTap names; a body from * Markdown import says `strong` and `em`. Asking through `canonicalMark` * keeps the weight in the submission manuscript rather than dropping it. */ const names = new Set(marks.map((m) => canonicalMark(m.type))); const isStrong = names.has('bold'); const isEm = names.has('italic'); const isStrike = names.has('strike'); const isUnderline = names.has('underline');
let rPr = ''; if (isStrong) rPr += '<w:b/>'; if (isEm) rPr += '<w:i/>'; if (isStrike) rPr += '<w:strike/>'; if (isUnderline) rPr += '<w:u w:val="single"/>';
out += `<w:r>${rPr ? `<w:rPr>${rPr}</w:rPr>` : ''}<w:t xml:space="preserve">${escapeXml(node.text)}</w:t></w:r>`; } return out;}
function paragraphXml(properties: string, runs: string): string { return `<w:p><w:pPr>${properties}</w:pPr>${runs}</w:p>`;}
function spacingXml(preset: DocxExportPreset, before = 0, after = 0): string { return `<w:spacing w:line="${preset.lineSpacingTwips}" w:lineRule="auto" w:before="${before}" w:after="${after}"/>`;}
function bodyParagraph(block: DocNode, preset: DocxExportPreset): string { const runs = inlineToRuns(block.content ?? []); return paragraphXml( `<w:ind w:firstLine="${preset.firstLineIndentTwips}"/>${spacingXml(preset)}`, runs );}
function quoteParagraph(block: DocNode, preset: DocxExportPreset): string { const runs = inlineToRuns(block.content ?? []); return paragraphXml( `<w:pStyle w:val="Quote"/><w:ind w:left="1440" w:right="720" w:firstLine="0"/>${spacingXml(preset, 120, 120)}`, runs );}
function listParagraph( block: DocNode | null, kind: 'bullet' | 'decimal', depth: number, preset: DocxExportPreset): string { const runs = block ? inlineToRuns(block.content ?? []) : ''; const level = Math.min(depth, LIST_DEPTH_LIMIT); return paragraphXml( `<w:pStyle w:val="ListParagraph"/><w:numPr><w:ilvl w:val="${level}"/><w:numId w:val="${LIST_NUM_ID[kind]}"/></w:numPr>${spacingXml(preset)}`, runs );}
function hasBlockChildren(node: DocNode): boolean { return (node.content ?? []).some((child) => BLOCK_TYPES.has(child.type));}
function listBlocks( items: DocNode[], kind: 'bullet' | 'decimal', depth: number, preset: DocxExportPreset): string { let out = '';
for (const item of items) { if (item.type !== 'listItem') { out += blockToDocx(item, preset); continue; }
const children = item.content ?? []; if (children.length === 0) { out += listParagraph(null, kind, depth, preset); continue; }
for (const child of children) { if (child.type === 'paragraph') { out += listParagraph(child, kind, depth, preset); } else if (child.type === 'bulletList') { out += listBlocks(child.content ?? [], 'bullet', depth + 1, preset); } else if (child.type === 'orderedList') { out += listBlocks(child.content ?? [], 'decimal', depth + 1, preset); } else { out += blockToDocx(child, preset); } } }
return out;}
function codeBlocks(block: DocNode, preset: DocxExportPreset): string { const text = (block.content ?? []).map((child) => child.text ?? '').join(''); let out = '';
for (const line of text.split('\n')) { const run = line.length > 0 ? `<w:r><w:t xml:space="preserve">${escapeXml(line)}</w:t></w:r>` : ''; out += paragraphXml( `<w:pStyle w:val="Code"/><w:ind w:firstLine="0"/>${spacingXml(preset)}`, run ); }
return out;}
/** A rule inside prose is a visual break, so Word gets a blank paragraph. */function emptyBlock(preset: DocxExportPreset): string { return paragraphXml( `<w:ind w:firstLine="${preset.firstLineIndentTwips}"/>${spacingXml(preset)}`, '' );}
function blockToDocx(block: DocNode, preset: DocxExportPreset): string { switch (block.type) { case 'heading': { const level = Number(block.attrs?.level ?? 3); const style = level <= 2 ? 'Heading2' : 'Heading3'; const runs = inlineToRuns(block.content ?? []); return `<w:p><w:pPr><w:pStyle w:val="${style}"/><w:ind w:firstLine="0"/><w:spacing w:before="240" w:after="120"/></w:pPr>${runs}</w:p>`; }
case 'blockquote': return (block.content ?? []) .map((child) => child.type === 'paragraph' ? quoteParagraph(child, preset) : blockToDocx(child, preset) ) .join('');
case 'bulletList': return listBlocks(block.content ?? [], 'bullet', 0, preset);
case 'orderedList': return listBlocks(block.content ?? [], 'decimal', 0, preset);
case 'codeBlock': return codeBlocks(block, preset);
case 'horizontalRule': return emptyBlock(preset);
default: // An unknown container keeps the words inside it, one block at a time. return hasBlockChildren(block) ? (block.content ?? []).map((child) => blockToDocx(child, preset)).join('') : bodyParagraph(block, preset); }}
export function exportDocx( manuscript: ManuscriptJson, presetOverride?: Partial<DocxExportPreset>, titleOverride?: string): Uint8Array { const preset: DocxExportPreset = { ...SUBMISSION_PRESET, ...presetOverride };
const title = titleOverride?.trim() || manuscript.project.title || 'Untitled Manuscript'; // The header carries the pen name, not the account the writer signs in with. const author = preset.runningHeader?.authorSurname || manuscript.project.author?.trim() || 'Author'; const shortTitle = preset.runningHeader?.shortTitle || title.slice(0, 30); const nowIso = new Date().toISOString();
const contentTypes = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"> <Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/> <Default Extension="xml" ContentType="application/xml"/> <Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/> <Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/> <Override PartName="/word/numbering.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml"/> <Override PartName="/word/header1.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml"/> <Override PartName="/docProps/core.xml" ContentType="application/vnd.openxmlformats-package.core-properties+xml"/></Types>`;
const rootRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/> <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/package/2006/relationships/metadata/core-properties" Target="docProps/core.xml"/></Relationships>`;
const docPropsCore = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><cp:coreProperties xmlns:cp="http://schemas.openxmlformats.org/package/2006/metadata/core-properties" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dcterms="http://purl.org/dc/terms/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <dc:title>${escapeXml(title)}</dc:title> <dc:creator>${escapeXml(author)}</dc:creator> <dcterms:created xsi:type="dcterms:W3CDTF">${nowIso}</dcterms:created> <dcterms:modified xsi:type="dcterms:W3CDTF">${nowIso}</dcterms:modified></cp:coreProperties>`;
const docRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"> <Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/> <Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/header" Target="header1.xml"/> <Relationship Id="rId3" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/numbering" Target="numbering.xml"/></Relationships>`;
const numbering = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:numbering xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> <w:abstractNum w:abstractNumId="0"> <w:multiLevelType w:val="hybridMultilevel"/> ${listLevels('bullet')} </w:abstractNum> <w:abstractNum w:abstractNumId="1"> <w:multiLevelType w:val="hybridMultilevel"/> ${listLevels('decimal')} </w:abstractNum> <w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num> <w:num w:numId="2"><w:abstractNumId w:val="1"/></w:num></w:numbering>`;
const header1 = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:hdr xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> <w:p> <w:pPr> <w:pStyle w:val="Header"/> <w:jc w:val="right"/> </w:pPr> <w:r> <w:t xml:space="preserve">${escapeXml(author)} / ${escapeXml(shortTitle)} / </w:t> </w:r> <w:fldSimple w:instr="PAGE"/> </w:p></w:hdr>`;
const styles = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"> <w:docDefaults> <w:rPrDefault> <w:rPr> <w:rFonts w:ascii="${preset.font}" w:hAnsi="${preset.font}" w:cs="${preset.font}"/> <w:sz w:val="${preset.fontSizeHalfPoints}"/> <w:szCs w:val="${preset.fontSizeHalfPoints}"/> </w:rPr> </w:rPrDefault> </w:docDefaults> <w:style w:type="paragraph" w:default="1" w:styleId="Normal"> <w:name w:val="Normal"/> <w:qFormat/> <w:pPr> <w:spacing w:line="${preset.lineSpacingTwips}" w:lineRule="auto" w:before="0" w:after="0"/> <w:ind w:firstLine="${preset.firstLineIndentTwips}"/> </w:pPr> </w:style> <w:style w:type="paragraph" w:styleId="Heading1"> <w:name w:val="heading 1"/> <w:basedOn w:val="Normal"/> <w:qFormat/> <w:pPr> <w:outlineLvl w:val="0"/> <w:ind w:firstLine="0"/> <w:jc w:val="center"/> <w:spacing w:before="720" w:after="360"/> </w:pPr> <w:rPr> <w:b/> <w:sz w:val="${preset.fontSizeHalfPoints + 4}"/> <w:szCs w:val="${preset.fontSizeHalfPoints + 4}"/> </w:rPr> </w:style> <w:style w:type="paragraph" w:styleId="Heading2"> <w:name w:val="heading 2"/> <w:basedOn w:val="Normal"/> <w:qFormat/> <w:pPr> <w:outlineLvl w:val="1"/> <w:ind w:firstLine="0"/> <w:spacing w:before="360" w:after="180"/> </w:pPr> <w:rPr> <w:b/> </w:rPr> </w:style> <w:style w:type="paragraph" w:styleId="Heading3"> <w:name w:val="heading 3"/> <w:basedOn w:val="Normal"/> <w:qFormat/> <w:pPr> <w:outlineLvl w:val="2"/> <w:ind w:firstLine="0"/> <w:spacing w:before="240" w:after="120"/> </w:pPr> <w:rPr> <w:i/> </w:rPr> </w:style> <w:style w:type="paragraph" w:styleId="SceneBreak"> <w:name w:val="Scene Break"/> <w:basedOn w:val="Normal"/> <w:pPr> <w:ind w:firstLine="0"/> <w:jc w:val="center"/> <w:spacing w:before="360" w:after="360"/> </w:pPr> </w:style> <w:style w:type="paragraph" w:styleId="Header"> <w:name w:val="header"/> <w:basedOn w:val="Normal"/> <w:pPr> <w:ind w:firstLine="0"/> <w:spacing w:line="240" w:lineRule="auto" w:before="0" w:after="0"/> </w:pPr> </w:style> <w:style w:type="paragraph" w:styleId="Quote"> <w:name w:val="Quote"/> <w:basedOn w:val="Normal"/> <w:qFormat/> <w:pPr> <w:ind w:left="1440" w:right="720" w:firstLine="0"/> <w:spacing w:line="${preset.lineSpacingTwips}" w:lineRule="auto" w:before="120" w:after="120"/> </w:pPr> </w:style> <w:style w:type="paragraph" w:styleId="ListParagraph"> <w:name w:val="List Paragraph"/> <w:basedOn w:val="Normal"/> <w:qFormat/> <w:pPr> <w:ind w:firstLine="0"/> <w:spacing w:line="${preset.lineSpacingTwips}" w:lineRule="auto" w:before="0" w:after="0"/> </w:pPr> </w:style> <w:style w:type="paragraph" w:styleId="Code"> <w:name w:val="Code"/> <w:basedOn w:val="Normal"/> <w:pPr> <w:ind w:firstLine="0"/> <w:spacing w:line="240" w:lineRule="auto" w:before="0" w:after="0"/> </w:pPr> <w:rPr> <w:rFonts w:ascii="Courier New" w:hAnsi="Courier New" w:cs="Courier New"/> </w:rPr> </w:style></w:styles>`;
let documentBody = ''; let chapterCount = 0;
const live = (row: { deletedAt?: string | null }) => !row.deletedAt;
for (const book of (manuscript.books ?? []).filter(live)) { const allChapters = orderedBookChapters(book).filter(live);
for (const chapter of allChapters) { const pageBreak = preset.pageBreakPerChapter && chapterCount > 0 ? '<w:pageBreakBefore/>' : ''; chapterCount += 1;
documentBody += `<w:p><w:pPr><w:pStyle w:val="Heading1"/>${pageBreak}<w:jc w:val="center"/><w:ind w:firstLine="0"/></w:pPr><w:r><w:rPr><w:b/></w:rPr><w:t>${escapeXml(chapter.title)}</w:t></w:r></w:p>`;
const scenes = (chapter.scenes ?? []).filter(live); for (let sIdx = 0; sIdx < scenes.length; sIdx += 1) { const scene = scenes[sIdx]; if (sIdx > 0) { documentBody += `<w:p><w:pPr><w:pStyle w:val="SceneBreak"/><w:jc w:val="center"/><w:ind w:firstLine="0"/></w:pPr><w:r><w:t>${escapeXml(preset.sceneSeparator)}</w:t></w:r></w:p>`; }
const doc = sanitiseBody(scene.body); if (doc && doc.content.length > 0) { for (const block of doc.content) { documentBody += blockToDocx(block, preset); } } else if (scene.bodyText) { documentBody += `<w:p><w:pPr><w:ind w:firstLine="${preset.firstLineIndentTwips}"/><w:spacing w:line="${preset.lineSpacingTwips}" w:lineRule="auto" w:before="0" w:after="0"/></w:pPr><w:r><w:t xml:space="preserve">${escapeXml(scene.bodyText)}</w:t></w:r></w:p>`; } } } }
const sectPr = `<w:sectPr> <w:headerReference w:type="default" r:id="rId2"/> <w:pgSz w:w="12240" w:h="15840"/> <w:pgMar w:top="${preset.marginTwips}" w:right="${preset.marginTwips}" w:bottom="${preset.marginTwips}" w:left="${preset.marginTwips}" w:header="720" w:footer="720" w:gutter="0"/> </w:sectPr>`;
const documentXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"> <w:body> ${documentBody} ${sectPr} </w:body></w:document>`;
return zipSync({ '[Content_Types].xml': strToU8(contentTypes), '_rels/.rels': strToU8(rootRels), 'docProps/core.xml': strToU8(docPropsCore), 'word/_rels/document.xml.rels': strToU8(docRels), 'word/styles.xml': strToU8(styles), 'word/numbering.xml': strToU8(numbering), 'word/header1.xml': strToU8(header1), 'word/document.xml': strToU8(documentXml) });}
export function buildDocxExport( projectId: string, options: { scope?: ContentScope; preset?: Partial<DocxExportPreset> } = {}): { filename: string; bytes: Uint8Array } { const { manuscript, stem, title } = buildReadingManuscript(projectId, options.scope); const bytes = exportDocx(manuscript, options.preset, title); return { filename: `${stem}.docx`, bytes };}