diff --git a/src/file/file.ts b/src/file/file.ts index 18bae5ce71..b4bd0fb9e4 100644 --- a/src/file/file.ts +++ b/src/file/file.ts @@ -328,7 +328,7 @@ export class File { // console.log("Generating content for paragraph: ", bookmarkId); // deep clone the original paragraph - const generatedParagraph = Object.assign(Object.create(Object.getPrototypeOf(paragraph)), paragraph); + const generatedParagraph = paragraph.clone() as Paragraph; generatedParagraph.clearPageBreaks().rightTabStop(9016, "dot"); diff --git a/src/file/paragraph/paragraph.spec.ts b/src/file/paragraph/paragraph.spec.ts index 2413769b1e..5bf4ee5f15 100644 --- a/src/file/paragraph/paragraph.spec.ts +++ b/src/file/paragraph/paragraph.spec.ts @@ -393,4 +393,23 @@ describe("Paragraph", () => { }); }); }); + + describe("#clone", () => { + it("changes in a cloned paragraph must not affect the original paragraph", () => { + paragraph.pageBreakBefore(); + + const clonedParagraph = paragraph.clone() as file.Paragraph; + clonedParagraph.clearPageBreaks(); + + const tree = new Formatter().format(paragraph); + expect(tree).to.deep.equal({ + "w:p": [{ "w:pPr": [{ "w:pageBreakBefore": [] }] }], + }); + + const clonedTree = new Formatter().format(clonedParagraph); + expect(clonedTree).to.deep.equal({ + "w:p": [{ "w:pPr": [] }], + }); + }); + }); }); diff --git a/src/file/xml-components/xml-component.ts b/src/file/xml-components/xml-component.ts index 0ed604e9ee..68b50da59d 100644 --- a/src/file/xml-components/xml-component.ts +++ b/src/file/xml-components/xml-component.ts @@ -30,7 +30,6 @@ export abstract class XmlComponent extends BaseXmlComponent { }; } - // TODO: Unused method public addChildElement(child: XmlComponent | string): XmlComponent { this.root.push(child); @@ -40,4 +39,10 @@ export abstract class XmlComponent extends BaseXmlComponent { public delete(): void { this.deleted = true; } + + public clone(): XmlComponent { + const newXmlComponent = Object.assign(Object.create(Object.getPrototypeOf(this)), this); + newXmlComponent.root = newXmlComponent.root.map((child) => (child instanceof XmlComponent ? child.clone() : child)); + return newXmlComponent as XmlComponent; + } }