import { describe, expect, it } from 'vitest'; import { buildDocxFromBody } from './fixtures/build-docx'; import { buildXlsx } from './fixtures/build-xlsx'; import { createConverter } from '@/core/converter/facade'; import { Ream } from '@/core/converter/ream'; import { ConversionLossError, pt } from '@/core/ir'; import { htmlWriter, writeHtml } from '@/html/html-writer'; import { readDocx } from '@/word/docx-reader'; const decode = (b: Uint8Array) => new TextDecoder().decode(b); describe('html writer (FlowDoc adapter)', () => { it('converts docx → flowed HTML with no fonts and no I/O', async () => { const docx = buildDocxFromBody( 'Title' + '' + 'styled run', ); // No fonts anywhere in the options — html conversion must not need them. const html = decode(await Ream.parse(docx).convert('html')); expect(html.startsWith('')).toBe(true); expect(html).toContain(''); }); it('materialized list markers ride along as text', async () => { const numberingXml = '' + '' + '' + ''; const li = (t: string) => `${t}`; const docx = buildDocxFromBody(li('first') + li('second'), { numberingXml }); const html = decode(await Ream.parse(docx).convert('html')); // applyNumbering prepends "1.\t" / "2.\t"; the tab renders as a .tab gap. expect(html).toContain('1.'); expect(html).toContain('2.'); expect(html).toContain('second'); }); it('tables carry colspan/rowspan, shading and borders', async () => { const tbl = '' + '' + '' + '' + '' + '' + // row 1: [A spans 2 cols][B starts a vertical merge] '' + 'A' + 'B' + '' + // row 2: [c][d][vMerge continue] '' + 'c' + 'd' + '' + ''; const html = decode(await Ream.parse(buildDocxFromBody(tbl)).convert('html')); expect(html).toContain(''); expect(html).toContain('colspan="2"'); expect(html).toContain('rowspan="2"'); expect(html).toContain('background-color:#FFCC00'); expect(html).toContain('border-top:'); // The vMerge continuation cell must not be emitted as its own . expect(html.match(/ { const xlsx = buildXlsx([ ['name', 'value'], ['answer', '42'], ]); const html = decode(await Ream.parse(xlsx).convert('html')); expect(html).toContain(' { // Thirty 20-character columns are some 4000pt: printed, the sheet is cut // into column bands a page wide, and the page breaks between them and // between the sheets. On a screen it is one table, and every tab shows — // the empty one too. const wide = Array.from({ length: 30 }, (_, i) => `c${String(i + 1)}`); const xlsx = buildXlsx({ sheets: [ { name: 'Wide', rows: [wide], columns: [{ min: 1, max: 30, widthChars: 20 }] }, { name: 'Empty', rows: [] }, { name: 'R&D', rows: [['x']] }, ], }); const html = decode(await Ream.parse(xlsx).convert('html')); expect( [...html.matchAll(/
/gu)].map((m) => m[1]), ).toEqual(['Wide', 'Empty', 'R&D']); const wideSheet = html.slice( html.indexOf('data-sheet="Wide"'), html.indexOf('data-sheet="Empty"'), ); expect(wideSheet.match(/R&D'); // No page, so no page-wide column for the sheet to be squeezed into. expect(html).toContain('
'); }); it("draws the window's gridlines, but not over a fill nor where the sheet hides them", async () => { const STYLES = ` `; const xlsx = buildXlsx({ stylesXml: STYLES, sheets: [ { name: 'Grid', rows: [['plain', { value: 'filled', styleIndex: 1 }]] }, { name: 'Clean', rows: [['plain']], hideGridLines: true }, ], }); const html = decode(await Ream.parse(xlsx).convert('html')); const sheet = (name: string): string => html.slice(html.indexOf(`data-sheet="${name}"`)).split('')[0]!; // Three edges round the plain cell: the fourth is the yellow one's, and a // fill covers the gridlines on every side of it. expect(sheet('Grid').match(/0\.5pt solid #D4D4D4/gu)).toHaveLength(3); expect( /
'); expect(html).toContain(''); expect(html).toMatch(/
\s*]*>]*>filled/u.exec(sheet('Grid'))?.[1], ).not.toContain('D4D4D4'); expect(sheet('Clean')).not.toContain('D4D4D4'); }); it('flags a noted cell in its corner, and shows the note on hover', async () => { const xlsx = buildXlsx({ rows: [['noted', 'plain']], comments: [{ ref: 'A1', author: 'Ada', text: 'look here' }], }); const html = decode(await Ream.parse(xlsx).convert('html')); expect(html).toMatch(/ { // A gridline and a thin rule come out the same pixel wide, and collapsed // borders then go to the cell above or to the left: a cell ruled all // round lost its top and left sides to the grey grid next to them. const STYLES = ` `; const xlsx = buildXlsx({ stylesXml: STYLES, rows: [ ['', 'above'], ['beside', { value: 'ruled', styleIndex: 1 }], ], }); const html = decode(await Ream.parse(xlsx).convert('html')); const styleOf = (word: string): string => new RegExp(`\\s*]*>]*>${word}<`, 'u').exec(html)?.[1] ?? ''; expect(styleOf('ruled')).toContain('border-top:0.75pt solid #000000'); expect(styleOf('above')).not.toContain('border-bottom'); expect(styleOf('beside')).not.toContain('border-right'); // The edges nobody rules keep their gridline. expect(styleOf('above')).toContain('border-top:0.5pt solid #D4D4D4'); }); it('sets a grid row at its height and a cell at the bottom of it', async () => { const xlsx = buildXlsx({ rows: [['tall'], ['plain']], rowHeights: [{ row: 0, heightPt: 30, customHeight: true }], columns: [{ min: 1, max: 1, widthChars: 10 }], }); const html = decode(await Ream.parse(xlsx).convert('html')); expect(html).toContain('
/u); }); it("places a sheet's drawing on its surface where it is anchored", () => { const { doc } = readDocx(buildDocxFromBody('x')); const html = decode( writeHtml({ ...doc, sections: [ { properties: { headers: [], footers: [] }, endIndex: 2, sheet: { name: 'Plot' } }, ], body: [ { kind: 'shape' as const, shape: { float: { wrap: 'none' as const, posH: { relativeFrom: 'margin' as const, offsetPt: pt(100) }, posV: { relativeFrom: 'margin' as const, offsetPt: pt(50) }, }, width: pt(80), height: pt(40), geometry: { kind: 'preset' as const, preset: 'rect' }, fill: { kind: 'solid' as const, colorHex: 'FF0000' }, paragraphProperties: {}, }, }, { kind: 'paragraph' as const, paragraph: { properties: {}, runs: [{ text: 'under it', properties: {} }] }, }, ], }).bytes, ); expect(html).toContain( '
', ); // The surface reaches the drawing's far corner, so the next sheet starts below it. expect(html).toContain('
'); }); it('reports headers/footers as a dropped loss; strict throws', async () => { const docx = buildDocxFromBody( 'body' + '', { headerXml: 'running head' }, ); const doc = Ream.parse(docx); const { bytes, losses } = await doc.convertWithReport('html'); expect(decode(bytes)).toContain('body'); expect(decode(bytes)).not.toContain('running head'); expect(losses.some((l) => l.feature === 'headersFooters' && l.severity === 'dropped')).toBe( true, ); await expect(doc.convert('html', { strict: true })).rejects.toThrow(ConversionLossError); }); it('is deterministic and exposed as a flow adapter', async () => { const docx = buildDocxFromBody('same bytes'); const a = await Ream.parse(docx).convert('html'); const b = await Ream.parse(docx).convert('html'); expect(Buffer.from(a).equals(Buffer.from(b))).toBe(true); expect(htmlWriter.id).toBe('html'); expect(htmlWriter.consumes).toBe('flow'); const { doc } = readDocx(docx); const direct = htmlWriter.write(doc); expect(decode(direct.bytes)).toContain('same bytes'); }); it('escapes markup-significant characters', async () => { const docx = buildDocxFromBody('a <b> & "c"'); const html = decode(await Ream.parse(docx).convert('html')); expect(html).toContain('a <b> & "c"'); expect(html).not.toContain('a '); }); it('emits hyperlinks as with a scheme allowlist', async () => { const docx = buildDocxFromBody( '' + 'safe link' + 'evil link' + 'internal' + '', { hyperlinks: { rId30: 'https://reamkit.dev/?a=1&b=2', rId31: 'javascript:alert(1)', }, }, ); const { bytes, losses } = await Ream.parse(docx).convertWithReport('html'); const html = decode(bytes); expect(html).toContain(''); expect(html).toContain('safe link'); expect(html).toContain('evil link'); // the text survives, the link does not expect(html).not.toContain('javascript:'); expect(html).toContain('internal'); // anchor-only hyperlink → plain text expect(losses.some((l) => l.feature === 'hyperlinks' && l.severity === 'degraded')).toBe(true); }); it('converts through the createConverter facade', async () => { const conv = createConverter(); const { bytes, losses } = await conv.convert( buildDocxFromBody('facade html'), { to: 'html' }, ); expect(decode(bytes)).toContain('facade html'); expect(losses).toEqual([]); }); it('writeHtml works on a hand-built raw FlowDoc (resolves the cascade itself)', () => { const { doc } = readDocx(buildDocxFromBody('x')); // Replace the body with a RAW (unresolved) paragraph — the writer must // resolve it over the empty sheet exactly like the PDF layout would. const raw = { ...doc, body: [ { kind: 'paragraph' as const, paragraph: { properties: { alignment: 'right' as const }, runs: [{ text: 'raw tree', properties: { bold: true } }], }, }, ], }; const html = decode(writeHtml(raw).bytes); expect(html).toContain('raw tree'); expect(html).toContain('font-weight:700'); expect(html).toContain('text-align:right'); }); it('sets a right-to-left paragraph to the sides its start and end are', () => { // §17.3.1.13 — in a `w:bidi` paragraph "right" is the END of the line, // which is the left of the page, and the indent named "left" is the one at // the start, on the right: the layout crosses them over, and so must CSS, // whose sides are the page's whatever `dir` says. const { doc } = readDocx( buildDocxFromBody( 'שלום', ), ); const html = decode(writeHtml(doc).bytes); expect(html).toMatch(/

{ // The family is a CSS string inside a double-quoted attribute: written in // double quotes it ended the attribute, and a browser dropped the size, // weight and colour after it. const docx = buildDocxFromBody( '' + 'Budget', ); const html = decode(await Ream.parse(docx).convert('html')); expect(/Budget<\/span>/u.exec(html)?.[1]).toBe( "font-family:'Century Gothic',sans-serif;font-size:25pt;font-weight:700;color:#4E5B6F", ); }); it('follows a family with its metric twin and its class, and escapes the name', () => { const { doc } = readDocx(buildDocxFromBody('x')); const run = (text: string, ascii: string) => ({ text, properties: { fontFamily: { ascii } } }); const html = decode( writeHtml({ ...doc, body: [ { kind: 'paragraph' as const, paragraph: { properties: {}, runs: [ run('calibri', 'Calibri'), run('cambria', 'Cambria'), run('courier', 'Courier New'), run('quoted', 'O\'Brien "Sans"'), ], }, }, ], }).bytes, ); const family = (text: string): string | undefined => new RegExp(`${text}`, 'u').exec( html, )?.[1]; expect(family('calibri')).toBe("'Calibri',Carlito,sans-serif"); expect(family('cambria')).toBe("'Cambria',Caladea,Noto Serif,serif"); expect(family('courier')).toBe("'Courier New',monospace"); // A quote of either kind stays inside the name: escaped for CSS, then for the attribute. expect(family('quoted')).toBe("'O\\'Brien "Sans"',sans-serif"); }); // ── charts and shapes as inline SVG ────────────────────────────────────── const C_NS = 'xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" ' + 'xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"'; const chartDrawing = (rId: string): string => ` `; const BAR_CHART = ` Quarterly Sales Q1Q2 1020 `; const PIE_CHART = ` AB 31 `; const shapeDrawing = (spPrInner: string, body = ''): string => ` ${spPrInner} ${body} `; it('renders a bar chart as inline SVG with anchored labels', async () => { const docx = buildDocxFromBody(chartDrawing('rId5'), { charts: { rId5: BAR_CHART } }); const html = decode(await Ream.parse(docx).convert('html')); expect(html).toContain(']*fill="#4472C4"/); expect(html).toContain('>Q1'); // category label, browser-rendered expect(html).toContain('text-anchor'); // The graphics flip wrapper (y-up scene → y-down viewport). expect(html).toContain(''); }); it("draws a chart's frame, plot fill and gridlines under its bars, as the PDF does", async () => { // 2ecd0c1 and 52663e9 moved these off the scene's polylines and rects into // layers of their own, and only the PDF learnt to draw them: the HTML of a // ruled chart lost its frame, its plot's fill and every gridline. const ruled = BAR_CHART.replace( '', '' + '' + '' + '', ); const docx = buildDocxFromBody(chartDrawing('rId7'), { charts: { rId7: ruled } }); const html = decode(await Ream.parse(docx).convert('html')); const frame = html.indexOf( ']*fill="#F2F2F2"/); const grid = html.indexOf('stroke="#C00000"'); const bar = html.search(/]*fill="#4472C4"/); expect(frame).toBeGreaterThan(0); expect(plot).toBeGreaterThan(frame); expect(html.slice(grid - 200, grid)).toContain(' { const boxed = BAR_CHART.replace( '', '', ).replace( '', '' + '' + '', ); const docx = buildDocxFromBody(chartDrawing('rId8'), { charts: { rId8: boxed } }); const html = decode(await Ream.parse(docx).convert('html')); const floor = html.search(/]*fill="none" stroke="#D9D9D9"/); const grid = html.indexOf('stroke="#C00000"'); expect(floor).toBeGreaterThan(0); expect(grid).toBeGreaterThan(floor); // The bars' tops, 0.76 of their colour, and their fronts over them. const top = html.search(/]*fill="#345795"/); expect(top).toBeGreaterThan(grid); expect(html.search(/]*fill="#4472C4"/)).toBeGreaterThan(top); }); it('renders pie wedges as bezier paths', async () => { const docx = buildDocxFromBody(chartDrawing('rId6'), { charts: { rId6: PIE_CHART } }); const html = decode(await Ream.parse(docx).convert('html')); expect(html).toMatch(/' + '' + ''; const html = decode(await Ream.parse(buildDocxFromBody(shapeDrawing(spPr))).convert('html')); expect(html).toContain(']*stroke="#2F528F" stroke-width="1"/); expect(html).toContain('transform="matrix('); }); it('overlays text-box content inside the shape with its anchor', async () => { const spPr = ''; const body = 'boxed text'; const withAnchor = shapeDrawing(spPr, body).replace( '', '', ); const html = decode(await Ream.parse(buildDocxFromBody(withAnchor)).convert('html')); expect(html).toContain('position:relative;width:144pt;height:72pt'); expect(html).toContain('justify-content:center'); expect(html).toContain('boxed text'); }); });