Files
docx-js/src/file/document/body/body.ts

51 lines
1.7 KiB
TypeScript
Raw Normal View History

import { Paragraph, ParagraphProperties } from "@file/paragraph";
import { IContext, IXmlableObject, XmlComponent } from "@file/xml-components";
2021-03-19 20:53:56 +00:00
import { ISectionPropertiesOptions, SectionProperties } from "./section-properties/section-properties";
2017-09-19 15:39:14 +01:00
export class Body extends XmlComponent {
// eslint-disable-next-line functional/prefer-readonly-type
2018-08-07 01:38:15 +01:00
private readonly sections: SectionProperties[] = [];
2022-08-31 07:52:27 +01:00
public constructor() {
2017-09-19 15:39:14 +01:00
super("w:body");
}
/**
* Adds new section properties.
* Note: Previous section is created in paragraph after the current element, and then new section will be added.
* The spec says:
* - section element should be in the last paragraph of the section
* - last section should be direct child of body
*
2019-07-31 08:48:02 +01:00
* @param options new section options
*/
2021-03-19 20:53:56 +00:00
public addSection(options: ISectionPropertiesOptions): void {
const currentSection = this.sections.pop() as SectionProperties;
this.root.push(this.createSectionParagraph(currentSection));
2019-07-31 08:48:02 +01:00
this.sections.push(new SectionProperties(options));
}
2019-07-31 08:48:02 +01:00
2021-03-11 01:06:55 +00:00
public prepForXml(context: IContext): IXmlableObject | undefined {
if (this.sections.length === 1) {
this.root.splice(0, 1);
this.root.push(this.sections.pop() as SectionProperties);
}
2021-03-11 01:06:55 +00:00
return super.prepForXml(context);
2017-09-19 15:39:14 +01:00
}
public push(component: XmlComponent): void {
this.root.push(component);
}
private createSectionParagraph(section: SectionProperties): Paragraph {
const paragraph = new Paragraph({});
const properties = new ParagraphProperties({});
properties.push(section);
paragraph.addChildElement(properties);
return paragraph;
}
2017-09-19 15:39:14 +01:00
}