import { 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, '''); } /** 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( `` ); } return levels.join(''); } function inlineToRuns(nodes: DocNode[] = []): string { let out = ''; for (const node of nodes) { if (node.type === 'hardBreak') { out += ''; 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 += ''; if (isEm) rPr += ''; if (isStrike) rPr += ''; if (isUnderline) rPr += ''; out += `${rPr ? `${rPr}` : ''}${escapeXml(node.text)}`; } return out; } function paragraphXml(properties: string, runs: string): string { return `${properties}${runs}`; } function spacingXml(preset: DocxExportPreset, before = 0, after = 0): string { return ``; } function bodyParagraph(block: DocNode, preset: DocxExportPreset): string { const runs = inlineToRuns(block.content ?? []); return paragraphXml( `${spacingXml(preset)}`, runs ); } function quoteParagraph(block: DocNode, preset: DocxExportPreset): string { const runs = inlineToRuns(block.content ?? []); return paragraphXml( `${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( `${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 ? `${escapeXml(line)}` : ''; out += paragraphXml( `${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( `${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 `${runs}`; } 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, 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 = ` `; const rootRels = ` `; const docPropsCore = ` ${escapeXml(title)} ${escapeXml(author)} ${nowIso} ${nowIso} `; const docRels = ` `; const numbering = ` ${listLevels('bullet')} ${listLevels('decimal')} `; const header1 = ` ${escapeXml(author)} / ${escapeXml(shortTitle)} / `; const 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 ? '' : ''; chapterCount += 1; documentBody += `${pageBreak}${escapeXml(chapter.title)}`; const scenes = (chapter.scenes ?? []).filter(live); for (let sIdx = 0; sIdx < scenes.length; sIdx += 1) { const scene = scenes[sIdx]; if (sIdx > 0) { documentBody += `${escapeXml(preset.sceneSeparator)}`; } 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 += `${escapeXml(scene.bodyText)}`; } } } } const sectPr = ` `; const documentXml = ` ${documentBody} ${sectPr} `; 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 } = {} ): { filename: string; bytes: Uint8Array } { const { manuscript, stem, title } = buildReadingManuscript(projectId, options.scope); const bytes = exportDocx(manuscript, options.preset, title); return { filename: `${stem}.docx`, bytes }; }