Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Tests/DocDOCXTests/RoundTripTests.swift3// Description: Export → reimport equality of the model, feature by feature, on models whose values DOCX can represent exactly;4// the full Import → Edit → Export → Reimport → Export → Reimport cycle; what the produced XML looks like.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Testing10import DocModel11import DocContainer12@testable import DocDOCX1314struct FixedFormatter: CitationFormatting {15 func citationText(_ citation: Citation, document: DocumentModel, numbering: Numbering) -> String {16 "[" + citation.items.map { String(numbering.citationOrder[$0.key] ?? 0) }.joined(separator: ", ") + "]"17 }18 func bibliographyParagraphs(document: DocumentModel, numbering: Numbering) -> [Paragraph] {19 numbering.citedKeys.map { Paragraph("[\(numbering.citationOrder[$0]!)] \(document.bibEntry($0)?.title ?? $0)", style: StyleID.bibliography) }20 }21}2223@Suite("DOCX export → reimport")24struct RoundTripTests {25 let d1 = Date(timeIntervalSince1970: 1_770_000_000), d2 = Date(timeIntervalSince1970: 1_771_000_000)2627 func para(_ runs: [Run], style: String = StyleID.normal, props: ParaProps = .none, id: String? = nil) -> Paragraph {28 var p = Paragraph(style: style, props: props, runs: runs)29 if let id { p.id = id }30 return p31 }3233 @Test func characterFormatting() throws {34 let all = CharProps(fontFamily: "Courier New", fontSize: 13.5, bold: true, italic: false, underline: true, strikethrough: true, color: RGBA(hex: 0x123456),35 highlight: RGBA(hex: 0xFFFF00), vertical: .superscript, baselineShift: 3, tracking: 0.5, kerning: false, ligatures: false,36 smallCaps: true, allCaps: false, language: "fr-CA")37 let doc = testDocument([.paragraph(para([38 Run("Plain "), Run("everything", props: all), Run(" custom highlight", props: CharProps(highlight: RGBA(hex: 0xABCDEF), vertical: .subscript)),39 Run(" styled", charStyle: StyleID.emphasis), Run(" not bold", props: CharProps(bold: false, underline: false, strikethrough: false, vertical: .baseline, kerning: true, ligatures: true)),40 ]))])41 let back = try assertRoundTrip(doc)42 #expect(back.bodyParagraphs[0].runs[1].props == all)43 let xml = try #require(try unpack(try DocxExporter.export(doc).data)["word/document.xml"])44 #expect(xml.contains("<w:rFonts w:ascii=\"Courier New\""))45 #expect(xml.contains("<w:sz w:val=\"27\"/>"))46 #expect(xml.contains("<w:highlight w:val=\"yellow\"/>"))47 #expect(xml.contains("<w:shd w:val=\"clear\" w:color=\"auto\" w:fill=\"ABCDEF\"/>"))48 #expect(xml.contains("<w:rStyle w:val=\"Emphasis\"/>"))49 }5051 @Test func textSpecialCharacters() throws {52 let text = "Tab\there, break\u{2028}next, <xml> & \"quotes\" 'apos', emoji 👩👩👧👦 🇨🇦, e\u{301}, 𝒳, nbsp\u{A0}x, hyphen\u{2011}x, soft\u{AD}x, two spaces "53 let doc = testDocument([.paragraph(para([Run(" leading space"), Run(text, props: CharProps(bold: true)), Run("trailing ")])), .paragraph(Paragraph()), .paragraph(Paragraph("]]> & A"))])54 let back = try assertRoundTrip(doc)55 #expect(back.bodyParagraphs[0].plainText == " leading space" + text + "trailing ")56 #expect(back.bodyParagraphs[0].length == (" leading space" + text + "trailing ").utf16.count)57 // Control characters XML cannot carry are removed instead of producing an unreadable file.58 let odd = testDocument([.paragraph(Paragraph("a\u{0}b\u{1}c\u{B}d\u{FFFE}e"))])59 #expect(try DocxImporter.importDocument(try DocxExporter.export(odd).data).document.bodyLines == ["abcde"])60 }6162 @Test func paragraphFormatting() throws {63 let props = ParaProps(alignment: .justified, indentLeft: 36, indentRight: 18, firstLineIndent: -18, spaceBefore: 6, spaceAfter: 12, lineSpacing: .exact(18),64 keepWithNext: true, keepLinesTogether: true, pageBreakBefore: true, widowControl: false,65 tabs: [TabStop(position: 100, kind: .left), TabStop(position: 200.5, kind: .center, leader: .dashes), TabStop(position: 300, kind: .right, leader: .dots),66 TabStop(position: 400, kind: .decimal, leader: .line)],67 hyphenate: true, outlineLevel: 2, shading: RGBA(hex: 0xEEF0F6), borderTop: BorderLine(width: 1, color: RGBA(hex: 0xFF0000)),68 borderBottom: BorderLine(width: 0.5, color: .black, style: .dotted), borderLeft: BorderLine(width: 2, color: RGBA(hex: 0x4F46E5), style: .double), rightToLeft: true)69 let doc = testDocument([70 .paragraph(Paragraph("All properties", props: props)),71 .paragraph(Paragraph("At least", props: ParaProps(alignment: .center, firstLineIndent: 24, lineSpacing: .atLeast(14), keepWithNext: false, hyphenate: false, outlineLevel: 0, rightToLeft: false))),72 .paragraph(Paragraph("Multiple", props: ParaProps(alignment: .right, lineSpacing: .multiple(1.5)))),73 .paragraph(Paragraph("Left", props: ParaProps(alignment: .left, lineSpacing: .multiple(1.15)))),74 ])75 let back = try assertRoundTrip(doc)76 #expect(back.bodyParagraphs[0].props == props)77 }7879 @Test func stylesDefaultsInheritanceAndNumberedHeadings() throws {80 var doc = testDocument([.paragraph(Paragraph("Chapter", style: StyleID.heading(1))), .paragraph(Paragraph("Section", style: StyleID.heading(2))),81 .paragraph(Paragraph("Body")), .paragraph(Paragraph("Custom", style: "MyStyle"))])82 for i in doc.styles.styles.indices where doc.styles.styles[i].id.hasPrefix("Heading") { doc.styles.styles[i].numbered = true }83 doc.styles.styles.append(Style(id: "MyStyle", name: "My Custom Style", basedOn: StyleID.heading(2), next: StyleID.normal, char: CharProps(italic: true, smallCaps: true),84 para: ParaProps(indentLeft: 12, outlineLevel: 0)))85 doc.styles.styles.append(Style(id: "Shout", name: "Shout", kind: .character, basedOn: StyleID.emphasis, char: CharProps(allCaps: true)))86 let back = try assertRoundTrip(doc)87 #expect(back.styles.style(StyleID.heading(1))?.numbered == true)88 #expect(back.styles.style(StyleID.heading(1))?.name == "Heading 1")89 #expect(back.styles.style(StyleID.normal)?.name == "Body")90 #expect(back.lists.isEmpty) // heading numbering is not a list91 let n = Numbering(back)92 #expect(n.headingNumbers[back.bodyParagraphs[0].id] == "1" && n.headingNumbers[back.bodyParagraphs[1].id] == "1.1")93 // Word sees built-in styles under their own names and a real multilevel numbering linked to the heading styles.94 let parts = try unpack(try DocxExporter.export(doc).data)95 #expect(parts["word/styles.xml"]!.contains("<w:name w:val=\"heading 1\"/><w:aliases w:val=\"Heading 1\"/>"))96 #expect(parts["word/styles.xml"]!.contains("w:default=\"1\" w:styleId=\"Normal\""))97 #expect(parts["word/numbering.xml"]!.contains("<w:pStyle w:val=\"Heading2\"/><w:lvlText w:val=\"%1.%2\"/>"))98 }99100 @Test func lists() throws {101 var doc = testDocument([])102 let bullets = ListDefinition.bullets(id: "B"), numbered = ListDefinition.numbered(id: "N"), legal = ListDefinition.multilevel(id: "M")103 var custom = ListDefinition(id: "C", levels: [ListLevel(format: .upperRoman, pattern: "(%1)", indent: 40, hanging: 20, start: 4), ListLevel(format: .upperAlpha, pattern: "%1-%2:", indent: 80, hanging: 30),104 ListLevel(format: .none, pattern: "", indent: 100, hanging: 0)])105 custom.levels[0].start = 4106 doc.lists = [bullets, numbered, legal, custom]107 func item(_ t: String, _ list: String, _ level: Int = 0) -> Block { .paragraph(Paragraph(style: StyleID.normal, runs: [Run(t)], list: ListItem(listID: list, level: level))) }108 doc.body = [item("b1", "B"), item("b2", "B", 1), item("b3", "B", 2), item("n1", "N"), item("n2", "N", 1), item("n3", "N", 2), item("n4", "N"),109 item("m1", "M"), item("m2", "M", 1), item("m3", "M", 2), .paragraph(Paragraph("between")), item("c4", "C"), item("c5", "C"), item("cA", "C", 1), item("none", "C", 2)]110 let back = try assertRoundTrip(doc)111 let labels = Numbering(back).listLabels112 #expect(back.bodyParagraphs.compactMap { labels[$0.id] } == ["•", "◦", "▪", "1.", "a.", "i.", "2.", "1.", "1.1.", "1.1.1.", "(IV)", "(V)", "V-A:", ""])113 }114115 @Test func tables() throws {116 var t = Table(columnWidths: [100, 150.5, 80], rows: [117 TableRow(cells: [TableCell(paragraphs: [Paragraph("Header A", style: StyleID.tableText)], colSpan: 2, shading: RGBA(hex: 0xEEF0F6)), TableCell("Header C", bold: true)], isHeader: true, minHeight: 24),118 TableRow(cells: [TableCell(paragraphs: [Paragraph("Tall", style: StyleID.tableText)], vMerge: .restart, vAlign: .center), TableCell("b2"), TableCell("c2")]),119 TableRow(cells: [TableCell(paragraphs: [Paragraph(style: StyleID.tableText)], vMerge: .continue), TableCell(paragraphs: [Paragraph("two", style: StyleID.tableText), Paragraph("paragraphs", style: StyleID.tableText)], vAlign: .bottom), TableCell("c3")]),120 ], style: .grid, alignment: .center)121 t.rows[1].cells[1].borderTop = BorderLine(width: 1.5, color: RGBA(hex: 0xFF0000), style: .dashed)122 t.rows[1].cells[1].borderBottom = BorderLine(width: 0.5)123 t.rows[1].cells[1].borderLeft = BorderLine(width: 2, color: RGBA(hex: 0x00AA00), style: .double)124 t.rows[1].cells[1].borderRight = BorderLine(width: 0.25, style: .dotted)125 var sum = Table(strings: [["Item", "Value"], ["a", "2"], ["b", "3"], ["Total", "5"]], width: 300, style: .banded)126 sum.rows[3].cells[1].formula = "=SUM(ABOVE)"127 let lined = Table(strings: [["x", "y"], ["1", "2"]], width: 200, style: .lined)128 let plain = Table(strings: [["only"]], width: 120, style: .plain)129 var custom = Table(strings: [["c"]], width: 100, style: TableStyle(name: "Mine", outerBorder: BorderLine(width: 2, color: RGBA(hex: 0x112233), style: .double), innerHorizontal: nil,130 innerVertical: BorderLine(width: 1, style: .dotted), headerShading: RGBA(hex: 0x101010), headerTextColor: .white,131 bandedRowShading: RGBA(hex: 0xFAFAFA), cellPadding: Insets(top: 2, left: 3, bottom: 4, right: 5)))132 custom.alignment = .right133 let doc = testDocument([.paragraph(Paragraph("Before")), .table(t), .paragraph(Paragraph("Between")), .table(sum), .table(lined), .table(plain), .table(custom), .paragraph(Paragraph("After"))])134 let back = try assertRoundTrip(doc)135 #expect(back.tables.count == 5) // adjacent tables stay separate, no stray paragraphs136 // A table that ends the document, and one that ends a section: Word gets the paragraph it needs, the model does not gain one.137 let ending = testDocument([.paragraph(Paragraph("Only text")), .table(lined), .sectionBreak(SectionBreak(kind: .nextPage, setup: PageSetup(paper: .a4, landscape: true))), .table(plain)])138 let endingBack = try assertRoundTrip(ending)139 #expect(endingBack.body.count == 4)140 #expect(try unpack(try DocxExporter.export(ending).data)["word/document.xml"]!.contains("</w:tbl><w:p><w:pPr><w:spacing w:before=\"0\" w:after=\"0\" w:line=\"20\" w:lineRule=\"exact\"/><w:rPr><w:vanish/>"))141 #expect(back.tables[1].rows[3].cells[1].formula == "=SUM(ABOVE)" && back.tables[1].rows[3].cells[1].plainText == "5")142 #expect(back.tables.map(\.style.name) == ["Grid", "Banded", "Lined", "Plain", "Mine"])143 let parts = try unpack(try DocxExporter.export(doc).data)144 let xml = parts["word/document.xml"]!145 #expect(xml.contains("<w:gridSpan w:val=\"2\"/>") && xml.contains("<w:vMerge w:val=\"restart\"/>") && xml.contains("<w:vMerge/>") && xml.contains("<w:tblHeader/>"))146 #expect(xml.contains("<w:gridCol w:w=\"3010\"/>"))147 #expect(parts["word/styles.xml"]!.contains("<w:tblStylePr w:type=\"firstRow\">"))148 }149150 @Test func imagesAndShapes() throws {151 var doc = testDocument([])152 let red = try Data(contentsOf: Corpus.directory.appendingPathComponent("sources/pixel-red.png"))153 doc.assets = ["logo": Asset(id: "logo", mimeType: "image/png", data: red), "dot": Asset(id: "dot", mimeType: "image/png", data: Pkg.png)]154 let inline = ImageObject(asset: "logo", width: 96, height: 64, altText: "Logo & <alt> \"text\"")155 let cropped = ImageObject(asset: "logo", width: 50, height: 25, altText: "", crop: Insets(top: 0.1, left: 0.2, bottom: 0.05, right: 0.25), rotation: 90)156 let floats: [Placement] = [.floating(wrap: .square, align: .left, xOffset: 20, yOffset: 10), .floating(wrap: .topAndBottom, align: .center, xOffset: 0, yOffset: 0),157 .floating(wrap: .behindText, align: .right, xOffset: 0, yOffset: 30), .floating(wrap: .inFrontOfText, align: .left, xOffset: -15, yOffset: 5)]158 var runs = [Run("Images: "), Run(inline: .image(inline)), Run(inline: .image(cropped))]159 for f in floats { runs.append(Run(inline: .image(ImageObject(asset: "dot", width: 30, height: 30, altText: "float", placement: f)))) }160 let shapes: [ShapeObject] = [161 ShapeObject(kind: .rectangle, width: 100, height: 40, stroke: RGBA(hex: 0x112233), strokeWidth: 2, fill: RGBA(hex: 0xFFEEDD), text: "Box", altText: "A box"),162 ShapeObject(kind: .roundedRectangle, width: 80, height: 30, fill: nil, text: "Two\nlines"),163 ShapeObject(kind: .ellipse, width: 60, height: 60, strokeWidth: 0, fill: RGBA(hex: 0x00FF00)),164 ShapeObject(kind: .line, width: 120, height: 1, strokeWidth: 1.5),165 ShapeObject(kind: .arrow, width: 120, height: 1),166 ShapeObject(kind: .callout, width: 90, height: 45, text: "Note", placement: .floating(wrap: .square, align: .right, xOffset: 0, yOffset: 12)),167 ]168 doc.body = [.paragraph(para(runs)), .paragraph(para([Run("Shapes: ")] + shapes.map { Run(inline: .shape($0)) }))]169 let back = try assertRoundTrip(doc)170 #expect(back.assets.count == 2)171 #expect(back.assets.values.contains { $0.data == red && $0.mimeType == "image/png" })172 let exported = try DocxExporter.export(doc)173 let names = try ZipReader(data: exported.data).names174 #expect(names.filter { $0.hasPrefix("word/media/") }.count == 2) // one file per asset, however often it is used175 #expect(try ZipReader(data: exported.data).data(for: "word/media/image1.png") == red)176 let xml = try unpack(exported.data)["word/document.xml"]!177 #expect(xml.contains("descr=\"Logo & <alt> "text"\""))178 #expect(xml.contains("<a:srcRect l=\"20000\" t=\"10000\" r=\"25000\" b=\"5000\"/>") && xml.contains("rot=\"5400000\""))179 #expect(xml.contains("<wp:wrapTopAndBottom/>") && xml.contains("behindDoc=\"1\""))180 }181182 @Test func headersFootersAndSections() throws {183 var first = PageSetup(paper: .a4, margins: Insets(top: 72, left: 90, bottom: 60, right: 54), headerDistance: 30, footerDistance: 24)184 first.header = HeaderFooter(default: [Paragraph("Default header", style: StyleID.header)], first: [Paragraph("First page header", style: StyleID.header)],185 even: [Paragraph("Even header", style: StyleID.header)])186 first.footer = HeaderFooter(default: [para([Run("Page "), Run(inline: .field(.pageNumber)), Run(" of "), Run(inline: .field(.pageCount)), Run("\t"), Run(inline: .field(.title))], style: StyleID.footer)])187 first.differentFirstPage = true188 first.differentOddEven = true189 first.watermark = "DRAFT"190 first.border = PageBorder(line: BorderLine(width: 1.5, color: RGBA(hex: 0x0000FF), style: .double), inset: 20)191 first.background = RGBA(hex: 0xFFFDF5)192 var second = PageSetup(paper: .a4, landscape: true, margins: Insets(all: 36), columns: 2, columnGap: 18, columnRule: true, pageNumberStart: 1, pageNumberFormat: .lowerRoman)193 second.differentOddEven = true194 second.background = RGBA(hex: 0xFFFDF5)195 second.footer = HeaderFooter(default: [Paragraph("Second footer", style: StyleID.footer)]) // header left empty on purpose: must not inherit196 var third = PageSetup(paper: .letter, columns: 3, columnGap: 12, pageNumberFormat: .upperAlpha)197 third.differentOddEven = true198 third.background = RGBA(hex: 0xFFFDF5)199 third.header = HeaderFooter(default: [Paragraph("Third header", style: StyleID.header)])200 third.watermark = "FINAL"201 var fourth = PageSetup(paper: PaperSize(name: "Custom", width: 400, height: 500), pageNumberStart: 10, pageNumberFormat: .upperRoman)202 fourth.differentOddEven = true203 fourth.background = RGBA(hex: 0xFFFDF5)204 let table = Table(strings: [["a", "b"]], width: 200)205 let doc: DocumentModel = {206 var d = testDocument([.paragraph(Paragraph("Section one")), .sectionBreak(SectionBreak(kind: .continuous, setup: second)), .paragraph(Paragraph("Section two")),207 .table(table), .sectionBreak(SectionBreak(kind: .oddPage, setup: third)), .sectionBreak(SectionBreak(kind: .evenPage, setup: fourth)),208 .paragraph(Paragraph("Section four")), .pageBreak(BreakBlock(kind: .page)), .paragraph(Paragraph("After page break")),209 .pageBreak(BreakBlock(kind: .column)), .paragraph(Paragraph("Last"))])210 d.pageSetup = first211 return d212 }()213 let back = try assertRoundTrip(doc)214 #expect(back.sectionSetups.count == 4)215 #expect(back.sectionSetups[1].header.isEmpty)216 #expect(back.sectionSetups[1].watermark == nil && back.sectionSetups[2].watermark == "FINAL")217 // Word's convention in the produced XML: the FIRST section's page size sits in the paragraph that ends it, the last one at the end of the body.218 let xml = try unpack(try DocxExporter.export(doc).data)["word/document.xml"]!219 let firstSect = try #require(xml.range(of: "<w:sectPr>"))220 let sectionOneText = try #require(xml.range(of: "Section one"))221 #expect(firstSect.lowerBound < sectionOneText.lowerBound) // inside the pPr of that paragraph, before its run222 let firstSectXML = String(xml[firstSect.lowerBound...].prefix(1500))223 #expect(firstSectXML.contains("<w:pgSz w:w=\"11906\" w:h=\"16838\"/>") && firstSectXML.contains("<w:titlePg/>"))224 #expect(!firstSectXML.prefix(900).contains("<w:type"))225 #expect(xml.hasSuffix("<w:pgNumType w:fmt=\"upperRoman\" w:start=\"10\"/><w:cols w:space=\"480\"/></w:sectPr></w:body></w:document>"))226 #expect(xml.contains("<w:type w:val=\"continuous\"/><w:pgSz w:w=\"16838\" w:h=\"11906\" w:orient=\"landscape\"/>"))227 }228229 @Test func linksBookmarksAndNotes() throws {230 var doc = testDocument([])231 let fn = Note(id: "fnA", kind: .footnote, paragraphs: [para([Run("Footnote with "), Run("a link", props: CharProps(link: "https://example.org/n?a=1&b=2"), charStyle: StyleID.hyperlink)], style: StyleID.footnoteText),232 Paragraph("Second paragraph", style: StyleID.footnoteText)])233 let fn2 = Note(id: "fnB", kind: .footnote, paragraphs: [Paragraph(" starts with a space", style: StyleID.footnoteText)])234 let en = Note(id: "enA", kind: .endnote, paragraphs: [Paragraph("An endnote", style: StyleID.footnoteText)])235 doc.notes = ["fnA": fn, "fnB": fn2, "enA": en]236 doc.body = [.paragraph(para([Run("Visit "), Run("the site", props: CharProps(link: "https://example.org/a b?q=ü#frag"), charStyle: StyleID.hyperlink), Run(" then "),237 Run("bold part", props: CharProps(bold: true, link: "#anchor-1")), Run(" of link", props: CharProps(link: "#anchor-1")), Run(". Mail "),238 Run("me", props: CharProps(link: "mailto:someone@example.org")), Run(inline: .note(NoteRef(kind: .footnote, id: "fnA"))), Run(" x"),239 Run(inline: .note(NoteRef(kind: .endnote, id: "enA"))), Run(" y"), Run(inline: .note(NoteRef(kind: .footnote, id: "fnB")))])),240 .paragraph(para([Run(inline: .bookmark("anchor-1")), Run("Target"), Run(inline: .bookmark("second_mark")), Run(" tail")]))]241 let back = try assertRoundTrip(doc)242 let n = Numbering(back)243 #expect(n.footnoteOrder.count == 2 && n.endnoteOrder.count == 1)244 #expect(back.notes[n.footnoteOrder[1]]?.paragraphs[0].plainText == " starts with a space")245 let parts = try unpack(try DocxExporter.export(doc).data)246 #expect(parts["word/_rels/document.xml.rels"]!.contains("Target=\"https://example.org/a b?q=ü#frag\" TargetMode=\"External\""))247 #expect(parts["word/_rels/footnotes.xml.rels"]!.contains("https://example.org/n?a=1&b=2"))248 #expect(parts["word/document.xml"]!.contains("<w:hyperlink w:anchor=\"anchor-1\" w:history=\"1\">"))249 #expect(parts["word/footnotes.xml"]!.contains("<w:footnoteRef/>") && parts["word/endnotes.xml"]!.contains("<w:endnoteRef/>"))250 }251252 @Test func commentsWithRepliesAndRanges() throws {253 var doc = testDocument([])254 doc.comments = [255 Comment(id: "cA", author: "Alice Martin", date: d1, text: "Please check\nthis sentence", resolved: false,256 replies: [CommentReply(id: "rA1", author: "Bob", date: d2, text: "Checked"), CommentReply(id: "rA2", author: "Alice Martin", date: d2, text: "Thanks <&>")]),257 Comment(id: "cB", author: "Carol", date: d2, text: "Spans paragraphs", resolved: true),258 Comment(id: "cC", author: "Dan", date: d1, text: "Inside a table"),259 Comment(id: "cD", author: "Eve", date: d1, text: "In a footnote"),260 ]261 doc.notes = ["n1": Note(id: "n1", kind: .footnote, paragraphs: [para([Run("Note "), Run("text", comments: ["cD"])], style: StyleID.footnoteText)])]262 var table = Table(strings: [["plain", "x"]], width: 200)263 table.rows[0].cells[1].paragraphs = [para([Run("cell ", comments: []), Run("commented", comments: ["cC"])], style: StyleID.tableText)]264 doc.body = [.paragraph(para([Run("Start "), Run("first", comments: ["cA"]), Run(" both", props: CharProps(bold: true), comments: ["cA", "cB"]), Run(" second", comments: ["cB"])])),265 .paragraph(para([Run("whole paragraph", comments: ["cB"])])),266 .paragraph(para([Run("end of range", comments: ["cB"]), Run(" free"), Run(inline: .note(NoteRef(kind: .footnote, id: "n1")))])),267 .table(table)]268 let back = try assertRoundTrip(doc)269 #expect(back.comments.map(\.replies.count) == [2, 0, 0, 0])270 #expect(back.comments[1].resolved)271 let parts = try unpack(try DocxExporter.export(doc).data)272 // Replies are real Word comment threads: their own w:comment, linked through commentsExtended.273 #expect(parts["word/comments.xml"]!.components(separatedBy: "<w:comment ").count - 1 == 6)274 #expect(parts["word/commentsExtended.xml"]!.components(separatedBy: "w15:paraIdParent=").count - 1 == 2)275 #expect(parts["word/commentsExtended.xml"]!.contains("w15:done=\"1\""))276 #expect(parts["word/comments.xml"]!.contains("w:author=\"Alice Martin\"") && parts["word/comments.xml"]!.contains("w:initials=\"AM\""))277 }278279 @Test func trackedChanges() throws {280 var doc = testDocument([])281 doc.settings.trackChanges = true282 let ins = Revision(id: "i1", kind: .insertion, author: "Alice", date: d1), del = Revision(id: "x1", kind: .deletion, author: "Bob \"B\" <b@example.org>", date: d2)283 var formatted = Run("reformatted", props: CharProps(bold: true, color: RGBA(hex: 0xFF0000)), charStyle: StyleID.emphasis)284 formatted.formatRevision = FormatRevision(id: "f1", author: "Carol", date: d1, previous: CharProps(fontSize: 10, italic: true), previousCharStyle: nil)285 var both = Run("inserted and reformatted", props: CharProps(italic: true), revision: ins)286 both.formatRevision = FormatRevision(id: "f2", author: "Alice", date: d1, previous: .none, previousCharStyle: StyleID.emphasis)287 var p1 = para([Run("Kept "), Run("added ", revision: ins), Run("more added", props: CharProps(bold: true), revision: ins), Run(" removed", revision: del), formatted, Run(" "), both,288 Run(inline: .field(.pageNumber), revision: del), Run(inline: .equation(Equation(latex: "x^{2}")), revision: ins),289 Run("linked insert", props: CharProps(link: "https://example.org"), revision: ins)])290 p1.markRevision = Revision(id: "m1", kind: .insertion, author: "Alice", date: d1)291 var p2 = para([Run("Paragraph to merge")])292 p2.markRevision = Revision(id: "m2", kind: .deletion, author: "Bob", date: d2)293 doc.body = [.paragraph(p1), .paragraph(p2), .paragraph(Paragraph("Untouched"))]294 let back = try assertRoundTrip(doc)295 #expect(back.settings.trackChanges)296 #expect(back.bodyParagraphs[0].visibleText == "Kept added more addedreformatted inserted and reformattedlinked insert")297 #expect(back.bodyParagraphs[0].runs[3].revision?.author == "Bob \"B\" <b@example.org>")298 #expect(back.bodyParagraphs[0].runs[3].revision?.date == d2)299 let parts = try unpack(try DocxExporter.export(doc).data)300 let xml = parts["word/document.xml"]!301 #expect(xml.contains("<w:delText xml:space=\"preserve\"> removed</w:delText>"))302 #expect(xml.contains("<w:ins w:id=") && xml.contains("w:author=\"Alice\"") && xml.contains("<w:rPrChange w:id="))303 #expect(xml.contains("<w:delInstrText"))304 #expect(parts["word/settings.xml"]!.contains("<w:trackRevisions/>"))305 // Revision ids are unique in the file.306 let ids = xml.components(separatedBy: "<w:ins w:id=\"").dropFirst().map { $0.prefix { $0 != "\"" } } + xml.components(separatedBy: "<w:del w:id=\"").dropFirst().map { $0.prefix { $0 != "\"" } }307 #expect(Set(ids).count == ids.count)308 }309310 @Test func equations() throws {311 let formulas = ["E=mc^{2}", "\\frac{a+b}{c}=\\sqrt{x^{2}+y^{2}}", "\\sum_{i=1}^{n}x_{i}", "\\int_{0}^{1}f(t)\\,dt", "\\begin{pmatrix}a&b\\\\c&d\\end{pmatrix}",312 "\\alpha+\\beta\\leq\\gamma", "\\sqrt[3]{x}", "\\hat{x}+\\bar{y}", "\\lim_{x\\to0}\\frac{\\sin x}{x}=1", "\\left(\\frac{a}{b}\\right)^{n}", "\\mathbb{R}^{n}"]313 var blocks: [Block] = [.paragraph(para([Run("Inline ")] + formulas.map { Run(inline: .equation(Equation(latex: $0))) } + [Run(" end")]))]314 for f in formulas { blocks.append(.paragraph(para([Run(inline: .equation(Equation(latex: f, display: true)))]))) }315 let doc = testDocument(blocks)316 try assertRoundTrip(doc)317 let xml = try unpack(try DocxExporter.export(doc).data)["word/document.xml"]!318 #expect(xml.components(separatedBy: "<m:oMathPara>").count - 1 == formulas.count)319 #expect(xml.contains("<m:f>") && xml.contains("<m:rad>") && xml.contains("<m:nary>"))320 // LaTeX the converter cannot parse is exported as text inside the equation and reported; it is not lost.321 let bad = testDocument([.paragraph(para([Run(inline: .equation(Equation(latex: "\\mycustommacro{x}")))]))])322 let out = try DocxExporter.export(bad)323 #expect(out.warnings.contains { $0.feature == "Equations" && $0.severity == .approximated })324 let reread = try DocxImporter.importDocument(out.data).document325 let eq: [Equation] = reread.inlines.compactMap { if case .equation(let e) = $0 { return e } else { return nil } }326 #expect(eq.count == 1 && eq[0].latex.contains("mycustommacro"))327 #expect(DocxExporter.preflight(bad).contains { $0.feature == "Equations" })328 }329330 @Test func fieldsCaptionsAndCrossReferences() throws {331 var doc = testDocument([])332 let caption1 = para([Run("Figure "), Run(inline: .field(.sequence("Figure"))), Run(": Yield curve")], style: StyleID.caption, id: "cap1")333 let caption2 = para([Run("Table "), Run(inline: .field(.sequence("Table"))), Run(": Data")], style: StyleID.caption, id: "cap2")334 let caption3 = para([Run("Figure "), Run(inline: .field(.sequence("Figure"))), Run(": Second")], style: StyleID.caption, id: "cap3")335 let refs = para([Run("See "), Run(inline: .crossRef(CrossRef(target: "cap3", display: .labelAndNumber))), Run(", "), Run(inline: .crossRef(CrossRef(target: "cap2", display: .number))), Run(", "),336 Run(inline: .crossRef(CrossRef(target: "cap1", display: .text))), Run(", "), Run(inline: .crossRef(CrossRef(target: "h1", display: .text))), Run(", "),337 Run(inline: .crossRef(CrossRef(target: "h1", display: .number))), Run(", "), Run(inline: .crossRef(CrossRef(target: "h1", display: .labelAndNumber))), Run(", p. "),338 Run(inline: .crossRef(CrossRef(target: "h1", display: .page))), Run(", "), Run(inline: .crossRef(CrossRef(target: "mark", display: .page))), Run(", "),339 Run(inline: .crossRef(CrossRef(target: "a long paragraph identifier that is not a legal bookmark name!", display: .text)))])340 var odd = Paragraph("Oddly identified heading", style: StyleID.heading(2))341 odd.id = "a long paragraph identifier that is not a legal bookmark name!"342 doc.body = [.paragraph(para([Run("Results")], style: StyleID.heading(1), id: "h1")), .paragraph(refs), .paragraph(caption1), .paragraph(caption2), .paragraph(caption3), .paragraph(odd),343 .paragraph(para([Run(inline: .bookmark("mark")), Run("Fields: "), Run(inline: .field(.pageNumber)), Run(inline: .field(.pageCount)), Run(inline: .field(.date(format: "EEEE d MMMM yyyy 'at' HH:mm"))),344 Run(inline: .field(.title)), Run(inline: .field(.author)), Run(inline: .field(.sequence("Equation"))), Run(inline: .field(.sequence("My Label"))),345 Run(inline: .field(.headingText(level: 1))), Run(inline: .field(.headingText(level: 3)))]))]346 for i in doc.styles.styles.indices where doc.styles.styles[i].id.hasPrefix("Heading") { doc.styles.styles[i].numbered = true }347 var options = DocxExportOptions()348 options.pageOf = { id in id == "h1" ? "7" : nil }349 options.pageCount = 12350 let back = try assertRoundTrip(doc, options: options)351 // Targets keep their identity: the references still resolve after the trip.352 let n = Numbering(back)353 let backRefs: [CrossRef] = back.bodyParagraphs[1].runs.compactMap { if case .crossRef(let c)? = $0.inline { return c } else { return nil } }354 #expect(backRefs.map { n.crossRefText($0, pageOf: { _ in "7" }) } == ["Figure 2", "1", "Figure 1: Yield curve", "Results", "1", "Section 1", "7", "7", "Oddly identified heading"])355 // Cached results in the file are the computed values, so a reader that does not update fields shows the right text.356 let xml = try unpack(try DocxExporter.export(doc, options: options).data)["word/document.xml"]!357 for cached in [">Figure 2<", ">Figure 1: Yield curve<", ">Section 1<", ">7<", ">12<", ">Test<", ">Tester<"] { #expect(xml.contains(cached), "missing cached \(cached)") }358 #expect(xml.contains(" SEQ Figure \\* ARABIC ") && xml.contains(" SEQ \"My Label\" \\* ARABIC ") && xml.contains(" PAGEREF _ORIX_T_h1 \\h "))359 #expect(xml.contains("w:name=\"_ORIX_L_cap3\"") && xml.contains("w:name=\"_ORIX_N_cap2\"") && xml.contains(" REF _ORIX_L_cap3 \\h "))360 #expect(xml.contains(" DATE \\@ \"dddd d MMMM yyyy 'at' HH:mm\" ") && xml.contains(" STYLEREF \"heading 3\" "))361 // A reference to nothing is exported as its text and reported.362 let dangling = testDocument([.paragraph(para([Run("See "), Run(inline: .crossRef(CrossRef(target: "nowhere")))]))])363 let out = try DocxExporter.export(dangling)364 #expect(out.warnings.contains { $0.feature == "Cross-references" })365 #expect(try DocxImporter.importDocument(out.data).document.bodyLines == ["See ??"])366 }367368 @Test func generatedBlocksCitationsAndBibliography() throws {369 var doc = testDocument([])370 doc.settings.citationStyle = "ieee"371 doc.settings.smartQuotes = false372 doc.settings.smartDashes = false373 doc.bibliography = [374 BibEntry(key: "smith2020", type: "article-journal", authors: [PersonName(family: "Smith", given: "Jane"), PersonName(family: "", literal: "World Health Organization")],375 editors: [PersonName(family: "Éditeur", given: "Émile")], year: 2020, month: 5, day: 17, fields: ["title": "On \"things\" & <stuff>", "container-title": "Journal", "DOI": "10.1/x"]),376 BibEntry(key: "doe19", type: "book", authors: [PersonName(family: "Doe", given: "John")], year: 2019, fields: ["title": "A Book", "publisher": "Press"]),377 BibEntry(key: "uncited", type: "report", fields: ["title": "Never cited"]),378 ]379 let cite1 = Citation(items: [CitationItem(key: "smith2020", locator: "pp. 12–14", prefix: "see", suffix: "for details", suppressAuthor: true), CitationItem(key: "doe19")])380 doc.body = [.toc(TOCBlock(kind: .contents, title: "Contents", maxLevel: 2)), .toc(TOCBlock(kind: .figures, title: "List of Figures", maxLevel: 3)),381 .toc(TOCBlock(kind: .tables, title: nil, maxLevel: 3)),382 .paragraph(para([Run("Intro")], style: StyleID.heading(1), id: "h1")), .paragraph(para([Run("Details")], style: StyleID.heading(2), id: "h2")),383 .paragraph(para([Run("Too deep")], style: StyleID.heading(3), id: "h3")),384 .paragraph(para([Run("As shown "), Run(inline: .citation(cite1)), Run(" and "), Run(inline: .citation(Citation("doe19"))), Run(".")])),385 .paragraph(para([Run("Figure "), Run(inline: .field(.sequence("Figure"))), Run(": A figure")], style: StyleID.caption)),386 .bibliography(BibliographyBlock(title: "References")), .bibliography(BibliographyBlock(title: nil))]387 var options = DocxExportOptions()388 options.citations = FixedFormatter()389 options.pageOf = { ["h1": "1", "h2": "2"][$0] }390 let back = try assertRoundTrip(doc, options: options)391 #expect(back.bibliography == doc.bibliography)392 #expect(back.settings == doc.settings)393 let cites: [Citation] = back.inlines.compactMap { if case .citation(let c) = $0 { return c } else { return nil } }394 #expect(cites == [cite1, Citation("doe19")])395 // Generated content is not reimported as text.396 #expect(back.bodyLines == ["Intro", "Details", "Too deep", "As shown and .", "Figure : A figure"])397 let exported = try DocxExporter.export(doc, options: options)398 let xml = try unpack(exported.data)["word/document.xml"]!399 // The file a reader sees: formatted citations, a contents list with page numbers, a formatted bibliography.400 #expect(xml.contains(">[1, 2]<") && xml.contains(">[2]<"))401 #expect(xml.contains(" ADDIN ORIX_CITATION {"items"") || xml.contains(" ADDIN ORIX_CITATION {\"items\""))402 #expect(xml.contains(" TOC \\o \"1-2\" \\h \\z \\u ") && xml.contains(" TOC \\h \\z \\c \"Figure\" ") && xml.contains(" TOC \\h \\z \\c \"Table\" "))403 #expect(xml.contains(">Intro<") && xml.contains(">[1] On \"things\" & <stuff><") && xml.contains(">Figure 1: A figure<"))404 #expect(!xml.contains("Never cited"))405 let plain = try #require(Tool.pandoc != nil ? Tool.pandocText(exported.data) : "")406 if Tool.pandoc != nil {407 #expect(plain.contains("Details") && plain.contains("[1] On \"things\" & <stuff>"))408 } else { recordSkip("pandoc missing: generated-block text not cross-checked") }409 // Without a formatter the keys are shown, the data still round-trips, and the user is told.410 let bare = try DocxExporter.export(doc)411 #expect(bare.warnings.contains { $0.feature == "Citations" && $0.severity == .info })412 #expect(try DocxImporter.importDocument(bare.data).document.bibliography == doc.bibliography)413 #expect(try unpack(bare.data)["word/document.xml"]!.contains(">(smith2020; doe19)<"))414 }415416 @Test func metadataSettingsAndPreservedParts() throws {417 var doc = testDocument([.paragraph(Paragraph("Text"))])418 doc.meta = DocumentMetadata(title: "Title with <&> \"quotes\"", author: "Ünïcode Author", subject: "Subject line", keywords: ["finance", "yield curve", "2026"], language: "fr-CA",419 created: d1, modified: d2)420 doc.settings.trackChanges = true421 doc.preservedParts = [422 "word/theme/theme1.xml": Data((Pkg.head + "<a:theme xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" name=\"Kept\"><a:themeElements><a:fontScheme name=\"F\"><a:majorFont><a:latin typeface=\"Avenir\"/></a:majorFont><a:minorFont><a:latin typeface=\"Georgia\"/></a:minorFont></a:fontScheme></a:themeElements></a:theme>").utf8),423 "word/fontTable.xml": Data((Pkg.head + "<w:fonts \(Hand.w)><w:font w:name=\"Georgia\"/></w:fonts>").utf8),424 "word/webSettings.xml": Data((Pkg.head + "<w:webSettings \(Hand.w)/>").utf8),425 "docProps/app.xml": Data((Pkg.head + "<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/extended-properties\"><Application>Other App</Application></Properties>").utf8),426 "docProps/custom.xml": Data((Pkg.head + "<Properties xmlns=\"http://schemas.openxmlformats.org/officeDocument/2006/custom-properties\"/>").utf8),427 "customXml/item1.xml": Data("<root xmlns=\"urn:example:data\"><value>42</value></root>".utf8),428 "customXml/itemProps1.xml": Data((Pkg.head + "<ds:datastoreItem ds:itemID=\"{11111111-2222-3333-4444-555555555555}\" xmlns:ds=\"http://schemas.openxmlformats.org/officeDocument/2006/customXml\"/>").utf8),429 "customXml/_rels/item1.xml.rels": Data((Pkg.head + "<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006/relationships\"><Relationship Id=\"rId1\" Type=\"\(Hand.rel)customXmlProps\" Target=\"itemProps1.xml\"/></Relationships>").utf8),430 ]431 let back = try assertRoundTrip(doc)432 #expect(back.preservedParts == doc.preservedParts) // byte for byte433 #expect(back.meta == doc.meta)434 let exported = try DocxExporter.export(doc)435 let parts = try unpack(exported.data)436 let types = parts["[Content_Types].xml"]!437 for (name, type) in [("/word/theme/theme1.xml", "theme+xml"), ("/word/fontTable.xml", "fontTable+xml"), ("/word/webSettings.xml", "webSettings+xml"),438 ("/docProps/app.xml", "extended-properties+xml"), ("/docProps/custom.xml", "custom-properties+xml"), ("/customXml/itemProps1.xml", "customXmlProperties+xml"),439 ("/customXml/itemProps2.xml", "customXmlProperties+xml"), ("/docProps/core.xml", "core-properties+xml")] {440 #expect(types.contains("PartName=\"\(name)\" ContentType=\"application/vnd.openxmlformats-") && types.contains(type), "content type of \(name)")441 }442 let rels = parts["word/_rels/document.xml.rels"]!443 #expect(rels.contains("relationships/theme\" Target=\"theme/theme1.xml\"") && rels.contains("relationships/fontTable\" Target=\"fontTable.xml\""))444 #expect(rels.contains("relationships/customXml\" Target=\"../customXml/item1.xml\"") && rels.contains("Target=\"../customXml/item2.xml\""))445 #expect(parts["_rels/.rels"]!.contains("extended-properties\" Target=\"docProps/app.xml\"") && parts["_rels/.rels"]!.contains("core-properties\" Target=\"docProps/core.xml\""))446 // Every relationship target of the package exists, and every part has a content type.447 let zip = try ZipReader(data: exported.data)448 let names = Set(zip.names)449 let ct = try ContentTypes(try zip.data(for: "[Content_Types].xml"))450 for name in names where name != "[Content_Types].xml" { #expect(ct.type(of: name) != nil, "no content type for \(name)") }451 for relsPart in names where relsPart.hasSuffix(".rels") {452 let owner = relsPart == "_rels/.rels" ? "" : relsPart.replacingOccurrences(of: "_rels/", with: "").replacingOccurrences(of: ".rels", with: "")453 for r in try OPC.parseRelationships(try zip.data(for: relsPart), part: owner) where !r.external {454 let target = OPC.resolve(target: r.target, from: owner)455 #expect(target != nil && names.contains(target!), "dangling relationship \(r.target) in \(relsPart)")456 }457 }458 }459460 @Test func everythingTogetherTwiceIsAFixedPoint() throws {461 let doc = richDocument()462 var options = DocxExportOptions()463 options.citations = FixedFormatter()464 let once = try assertRoundTrip(doc, options: options)465 let twice = try assertRoundTrip(once, options: options)466 expectSameModel(doc, twice)467 // The exporter is deterministic: same model, same bytes.468 #expect(try DocxExporter.export(doc, options: options).data == (try DocxExporter.export(doc, options: options).data))469 }470471 @Test func standardStyleSheetIsApproximatedOnceThenStable() throws {472 // The built-in ORIX theme uses sizes DOCX cannot hold exactly (27.6 pt …): the first trip rounds them, later trips change nothing.473 var doc = DocumentModel(meta: DocumentMetadata(title: "Std", created: d1, modified: d1), styles: .standard(), pageSetup: PageSetup(paper: .a4),474 body: [.paragraph(Paragraph("Title", style: StyleID.title)), .paragraph(Paragraph("Body text")), .paragraph(Paragraph("code", style: StyleID.code))])475 doc.lists = [ListDefinition.bullets(id: "b")]476 let pre = DocxExporter.preflight(doc)477 #expect(pre.contains { $0.feature == "Font sizes" && $0.severity == .approximated })478 let first = try DocxImporter.importDocument(try DocxExporter.export(doc).data).document479 #expect(first.bodyLines == ["Title", "Body text", "code"])480 #expect(first.styles.styles.map(\.id) == doc.styles.styles.map(\.id))481 #expect(first.styles.themeName == "ORIX")482 let title = try #require(first.styles.style(StyleID.title))483 #expect(title.char.fontSize == 27.5 && title.char.tracking == -0.3 && title.char.fontFamily == "SF Pro Display")484 #expect(first.styles.style(StyleID.code)?.char.ligatures == false)485 #expect(first.styles.style(StyleID.heading(1))?.para.outlineLevel == 1)486 let second = try DocxImporter.importDocument(try DocxExporter.export(first).data).document487 expectSameModel(first, second)488 }489490 @Test func preflightReportsWhatExportWouldLose() throws {491 var doc = testDocument([.paragraph(Paragraph("Drop", props: ParaProps(dropCapLines: 3))), .paragraph(para([Run("w", props: CharProps(fontSize: 11.3, weight: 300))])),492 .paragraph(para([Run(inline: .image(ImageObject(asset: "missing", width: 10, height: 10))), Run(inline: .note(NoteRef(kind: .footnote, id: "ghost")))]))])493 doc.notes["unused"] = Note(id: "unused", kind: .footnote, paragraphs: [Paragraph("orphan")])494 doc.comments = [Comment(id: "lost", author: "A", date: d1, text: "nowhere")]495 doc.pageSetup.header.default = [para([Run("hdr", comments: ["lost2"])])]496 let pre = DocxExporter.preflight(doc)497 func has(_ f: String, _ s: FormatWarning.Severity) -> Bool { pre.contains { $0.feature == f && $0.severity == s } }498 #expect(has("Drop caps", .dropped) && has("Font weights", .approximated) && has("Font sizes", .approximated) && has("Pictures", .dropped) && has("Notes", .dropped) && has("Comments", .approximated))499 // Most severe first.500 #expect(pre.map(\.severity) == pre.map(\.severity).sorted(by: >))501 // A clean document produces no warning at all, and preflight says the same thing export does.502 let clean = testDocument([.paragraph(Paragraph("Fine"))])503 #expect(DocxExporter.preflight(clean).isEmpty)504 #expect(try DocxExporter.export(clean).warnings.isEmpty)505 #expect(Set(try DocxExporter.export(doc).warnings.map(\.id)) == Set(pre.map(\.id)))506 }507508 @Test func fullCycleImportEditExportReimportExportReimport() throws {509 for name in ["pandoc-basic.docx", "pandoc-footnotes.docx", "libreoffice-pagesetup.docx"] {510 var doc = try DocxImporter.importDocument(try Corpus.data(name)).document511 let originalLines = doc.bodyLines512 // Edit: retitle the first paragraph, make a run bold, insert a tracked paragraph with a comment, a footnote and an equation.513 let firstIndex = try #require(doc.body.firstIndex { $0.paragraph?.runs.isEmpty == false })514 var first = doc.body[firstIndex].paragraph!515 first.insert(Run("EDITED ", props: CharProps(bold: true)), at: 0)516 doc.body[firstIndex] = .paragraph(first)517 let note = Note(kind: .footnote, paragraphs: [Paragraph("Added during the cycle")])518 doc.notes[note.id] = note519 let comment = Comment(author: "Cycle", date: d1, text: "Added comment", replies: [CommentReply(author: "Cycle 2", date: d2, text: "Reply")])520 doc.comments.append(comment)521 var added = Paragraph(style: first.style == StyleID.title ? StyleID.normal : first.style,522 runs: [Run("New paragraph ", revision: Revision(kind: .insertion, author: "Cycle", date: d1)), Run("with a comment", comments: [comment.id]),523 Run(inline: .note(NoteRef(kind: .footnote, id: note.id))), Run(inline: .equation(Equation(latex: "a^{2}+b^{2}=c^{2}")))])524 added.markRevision = Revision(kind: .insertion, author: "Cycle", date: d1)525 doc.body.insert(.paragraph(added), at: firstIndex + 1)526 doc.meta.title = "Edited " + name527 doc.settings.trackChanges = true528529 let export1 = try DocxExporter.export(doc)530 let import1 = try DocxImporter.importDocument(export1.data).document531 expectSameModel(doc, import1, name + " first trip")532 // The edits are there, the rest of the text is untouched.533 var expected = originalLines534 let lineIndex = try #require(expected.firstIndex { !$0.isEmpty })535 expected[lineIndex] = "EDITED " + expected[lineIndex]536 expected.insert("New paragraph with a comment", at: lineIndex + 1)537 #expect(import1.bodyLines == expected, "\(name)")538 #expect(import1.meta.title == "Edited " + name && import1.settings.trackChanges)539 #expect(import1.comments.last?.text == "Added comment" && import1.comments.last?.replies.first?.text == "Reply")540 #expect(import1.notes.values.contains { $0.paragraphs.first?.visibleText == "Added during the cycle" })541 #expect(import1.preservedParts == doc.preservedParts)542 #expect(import1.assets.count == doc.assets.count)543544 let export2 = try DocxExporter.export(import1)545 let import2 = try DocxImporter.importDocument(export2.data).document546 expectSameModel(import1, import2, name + " second trip")547 #expect(import2.bodyLines == expected)548 // Once the identifiers are the importer's own, the bytes themselves are stable.549 let export3 = try DocxExporter.export(import2)550 expectSameModel(import2, try DocxImporter.importDocument(export3.data).document, name + " third trip")551 }552 }553}554555/// A document that uses every feature at once (shared with the external validation and the compatibility report).556func richDocument() -> DocumentModel {557 let d1 = Date(timeIntervalSince1970: 1_770_000_000)558 var doc = testDocument([])559 doc.meta.title = "Rich document"560 let red = (try? Data(contentsOf: Corpus.directory.appendingPathComponent("sources/pixel-red.png"))) ?? Pkg.png561 doc.assets = ["red": Asset(id: "red", mimeType: "image/png", data: red)]562 doc.lists = [ListDefinition.bullets(id: "B"), ListDefinition.numbered(id: "N")]563 doc.bibliography = [BibEntry(key: "smith2020", authors: [PersonName(family: "Smith", given: "Jane")], year: 2020, fields: ["title": "Yield Curves"])]564 doc.notes = ["f1": Note(id: "f1", kind: .footnote, paragraphs: [Paragraph("First footnote text.", style: StyleID.footnoteText)]),565 "f2": Note(id: "f2", kind: .footnote, paragraphs: [Paragraph("Second footnote, first paragraph.", style: StyleID.footnoteText), Paragraph("Second footnote, second paragraph.", style: StyleID.footnoteText)]),566 "e1": Note(id: "e1", kind: .endnote, paragraphs: [Paragraph("The only endnote.", style: StyleID.footnoteText)])]567 doc.comments = [Comment(id: "c1", author: "Reviewer One", date: d1, text: "Is this right?", replies: [CommentReply(id: "r1", author: "Author", date: d1, text: "Yes.")])]568 var setup = PageSetup(paper: .a4)569 setup.header = HeaderFooter(default: [Paragraph("Rich document header", style: StyleID.header)])570 setup.footer = HeaderFooter(default: [Paragraph(style: StyleID.footer, runs: [Run("Page "), Run(inline: .field(.pageNumber))])])571 doc.pageSetup = setup572 func p(_ runs: [Run], _ style: String = StyleID.normal, id: String? = nil, list: ListItem? = nil) -> Block {573 var x = Paragraph(style: style, runs: runs, list: list)574 if let id { x.id = id }575 return .paragraph(x)576 }577 var table = Table(columnWidths: [120, 120, 120], rows: [578 TableRow(cells: [TableCell("Name", bold: true), TableCell("Quantity", bold: true), TableCell("Price", bold: true)], isHeader: true),579 TableRow(cells: [TableCell("Apples"), TableCell("3"), TableCell("1.25")]),580 TableRow(cells: [TableCell(paragraphs: [Paragraph("Merged across two", style: StyleID.tableText)], colSpan: 2), TableCell("9.50")]),581 TableRow(cells: [TableCell("Pears"), TableCell("7"), TableCell("0.80")]),582 ], style: .grid)583 table.rows[1].cells[0].shading = RGBA(hex: 0xEEF0F6)584 var landscape = PageSetup(paper: .a4, landscape: true, columns: 2, columnGap: 18)585 landscape.header = HeaderFooter(default: [Paragraph("Rich document header", style: StyleID.header)])586 landscape.footer = HeaderFooter(default: [Paragraph(style: StyleID.footer, runs: [Run("Page "), Run(inline: .field(.pageNumber))])])587 doc.body = [588 p([Run("Rich document")], StyleID.heading(1), id: "h1"),589 p([Run("An opening paragraph with "), Run("bold", props: CharProps(bold: true)), Run(", "), Run("italic", props: CharProps(italic: true)), Run(" and "),590 Run("a link", props: CharProps(link: "https://example.org/rich"), charStyle: StyleID.hyperlink), Run(" plus a note"), Run(inline: .note(NoteRef(kind: .footnote, id: "f1"))), Run(".")]),591 p([Run("Background")], StyleID.heading(2), id: "h2"),592 p([Run("First bullet")], list: ListItem(listID: "B")), p([Run("Nested bullet")], list: ListItem(listID: "B", level: 1)), p([Run("Second bullet")], list: ListItem(listID: "B")),593 p([Run("Step one")], list: ListItem(listID: "N")), p([Run("Step two")], list: ListItem(listID: "N")),594 p([Run("The table follows"), Run(inline: .note(NoteRef(kind: .footnote, id: "f2"))), Run(" and is "), Run("commented", comments: ["c1"]), Run(" here"),595 Run(inline: .note(NoteRef(kind: .endnote, id: "e1"))), Run(".")]),596 .table(table),597 p([Run("Table "), Run(inline: .field(.sequence("Table"))), Run(": Fruit prices")], StyleID.caption, id: "cap1"),598 p([Run("Inline math "), Run(inline: .equation(Equation(latex: "E=mc^{2}"))), Run(" cited by "), Run(inline: .citation(Citation("smith2020"))), Run(", see "),599 Run(inline: .crossRef(CrossRef(target: "cap1", display: .labelAndNumber))), Run(".")]),600 p([Run(inline: .equation(Equation(latex: "\\frac{a+b}{c}=\\sqrt{x^{2}+y^{2}}", display: true)))]),601 p([Run("A picture "), Run(inline: .image(ImageObject(asset: "red", width: 96, height: 64, altText: "Red rectangle"))), Run(" in the text.")]),602 .sectionBreak(SectionBreak(kind: .nextPage, setup: landscape)),603 p([Run("Methods")], StyleID.heading(1), id: "h3"),604 p([Run("Landscape section with "), Run("tracked insertion", revision: Revision(id: "rv1", kind: .insertion, author: "Editor", date: d1)), Run(" and "),605 Run("tracked deletion", revision: Revision(id: "rv2", kind: .deletion, author: "Editor", date: d1)), Run(" text.")]),606 .pageBreak(BreakBlock(kind: .page)),607 p([Run("Closing paragraph after a page break.")]),608 .bibliography(BibliographyBlock(title: "References")),609 ]610 return doc611}612613@Suite("DOCX engine — scale")614struct ScaleTests {615 @Test func largeDocumentRoundTripsInReasonableTime() throws {616 // 12 000 paragraphs, 200 tables, notes and comments: correctness at scale and a loose guard against quadratic behaviour.617 var doc = testDocument([])618 var body: [Block] = []619 body.reserveCapacity(13_000)620 for i in 0..<12_000 {621 if i % 400 == 0 { body.append(.paragraph(Paragraph("Chapter \(i / 400 + 1)", style: StyleID.heading(1)))) }622 var runs = [Run("Paragraph \(i) with some ordinary text, "), Run("a bold part", props: CharProps(bold: true)), Run(" and an ending — ünïcode 👍.")]623 if i % 500 == 0 {624 let note = Note(id: "n\(i)", kind: .footnote, paragraphs: [Paragraph("Note \(i)", style: StyleID.footnoteText)])625 doc.notes[note.id] = note626 runs.append(Run(inline: .note(NoteRef(kind: .footnote, id: note.id))))627 }628 if i % 1000 == 0 {629 doc.comments.append(Comment(id: "c\(i)", author: "Scale", date: Date(timeIntervalSince1970: 1_770_000_000), text: "Comment \(i)"))630 runs[1].comments = ["c\(i)"]631 }632 body.append(.paragraph(Paragraph(style: StyleID.normal, runs: runs)))633 if i % 60 == 0 { body.append(.table(Table(strings: [["a\(i)", "b"], ["c", "d"]], width: 300))); body.append(.paragraph(Paragraph("After table \(i)"))) }634 }635 doc.body = body636 let started = Date()637 let exported = try DocxExporter.export(doc)638 let back = try DocxImporter.importDocument(exported.data).document639 let elapsed = Date().timeIntervalSince(started)640 #expect(back.body.count == doc.body.count)641 #expect(back.bodyLines == doc.bodyLines)642 #expect(back.notes.count == 24 && back.comments.count == 12 && back.tables.count == 200)643 #expect(elapsed < 60, "export + import of a 12 000 paragraph document took \(elapsed) s")644 print("ORIX-DOCX-SCALE: \(doc.body.count) blocks, \(exported.data.count) bytes, export+import \(String(format: "%.2f", elapsed)) s (debug build)")645 }646}647