import { Editor } from '@tiptap/core'
import { TextSelection } from '@tiptap/pm/state'
import { parseDocx, saveDocx } from '@genoffice/docx-engine'
import JSZip from 'jszip'
import { describe, expect, it } from 'vitest'
import { buildDocx } from '../../../packages/docx-engine/tests/helpers/build-docx'
import { blocksToPmDoc, pmDocToSavePlan, type PmNode } from '../src/renderer/editor/convert'
import { editorExtensions } from '../src/renderer/editor/extensions'
// Hyperlinks (and their relationship entries) used to vanish on save:
// regenerated runs merged adjacent same-target links under one rId, and a
// nested table re-read from the DOM lost its trailing empty paragraph and went
// through the plain-text cell patch (first pPr/rPr on every paragraph).
const link = (rId: string, text: string, extraRPr = '') =>
`${extraRPr}${text}`
const BODY =
`See ${link('rId20', 'the site')}.` +
// two adjacent hyperlinks to the same URL, each with its own relationship
`Read ${link('rId21', ' ')}${link('rId22', 'the agreement', '')}.` +
// tracked insertion wrapping a hyperlink
`Mail ${link('rId23', 'us')}` +
'' +
'' +
// hyperlink in a plain cell
`Contact ${link('rId24', 'team')}` +
// nested table whose cell ends with an empty paragraph and holds a mailto link
'' +
`Jane Doe${link('rId25', 'jane@example.com')}` +
''
const REL = (id: string, target: string) =>
``
const RELS =
REL('rId20', 'https://example.com/') +
REL('rId21', 'https://example.com/agreement.pdf') +
REL('rId22', 'https://example.com/agreement.pdf') +
REL('rId23', 'mailto:hello@example.com') +
REL('rId24', 'mailto:team@example.com') +
REL('rId25', 'mailto:jane@example.com')
async function openDoc(bodyXml = BODY) {
const source = await buildDocx({ bodyXml, extraRels: RELS })
const parsed = await parseDocx(source)
const host = document.createElement('div')
document.body.appendChild(host)
const editor = new Editor({
element: host,
extensions: editorExtensions,
content: blocksToPmDoc(parsed.blocks) as never,
})
return { source, parsed, editor, host }
}
async function partsOf(bytes: Uint8Array) {
const zip = await JSZip.loadAsync(bytes)
return {
doc: await zip.file('word/document.xml')!.async('string'),
rels: await zip.file('word/_rels/document.xml.rels')!.async('string'),
}
}
const ALL_IDS = ['rId20', 'rId21', 'rId22', 'rId23', 'rId24', 'rId25']
describe('hyperlinks and their relationships survive saving', () => {
it('leaves every block byte-exact when nothing was edited', async () => {
const { source, parsed, editor, host } = await openDoc()
window.dispatchEvent(new Event('ai-docs-commit-tables'))
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
expect(plan.changedCount).toBe(0)
expect(await saveDocx(parsed, plan.saveBlocks)).toEqual(source)
editor.destroy()
host.remove()
})
it('keeps distinct relationships for adjacent same-target links in a regenerated paragraph', async () => {
const { parsed, editor, host } = await openDoc()
let at = -1
editor.state.doc.descendants((node, pos) => {
if (node.isText && node.text === 'Read ') at = pos + 'Read'.length
})
expect(at).toBeGreaterThan(-1)
editor.view.dispatch(
editor.state.tr.setSelection(TextSelection.create(editor.state.doc, at)).insertText('X', at),
)
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
expect(plan.changedCount).toBe(1)
const { doc, rels } = await partsOf(await saveDocx(parsed, plan.saveBlocks))
expect(doc).toContain('')
expect(doc).toContain('')
for (const id of ALL_IDS) expect(rels).toContain(`Id="${id}"`)
editor.destroy()
host.remove()
})
it('patches only the edited nested-cell paragraph and keeps its neighbours', async () => {
const { parsed, editor, host } = await openDoc()
const nestedTd = host.querySelector('.doc-nested-table td')!
const first = nestedTd.querySelector('div')!
expect(first.textContent).toBe('Jane Doe')
first.textContent = 'Jane Roe'
first.dispatchEvent(new Event('input', { bubbles: true }))
window.dispatchEvent(new Event('ai-docs-commit-tables'))
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
expect(plan.changedCount).toBe(1)
const { doc, rels } = await partsOf(await saveDocx(parsed, plan.saveBlocks))
expect(doc).toContain('Jane Roe')
// untouched sibling paragraphs keep their bytes: hyperlink, pPr and the trailing empty paragraph
expect(doc).toContain(
`${link('rId25', 'jane@example.com')}`,
)
for (const id of ALL_IDS) expect(rels).toContain(`Id="${id}"`)
editor.destroy()
host.remove()
})
it('reads paragraphs below the exact-height clip wrapper', async () => {
const exactRow = BODY.replace(
'Jane Doe',
'Jane Doe',
)
expect(exactRow).not.toBe(BODY)
const { parsed, editor, host } = await openDoc(exactRow)
const nestedTd = host.querySelector('.doc-nested-table td')!
const first = nestedTd.querySelector('.cell-clip > div')!
expect(first.textContent).toBe('Jane Doe')
first.textContent = 'Jane Roe'
first.dispatchEvent(new Event('input', { bubbles: true }))
window.dispatchEvent(new Event('ai-docs-commit-tables'))
const plan = pmDocToSavePlan(editor.getJSON() as PmNode, parsed.blocks)
expect(plan.changedCount).toBe(1)
const { doc } = await partsOf(await saveDocx(parsed, plan.saveBlocks))
expect(doc).toContain('Jane Roe')
expect(doc).toContain(
`${link('rId25', 'jane@example.com')}`,
)
editor.destroy()
host.remove()
})
})