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

60 lines
2.1 KiB
TypeScript
Raw Normal View History

2018-06-22 23:04:03 +01:00
import { IXmlableObject, XmlComponent } from "file/xml-components";
import { Paragraph, ParagraphProperties } from "../..";
2018-06-25 19:53:40 +01:00
import { SectionProperties, SectionPropertiesOptions } from "./section-properties";
2017-09-19 15:39:14 +01:00
export class Body extends XmlComponent {
private defaultSection: SectionProperties;
private sections: SectionProperties[] = [];
2018-01-24 13:09:34 +00:00
constructor(sectionPropertiesOptions?: SectionPropertiesOptions) {
2017-09-19 15:39:14 +01:00
super("w:body");
2018-01-25 01:21:03 +00:00
this.defaultSection = new SectionProperties(sectionPropertiesOptions);
this.sections.push(this.defaultSection);
}
/**
* 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
* @param section new section
*/
2018-06-22 23:04:03 +01:00
public addSection(section: SectionPropertiesOptions | SectionProperties): void {
const currentSection = this.sections.pop() as SectionProperties;
this.root.push(this.createSectionParagraph(currentSection));
if (section instanceof SectionProperties) {
this.sections.push(section);
} else {
this.sections.push(new SectionProperties(section));
}
}
public prepForXml(): IXmlableObject {
if (this.sections.length === 1) {
this.root.push(this.sections[0]);
} else if (this.sections.length > 1) {
throw new Error("Invalid usage of sections. At the end of the body element there must be ONE section.");
}
return super.prepForXml();
2017-09-19 15:39:14 +01:00
}
public push(component: XmlComponent): void {
this.root.push(component);
}
2018-06-22 23:04:03 +01:00
get DefaultSection(): SectionProperties {
return this.defaultSection;
}
2018-06-22 23:04:03 +01:00
private createSectionParagraph(section: SectionProperties): Paragraph {
const paragraph = new Paragraph();
const properties = new ParagraphProperties();
properties.addChildElement(section);
paragraph.addChildElement(properties);
return paragraph;
}
2017-09-19 15:39:14 +01:00
}