mirror of
https://github.com/docmost/docmost.git
synced 2026-07-22 20:42:47 +10:00
feat(ee): docx word export
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
"name": "@docmost/editor-ext",
|
||||
"homepage": "https://docmost.com",
|
||||
"private": true,
|
||||
"sideEffects": false,
|
||||
"scripts": {
|
||||
"build": "tsc --build",
|
||||
"dev": "tsc --watch"
|
||||
|
||||
@@ -34,3 +34,7 @@ export * from "./lib/pdf";
|
||||
export * from "./lib/page-break";
|
||||
export * from "./lib/resizable-nodeview";
|
||||
|
||||
export {
|
||||
pageNodeToDocxBuffer,
|
||||
type DocxImageResolver,
|
||||
} from "./lib/prosemirror-docx";
|
||||
|
||||
@@ -16,10 +16,9 @@ export {
|
||||
MAX_IMAGE_WIDTH,
|
||||
} from './serializer';
|
||||
export {
|
||||
defaultDocxSerializer,
|
||||
defaultDocxSerializerAsync,
|
||||
defaultAsyncNodes,
|
||||
defaultNodes,
|
||||
defaultMarks,
|
||||
pageNodeToDocxBuffer,
|
||||
type DocxImageResolver,
|
||||
} from './schema';
|
||||
export { writeDocx, createDocFromState, buildDoc } from './utils';
|
||||
|
||||
@@ -1,76 +1,67 @@
|
||||
import { HeadingLevel, ShadingType } from 'docx';
|
||||
import { Node } from 'prosemirror-model';
|
||||
import {
|
||||
DocxSerializer,
|
||||
MarkSerializer,
|
||||
NodeSerializer,
|
||||
DocxSerializerAsync,
|
||||
MarkSerializer,
|
||||
NodeSerializerAsync,
|
||||
OptionsAsync,
|
||||
} from './serializer';
|
||||
import { getLatexFromNode } from './utils';
|
||||
import { writeDocx } from './utils';
|
||||
|
||||
export const defaultNodes: NodeSerializer = {
|
||||
text(state, node) {
|
||||
state.text(node.text ?? '');
|
||||
},
|
||||
paragraph(state, node) {
|
||||
state.renderInline(node);
|
||||
state.closeBlock(node);
|
||||
},
|
||||
heading(state, node) {
|
||||
state.renderInline(node);
|
||||
const heading = [
|
||||
HeadingLevel.HEADING_1,
|
||||
HeadingLevel.HEADING_2,
|
||||
HeadingLevel.HEADING_3,
|
||||
HeadingLevel.HEADING_4,
|
||||
HeadingLevel.HEADING_5,
|
||||
HeadingLevel.HEADING_6,
|
||||
][node.attrs.level - 1];
|
||||
state.closeBlock(node, { heading });
|
||||
},
|
||||
blockquote(state, node) {
|
||||
state.renderContent(node, { style: 'IntenseQuote' });
|
||||
},
|
||||
code_block(state, node) {
|
||||
// TODO: something for code
|
||||
state.renderContent(node);
|
||||
state.closeBlock(node);
|
||||
},
|
||||
horizontal_rule(state, node) {
|
||||
// Kinda hacky, but this works to insert two paragraphs, the first with a break
|
||||
state.closeBlock(node, { thematicBreak: true });
|
||||
state.closeBlock(node);
|
||||
},
|
||||
hard_break(state) {
|
||||
state.addRunOptions({ break: 1 });
|
||||
},
|
||||
ordered_list(state, node) {
|
||||
state.renderList(node, 'numbered');
|
||||
},
|
||||
bullet_list(state, node) {
|
||||
state.renderList(node, 'bullets');
|
||||
},
|
||||
list_item(state, node) {
|
||||
state.renderListItem(node);
|
||||
},
|
||||
// Presentational
|
||||
image(state, node) {
|
||||
const { src } = node.attrs;
|
||||
state.image(src);
|
||||
state.closeBlock(node);
|
||||
},
|
||||
// Technical
|
||||
math(state, node) {
|
||||
state.math(getLatexFromNode(node), { inline: true });
|
||||
},
|
||||
equation(state, node) {
|
||||
const { id, numbered } = node.attrs;
|
||||
state.math(getLatexFromNode(node), { inline: false, numbered, id });
|
||||
state.closeBlock(node);
|
||||
},
|
||||
table(state, node) {
|
||||
state.table(node);
|
||||
},
|
||||
export type DocxImageResolver = OptionsAsync['getImageBuffer'];
|
||||
|
||||
// docx requires a 6-digit hex color (no leading #). Convert #rgb, #rrggbb,
|
||||
// and rgb()/rgba() inputs to 6-digit hex; return undefined for anything else
|
||||
// (named colors, hsl, etc.) so the caller omits the color rather than letting
|
||||
// docx throw "Invalid hex value".
|
||||
function toDocxColor(input?: string): string | undefined {
|
||||
if (!input) return undefined;
|
||||
const value = input.trim().toLowerCase();
|
||||
const hex = value.startsWith('#') ? value.slice(1) : value;
|
||||
if (/^[0-9a-f]{6}$/.test(hex)) return hex;
|
||||
if (/^[0-9a-f]{3}$/.test(hex)) {
|
||||
return hex
|
||||
.split('')
|
||||
.map((ch) => ch + ch)
|
||||
.join('');
|
||||
}
|
||||
const rgb = value.match(/^rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
|
||||
if (rgb) {
|
||||
const channel = (n: string) =>
|
||||
Math.max(0, Math.min(255, parseInt(n, 10)))
|
||||
.toString(16)
|
||||
.padStart(2, '0');
|
||||
return channel(rgb[1]) + channel(rgb[2]) + channel(rgb[3]);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Images and diagrams embed via the image resolver; the URL (with its file
|
||||
// extension) is passed through so docx can infer the image type.
|
||||
const renderImage: NodeSerializerAsync[string] = async (state, node) => {
|
||||
const src = node.attrs?.src || node.attrs?.attachmentId;
|
||||
if (src) {
|
||||
try {
|
||||
await state.image(src, 100);
|
||||
} catch {
|
||||
// Unrenderable/missing image: skip rather than fail the whole export.
|
||||
}
|
||||
}
|
||||
state.closeBlock(node);
|
||||
};
|
||||
|
||||
// Non-embeddable media render as a labelled line.
|
||||
const renderFileLine: NodeSerializerAsync[string] = (state, node) => {
|
||||
const label =
|
||||
node.attrs?.name || node.attrs?.src || node.attrs?.url || 'attachment';
|
||||
state.text(label);
|
||||
state.closeBlock(node);
|
||||
};
|
||||
|
||||
const renderEmbedLine: NodeSerializerAsync[string] = (state, node) => {
|
||||
const label = node.attrs?.src || node.attrs?.url || 'embed';
|
||||
state.text(label);
|
||||
state.closeBlock(node);
|
||||
};
|
||||
|
||||
export const defaultAsyncNodes: NodeSerializerAsync = {
|
||||
@@ -90,111 +81,170 @@ export const defaultAsyncNodes: NodeSerializerAsync = {
|
||||
HeadingLevel.HEADING_4,
|
||||
HeadingLevel.HEADING_5,
|
||||
HeadingLevel.HEADING_6,
|
||||
][node.attrs.level - 1];
|
||||
][(node.attrs.level ?? 1) - 1];
|
||||
state.closeBlock(node, { heading });
|
||||
},
|
||||
blockquote(state, node) {
|
||||
state.renderContent(node, { style: 'IntenseQuote' });
|
||||
async blockquote(state, node) {
|
||||
await state.renderContent(node, { style: 'IntenseQuote' });
|
||||
},
|
||||
code_block(state, node) {
|
||||
// TODO: something for code
|
||||
state.renderContent(node);
|
||||
async codeBlock(state, node) {
|
||||
await state.renderContent(node);
|
||||
state.closeBlock(node);
|
||||
},
|
||||
horizontal_rule(state, node) {
|
||||
// Kinda hacky, but this works to insert two paragraphs, the first with a break
|
||||
horizontalRule(state, node) {
|
||||
state.closeBlock(node, { thematicBreak: true });
|
||||
state.closeBlock(node);
|
||||
},
|
||||
hard_break(state) {
|
||||
hardBreak(state) {
|
||||
state.addRunOptions({ break: 1 });
|
||||
},
|
||||
async ordered_list(state, node) {
|
||||
await state.renderList(node, 'numbered');
|
||||
},
|
||||
async bullet_list(state, node) {
|
||||
async bulletList(state, node) {
|
||||
await state.renderList(node, 'bullets');
|
||||
},
|
||||
async list_item(state, node) {
|
||||
async orderedList(state, node) {
|
||||
await state.renderList(node, 'numbered');
|
||||
},
|
||||
async listItem(state, node) {
|
||||
await state.renderListItem(node);
|
||||
},
|
||||
// Presentational
|
||||
async image(state, node) {
|
||||
const { src } = node.attrs;
|
||||
await state.image(src);
|
||||
state.closeBlock(node);
|
||||
async taskList(state, node) {
|
||||
await state.renderList(node, 'bullets');
|
||||
},
|
||||
// Technical
|
||||
math(state, node) {
|
||||
state.math(getLatexFromNode(node), { inline: true });
|
||||
},
|
||||
equation(state, node) {
|
||||
const { id, numbered } = node.attrs;
|
||||
state.math(getLatexFromNode(node), { inline: false, numbered, id });
|
||||
state.closeBlock(node);
|
||||
async taskItem(state, node) {
|
||||
if (state.currentNumbering) {
|
||||
state.addParagraphOptions({ numbering: state.currentNumbering });
|
||||
}
|
||||
state.text(node.attrs?.checked ? '☑ ' : '☐ ');
|
||||
await state.renderContent(node);
|
||||
},
|
||||
async table(state, node) {
|
||||
await state.table(node);
|
||||
},
|
||||
// Docmost stores LaTeX in attrs.text.
|
||||
mathInline(state, node) {
|
||||
state.math(node.attrs?.text ?? '', { inline: true });
|
||||
},
|
||||
mathBlock(state, node) {
|
||||
state.math(node.attrs?.text ?? '', { inline: false, numbered: false });
|
||||
state.closeBlock(node);
|
||||
},
|
||||
image: renderImage,
|
||||
drawio: renderImage,
|
||||
excalidraw: renderImage,
|
||||
video: renderFileLine,
|
||||
audio: renderFileLine,
|
||||
pdf: renderFileLine,
|
||||
attachment: renderFileLine,
|
||||
embed: renderEmbedLine,
|
||||
youtube: renderEmbedLine,
|
||||
async callout(state, node) {
|
||||
await state.renderContent(node, { style: 'IntenseQuote' });
|
||||
},
|
||||
async details(state, node) {
|
||||
await state.renderContent(node);
|
||||
},
|
||||
async detailsSummary(state, node) {
|
||||
await state.renderInline(node);
|
||||
state.closeBlock(node, { heading: HeadingLevel.HEADING_4 });
|
||||
},
|
||||
async detailsContent(state, node) {
|
||||
await state.renderContent(node);
|
||||
},
|
||||
async columns(state, node) {
|
||||
await state.renderContent(node);
|
||||
},
|
||||
async column(state, node) {
|
||||
await state.renderContent(node);
|
||||
},
|
||||
async transclusionSource(state, node) {
|
||||
await state.renderContent(node);
|
||||
},
|
||||
mention(state, node) {
|
||||
state.text(`@${node.attrs?.label ?? ''}`);
|
||||
},
|
||||
status(state, node) {
|
||||
state.text(`[${node.attrs?.text ?? ''}]`);
|
||||
},
|
||||
pageBreak(state, node) {
|
||||
state.closeBlock(node, { pageBreakBefore: true });
|
||||
},
|
||||
// No usable static export representation: skip without failing.
|
||||
subpages() {},
|
||||
transclusionReference() {},
|
||||
};
|
||||
|
||||
export const defaultMarks: MarkSerializer = {
|
||||
em() {
|
||||
return { italics: true };
|
||||
},
|
||||
strong() {
|
||||
bold() {
|
||||
return { bold: true };
|
||||
},
|
||||
italic() {
|
||||
return { italics: true };
|
||||
},
|
||||
bold() {
|
||||
return { bold: true };
|
||||
strike() {
|
||||
return { strike: true };
|
||||
},
|
||||
link() {
|
||||
// Note, this is handled specifically in the serializer
|
||||
// Word treats links more like a Node rather than a mark
|
||||
return {};
|
||||
underline() {
|
||||
return { underline: {} };
|
||||
},
|
||||
code() {
|
||||
return {
|
||||
font: {
|
||||
name: 'Monospace',
|
||||
},
|
||||
font: { name: 'Monospace' },
|
||||
color: '000000',
|
||||
shading: {
|
||||
type: ShadingType.SOLID,
|
||||
color: 'D2D3D2',
|
||||
fill: 'D2D3D2',
|
||||
},
|
||||
shading: { type: ShadingType.SOLID, color: 'D2D3D2', fill: 'D2D3D2' },
|
||||
};
|
||||
},
|
||||
abbr() {
|
||||
// TODO: abbreviation
|
||||
return {};
|
||||
},
|
||||
subscript() {
|
||||
return { subScript: true };
|
||||
},
|
||||
superscript() {
|
||||
return { superScript: true };
|
||||
},
|
||||
strikethrough() {
|
||||
// doubleStrike!
|
||||
return { strike: true };
|
||||
subscript() {
|
||||
return { subScript: true };
|
||||
},
|
||||
underline() {
|
||||
return {
|
||||
underline: {},
|
||||
};
|
||||
link() {
|
||||
// Handled specifically in the serializer; Word treats links as nodes.
|
||||
return {};
|
||||
},
|
||||
smallcaps() {
|
||||
return { smallCaps: true };
|
||||
highlight(_state, _node, mark) {
|
||||
const fill = toDocxColor(mark.attrs?.color);
|
||||
return fill
|
||||
? { shading: { type: ShadingType.CLEAR, fill } }
|
||||
: { highlight: 'yellow' };
|
||||
},
|
||||
allcaps() {
|
||||
return { allCaps: true };
|
||||
// @tiptap/extension-color stores the color on the textStyle mark.
|
||||
textStyle(_state, _node, mark) {
|
||||
const color = toDocxColor(mark.attrs?.color);
|
||||
return color ? { color } : {};
|
||||
},
|
||||
// Comments are editor-only; drop the annotation in the export.
|
||||
comment() {
|
||||
return {};
|
||||
},
|
||||
};
|
||||
|
||||
export const defaultDocxSerializer = new DocxSerializer(defaultNodes, defaultMarks);
|
||||
export const defaultDocxSerializerAsync = new DocxSerializerAsync(defaultAsyncNodes, defaultMarks);
|
||||
export async function pageNodeToDocxBuffer(
|
||||
doc: Node,
|
||||
getImageBuffer: DocxImageResolver,
|
||||
): Promise<Buffer> {
|
||||
const serializer = new DocxSerializerAsync(defaultAsyncNodes, defaultMarks);
|
||||
const wordDoc = await serializer.serializeAsync(
|
||||
doc,
|
||||
{ getImageBuffer },
|
||||
// docx's built-in heading styles are blue (#2E74B5 / #1F4D78). The editor
|
||||
// has no heading color, so override the default heading run colors to the
|
||||
// normal text color. Sizes/italics mirror docx's own defaults so only the
|
||||
// color changes.
|
||||
() =>
|
||||
({
|
||||
styles: {
|
||||
default: {
|
||||
heading1: { run: { color: '000000', size: 32 } },
|
||||
heading2: { run: { color: '000000', size: 26 } },
|
||||
heading3: { run: { color: '000000', size: 24 } },
|
||||
heading4: { run: { color: '000000', italics: true } },
|
||||
heading5: { run: { color: '000000' } },
|
||||
heading6: { run: { color: '000000' } },
|
||||
},
|
||||
},
|
||||
}) as any,
|
||||
);
|
||||
return writeDocx(wordDoc);
|
||||
}
|
||||
|
||||
@@ -117,7 +117,7 @@ export class DocxSerializerState {
|
||||
constructor(nodes: NodeSerializer, marks: MarkSerializer, options: Options) {
|
||||
this.nodes = nodes;
|
||||
this.marks = marks;
|
||||
this.options = options ?? {};
|
||||
this.options = options ?? ({} as Options);
|
||||
this.children = [];
|
||||
this.numbering = [];
|
||||
|
||||
@@ -342,7 +342,7 @@ export class DocxSerializerState {
|
||||
// Check if all cells are headers in this row
|
||||
let tableHeader = true;
|
||||
row.content.forEach((cell) => {
|
||||
if (cell.type.name !== 'table_header') {
|
||||
if (cell.type.name !== 'tableHeader') {
|
||||
tableHeader = false;
|
||||
}
|
||||
});
|
||||
@@ -529,7 +529,7 @@ export class DocxSerializerStateAsync {
|
||||
constructor(nodes: NodeSerializerAsync, marks: MarkSerializer, options: OptionsAsync) {
|
||||
this.nodes = nodes;
|
||||
this.marks = marks;
|
||||
this.options = options ?? {};
|
||||
this.options = options ?? ({} as OptionsAsync);
|
||||
this.children = [];
|
||||
this.numbering = [];
|
||||
|
||||
@@ -765,7 +765,7 @@ export class DocxSerializerStateAsync {
|
||||
// Check if all cells in the row are headers
|
||||
for (let cellIndex = 0; cellIndex < row.content.childCount; cellIndex += 1) {
|
||||
const cell = row.content.child(cellIndex);
|
||||
if (cell.type.name !== 'table_header') {
|
||||
if (cell.type.name !== 'tableHeader') {
|
||||
tableHeader = false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { Schema } from 'prosemirror-model';
|
||||
import { builders } from 'prosemirror-test-builder';
|
||||
import { schemas } from '@curvenote/schema';
|
||||
|
||||
const schema = new Schema(schemas.presets.full);
|
||||
|
||||
export const tnodes = builders(schema, {
|
||||
p: { nodeType: 'paragraph' },
|
||||
h1: { nodeType: 'heading', level: 1 },
|
||||
h2: { nodeType: 'heading', level: 2 },
|
||||
hr: { nodeType: 'horizontal_rule' },
|
||||
li: { nodeType: 'list_item' },
|
||||
ol: { nodeType: 'ordered_list' },
|
||||
ol3: { nodeType: 'ordered_list', order: 3 },
|
||||
ul: { nodeType: 'bullet_list' },
|
||||
pre: { nodeType: 'code_block' },
|
||||
br: { nodeType: 'hard_break' },
|
||||
img: { nodeType: 'image', src: 'img.png', alt: 'x' },
|
||||
a: { markType: 'link', href: 'https://example.com' },
|
||||
math: { nodeType: 'math' },
|
||||
equation: { nodeType: 'equation', numbered: true, id: 'eq1' },
|
||||
equationUnnumbered: { nodeType: 'equation', numbered: false, id: 'eq2' },
|
||||
abbr: { nodeType: 'abbr', title: 'Cascading Style Sheets' },
|
||||
aside: { nodeType: 'aside' },
|
||||
figure: { nodeType: 'figure' },
|
||||
}) as any;
|
||||
|
||||
export const tdoc = (...args: Parameters<typeof tnodes.doc>) => tnodes.doc('', ...args);
|
||||
@@ -1,109 +0,0 @@
|
||||
import * as fs from 'fs';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
DocxSerializerAsync,
|
||||
defaultAsyncNodes,
|
||||
defaultMarks,
|
||||
defaultDocxSerializer,
|
||||
writeDocx,
|
||||
} from '../src';
|
||||
import { tnodes, tdoc } from './build';
|
||||
import { writeFileSync } from 'fs';
|
||||
const {
|
||||
blockquote,
|
||||
h1,
|
||||
h2,
|
||||
p,
|
||||
hr,
|
||||
li,
|
||||
ol,
|
||||
ol3,
|
||||
ul,
|
||||
pre,
|
||||
em,
|
||||
strong,
|
||||
code,
|
||||
a,
|
||||
br,
|
||||
img,
|
||||
math,
|
||||
equation,
|
||||
equationUnnumbered,
|
||||
figure,
|
||||
} = tnodes;
|
||||
|
||||
const imageBase64Data = `iVBORw0KGgoAAAANSUhEUgAAAIAAAACACAMAAAD04JH5AAACzVBMVEUAAAAAAAAAAAAAAAA/AD8zMzMqKiokJCQfHx8cHBwZGRkuFxcqFSonJyckJCQiIiIfHx8eHh4cHBwoGhomGSYkJCQhISEfHx8eHh4nHR0lHBwkGyQjIyMiIiIgICAfHx8mHh4lHh4kHR0jHCMiGyIhISEgICAfHx8lHx8kHh4jHR0hHCEhISEgICAlHx8kHx8jHh4jHh4iHSIhHCEhISElICAkHx8jHx8jHh4iHh4iHSIhHSElICAkICAjHx8jHx8iHh4iHh4hHiEhHSEkICAjHx8iHx8iHx8hHh4hHiEkHSEjHSAjHx8iHx8iHx8hHh4kHiEkHiEjHSAiHx8hHx8hHh4kHiEjHiAjHSAiHx8iHx8hHx8kHh4jHiEjHiAjHiAiICAiHx8kHx8jHh4jHiEjHiAiHiAiHSAiHx8jHx8jHx8jHiAiHiAiHiAiHSAiHx8jHx8jHx8iHiAiHiAiHiAjHx8jHx8jHx8jHx8iHiAiHiAiHiAjHx8jHx8jHx8iHx8iHSAiHiAjHiAjHx8jHx8hHx8iHx8iHyAiHiAjHiAjHiAjHh4hHx8iHx8iHx8iHyAjHSAjHiAjHiAjHh4hHx8iHx8iHx8jHyAjHiAhHh4iHx8iHx8jHyAjHSAjHSAhHiAhHh4iHx8iHx8jHx8jHyAjHSAjHSAiHh4iHh4jHx8jHx8jHyAjHyAhHSAhHSAiHh4iHh4jHx8jHx8jHyAh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an5+ohf+z1pP8lQY/GHZQMV4YD3FpXDp4qerqbF/lBWBswyi+AL+ia+maLgcRRQj4IYlY/UpauqKBsPJAxQF8NM1TRQ/RudSPAD34rK3scOuR8/HGcspxsJfOVS8NZbiGXiUtPgINU3v3WFDmx8pEuG3EiqKKVbCC1vm2iZqap5LAtCtleQf8F9sFYWDohzeJczYyQ4V2bEZFGsQgJRGqqqhS2phHTWn9lDkIhBTqWqxQZ+IsRvtdHY9AvI2VX2hW68nfqGmuQsCEl3JdjfCF8OW1bPdtwhQ0gm2mQzfRE3a7KCYj0BNZJs8+Kxf/r6WtTEI2FIqlsMfFgRB5A6KUnSe/vUkX0AnuvUIt8SjM1m6wWQymUwmk8lkMgXRf5vi8rLQxtUhAAAAAElFTkSuQmCC`;
|
||||
|
||||
/**
|
||||
* Adds image type to base64 encoded images
|
||||
*/
|
||||
export const docxSerializer = new DocxSerializerAsync(
|
||||
{
|
||||
...defaultAsyncNodes,
|
||||
async image(state, node) {
|
||||
const { src } = node.attrs;
|
||||
await state.image(src, 70, 'center', undefined, 'png');
|
||||
state.closeBlock(node);
|
||||
},
|
||||
},
|
||||
defaultMarks,
|
||||
);
|
||||
|
||||
describe('DOCX Serialization', () => {
|
||||
it('serializes document structure with async image handling', async () => {
|
||||
const w = await docxSerializer.serializeAsync(
|
||||
tdoc(
|
||||
h1('Welcome to ', code('prosemirror-docx'), strong('!!')),
|
||||
p('This is ', code('code'), br(), 'hello!'),
|
||||
ul(li(p('bullet 1')), li(p('bullet 2')), ul(li(p('bullet 3.1')), li(p('bullet 3.2')))),
|
||||
ul(li(p('bullet 1')), li(p('bullet 2')), ul(li(p('bullet 3.1')), li(p('bullet 3.2')))),
|
||||
ol(li(p('bullet 1')), li(p('bullet 2')), ul(li(p('bullet 3.1')), li(p('bullet 3.2')))),
|
||||
p(a('This is '), a(em('emphasized'))),
|
||||
hr(),
|
||||
p('Some math in a paragraph: ', math('Ax=b'), ' and then a standalone numbered equation:'),
|
||||
equation('Ax=b'),
|
||||
p('And an unnumbered equation:'),
|
||||
equationUnnumbered('\\sum^{9}_{i=0}i+2 = ??'),
|
||||
img({ src: 'https://avatars.githubusercontent.com/u/78044536' }),
|
||||
img({ src: `data:text/plain;base64,${imageBase64Data}` }),
|
||||
),
|
||||
{
|
||||
async getImageBuffer(src: string) {
|
||||
const arrayBuffer = await fetch(src).then((res) => res.arrayBuffer());
|
||||
return new Uint8Array(arrayBuffer);
|
||||
},
|
||||
},
|
||||
);
|
||||
const buffer = await writeDocx(w);
|
||||
fs.writeFileSync(`hello-async.docx`, buffer);
|
||||
expect(1).toBe(1);
|
||||
});
|
||||
|
||||
it('serializes document structure with sync image handling', async () => {
|
||||
const w = defaultDocxSerializer.serialize(
|
||||
tdoc(
|
||||
h1('Welcome to ', code('prosemirror-docx'), strong('!!')),
|
||||
p('This is ', code('code'), br(), 'hello!'),
|
||||
ul(li(p('bullet 1')), li(p('bullet 2')), ul(li(p('bullet 3.1')), li(p('bullet 3.2')))),
|
||||
ul(li(p('bullet 1')), li(p('bullet 2')), ul(li(p('bullet 3.1')), li(p('bullet 3.2')))),
|
||||
ol(li(p('bullet 1')), li(p('bullet 2')), ul(li(p('bullet 3.1')), li(p('bullet 3.2')))),
|
||||
p(a('This is '), a(em('emphasized'))),
|
||||
hr(),
|
||||
p('Some math in a paragraph: ', math('Ax=b'), ' and then a standalone numbered equation:'),
|
||||
equation('Ax=b'),
|
||||
p('And an unnumbered equation:'),
|
||||
equationUnnumbered('\\sum^{9}_{i=0}i+2 = ??'),
|
||||
img(),
|
||||
),
|
||||
{
|
||||
getImageBuffer(src: string) {
|
||||
return Buffer.from(imageBase64Data, 'base64');
|
||||
},
|
||||
},
|
||||
);
|
||||
await writeDocx(w).then((buffer) => {
|
||||
fs.writeFileSync('hello.docx', buffer);
|
||||
});
|
||||
expect(2).toBe(2);
|
||||
});
|
||||
});
|
||||
@@ -14,14 +14,16 @@ export function createShortId() {
|
||||
}
|
||||
|
||||
export function buildDoc(state: SerializationState, opts?: IPropertiesOptions): Document {
|
||||
let sections = state?.sections?.map((section) => ({
|
||||
properties: section.config.properties || {
|
||||
type: SectionType.CONTINUOUS,
|
||||
},
|
||||
headers: section.config.headers,
|
||||
footers: section.config.footers,
|
||||
children: section.children,
|
||||
}));
|
||||
let sections = state?.sections?.length
|
||||
? state.sections.map((section) => ({
|
||||
properties: section.config.properties || {
|
||||
type: SectionType.CONTINUOUS,
|
||||
},
|
||||
headers: section.config.headers,
|
||||
footers: section.config.footers,
|
||||
children: section.children,
|
||||
}))
|
||||
: undefined;
|
||||
if (!sections) {
|
||||
sections = [
|
||||
{
|
||||
|
||||
Reference in New Issue
Block a user