mirror of
https://github.com/dolanmiu/docx.git
synced 2026-11-30 16:47:55 +01:00
fix: read and write XML without xml and xml-js, which are no longer maintained (#3779)
This commit is contained in:
Generated
+1
-61
@@ -12,16 +12,13 @@
|
||||
"@types/node": "^26.6.2",
|
||||
"hash.js": "^1.1.7",
|
||||
"jszip": "^3.10.1",
|
||||
"nanoid": "^6.0.1",
|
||||
"xml": "^1.0.1",
|
||||
"xml-js": "^1.6.8"
|
||||
"nanoid": "^6.0.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@microsoft/api-extractor": "^7.58.7",
|
||||
"@types/pngjs": "^6.0.5",
|
||||
"@types/unzipper": "^0.10.4",
|
||||
"@types/xml": "^1.0.8",
|
||||
"@typescript-eslint/eslint-plugin": "^8.8.1",
|
||||
"@typescript-eslint/parser": "^8.8.1",
|
||||
"@typescript/native": "npm:typescript@7.0.2",
|
||||
@@ -3029,15 +3026,6 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/xml": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@types/xml/-/xml-1.0.11.tgz",
|
||||
"integrity": "sha512-9gktTjxBWoz4+X8ZOS+QRFM2/liMQgBv8Z36wuNnomK5jtXFq4IJa7Az4Hzoy+rYux343NkH9Dq+nzIdejVrjw==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||
"version": "8.71.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.71.2.tgz",
|
||||
@@ -10567,11 +10555,6 @@
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/sax": {
|
||||
"version": "1.2.4",
|
||||
"resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz",
|
||||
"integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw=="
|
||||
},
|
||||
"node_modules/saxes": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
|
||||
@@ -12361,22 +12344,6 @@
|
||||
"url": "https://github.com/sponsors/sindresorhus"
|
||||
}
|
||||
},
|
||||
"node_modules/xml": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/xml/-/xml-1.0.1.tgz",
|
||||
"integrity": "sha1-eLpyAgApxbyHuKgaPPzXS0ovweU="
|
||||
},
|
||||
"node_modules/xml-js": {
|
||||
"version": "1.6.11",
|
||||
"resolved": "https://registry.npmjs.org/xml-js/-/xml-js-1.6.11.tgz",
|
||||
"integrity": "sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==",
|
||||
"dependencies": {
|
||||
"sax": "^1.2.4"
|
||||
},
|
||||
"bin": {
|
||||
"xml-js": "bin/cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/xml-name-validator": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
||||
@@ -14340,15 +14307,6 @@
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"@types/xml": {
|
||||
"version": "1.0.11",
|
||||
"resolved": "https://registry.npmjs.org/@types/xml/-/xml-1.0.11.tgz",
|
||||
"integrity": "sha512-9gktTjxBWoz4+X8ZOS+QRFM2/liMQgBv8Z36wuNnomK5jtXFq4IJa7Az4Hzoy+rYux343NkH9Dq+nzIdejVrjw==",
|
||||
"dev": true,
|
||||
"requires": {
|
||||
"@types/node": "*"
|
||||
}
|
||||
},
|
||||
"@typescript-eslint/eslint-plugin": {
|
||||
"version": "8.71.2",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.71.2.tgz",
|
||||
@@ -19136,11 +19094,6 @@
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||
"dev": true
|
||||
},
|
||||
"sax": {
|
||||
"version": "1.2.4",
|
||||
"resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz",
|
||||
"integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw=="
|
||||
},
|
||||
"saxes": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
|
||||
@@ -20270,19 +20223,6 @@
|
||||
"integrity": "sha512-GCPAHLvrIH13+c0SuacwvRYj2SxJXQ4kaVTT5xgL3kPrz56XxkF21IGhjSE1+W0aw7gpBWRGXLCPnPby6lSpmQ==",
|
||||
"dev": true
|
||||
},
|
||||
"xml": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/xml/-/xml-1.0.1.tgz",
|
||||
"integrity": "sha1-eLpyAgApxbyHuKgaPPzXS0ovweU="
|
||||
},
|
||||
"xml-js": {
|
||||
"version": "1.6.11",
|
||||
"resolved": "https://registry.npmjs.org/xml-js/-/xml-js-1.6.11.tgz",
|
||||
"integrity": "sha512-7rVi2KMfwfWFl+GpPg6m80IVMWXLRjO+PxTq7V2CDhoGak0wzYzFgUY2m4XJ47OGdXd8eLE8EmwfAmdjw7lC1g==",
|
||||
"requires": {
|
||||
"sax": "^1.2.4"
|
||||
}
|
||||
},
|
||||
"xml-name-validator": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
||||
|
||||
+1
-4
@@ -145,9 +145,7 @@
|
||||
"@types/node": "^26.6.2",
|
||||
"hash.js": "^1.1.7",
|
||||
"jszip": "^3.10.1",
|
||||
"nanoid": "^6.0.1",
|
||||
"xml": "^1.0.1",
|
||||
"xml-js": "^1.6.8"
|
||||
"nanoid": "^6.0.1"
|
||||
},
|
||||
"author": "Dolan Miu",
|
||||
"license": "MIT",
|
||||
@@ -160,7 +158,6 @@
|
||||
"@microsoft/api-extractor": "^7.58.7",
|
||||
"@types/pngjs": "^6.0.5",
|
||||
"@types/unzipper": "^0.10.4",
|
||||
"@types/xml": "^1.0.8",
|
||||
"@typescript-eslint/eslint-plugin": "^8.8.1",
|
||||
"@typescript-eslint/parser": "^8.8.1",
|
||||
"@typescript/native": "npm:typescript@7.0.2",
|
||||
|
||||
@@ -42,7 +42,7 @@ type PackageJson = {
|
||||
};
|
||||
|
||||
const ROOT = resolve(import.meta.dirname, "..");
|
||||
// Inside the repository, so the declarations' imports of jszip, xml-js and Node's types resolve
|
||||
// Inside the repository, so the declarations' imports of jszip and Node's types resolve
|
||||
const WORK = join(ROOT, "build", "api-check");
|
||||
|
||||
const readPackage = (directory: string): PackageJson => JSON.parse(readFileSync(join(directory, "package.json"), "utf8")) as PackageJson;
|
||||
|
||||
@@ -26,7 +26,7 @@ import { existsSync, readFileSync, readdirSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
import JSZip from "jszip";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
import { type XmlElement as Element, parseXml } from "../src/util/xml";
|
||||
|
||||
import { estimatePageNumbers } from "../src/layout/estimate-page-numbers";
|
||||
|
||||
@@ -55,7 +55,7 @@ const paragraphsIn = (element: Element): readonly Element[] =>
|
||||
/** Each entry of the document's tables of contents: its heading's text, and the page number written for it */
|
||||
const entriesOf = async (path: string): Promise<readonly { readonly title: string; readonly page: string }[]> => {
|
||||
const zip = await JSZip.loadAsync(readFileSync(path));
|
||||
const document = xml2js(await zip.file("word/document.xml")!.async("string"), { compact: false }) as Element;
|
||||
const document = parseXml(await zip.file("word/document.xml")!.async("string"));
|
||||
return paragraphsIn(document)
|
||||
.filter((paragraph) => JSON.stringify(paragraph).includes("PAGEREF _Toc"))
|
||||
.map((paragraph) => {
|
||||
@@ -96,7 +96,7 @@ const pageCountsOf = async (path: string): Promise<readonly string[]> => {
|
||||
}
|
||||
};
|
||||
for (const part of parts) {
|
||||
read(xml2js(await zip.file(part)!.async("string"), { compact: false }) as Element);
|
||||
read(parseXml(await zip.file(part)!.async("string")));
|
||||
}
|
||||
return results;
|
||||
};
|
||||
@@ -113,13 +113,7 @@ const partsOf = async (path: string): Promise<ReadonlyMap<string, Element>> => {
|
||||
const paths = Object.keys(zip.files).filter((file) => file.endsWith(".xml") || file.endsWith(".rels"));
|
||||
return new Map(
|
||||
await Promise.all(
|
||||
paths.map(
|
||||
async (file) =>
|
||||
[
|
||||
file,
|
||||
xml2js(await zip.file(file)!.async("string"), { compact: false, captureSpacesBetweenElements: true }) as Element,
|
||||
] as const,
|
||||
),
|
||||
paths.map(async (file) => [file, parseXml(await zip.file(file)!.async("string"), { keepWhitespaceText: true })] as const),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
@@ -15,7 +15,7 @@
|
||||
import { execSync } from "node:child_process";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
import { type XmlElement as Element, parseXml } from "../src/util/xml";
|
||||
|
||||
import { PRESET_SHAPE_OOXML_NAMES } from "../src/shapes/preset-shape/preset-shape-type";
|
||||
|
||||
@@ -51,7 +51,7 @@ const guides = (shape: Element, list: string): readonly (readonly [string, strin
|
||||
children(child(shape, list), "gd").map((guide) => [attribute(guide, "name"), attribute(guide, "fmla")] as const);
|
||||
|
||||
const main = async (): Promise<void> => {
|
||||
const document = xml2js(await loadDefinitions(process.argv[2]), { compact: false }) as Element;
|
||||
const document = parseXml(await loadDefinitions(process.argv[2]));
|
||||
const root = children(document)[0];
|
||||
const shapes = new Map(children(root).map((shape) => [shape.name!, shape]));
|
||||
const lines: string[] = [];
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import JSZip from "jszip";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
import { type XmlElement as Element, parseXml } from "../../src/util/xml";
|
||||
|
||||
import type { BlockLayout } from "../../src/layout";
|
||||
import { layOutPasses } from "../../src/layout/layout-passes";
|
||||
@@ -65,13 +65,7 @@ const parts = new Map(
|
||||
await Promise.all(
|
||||
Object.keys(zip.files)
|
||||
.filter((file) => file.endsWith(".xml") || file.endsWith(".rels"))
|
||||
.map(
|
||||
async (file) =>
|
||||
[
|
||||
file,
|
||||
xml2js(await zip.file(file)!.async("string"), { compact: false, captureSpacesBetweenElements: true }) as Element,
|
||||
] as const,
|
||||
),
|
||||
.map(async (file) => [file, parseXml(await zip.file(file)!.async("string"), { keepWhitespaceText: true })] as const),
|
||||
),
|
||||
);
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import JSZip from "jszip";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
import { type XmlElement as Element, parseXml } from "../../src/util/xml";
|
||||
|
||||
import type { BlockLayout } from "../../src/layout";
|
||||
import { layOutPasses } from "../../src/layout/layout-passes";
|
||||
@@ -60,7 +60,7 @@ for (const [path, file] of Object.entries(zip.files)) {
|
||||
continue;
|
||||
}
|
||||
if (path.endsWith(".xml") || path.endsWith(".rels")) {
|
||||
parts.set(path, xml2js(await file.async("string"), { compact: false, captureSpacesBetweenElements: true }) as Element);
|
||||
parts.set(path, parseXml(await file.async("string"), { keepWhitespaceText: true }));
|
||||
} else {
|
||||
binaryParts.set(path, await file.async("uint8array"));
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
*/
|
||||
import { readFileSync } from "node:fs";
|
||||
|
||||
import type { Element } from "xml-js";
|
||||
import type { XmlElement as Element } from "../../../src/util/xml";
|
||||
|
||||
import { patchDocument } from "../../../src/index";
|
||||
import { layOutPasses } from "../../../src/layout/layout-passes";
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
/* eslint-disable @typescript-eslint/naming-convention -- The keys of objects here are paths of parts in a package */
|
||||
import JSZip from "jszip";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { type XmlElement as Element, parseXml } from "@util/xml";
|
||||
import {
|
||||
Document,
|
||||
DrawingPatch,
|
||||
@@ -41,7 +41,7 @@ import { attributeOf, childOf, childrenOf, descendantsOf, elementsOf, textOf, va
|
||||
// ---------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
// Parsed with the spaces in text, such as a category that is a space
|
||||
const parse = (text: string): Element => xml2js(text, { compact: false, captureSpacesBetweenElements: true }) as Element;
|
||||
const parse = (text: string): Element => parseXml(text, { keepWhitespaceText: true });
|
||||
|
||||
const readText = async (zip: JSZip, path: string): Promise<string> => (await zip.file(path)?.async("text")) ?? "";
|
||||
|
||||
|
||||
@@ -4,9 +4,8 @@
|
||||
* @module
|
||||
*/
|
||||
// cspell:ignore descr
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import { DrawingPatch, type TemplateDrawing, type TemplatePackage } from "docx";
|
||||
import { DrawingPatch, type XmlElement as Element, type TemplateDrawing, type TemplatePackage } from "docx";
|
||||
|
||||
import { leafCategoriesOf } from "./chart-categories";
|
||||
import { TYPE_NAMES, checkChartOptions } from "./chart-checks";
|
||||
|
||||
@@ -1,28 +1,30 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
|
||||
import { createElement, createText, createValue } from "./chart-elements";
|
||||
|
||||
describe("chart elements", () => {
|
||||
it("should write an element's attributes in order, leaving out undefined ones, and its children", () => {
|
||||
expect(xml(new Formatter().format(createElement("c:numFmt", { formatCode: "0%", skipped: undefined, sourceLinked: 1 })))).to.equal(
|
||||
'<c:numFmt formatCode="0%" sourceLinked="1"/>',
|
||||
);
|
||||
expect(xml(new Formatter().format(createElement("c:layout")))).to.equal("<c:layout/>");
|
||||
expect(xml(new Formatter().format(createElement("c:scaling", {}, [createValue("c:orientation", "minMax")])))).to.equal(
|
||||
expect(
|
||||
stringifyXmlable(new Formatter().format(createElement("c:numFmt", { formatCode: "0%", skipped: undefined, sourceLinked: 1 }))),
|
||||
).to.equal('<c:numFmt formatCode="0%" sourceLinked="1"/>');
|
||||
expect(stringifyXmlable(new Formatter().format(createElement("c:layout")))).to.equal("<c:layout/>");
|
||||
expect(stringifyXmlable(new Formatter().format(createElement("c:scaling", {}, [createValue("c:orientation", "minMax")])))).to.equal(
|
||||
'<c:scaling><c:orientation val="minMax"/></c:scaling>',
|
||||
);
|
||||
});
|
||||
|
||||
it("should write a boolean value as 1 or 0", () => {
|
||||
expect(xml(new Formatter().format(createValue("c:varyColors", true)))).to.equal('<c:varyColors val="1"/>');
|
||||
expect(xml(new Formatter().format(createValue("c:varyColors", false)))).to.equal('<c:varyColors val="0"/>');
|
||||
expect(xml(new Formatter().format(createValue("c:gapWidth", 219)))).to.equal('<c:gapWidth val="219"/>');
|
||||
expect(stringifyXmlable(new Formatter().format(createValue("c:varyColors", true)))).to.equal('<c:varyColors val="1"/>');
|
||||
expect(stringifyXmlable(new Formatter().format(createValue("c:varyColors", false)))).to.equal('<c:varyColors val="0"/>');
|
||||
expect(stringifyXmlable(new Formatter().format(createValue("c:gapWidth", 219)))).to.equal('<c:gapWidth val="219"/>');
|
||||
});
|
||||
|
||||
it("should write text, escaped", () => {
|
||||
expect(xml(new Formatter().format(createText("c:v", "Sales & <costs>")))).to.equal("<c:v>Sales & <costs></c:v>");
|
||||
expect(stringifyXmlable(new Formatter().format(createText("c:v", "Sales & <costs>")))).to.equal(
|
||||
"<c:v>Sales & <costs></c:v>",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { File } from "@file/file";
|
||||
import { Relationships } from "@file/relationships";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import { type IContext, PackagePart } from "docx";
|
||||
|
||||
import { createChartData } from "./chart-data";
|
||||
@@ -15,7 +14,7 @@ import chartSchema from "../../ooxml-schemas/ISO-IEC29500-4_2016/dml-chart.xsd?r
|
||||
|
||||
// The chart schema, which every chart part's elements are checked against: each element's children are ones its type
|
||||
// has, in its type's order. The Open XML SDK validator checks this too, for the demos only
|
||||
const schema = xml2js(chartSchema as string) as Element;
|
||||
const schema = parseXml(chartSchema as string);
|
||||
|
||||
const definitions = new Map(
|
||||
schema
|
||||
@@ -103,14 +102,14 @@ const workbook = new PackagePart({
|
||||
|
||||
const chartSpaceOf = (options: ChartRunOptions): Element => {
|
||||
const component = createChartSpace(options, createChartData(options), workbook);
|
||||
const written = xml(
|
||||
const written = stringifyXmlable(
|
||||
new Formatter().format(component, {
|
||||
file: new File({ sections: [] }),
|
||||
viewWrapper: { View: component, Relationships: new Relationships() },
|
||||
stack: [],
|
||||
} as IContext),
|
||||
);
|
||||
return (xml2js(written) as Element).elements![0];
|
||||
return parseXml(written).elements![0];
|
||||
};
|
||||
|
||||
const problemsOf = (options: ChartRunOptions): readonly string[] => problemsIn(chartSpaceOf(options), "CT_ChartSpace", "c:chartSpace");
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { File } from "@file/file";
|
||||
import { Relationships } from "@file/relationships";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import { type IContext, PackagePart, type XmlComponent } from "docx";
|
||||
|
||||
import { createChartData } from "./chart-data";
|
||||
@@ -21,7 +20,7 @@ const workbook = new PackagePart({
|
||||
});
|
||||
|
||||
const format = (component: XmlComponent, relationships = new Relationships()): string =>
|
||||
xml(
|
||||
stringifyXmlable(
|
||||
new Formatter().format(component, {
|
||||
file: new File({ sections: [] }),
|
||||
viewWrapper: { View: component, Relationships: relationships },
|
||||
@@ -31,7 +30,7 @@ const format = (component: XmlComponent, relationships = new Relationships()): s
|
||||
|
||||
const chartSpace = (options: Partial<ChartRunOptions> = {}): Element => {
|
||||
const full = { type: "column", categories: ["A"], series: [{ name: "S", values: [1] }], ...options } as ChartRunOptions;
|
||||
return (xml2js(format(createChartSpace(full, createChartData(full), workbook))) as Element).elements![0];
|
||||
return parseXml(format(createChartSpace(full, createChartData(full), workbook))).elements![0];
|
||||
};
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const child = (element: Element, name: string): Element => element.elements!.find((one) => one.name === name)!;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// cspell:ignore cmpd prst
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import {
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
createTextProperties,
|
||||
} from "./chart-style";
|
||||
|
||||
const toXml = (component: XmlComponent): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: XmlComponent): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
const ACCENT1 = '<a:schemeClr val="accent1"/>';
|
||||
const FILL = `<a:solidFill>${ACCENT1}</a:solidFill>`;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
|
||||
import { createAxisTitle, createChartTitle, fontOf, titleOf } from "./chart-text";
|
||||
|
||||
@@ -13,7 +13,7 @@ const BODY = (rotation: number): string =>
|
||||
describe("createChartTitle", () => {
|
||||
it("should write the title as Office does: 14 point text in the theme's body font, not over the plot", () => {
|
||||
const properties = `<a:pPr><a:defRPr sz="1400" b="0" i="0" u="none" strike="noStrike" kern="1200" spc="0" baseline="0">${TEXT_COLOR}${FONTS}</a:defRPr></a:pPr>`;
|
||||
expect(xml(new Formatter().format(createChartTitle("Sales")))).to.equal(
|
||||
expect(stringifyXmlable(new Formatter().format(createChartTitle("Sales")))).to.equal(
|
||||
"<c:title>" +
|
||||
`<c:tx><c:rich>${BODY(0)}<a:p>${properties}<a:r><a:rPr lang="en-US"/><a:t>Sales</a:t></a:r></a:p></c:rich></c:tx>` +
|
||||
'<c:overlay val="0"/>' +
|
||||
@@ -24,30 +24,30 @@ describe("createChartTitle", () => {
|
||||
});
|
||||
|
||||
it("should write each line of the title as a paragraph", () => {
|
||||
const title = xml(new Formatter().format(createChartTitle("Sales\nby month")));
|
||||
const title = stringifyXmlable(new Formatter().format(createChartTitle("Sales\nby month")));
|
||||
expect(title.match(/<a:t>[^<]*<\/a:t>/g)).to.deep.equal(["<a:t>Sales</a:t>", "<a:t>by month</a:t>"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createAxisTitle", () => {
|
||||
it("should write 10 point text, reading from bottom to top on a vertical axis", () => {
|
||||
const vertical = xml(new Formatter().format(createAxisTitle("Units", true)));
|
||||
const vertical = stringifyXmlable(new Formatter().format(createAxisTitle("Units", true)));
|
||||
expect(vertical).to.contain(BODY(-5400000));
|
||||
expect(vertical).to.contain('<a:defRPr sz="1000" b="0" i="0" u="none" strike="noStrike" kern="1200" baseline="0">');
|
||||
expect(vertical).to.contain("<a:t>Units</a:t>");
|
||||
expect(xml(new Formatter().format(createAxisTitle("Month", false)))).to.contain(BODY(0));
|
||||
expect(stringifyXmlable(new Formatter().format(createAxisTitle("Month", false)))).to.contain(BODY(0));
|
||||
});
|
||||
});
|
||||
|
||||
describe("titles with fonts", () => {
|
||||
it("should write a title's own font over the chart's", () => {
|
||||
const title = xml(
|
||||
const title = stringifyXmlable(
|
||||
new Formatter().format(createChartTitle({ text: "Sales", font: { size: 18, bold: true } }, { name: "Arial", bold: false })),
|
||||
);
|
||||
|
||||
expect(title).to.contain('<a:defRPr sz="1800" b="1" i="0"');
|
||||
expect(title).to.contain('<a:latin typeface="Arial"/>');
|
||||
expect(xml(new Formatter().format(createAxisTitle({ text: "Units", font: { italics: true } }, true)))).to.contain(
|
||||
expect(stringifyXmlable(new Formatter().format(createAxisTitle({ text: "Units", font: { italics: true } }, true)))).to.contain(
|
||||
'sz="1000" b="0" i="1"',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import JSZip from "jszip";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { type XmlElement as Element, parseXml } from "@util/xml";
|
||||
import { Document, Footer, FootnoteReferenceRun, Header, Packer, Paragraph, Run, Table, TableCell, TableRow, TextRun } from "docx";
|
||||
|
||||
import { ChartRun, type ChartRunOptions } from ".";
|
||||
@@ -95,7 +95,7 @@ const paragraphWith = (options: ChartRunOptions): Paragraph => new Paragraph({ c
|
||||
|
||||
const read = async (zip: JSZip, path: string): Promise<string> => (await zip.file(path)?.async("text")) ?? "";
|
||||
|
||||
const parse = (text: string): Element => xml2js(text) as Element;
|
||||
const parse = (text: string): Element => parseXml(text);
|
||||
|
||||
const descendants = (element: Element, name: string): readonly Element[] =>
|
||||
(element.elements ?? []).flatMap((child) => [...(child.name === name ? [child] : []), ...descendants(child, name)]);
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { createChartData } from "../chart-data";
|
||||
import type { AreaChartOptions } from "../chart-options";
|
||||
import { createCategoryCharts } from "./category-chart";
|
||||
|
||||
const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0];
|
||||
const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name);
|
||||
const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val;
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
// cspell:ignore cmpd
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { PRIMARY_AXES, createCategoryAxis, createPointAxes, createValueAxis } from "./axes";
|
||||
|
||||
const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0];
|
||||
const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const child = (element: Element, name: string): Element => element.elements!.find((one) => one.name === name)!;
|
||||
const value = (element: Element, name: string): unknown => child(element, name)?.attributes?.val;
|
||||
@@ -63,7 +62,7 @@ describe("createCategoryAxis", () => {
|
||||
]);
|
||||
expect(value(axis, "c:delete")).to.equal("1");
|
||||
// The title of an axis on the left reads from bottom to top
|
||||
expect(xml(new Formatter().format(createCategoryAxis({ ...CATEGORY, position: "l" }, { title: "Month" })))).to.contain(
|
||||
expect(stringifyXmlable(new Formatter().format(createCategoryAxis({ ...CATEGORY, position: "l" }, { title: "Month" })))).to.contain(
|
||||
'rot="-5400000"',
|
||||
);
|
||||
});
|
||||
@@ -90,7 +89,7 @@ describe("createCategoryAxis", () => {
|
||||
});
|
||||
|
||||
it("should turn the labels as asked, in 60,000ths of a degree, in the font given over the chart's", () => {
|
||||
const written = xml(
|
||||
const written = stringifyXmlable(
|
||||
new Formatter().format(
|
||||
createCategoryAxis(
|
||||
{ ...CATEGORY, font: { name: "Arial", bold: true } },
|
||||
@@ -103,7 +102,7 @@ describe("createCategoryAxis", () => {
|
||||
expect(written).to.contain('<a:defRPr sz="1200" b="0" i="0"');
|
||||
expect(written).to.contain('<a:latin typeface="Arial"/><a:ea typeface="+mn-ea"/><a:cs typeface="Arial"/>');
|
||||
// Office's automatic rotation otherwise
|
||||
expect(xml(new Formatter().format(createCategoryAxis(CATEGORY)))).to.contain('<a:bodyPr rot="-60000000"');
|
||||
expect(stringifyXmlable(new Formatter().format(createCategoryAxis(CATEGORY)))).to.contain('<a:bodyPr rot="-60000000"');
|
||||
});
|
||||
|
||||
it("should write a date axis for dates, spaced by their unit and labelled in their format", () => {
|
||||
@@ -214,10 +213,12 @@ describe("createValueAxis", () => {
|
||||
expect(value(units, "c:builtInUnit")).to.equal("thousands");
|
||||
expect(names(child(units, "c:dispUnitsLbl"))).to.deep.equal(["c:layout", "c:spPr", "c:txPr"]);
|
||||
// Upright beside a vertical axis, and level beside a horizontal one
|
||||
expect(xml(new Formatter().format(createValueAxis(VALUE, { displayUnits: "millions" })))).to.contain(
|
||||
expect(stringifyXmlable(new Formatter().format(createValueAxis(VALUE, { displayUnits: "millions" })))).to.contain(
|
||||
'<c:dispUnits><c:builtInUnit val="millions"/><c:dispUnitsLbl><c:layout/><c:spPr><a:noFill/><a:ln><a:noFill/></a:ln><a:effectLst/></c:spPr><c:txPr><a:bodyPr rot="-5400000"',
|
||||
);
|
||||
expect(xml(new Formatter().format(createValueAxis({ ...VALUE, position: "b" }, { displayUnits: "millions" })))).to.contain(
|
||||
expect(
|
||||
stringifyXmlable(new Formatter().format(createValueAxis({ ...VALUE, position: "b" }, { displayUnits: "millions" }))),
|
||||
).to.contain(
|
||||
'<c:dispUnitsLbl><c:layout/><c:spPr><a:noFill/><a:ln><a:noFill/></a:ln><a:effectLst/></c:spPr><c:txPr><a:bodyPr rot="0"',
|
||||
);
|
||||
});
|
||||
@@ -228,7 +229,7 @@ describe("createValueAxis", () => {
|
||||
});
|
||||
|
||||
it("should give a radar chart's value axis a line and tick marks", () => {
|
||||
const written = xml(new Formatter().format(createValueAxis({ ...VALUE, radar: true })));
|
||||
const written = stringifyXmlable(new Formatter().format(createValueAxis({ ...VALUE, radar: true })));
|
||||
|
||||
expect(written).to.contain('<c:majorTickMark val="cross"/>');
|
||||
expect(written).to.contain(
|
||||
@@ -240,7 +241,7 @@ describe("createValueAxis", () => {
|
||||
const axis = parse(createValueAxis({ ...VALUE, crossBetween: "midCat", scatter: true }));
|
||||
|
||||
expect(value(axis, "c:crossBetween")).to.equal("midCat");
|
||||
expect(xml(new Formatter().format(createValueAxis({ ...VALUE, crossBetween: "midCat", scatter: true })))).to.contain(
|
||||
expect(stringifyXmlable(new Formatter().format(createValueAxis({ ...VALUE, crossBetween: "midCat", scatter: true })))).to.contain(
|
||||
'<c:spPr><a:noFill/><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="25000"/>',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { createChartData } from "../chart-data";
|
||||
import type { BarChartOptions, ColumnChartOptions } from "../chart-options";
|
||||
import { createCategoryCharts } from "./category-chart";
|
||||
|
||||
const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0];
|
||||
const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name);
|
||||
const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val;
|
||||
@@ -67,7 +66,7 @@ describe("createBarChart", () => {
|
||||
]);
|
||||
expect(value(series[0], "c:invertIfNegative")).to.equal("0");
|
||||
expect(
|
||||
xml(
|
||||
stringifyXmlable(
|
||||
new Formatter().format(
|
||||
createCategoryCharts(
|
||||
{
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { createChartData } from "../chart-data";
|
||||
import type { BubbleChartOptions } from "../chart-options";
|
||||
import { createBubbleChart } from "./bubble-chart";
|
||||
|
||||
const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0];
|
||||
const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name);
|
||||
const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val;
|
||||
@@ -69,14 +68,14 @@ describe("createBubbleChart", () => {
|
||||
"c:bubble3D",
|
||||
]);
|
||||
expect(value(series, "c:bubble3D")).to.equal("0");
|
||||
const sizes = xml(new Formatter().format(create().group));
|
||||
const sizes = stringifyXmlable(new Formatter().format(create().group));
|
||||
expect(sizes).to.contain(
|
||||
'<c:bubbleSize><c:numRef><c:f>Sheet1!$C$2:$C$3</c:f><c:numCache><c:formatCode>General</c:formatCode><c:ptCount val="2"/><c:pt idx="0"><c:v>10</c:v></c:pt><c:pt idx="1"><c:v>20</c:v></c:pt></c:numCache></c:numRef></c:bubbleSize>',
|
||||
);
|
||||
});
|
||||
|
||||
it("should fill bubbles with the series' colour at 75% opacity, without a line", () => {
|
||||
const written = xml(new Formatter().format(create().group));
|
||||
const written = stringifyXmlable(new Formatter().format(create().group));
|
||||
|
||||
expect(written).to.contain(
|
||||
'<c:spPr><a:solidFill><a:schemeClr val="accent1"><a:alpha val="75000"/></a:schemeClr></a:solidFill><a:ln><a:noFill/></a:ln><a:effectLst/></c:spPr>',
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { createChartData } from "../chart-data";
|
||||
@@ -11,7 +10,7 @@ import { createCategoryCharts } from "./category-chart";
|
||||
|
||||
type Options = ColumnChartOptions | BarChartOptions | LineChartOptions | AreaChartOptions;
|
||||
|
||||
const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0];
|
||||
const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name);
|
||||
const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val;
|
||||
@@ -223,7 +222,7 @@ describe("createCategoryCharts", () => {
|
||||
it("should write the chart's font on its axes", () => {
|
||||
const full: ColumnChartOptions = { type: "column", categories: ["A"], series: [{ name: "A", values: [1] }] };
|
||||
const written = createCategoryCharts(full, createChartData(full), { name: "Arial" })
|
||||
.axes.map((axis) => xml(new Formatter().format(axis)))
|
||||
.axes.map((axis) => stringifyXmlable(new Formatter().format(axis)))
|
||||
.join("");
|
||||
|
||||
expect(written.match(/<a:latin typeface="Arial"\/>/g)).to.have.length(2);
|
||||
@@ -238,7 +237,7 @@ describe("createCategoryCharts' series", () => {
|
||||
const point = children(series, "c:dPt")[0];
|
||||
expect(names(point)).to.deep.equal(["c:idx", "c:invertIfNegative", "c:bubble3D", "c:spPr"]);
|
||||
expect(value(point, "c:idx")).to.equal("1");
|
||||
expect(xml(new Formatter().format(createCategoryCharts(...colored()).groups[0]))).to.contain(
|
||||
expect(stringifyXmlable(new Formatter().format(createCategoryCharts(...colored()).groups[0]))).to.contain(
|
||||
'<c:dPt><c:idx val="1"/><c:invertIfNegative val="0"/><c:bubble3D val="0"/><c:spPr><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill><a:ln><a:noFill/></a:ln><a:effectLst/></c:spPr></c:dPt>',
|
||||
);
|
||||
});
|
||||
@@ -315,7 +314,7 @@ describe("createCategoryCharts' series", () => {
|
||||
expect(value(marker, "c:symbol")).to.equal("square");
|
||||
expect(value(marker, "c:size")).to.equal("8");
|
||||
expect(value(series, "c:smooth")).to.equal("1");
|
||||
expect(xml(new Formatter().format(createCategoryCharts(...dashed()).groups[0]))).to.contain(
|
||||
expect(stringifyXmlable(new Formatter().format(createCategoryCharts(...dashed()).groups[0]))).to.contain(
|
||||
'<c:spPr><a:ln w="12700" cap="rnd"><a:solidFill><a:srgbClr val="00FF00"/></a:solidFill><a:prstDash val="dash"/><a:round/></a:ln>',
|
||||
);
|
||||
});
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import type { ChartDataLabelPosition } from "../chart-options";
|
||||
import { type LabelledShape, createGroupDataLabels, createSeriesDataLabels } from "./data-labels";
|
||||
|
||||
const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0];
|
||||
const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const values = (element: Element): Readonly<Record<string, unknown>> =>
|
||||
Object.fromEntries(
|
||||
@@ -116,7 +115,7 @@ describe("createSeriesDataLabels' formats and fonts", () => {
|
||||
});
|
||||
|
||||
it("should write the labels' font over the chart's, over Office's 9 point grey", () => {
|
||||
const written = xml(
|
||||
const written = stringifyXmlable(
|
||||
new Formatter().format(
|
||||
createSeriesDataLabels(
|
||||
{ value: true, font: { color: "FFFFFF", bold: true } },
|
||||
@@ -207,7 +206,7 @@ describe("createSeriesDataLabels' labels of single points", () => {
|
||||
"c:showBubbleSize",
|
||||
]);
|
||||
expect(values(point)).to.include({ "c:dLblPos": "ctr", "c:showVal": "1" });
|
||||
const written = xml(
|
||||
const written = stringifyXmlable(
|
||||
new Formatter().format(createSeriesDataLabels(undefined, { ...BARS, pointLabels: [{ text: "Record\nhigh" }] })[0]),
|
||||
);
|
||||
expect(written).to.contain("<a:t>Record</a:t>");
|
||||
@@ -260,7 +259,7 @@ describe("createSeriesDataLabels' labels of single points", () => {
|
||||
// Its own flags replace the series', and its own number format and font replace theirs
|
||||
expect(values(own)).to.include({ "c:dLblPos": "inEnd", "c:showVal": "0", "c:showCatName": "1" });
|
||||
expect(own.elements!.find(({ name }) => name === "c:numFmt")!.attributes!.formatCode).to.equal("0.0");
|
||||
const written = xml(
|
||||
const written = stringifyXmlable(
|
||||
new Formatter().format(createSeriesDataLabels(series, { ...BARS, pointLabels: [{ font: { bold: true } }] })[0]),
|
||||
);
|
||||
expect(written).to.contain('<a:defRPr sz="900" b="1"');
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
// cspell:ignore cmpd cust
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import type { ChartErrorData } from "../chart-data";
|
||||
import type { ChartErrorBars } from "../chart-options";
|
||||
import { createErrorBars } from "./error-bars";
|
||||
|
||||
const write = (component: XmlComponent): string => xml(new Formatter().format(component));
|
||||
const parse = (component: XmlComponent): Element => (xml2js(write(component)) as Element).elements![0];
|
||||
const write = (component: XmlComponent): string => stringifyXmlable(new Formatter().format(component));
|
||||
const parse = (component: XmlComponent): Element => parseXml(write(component)).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const value = (element: Element, name: string): unknown => element.elements!.find((one) => one.name === name)?.attributes?.val;
|
||||
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { createChartData } from "../chart-data";
|
||||
import type { LineChartOptions } from "../chart-options";
|
||||
import { createCategoryCharts } from "./category-chart";
|
||||
|
||||
const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0];
|
||||
const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name);
|
||||
const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val;
|
||||
@@ -40,7 +39,7 @@ describe("createLineChart", () => {
|
||||
expect(value(children(series, "c:marker")[0], "c:symbol")).to.equal("none");
|
||||
expect(value(series, "c:smooth")).to.equal("0");
|
||||
expect(
|
||||
xml(
|
||||
stringifyXmlable(
|
||||
new Formatter().format(
|
||||
createCategoryCharts(
|
||||
{ type: "line", categories: ["A"], series: [{ name: "A", values: [1] }] },
|
||||
@@ -57,7 +56,7 @@ describe("createLineChart", () => {
|
||||
|
||||
expect(names(group)).to.deep.equal(["c:grouping", "c:varyColors", "c:ser", "c:dLbls", "c:marker", "c:axId", "c:axId"]);
|
||||
expect(value(group, "c:marker")).to.equal("1");
|
||||
const marker = xml(
|
||||
const marker = stringifyXmlable(
|
||||
new Formatter().format(
|
||||
createCategoryCharts(
|
||||
{ type: "line", markers: true, categories: ["A"], series: [{ name: "Red", values: [1], color: "FF0000" }] },
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
// cspell:ignore cmpd cust
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { createChartData } from "../chart-data";
|
||||
import type { BarOfPieChartOptions, DoughnutChartOptions, PieChartOptions, PieOfPieChartOptions } from "../chart-options";
|
||||
import { createPieChart } from "./pie-chart";
|
||||
|
||||
const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0];
|
||||
const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name);
|
||||
const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val;
|
||||
@@ -219,7 +218,9 @@ describe("createPieChart for a pie of pie or bar of pie chart", () => {
|
||||
const element = split({ secondPlotSize: 150.4, gapWidth: 250.6 });
|
||||
expect([value(element, "c:secondPieSize"), value(element, "c:gapWidth")]).to.deep.equal(["150", "251"]);
|
||||
const written = (options: Partial<PieOfPieChartOptions>): string =>
|
||||
xml(new Formatter().format(create({ type: "pieOfPie", categories, series: [{ name: "S", values: [1] }], ...options }).group));
|
||||
stringifyXmlable(
|
||||
new Formatter().format(create({ type: "pieOfPie", categories, series: [{ name: "S", values: [1] }], ...options }).group),
|
||||
);
|
||||
expect(written({})).to.contain(
|
||||
'<c:serLines><c:spPr><a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"><a:solidFill><a:schemeClr val="tx1"><a:lumMod val="35000"/><a:lumOff val="65000"/></a:schemeClr></a:solidFill><a:round/></a:ln><a:effectLst/></c:spPr></c:serLines>',
|
||||
);
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
// cspell:ignore cmpd
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
|
||||
import { createChartData } from "../chart-data";
|
||||
import type { ChartRunOptions } from "../chart-options";
|
||||
import { createPlotArea } from "./plot-area";
|
||||
|
||||
const plotArea = (options: ChartRunOptions): Element =>
|
||||
(xml2js(xml(new Formatter().format(createPlotArea(options, createChartData(options))))) as Element).elements![0];
|
||||
parseXml(stringifyXmlable(new Formatter().format(createPlotArea(options, createChartData(options))))).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name);
|
||||
const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val;
|
||||
@@ -87,7 +86,7 @@ describe("createPlotArea's data table", () => {
|
||||
"1",
|
||||
"1",
|
||||
]);
|
||||
const written = xml(
|
||||
const written = stringifyXmlable(
|
||||
new Formatter().format(
|
||||
createPlotArea(
|
||||
{ type: "column", categories, series, dataTable: true },
|
||||
@@ -115,7 +114,7 @@ describe("createPlotArea's data table", () => {
|
||||
"0",
|
||||
"0",
|
||||
]);
|
||||
const written = xml(new Formatter().format(createPlotArea(options, createChartData(options))));
|
||||
const written = stringifyXmlable(new Formatter().format(createPlotArea(options, createChartData(options))));
|
||||
expect(written).to.contain('<a:defRPr sz="800"');
|
||||
expect(written).to.contain('<a:latin typeface="Arial"/>');
|
||||
});
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { createChartData } from "../chart-data";
|
||||
import type { RadarChartOptions } from "../chart-options";
|
||||
import { createRadarChart } from "./radar-chart";
|
||||
|
||||
const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0];
|
||||
const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name);
|
||||
const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val;
|
||||
@@ -39,7 +38,7 @@ describe("createRadarChart", () => {
|
||||
expect(value(group, "c:varyColors")).to.equal("0");
|
||||
expect(names(series)).to.deep.equal(["c:idx", "c:order", "c:tx", "c:spPr", "c:marker", "c:cat", "c:val"]);
|
||||
expect(value(children(series, "c:marker")[0], "c:symbol")).to.equal("none");
|
||||
expect(xml(new Formatter().format(create().group))).to.contain(
|
||||
expect(stringifyXmlable(new Formatter().format(create().group))).to.contain(
|
||||
'<c:spPr><a:ln w="28575" cap="rnd"><a:solidFill><a:srgbClr val="FF0000"/></a:solidFill><a:round/></a:ln><a:effectLst/></c:spPr>',
|
||||
);
|
||||
});
|
||||
@@ -58,9 +57,9 @@ describe("createRadarChart", () => {
|
||||
const symbols = children(group, "c:ser").map((series) => value(children(series, "c:marker")[0], "c:symbol"));
|
||||
|
||||
expect(symbols).to.deep.equal(["diamond", "circle", "none"]);
|
||||
expect(xml(new Formatter().format(create({ series: [{ name: "A", values: [1], line: { dash: "dot" } }] }).group))).to.contain(
|
||||
'<a:prstDash val="dot"/>',
|
||||
);
|
||||
expect(
|
||||
stringifyXmlable(new Formatter().format(create({ series: [{ name: "A", values: [1], line: { dash: "dot" } }] }).group)),
|
||||
).to.contain('<a:prstDash val="dot"/>');
|
||||
});
|
||||
|
||||
it("should fill the series of a filled radar chart, without lines or markers", () => {
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { createChartData } from "../chart-data";
|
||||
import type { ScatterChartOptions } from "../chart-options";
|
||||
import { createScatterChart } from "./scatter-chart";
|
||||
|
||||
const parse = (component: XmlComponent): Element => (xml2js(xml(new Formatter().format(component))) as Element).elements![0];
|
||||
const parse = (component: XmlComponent): Element => parseXml(stringifyXmlable(new Formatter().format(component))).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name);
|
||||
const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { createCategoriesAndValues, createDataSource, createSeriesStart, formatNumber } from "./series";
|
||||
|
||||
const toXml = (component: XmlComponent): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: XmlComponent): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
describe("series", () => {
|
||||
it("should write numbers in JavaScript's shortest form that reads back as the same number", () => {
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
// cspell:ignore cmpd
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { createChartData } from "../chart-data";
|
||||
import type { StockChartOptions } from "../chart-options";
|
||||
import { createStockChart } from "./stock-chart";
|
||||
|
||||
const write = (component: XmlComponent): string => xml(new Formatter().format(component));
|
||||
const parse = (component: XmlComponent): Element => (xml2js(write(component)) as Element).elements![0];
|
||||
const write = (component: XmlComponent): string => stringifyXmlable(new Formatter().format(component));
|
||||
const parse = (component: XmlComponent): Element => parseXml(write(component)).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const children = (element: Element, name: string): readonly Element[] => element.elements!.filter((one) => one.name === name);
|
||||
const value = (element: Element, name: string): unknown => children(element, name)[0]?.attributes?.val;
|
||||
|
||||
@@ -1,16 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import type { ChartTrendline } from "../chart-options";
|
||||
import { createSeriesColor } from "../chart-style";
|
||||
import { createTrendlines } from "./trendline";
|
||||
|
||||
const write = (component: XmlComponent): string => xml(new Formatter().format(component));
|
||||
const parse = (component: XmlComponent): Element => (xml2js(write(component)) as Element).elements![0];
|
||||
const write = (component: XmlComponent): string => stringifyXmlable(new Formatter().format(component));
|
||||
const parse = (component: XmlComponent): Element => parseXml(write(component)).elements![0];
|
||||
const names = (element: Element): readonly string[] => (element.elements ?? []).map(({ name }) => name!);
|
||||
const value = (element: Element, name: string): unknown => element.elements!.find((one) => one.name === name)?.attributes?.val;
|
||||
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, js2xml, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyElement, stringifyXmlable } from "@util/xml";
|
||||
import type { XmlComponent } from "docx";
|
||||
|
||||
import { createChartData } from "../chart-data";
|
||||
@@ -21,12 +20,12 @@ import { childOf, childrenOf, descendantsOf, textOf } from "./template-xml";
|
||||
// cspell:ignore dLbls dLbl dPt varyColors barDir axId crossAx valAx catAx dateAx baseTimeUnit majorTimeUnit legendEntry schemeClr srgbClr lumMod
|
||||
// cspell:ignore numCache strCache ptCount strRef numRef formatCode datalabelsRange trendlineLbl errBars sqref externalData autoUpdate userShapes
|
||||
|
||||
const parse = (text: string): Element => (xml2js(text, { compact: false, captureSpacesBetweenElements: true }) as Element).elements![0];
|
||||
const parse = (text: string): Element => parseXml(text, { keepWhitespaceText: true }).elements![0];
|
||||
|
||||
const write = (element: Element | undefined): string => (element === undefined ? "" : js2xml({ elements: [element] }));
|
||||
const write = (element: Element | undefined): string => (element === undefined ? "" : stringifyElement({ elements: [element] }));
|
||||
|
||||
const formatter = new Formatter();
|
||||
const format = (content: XmlComponent): Element => parse(xml(formatter.format(content)));
|
||||
const format = (content: XmlComponent): Element => parse(stringifyXmlable(formatter.format(content)));
|
||||
|
||||
const NAMESPACES =
|
||||
'xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" ' +
|
||||
|
||||
@@ -5,9 +5,8 @@
|
||||
* @module
|
||||
*/
|
||||
// cspell:ignore sqref
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlComponent } from "docx";
|
||||
import type { XmlElement as Element, XmlComponent } from "docx";
|
||||
|
||||
import type { ChartData, ChartSeriesData } from "../chart-data";
|
||||
import type { TimeUnit } from "../chart-dates";
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { type XmlElement as Element, parseXml } from "@util/xml";
|
||||
|
||||
import { formatCodeOf, isDateFormat, pointCountOf, readTemplateChart } from "./template-chart";
|
||||
|
||||
// cspell:ignore varyColors barDir radarStyle scatterStyle ofPieType ofPie dLbls strRef numRef numCache formatCode ptCount pivotSource
|
||||
|
||||
const parse = (text: string): Element => (xml2js(text, { compact: false, captureSpacesBetweenElements: true }) as Element).elements![0];
|
||||
const parse = (text: string): Element => parseXml(text, { keepWhitespaceText: true }).elements![0];
|
||||
|
||||
// A series, with its order, or null for none
|
||||
const series = (index: number, order: number | null = index): string =>
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
* @module
|
||||
*/
|
||||
// cspell:ignore dmyhs
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "docx";
|
||||
|
||||
import type { ChartType } from "../chart-options";
|
||||
import { childOf, childrenOf, descendantsOf, elementsOf, nameOf, numberOf, textOf, valueOf } from "./template-xml";
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { type Element, js2xml, xml2js } from "xml-js";
|
||||
|
||||
import { type XmlElement as Element, parseXml, stringifyElement } from "@util/xml";
|
||||
|
||||
import { CHART_SPACE_ORDER } from "./patch-chart";
|
||||
import {
|
||||
@@ -17,9 +18,9 @@ import {
|
||||
|
||||
// cspell:ignore srgbClr schemeClr lumMod lumOff dLbls dLbl dPt extLst errBars trendline uniqueId spPr gradFill gsLst prstClr sysClr
|
||||
|
||||
const parse = (text: string): Element => (xml2js(text, { compact: false, captureSpacesBetweenElements: true }) as Element).elements![0];
|
||||
const parse = (text: string): Element => parseXml(text, { keepWhitespaceText: true }).elements![0];
|
||||
|
||||
const write = (element: Element | undefined): string => (element === undefined ? "" : js2xml({ elements: [element] }));
|
||||
const write = (element: Element | undefined): string => (element === undefined ? "" : stringifyElement({ elements: [element] }));
|
||||
|
||||
// The children of each type in ooxml-schemas/ISO-IEC29500-4_2016/dml-chart.xsd, in order, with the children of the
|
||||
// groups it refers to (EG_SerShared) in their places
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "docx";
|
||||
|
||||
import {
|
||||
childOf,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { type Element, js2xml, xml2js } from "xml-js";
|
||||
|
||||
import { type XmlElement as Element, parseXml, stringifyElement } from "@util/xml";
|
||||
|
||||
import {
|
||||
attributeOf,
|
||||
@@ -21,9 +22,9 @@ import {
|
||||
} from "./template-xml";
|
||||
|
||||
// Parsed as patchDocument parses a template's parts, with the spaces between elements
|
||||
const parse = (text: string): Element => (xml2js(text, { compact: false, captureSpacesBetweenElements: true }) as Element).elements![0];
|
||||
const parse = (text: string): Element => parseXml(text, { keepWhitespaceText: true }).elements![0];
|
||||
|
||||
const write = (element: Element): string => js2xml({ elements: [element] });
|
||||
const write = (element: Element): string => stringifyElement({ elements: [element] });
|
||||
|
||||
describe("template-xml", () => {
|
||||
describe("nameOf", () => {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
/**
|
||||
* Small helpers for reading and changing a template's XML, as `patchDocument` parses it (xml-js elements). Changes make
|
||||
* Small helpers for reading and changing a template's XML, as `patchDocument` parses it (`XmlElement`s). Changes make
|
||||
* new elements rather than changing the template's, and keep its text, comments and elements they don't know.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
import type { XmlElement as Element } from "docx";
|
||||
|
||||
/**
|
||||
* An element's name, such as "c:ser", or "" for text and comments, which have none.
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
// cspell:ignore Fmts
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import type { EmbeddedPackageFile, XmlComponent } from "docx";
|
||||
|
||||
import { createWorkbookFiles } from "./workbook";
|
||||
|
||||
const toXml = (component: EmbeddedPackageFile["content"]): string => xml(new Formatter().format(component as XmlComponent));
|
||||
const toXml = (component: EmbeddedPackageFile["content"]): string => stringifyXmlable(new Formatter().format(component as XmlComponent));
|
||||
|
||||
const files = (sheet: Parameters<typeof createWorkbookFiles>[0]): Readonly<Record<string, string>> =>
|
||||
Object.fromEntries(createWorkbookFiles(sheet).map(({ path, content }) => [path, toXml(content)]));
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
* @module
|
||||
*/
|
||||
import JSZip from "jszip";
|
||||
import xml from "xml";
|
||||
|
||||
import type { File } from "@file/file";
|
||||
import { obfuscate } from "@file/fonts/obfuscate-ttf-to-odttf";
|
||||
import { Relationships } from "@file/relationships";
|
||||
import { encodeUtf8 } from "@util/convenience-functions";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
|
||||
import { Formatter } from "../formatter";
|
||||
import { ImageReplacer } from "./image-replacer";
|
||||
@@ -181,7 +181,7 @@ export class Compiler {
|
||||
}
|
||||
|
||||
private xmlifyFile(file: File, prettify?: (typeof PrettifyType)[keyof typeof PrettifyType]): IXmlifyedFileMapping {
|
||||
const documentXmlData = xml(
|
||||
const documentXmlData = stringifyXmlable(
|
||||
this.formatter.format(file.Document.View, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -196,7 +196,7 @@ export class Compiler {
|
||||
},
|
||||
);
|
||||
|
||||
const commentXmlData = xml(
|
||||
const commentXmlData = stringifyXmlable(
|
||||
this.formatter.format(file.Comments, {
|
||||
viewWrapper: {
|
||||
View: file.Comments,
|
||||
@@ -214,7 +214,7 @@ export class Compiler {
|
||||
},
|
||||
);
|
||||
|
||||
const footnoteXmlData = xml(
|
||||
const footnoteXmlData = stringifyXmlable(
|
||||
this.formatter.format(file.FootNotes.View, {
|
||||
viewWrapper: file.FootNotes,
|
||||
file,
|
||||
@@ -229,7 +229,7 @@ export class Compiler {
|
||||
},
|
||||
);
|
||||
|
||||
const endnoteXmlData = xml(
|
||||
const endnoteXmlData = stringifyXmlable(
|
||||
this.formatter.format(file.Endnotes.View, {
|
||||
viewWrapper: file.Endnotes,
|
||||
file,
|
||||
@@ -274,7 +274,7 @@ export class Compiler {
|
||||
"fontTable.xml",
|
||||
);
|
||||
|
||||
return xml(
|
||||
return stringifyXmlable(
|
||||
this.formatter.format(relationships, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -300,7 +300,7 @@ export class Compiler {
|
||||
},
|
||||
Styles: {
|
||||
data: (() => {
|
||||
const xmlStyles = xml(
|
||||
const xmlStyles = stringifyXmlable(
|
||||
this.formatter.format(file.Styles, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -320,7 +320,7 @@ export class Compiler {
|
||||
path: "word/styles.xml",
|
||||
},
|
||||
Properties: {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.CoreProperties, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -337,7 +337,7 @@ export class Compiler {
|
||||
path: "docProps/core.xml",
|
||||
},
|
||||
FileRelationships: {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.FileRelationships, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -353,7 +353,7 @@ export class Compiler {
|
||||
path: "_rels/.rels",
|
||||
},
|
||||
HeaderRelationships: file.Headers.map((headerWrapper, index) => {
|
||||
const xmlData = xml(
|
||||
const xmlData = stringifyXmlable(
|
||||
this.formatter.format(headerWrapper.View, {
|
||||
viewWrapper: headerWrapper,
|
||||
file,
|
||||
@@ -379,7 +379,7 @@ export class Compiler {
|
||||
});
|
||||
|
||||
return {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(relationships, {
|
||||
viewWrapper: headerWrapper,
|
||||
file,
|
||||
@@ -396,7 +396,7 @@ export class Compiler {
|
||||
};
|
||||
}),
|
||||
FooterRelationships: file.Footers.map((footerWrapper, index) => {
|
||||
const xmlData = xml(
|
||||
const xmlData = stringifyXmlable(
|
||||
this.formatter.format(footerWrapper.View, {
|
||||
viewWrapper: footerWrapper,
|
||||
file,
|
||||
@@ -422,7 +422,7 @@ export class Compiler {
|
||||
});
|
||||
|
||||
return {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(relationships, {
|
||||
viewWrapper: footerWrapper,
|
||||
file,
|
||||
@@ -439,7 +439,7 @@ export class Compiler {
|
||||
};
|
||||
}),
|
||||
Headers: file.Headers.map((headerWrapper, index) => {
|
||||
const tempXmlData = xml(
|
||||
const tempXmlData = stringifyXmlable(
|
||||
this.formatter.format(headerWrapper.View, {
|
||||
viewWrapper: headerWrapper,
|
||||
file,
|
||||
@@ -464,7 +464,7 @@ export class Compiler {
|
||||
};
|
||||
}),
|
||||
Footers: file.Footers.map((footerWrapper, index) => {
|
||||
const tempXmlData = xml(
|
||||
const tempXmlData = stringifyXmlable(
|
||||
this.formatter.format(footerWrapper.View, {
|
||||
viewWrapper: footerWrapper,
|
||||
file,
|
||||
@@ -489,7 +489,7 @@ export class Compiler {
|
||||
};
|
||||
}),
|
||||
CustomProperties: {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.CustomProperties, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -506,7 +506,7 @@ export class Compiler {
|
||||
path: "docProps/custom.xml",
|
||||
},
|
||||
AppProperties: {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.AppProperties, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -541,7 +541,7 @@ export class Compiler {
|
||||
`media/${mediaData.fileName}`,
|
||||
);
|
||||
});
|
||||
return xml(
|
||||
return stringifyXmlable(
|
||||
this.formatter.format(relationships, {
|
||||
viewWrapper: file.FootNotes,
|
||||
file,
|
||||
@@ -576,7 +576,7 @@ export class Compiler {
|
||||
`media/${mediaData.fileName}`,
|
||||
);
|
||||
});
|
||||
return xml(
|
||||
return stringifyXmlable(
|
||||
this.formatter.format(relationships, {
|
||||
viewWrapper: file.Endnotes,
|
||||
file,
|
||||
@@ -593,7 +593,7 @@ export class Compiler {
|
||||
path: "word/_rels/endnotes.xml.rels",
|
||||
},
|
||||
Settings: {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.Settings, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -631,7 +631,7 @@ export class Compiler {
|
||||
`media/${mediaData.fileName}`,
|
||||
);
|
||||
});
|
||||
return xml(
|
||||
return stringifyXmlable(
|
||||
this.formatter.format(relationships, {
|
||||
viewWrapper: {
|
||||
View: file.Comments,
|
||||
@@ -654,7 +654,7 @@ export class Compiler {
|
||||
...(file.CommentsExtended
|
||||
? {
|
||||
CommentsExtended: {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.CommentsExtended, {
|
||||
viewWrapper: {
|
||||
View: file.CommentsExtended,
|
||||
@@ -678,7 +678,7 @@ export class Compiler {
|
||||
...(file.CommentsIds
|
||||
? {
|
||||
CommentsIds: {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.CommentsIds, {
|
||||
viewWrapper: {
|
||||
View: file.CommentsIds,
|
||||
@@ -700,7 +700,7 @@ export class Compiler {
|
||||
}
|
||||
: {}),
|
||||
FontTable: {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.FontTable.View, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -718,7 +718,7 @@ export class Compiler {
|
||||
},
|
||||
FontTableRelationships: {
|
||||
data: (() =>
|
||||
xml(
|
||||
stringifyXmlable(
|
||||
this.formatter.format(file.FontTable.Relationships, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -734,7 +734,7 @@ export class Compiler {
|
||||
path: "word/_rels/fontTable.xml.rels",
|
||||
},
|
||||
Theme: {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.Theme, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -755,7 +755,7 @@ export class Compiler {
|
||||
// After every part that can have lists, such as headers and footers, as the lists they use are added to the
|
||||
// numbering while they're written
|
||||
Numbering: {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.Numbering, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
@@ -773,7 +773,7 @@ export class Compiler {
|
||||
},
|
||||
// Last, as parts are added to the package, with their content types, while the others are written
|
||||
ContentTypes: {
|
||||
data: xml(
|
||||
data: stringifyXmlable(
|
||||
this.formatter.format(file.ContentTypes, {
|
||||
viewWrapper: file.Document,
|
||||
file,
|
||||
|
||||
@@ -5,13 +5,13 @@
|
||||
* @module
|
||||
*/
|
||||
import JSZip from "jszip";
|
||||
import xml from "xml";
|
||||
|
||||
import type { File } from "@file/file";
|
||||
import type { PackagePart } from "@file/package-part/package-part";
|
||||
import { Relationships } from "@file/relationships";
|
||||
import type { XmlComponent } from "@file/xml-components";
|
||||
import { encodeUtf8 } from "@util/convenience-functions";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
|
||||
import { Formatter } from "../formatter";
|
||||
import type { PrettifyType } from "./packer";
|
||||
@@ -33,7 +33,7 @@ const formatter = new Formatter();
|
||||
* Formats a part's XML, with the relationships that anything in it that refers to other parts adds to.
|
||||
*/
|
||||
const xmlifyPart = (file: File, content: XmlComponent, prettify: Prettify, relationships: Relationships, standalone = true): string =>
|
||||
xml(formatter.format(content, { viewWrapper: { View: content, Relationships: relationships }, file, stack: [] }), {
|
||||
stringifyXmlable(formatter.format(content, { viewWrapper: { View: content, Relationships: relationships }, file, stack: [] }), {
|
||||
indent: prettify,
|
||||
declaration: standalone ? { standalone: "yes", encoding: "UTF-8" } : { encoding: "UTF-8" },
|
||||
});
|
||||
|
||||
@@ -7,9 +7,9 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type Element as XMLElement, xml2js } from "xml-js";
|
||||
|
||||
import { ImportedRootElementAttributes, type ImportedXmlComponent, convertToXmlComponent } from "@file/xml-components";
|
||||
import { type XmlElement as XMLElement, parseXml } from "@util/xml";
|
||||
|
||||
import type { IStylesOptions } from "./styles";
|
||||
|
||||
@@ -54,7 +54,7 @@ export class ExternalStylesFactory {
|
||||
* @throws Error if styles element cannot be found in the XML
|
||||
*/
|
||||
public newInstance(xmlData: string): IStylesOptions {
|
||||
const xmlObj = xml2js(xmlData, { compact: false }) as XMLElement;
|
||||
const xmlObj = parseXml(xmlData);
|
||||
|
||||
let stylesXmlElement: XMLElement | undefined;
|
||||
for (const xmlElm of xmlObj.elements || []) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { EMPTY_OBJECT } from "@file/xml-components";
|
||||
import { type XmlElement as Element, parseXml } from "@util/xml";
|
||||
|
||||
import type { IContext } from "./base";
|
||||
import { ImportedRootElementAttributes, ImportedXmlComponent, convertToXmlComponent } from "./imported-xml-component";
|
||||
@@ -85,7 +85,7 @@ describe("ImportedXmlComponent", () => {
|
||||
|
||||
describe("convertToXmlComponent", () => {
|
||||
it("should convert to xml component", () => {
|
||||
const xmlObj = xml2js(xmlString, { compact: false }) as Element;
|
||||
const xmlObj = parseXml(xmlString);
|
||||
const converted = convertToXmlComponent(xmlObj);
|
||||
expect(JSON.parse(JSON.stringify(converted))).to.deep.equal(convertedXmlElement);
|
||||
});
|
||||
|
||||
@@ -7,26 +7,28 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import { type Element as XmlElement, xml2js } from "xml-js";
|
||||
|
||||
import { type IXmlableObject, XmlAttributeComponent, XmlComponent } from "@file/xml-components";
|
||||
import { type XmlElement, parseXml } from "@util/xml";
|
||||
|
||||
import type { IContext } from "./base";
|
||||
|
||||
/**
|
||||
* Converts an xml-js Element into an XmlComponent tree.
|
||||
* Converts an XML element, in the shape of xml-js's non-compact `Element`, into an XmlComponent tree.
|
||||
*
|
||||
* This function recursively processes XML elements in JSON format (from xml-js)
|
||||
* and creates a tree of ImportedXmlComponent objects that match the structure
|
||||
* of the original XML.
|
||||
* This function recursively processes the element and creates a tree of
|
||||
* ImportedXmlComponent objects that match the structure of the original XML.
|
||||
*
|
||||
* @param element - The XML element in JSON representation from xml-js
|
||||
* @param element - The XML element as an {@link XmlElement}
|
||||
* @returns An ImportedXmlComponent tree, text string, or undefined
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const xmlElement = xml2js('<w:p><w:r><w:t>Hello</w:t></w:r></w:p>');
|
||||
* const component = convertToXmlComponent(xmlElement);
|
||||
* const component = convertToXmlComponent({
|
||||
* type: "element",
|
||||
* name: "w:p",
|
||||
* elements: [{ type: "element", name: "w:r", elements: [{ type: "element", name: "w:t", elements: [{ type: "text", text: "Hello" }] }] }],
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export const convertToXmlComponent = (element: XmlElement): ImportedXmlComponent | string | undefined => {
|
||||
@@ -85,7 +87,7 @@ export class ImportedXmlComponent extends XmlComponent {
|
||||
* Parses an XML string and converts it to an ImportedXmlComponent tree.
|
||||
*
|
||||
* This static method is the primary way to import external XML content.
|
||||
* It uses xml-js to parse the XML string into a JSON representation,
|
||||
* It parses the XML string into an {@link XmlElement} tree,
|
||||
* then converts that into a tree of XmlComponent objects.
|
||||
*
|
||||
* @param importedContent - The XML content as a string
|
||||
@@ -98,7 +100,7 @@ export class ImportedXmlComponent extends XmlComponent {
|
||||
* ```
|
||||
*/
|
||||
public static fromXmlString(importedContent: string): ImportedXmlComponent {
|
||||
const xmlObj = xml2js(importedContent, { compact: false }) as XmlElement;
|
||||
const xmlObj = parseXml(importedContent);
|
||||
return convertToXmlComponent(xmlObj) as ImportedXmlComponent;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,9 +2,9 @@ import type { Element } from "domhandler";
|
||||
import { parse } from "parse5";
|
||||
import { adapter } from "parse5-htmlparser2-tree-adapter";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import {
|
||||
Math,
|
||||
type MathComponent,
|
||||
@@ -34,7 +34,7 @@ const elementIn = (html: string, name: string): Element => {
|
||||
return find(document)!;
|
||||
};
|
||||
|
||||
const written = (...children: readonly MathComponent[]): string => xml(new Formatter().format(new Math({ children })));
|
||||
const written = (...children: readonly MathComponent[]): string => stringifyXmlable(new Formatter().format(new Math({ children })));
|
||||
const read = (mathMl: string): string => written(...mathOf(elementIn(`<math>${mathMl}</math>`, "math")));
|
||||
const run = (text: string, options: Omit<ConstructorParameters<typeof MathRun>[0] & object, "text"> = {}): MathRun =>
|
||||
new MathRun({ text, ...options });
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
// cspell:ignore endedi
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { type XmlElement as Element, parseXml } from "@util/xml";
|
||||
|
||||
import type { DocxPackage } from "./imported-documents";
|
||||
import { type Block, type DocumentContent, type ParagraphBlock } from "./read-document";
|
||||
import { readDocx } from "./read-docx";
|
||||
|
||||
/** Parses XML as patchDocument parses a template's parts */
|
||||
const parse = (xml: string): Element => xml2js(xml, { compact: false, captureSpacesBetweenElements: true }) as Element;
|
||||
const parse = (xml: string): Element => parseXml(xml, { keepWhitespaceText: true });
|
||||
|
||||
const W = 'xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"';
|
||||
const R = 'xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships"';
|
||||
|
||||
@@ -33,7 +33,8 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "docx";
|
||||
|
||||
import {
|
||||
type FontFace,
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import JSZip from "jszip";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { obfuscate } from "@file/fonts/obfuscate-ttf-to-odttf";
|
||||
import { type XmlElement as Element, parseXml } from "@util/xml";
|
||||
import {
|
||||
AlignmentType,
|
||||
Document,
|
||||
@@ -31,7 +31,7 @@ import { type DocumentContent, type ParagraphBlock, readDocument } from "./read-
|
||||
import { readDocx } from "./read-docx";
|
||||
|
||||
/** Parses XML as patchDocument parses a template's parts */
|
||||
const parse = (xml: string): Element => xml2js(xml, { compact: false, captureSpacesBetweenElements: true }) as Element;
|
||||
const parse = (xml: string): Element => parseXml(xml, { keepWhitespaceText: true });
|
||||
|
||||
/** The XML parts of a .docx, parsed, by their paths */
|
||||
const partsOf = async (buffer: Buffer): Promise<ReadonlyMap<string, Element>> => {
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "docx";
|
||||
|
||||
import { type XmlObject, attributesOf, childrenOf, find, readTextStyles, readThemeFonts, stringOf, withoutUndefined } from "../text-layout";
|
||||
import type { DataStores } from "./bound-controls";
|
||||
@@ -26,7 +27,7 @@ type Relationship = {
|
||||
const DEFAULT_DOCUMENT = "word/document.xml";
|
||||
|
||||
/**
|
||||
* An element as xml-js parses it, formatted as docx formats elements: `{ "w:p": [{ _attr: {...} }, ...content] }`, with
|
||||
* An element as `parseXml` reads it, formatted as docx formats elements: `{ "w:p": [{ _attr: {...} }, ...content] }`, with
|
||||
* text as strings.
|
||||
*/
|
||||
const formatted = (element: Element): unknown => {
|
||||
@@ -250,8 +251,8 @@ const dataStoresOf = (parts: ReadonlyMap<string, Element>, documentPath: string)
|
||||
* Reads a .docx's main document, with the parts it refers to, and the documents it imports (`w:altChunk`) as Word turns
|
||||
* them into its own paragraphs and tables when it opens it (see `imported-documents.ts`).
|
||||
*
|
||||
* @param parts - The XML parts of its package, parsed by xml-js's `xml2js`, not compact and keeping the spaces between
|
||||
* elements, by their paths, such as "word/document.xml"
|
||||
* @param parts - The XML parts of its package, read by `parseXml` keeping the text that is only whitespace, by their
|
||||
* paths, such as "word/document.xml"
|
||||
* @param binaryParts - Its other parts, such as the fonts it embeds, by their paths
|
||||
* @param options - How it is read: to be laid out with a guess, or not
|
||||
* @param importedDocuments - The .docx files it imports, by their paths, each read as it is
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import {
|
||||
Math,
|
||||
type MathComponent,
|
||||
@@ -29,7 +29,7 @@ import { MathLargeOperator } from "./math-large-operator";
|
||||
import { MathMatrix } from "./math-matrix";
|
||||
import { MathPhantom } from "./math-phantom";
|
||||
|
||||
const written = (...children: readonly MathComponent[]): string => xml(new Formatter().format(new Math({ children })));
|
||||
const written = (...children: readonly MathComponent[]): string => stringifyXmlable(new Formatter().format(new Math({ children })));
|
||||
|
||||
/** The math the LaTeX is read as, written, to compare with the same math built by hand */
|
||||
const read = (latex: string): string => written(...latexToMath(latex));
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import { Math, MathRun } from "docx";
|
||||
|
||||
import { MathAccent, type MathAccentName } from "./math-accent";
|
||||
|
||||
const toXml = (component: MathAccent): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: MathAccent): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
const x = "<m:e><m:r><m:t>x</m:t></m:r></m:e>";
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import { Math, MathRun } from "docx";
|
||||
|
||||
import { MathBar } from "./math-bar";
|
||||
|
||||
const toXml = (component: MathBar): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: MathBar): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
describe("MathBar", () => {
|
||||
it("puts a line above its children by default, writing the position, as the schema's default is below", () => {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import { Math, MathRun } from "docx";
|
||||
|
||||
import { MathBox } from "./math-box";
|
||||
|
||||
const toXml = (component: MathBox): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: MathBox): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
describe("MathBox", () => {
|
||||
it("draws a box around its children, with no properties, as all four sides are drawn by default", () => {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import { Math, MathRun } from "docx";
|
||||
|
||||
import { MathBrace } from "./math-brace";
|
||||
|
||||
const toXml = (component: MathBrace): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: MathBrace): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
const e = "<m:e><m:r><m:t>a+b</m:t></m:r></m:e>";
|
||||
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import { Math, MathFraction, MathRun, Paragraph, TextRun } from "docx";
|
||||
|
||||
import { MathBrackets } from "./math-brackets";
|
||||
import { MathMatrix } from "./math-matrix";
|
||||
|
||||
const toXml = (component: MathBrackets): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: MathBrackets): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
const x = "<m:e><m:r><m:t>x</m:t></m:r></m:e>";
|
||||
|
||||
@@ -104,7 +104,7 @@ describe("MathBrackets", () => {
|
||||
numerator: [new MathBrackets({ open: "|", close: "|", children: [new MathRun("x")] })],
|
||||
denominator: [new MathRun("2")],
|
||||
});
|
||||
expect(xml(new Formatter().format(fraction))).toContain('<m:num><m:d><m:dPr><m:begChr m:val="|"/>');
|
||||
expect(stringifyXmlable(new Formatter().format(fraction))).toContain('<m:num><m:d><m:dPr><m:begChr m:val="|"/>');
|
||||
expect(toXml(new MathBrackets({ children: [new MathMatrix({ rows: [[[new MathRun("1")]]] })] }))).toContain("<m:e><m:m>");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import { Math, MathRun } from "docx";
|
||||
|
||||
import { type MathCase, MathCases } from "./math-cases";
|
||||
import { MathMatrix } from "./math-matrix";
|
||||
|
||||
const toXml = (component: MathCases): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: MathCases): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
const e = (text: string): string => `<m:e><m:r><m:t>${text}</m:t></m:r></m:e>`;
|
||||
const EMPTY = '<m:e><m:r><m:t xml:space="preserve">\u200B</m:t></m:r></m:e>';
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import { Math, MathRun, MathSuperScript, TextRun } from "docx";
|
||||
|
||||
import { MathCases } from "./math-cases";
|
||||
import { MathEquationArray, type MathEquationArrayOptions, type MathEquationArrayRow } from "./math-equation-array";
|
||||
|
||||
const toXml = (component: MathEquationArray | MathCases): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: MathEquationArray | MathCases): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
const r = (text: string): string => `<m:r><m:t>${text}</m:t></m:r>`;
|
||||
const AMP = r("&");
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import { Math, MathRun } from "docx";
|
||||
|
||||
import { LARGE_OPERATORS, MathLargeOperator, type MathLargeOperatorName } from "./math-large-operator";
|
||||
|
||||
const toXml = (component: MathLargeOperator): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: MathLargeOperator): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
describe("MathLargeOperator", () => {
|
||||
it("writes the operator with its limits above and below, and what it applies to", () => {
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import { Math, type MathComponent, MathFraction, MathRun } from "docx";
|
||||
|
||||
import { type MathColumnAlignment, MathMatrix, type MathMatrixBrackets, type MathMatrixOptions } from "./math-matrix";
|
||||
|
||||
const toXml = (component: MathMatrix | MathFraction): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: MathMatrix | MathFraction): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
const cell = (text: string): readonly MathComponent[] => [new MathRun(text)];
|
||||
const e = (text: string): string => `<m:e><m:r><m:t>${text}</m:t></m:r></m:e>`;
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
import { Math, MathRun } from "docx";
|
||||
|
||||
import { MathPhantom } from "./math-phantom";
|
||||
|
||||
const toXml = (component: MathPhantom): string => xml(new Formatter().format(component));
|
||||
const toXml = (component: MathPhantom): string => stringifyXmlable(new Formatter().format(component));
|
||||
|
||||
describe("MathPhantom", () => {
|
||||
it("hides its children, which still take up their room, by default", () => {
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
import { Math, type MathComponent, MathFraction, MathIntegral, MathRun, MathSum, MathSuperScript } from "docx";
|
||||
|
||||
import { latexToMath } from "./latex-to-math";
|
||||
@@ -21,7 +20,7 @@ import mathSchema from "../../ooxml-schemas/ISO-IEC29500-4_2016/shared-math.xsd?
|
||||
|
||||
// The math schema, which docx/math's elements are checked against: each element's children are ones its type has, in
|
||||
// its type's order. The Open XML SDK validator checks this too, for the demos only
|
||||
const schema = xml2js(mathSchema as string) as Element;
|
||||
const schema = parseXml(mathSchema as string);
|
||||
|
||||
const definitions = new Map(
|
||||
schema
|
||||
@@ -103,8 +102,8 @@ const problemsIn = (element: Element, type: string, path: string): readonly stri
|
||||
};
|
||||
|
||||
const problemsOf = (children: readonly MathComponent[]): readonly string[] => {
|
||||
const written = xml(new Formatter().format(new Math({ children })));
|
||||
return problemsIn((xml2js(written) as Element).elements![0], "CT_OMath", "m:oMath");
|
||||
const written = stringifyXmlable(new Formatter().format(new Math({ children })));
|
||||
return problemsIn(parseXml(written).elements![0], "CT_OMath", "m:oMath");
|
||||
};
|
||||
|
||||
const run = (text: string): MathRun => new MathRun(text);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import { findBookmarkIds, renumberBookmarksAvoiding } from "./bookmark-ids";
|
||||
import { toJson } from "./util";
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
/**
|
||||
* Renumbers the bookmarks in content that is about to be inserted into a document.
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import { getFirstLevelElements } from "./util";
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import { findDrawingIds, renumberDrawingsAvoiding } from "./drawing-ids";
|
||||
import { toJson } from "./util";
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
/**
|
||||
* Renumbers the drawings in content that is about to be inserted into a document.
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
/* eslint-disable @typescript-eslint/naming-convention -- The keys of objects here are paths of parts in a package */
|
||||
import JSZip from "jszip";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import { PackagePart } from "@file/package-part";
|
||||
import { ExternalHyperlink, ImageRun, TextRun } from "@file/paragraph";
|
||||
import { BuilderElement } from "@file/xml-components";
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import {
|
||||
DrawingPatch,
|
||||
|
||||
@@ -7,13 +7,12 @@
|
||||
* @module
|
||||
*/
|
||||
// cspell:ignore descr
|
||||
import xml from "xml";
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import type { File } from "@file/file";
|
||||
import type { PackagePart } from "@file/package-part";
|
||||
import type { IContext, XmlComponent } from "@file/xml-components";
|
||||
import { type XmlElement as Element, stringifyXmlable } from "@util/xml";
|
||||
|
||||
import { removeContentTypeOverride } from "./content-types-manager";
|
||||
import { PatchType } from "./patch-type";
|
||||
@@ -320,7 +319,7 @@ const createTemplatePackage = (
|
||||
return String(relationship.attributes.Id);
|
||||
},
|
||||
|
||||
format: (content) => toJson(xml(formatter.format(content, context))).elements![0],
|
||||
format: (content) => toJson(stringifyXmlable(formatter.format(content, context))).elements![0],
|
||||
};
|
||||
};
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
* @module
|
||||
*/
|
||||
import JSZip from "jszip";
|
||||
import { type Element, js2xml } from "xml-js";
|
||||
|
||||
import { ImageReplacer } from "@export/packer/image-replacer";
|
||||
import { xmlifyPackageParts } from "@export/packer/package-part-writer";
|
||||
@@ -25,6 +24,7 @@ import { type RelationshipType, TargetModeType } from "@file/relationships/relat
|
||||
import type { IContext } from "@file/xml-components";
|
||||
import { encodeUtf8, uniqueId } from "@util/convenience-functions";
|
||||
import type { OutputByType, OutputType } from "@util/output-type";
|
||||
import { type XmlElement as Element, stringifyElement } from "@util/xml";
|
||||
|
||||
import { findBookmarkIds, renumberBookmarksAvoiding } from "./bookmark-ids";
|
||||
import { appendContentType, appendContentTypeOverride } from "./content-types-manager";
|
||||
@@ -643,7 +643,7 @@ export const patchDocument = async <T extends PatchDocumentOutputType = PatchDoc
|
||||
const zip = new JSZip();
|
||||
|
||||
for (const [key, value] of map) {
|
||||
const output = toXml(value);
|
||||
const output = stringifyElement(value);
|
||||
|
||||
zip.file(key, encodeUtf8(output));
|
||||
}
|
||||
@@ -666,37 +666,3 @@ export const patchDocument = async <T extends PatchDocumentOutputType = PatchDoc
|
||||
compression: "DEFLATE",
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* The element with an extra escape on each "&" in its text and attributes. xml-js reads "&" in text as an "&"
|
||||
* already escaped, and would write a text's literal "&", such as in a document about HTML, as "&". It escapes the
|
||||
* quotes in an attribute before `attributeValueFn` is given it, so that can't tell its """ from a literal one.
|
||||
*/
|
||||
const withAmpersandsEscaped = (element: Element): Element => ({
|
||||
...element,
|
||||
...(element.attributes === undefined
|
||||
? {}
|
||||
: {
|
||||
attributes: Object.fromEntries(
|
||||
Object.entries(element.attributes).map(([key, value]) => [
|
||||
key,
|
||||
value === undefined ? value : String(value).replace(/&/g, "&"),
|
||||
]),
|
||||
),
|
||||
}),
|
||||
...(element.elements === undefined
|
||||
? {}
|
||||
: {
|
||||
elements: element.elements.map((child) =>
|
||||
child.type === "text" ? { ...child, text: String(child.text).replace(/&/g, "&") } : withAmpersandsEscaped(child),
|
||||
),
|
||||
}),
|
||||
});
|
||||
|
||||
const toXml = (jsonObj: Element): string => {
|
||||
const output = js2xml(withAmpersandsEscaped(jsonObj), {
|
||||
// xml-js has already escaped the quotes, and withAmpersandsEscaped each "&"
|
||||
attributeValueFn: (str) => String(str).replace(/</g, "<").replace(/>/g, ">").replace(/'/g, "'"), // cspell:words apos
|
||||
});
|
||||
return output;
|
||||
};
|
||||
|
||||
@@ -3,8 +3,6 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import xml from "xml";
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { EndnoteRefRun } from "@file/endnotes/endnote/run/endnote-ref-run";
|
||||
@@ -23,6 +21,7 @@ import {
|
||||
} from "@file/styles/style/default-styles";
|
||||
import type { IContext, XmlComponent } from "@file/xml-components";
|
||||
import { uniqueId } from "@util/convenience-functions";
|
||||
import { type XmlElement as Element, stringifyXmlable } from "@util/xml";
|
||||
|
||||
import type { RenumberBookmarks } from "./bookmark-ids";
|
||||
import type { RenumberDrawings } from "./drawing-ids";
|
||||
@@ -127,7 +126,7 @@ export type NotesPatcher = {
|
||||
};
|
||||
|
||||
const formatElement = (component: XmlComponent, context: IContext): Element =>
|
||||
toJson(xml(formatter.format(component, context))).elements![0];
|
||||
toJson(stringifyXmlable(formatter.format(component, context))).elements![0];
|
||||
|
||||
const findIds = (element: Element, names: readonly string[]): readonly number[] => {
|
||||
const id = names.includes(element.name ?? "") ? Number(element.attributes?.["w:id"]) : NaN;
|
||||
|
||||
@@ -3,13 +3,12 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import xml from "xml";
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import type { ConcreteNumbering, Numbering } from "@file/numbering";
|
||||
import type { IContext, XmlComponent } from "@file/xml-components";
|
||||
import { uniqueId } from "@util/convenience-functions";
|
||||
import { type XmlElement as Element, stringifyXmlable } from "@util/xml";
|
||||
|
||||
import { relationshipsPathOf, relativeTarget, resolveTarget } from "./drawing-patch";
|
||||
import { getFirstLevelElements, toJson } from "./util";
|
||||
@@ -53,7 +52,7 @@ export type NumberingPatcher = {
|
||||
};
|
||||
|
||||
const formatElement = (component: XmlComponent, context: IContext): Element =>
|
||||
toJson(xml(formatter.format(component, context))).elements![0];
|
||||
toJson(stringifyXmlable(formatter.format(component, context))).elements![0];
|
||||
|
||||
const highestOf = (ids: readonly number[]): number => ids.reduce((highest, id) => Math.max(highest, id), 0);
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import JSZip from "jszip";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { type Element, js2xml } from "xml-js";
|
||||
|
||||
import { type XmlElement as Element, stringifyElement } from "@util/xml";
|
||||
|
||||
import { type PatchedTemplate, fillTemplatePageNumbers } from "./page-numbers";
|
||||
import { toJson } from "./util";
|
||||
@@ -23,7 +24,7 @@ const sectionEnd = (references: string): string => `<w:p><w:pPr><w:sectPr>${refe
|
||||
|
||||
/** The text of a part, with each field's result where it is */
|
||||
const textOf = (part: Element): string =>
|
||||
js2xml(part)
|
||||
stringifyElement(part)
|
||||
.replace(/<w:instrText[^>]*>[^<]*<\/w:instrText>/g, "")
|
||||
.replace(/<w:t[^>]*>([^<]*)<\/w:t>|<w:t[^>]*\/>|<[^>]+>/g, "$1");
|
||||
|
||||
@@ -101,7 +102,7 @@ describe("fillTemplatePageNumbers", () => {
|
||||
],
|
||||
]);
|
||||
await fillTemplatePageNumbers(parts, () => ({ bookmarks: new Map([["_Toc1", "3"]]) }));
|
||||
const document = js2xml(parts.get("word/document.xml")!);
|
||||
const document = stringifyElement(parts.get("word/document.xml")!);
|
||||
expect(document.match(/<w:fldChar [^>]*w:fldCharType="begin"[^>]*\/>/g)).to.deep.equal([
|
||||
'<w:fldChar w:fldCharType="begin"/>',
|
||||
'<w:fldChar w:fldCharType="begin"/>',
|
||||
@@ -140,7 +141,7 @@ describe("fillTemplatePageNumbers", () => {
|
||||
const outer = await zipOf(
|
||||
new Map([
|
||||
["word/document.xml", `<w:document ${W}><w:body><w:altChunk/></w:body></w:document>`],
|
||||
["word/_rels/document.xml.rels", js2xml(relationships(["rId1", "inner.docx"]))],
|
||||
["word/_rels/document.xml.rels", stringifyElement(relationships(["rId1", "inner.docx"]))],
|
||||
["word/inner.docx", ""],
|
||||
["word/media/image1.png", "png"],
|
||||
["word/folder/", ""],
|
||||
@@ -186,7 +187,7 @@ describe("fillTemplatePageNumbers", () => {
|
||||
const inner = await zipOf(new Map([["word/document.xml", `<w:document ${W}><w:body><w:p/></w:body></w:document>`]]));
|
||||
const outer = new JSZip();
|
||||
outer.file("word/document.xml", `<w:document ${W}><w:body><w:altChunk/></w:body></w:document>`);
|
||||
outer.file("word/_rels/document.xml.rels", js2xml(relationships(["rId1", "inner.docx"])));
|
||||
outer.file("word/_rels/document.xml.rels", stringifyElement(relationships(["rId1", "inner.docx"])));
|
||||
outer.file("word/inner.docx", inner);
|
||||
const parts = new Map([
|
||||
["word/document.xml", toJson(`<w:document ${W}><w:body/></w:document>`)],
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
* @module
|
||||
*/
|
||||
import JSZip from "jszip";
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import { type ElementTree, fillBodyFields, fillPartFields } from "@file/document/body/page-number-fields";
|
||||
import type { EstimatedPageNumbers } from "@file/document/body/page-numbers";
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import { relationshipsPathOf, resolveTarget, sourceOfRelationships } from "./drawing-patch";
|
||||
import { toJson } from "./util";
|
||||
@@ -21,8 +21,8 @@ import { toJson } from "./util";
|
||||
export type PatchedTemplate = {
|
||||
/**
|
||||
* Each XML part of the template's package, by its path in the package, such as "word/document.xml". Each is parsed as
|
||||
* `patchDocument` parses it, with xml-js's `xml2js`, not compact, and keeping the spaces between elements
|
||||
* (`captureSpacesBetweenElements`), as the spaces in a text element are its text
|
||||
* `patchDocument` parses it, with `parseXml` keeping the text that is only whitespace (`keepWhitespaceText`), as the
|
||||
* spaces in a text element are its text
|
||||
*/
|
||||
readonly parts: ReadonlyMap<string, Element>;
|
||||
/** Each of its other parts, such as its pictures and the fonts it embeds, by its path in the package, as bytes */
|
||||
@@ -45,7 +45,7 @@ export type PatchedTemplate = {
|
||||
*/
|
||||
export type TemplatePageNumberEstimator = (template: PatchedTemplate) => EstimatedPageNumbers;
|
||||
|
||||
/** The elements of a template, as xml-js parses them */
|
||||
/** The elements of a template, as `parseXml` reads them */
|
||||
const PARSED: ElementTree<Element> = {
|
||||
nameOf: (element) => (element.type === "element" ? element.name : undefined),
|
||||
contentOf: (element) => element.elements,
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import { createTextElementContents, patchSpaceAttribute } from "./util";
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import type { IRenderedParagraphNode } from "./run-renderer";
|
||||
import { createTextElementContents, patchSpaceAttribute } from "./util";
|
||||
|
||||
@@ -3,9 +3,9 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { RelationshipType, TargetModeType } from "@file/relationships/relationship/relationship";
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import { getFirstLevelElements } from "./util";
|
||||
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { IViewWrapper } from "@file/document-wrapper";
|
||||
import type { File } from "@file/file";
|
||||
@@ -8,6 +7,7 @@ import { FootnoteReferenceRun } from "@file/footnotes/footnote/run/reference-run
|
||||
import { Bookmark, ConcreteHyperlink, Paragraph, type ParagraphChild, TextRun } from "@file/paragraph";
|
||||
import { WpsShapeRun } from "@file/paragraph/run/wps-shape-run";
|
||||
import { Table, TableCell, TableRow } from "@file/table";
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import { PatchType } from "./from-docx";
|
||||
import { replacer } from "./replacer";
|
||||
|
||||
@@ -3,10 +3,9 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import xml from "xml";
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { IContext, XmlComponent } from "@file/xml-components";
|
||||
import { type XmlElement as Element, stringifyXmlable } from "@util/xml";
|
||||
|
||||
import { type IPatch, PatchType } from "./from-docx";
|
||||
import { findRunElementIndexWithToken, splitRunElement } from "./paragraph-split-inject";
|
||||
@@ -134,7 +133,7 @@ const formatChildren = (patch: IPatch, context: IContext, renumberIds: RenumberI
|
||||
// A child written as nothing in this part, such as a footnote's reference in a header, is left out
|
||||
.flatMap((c) => {
|
||||
const formatted = c.prepForXml(context);
|
||||
return formatted ? [toJson(xml(formatted)).elements![0]] : [];
|
||||
return formatted ? [toJson(stringifyXmlable(formatted)).elements![0]] : [];
|
||||
}),
|
||||
);
|
||||
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import type { ElementWrapper } from "./traverser";
|
||||
|
||||
|
||||
@@ -3,12 +3,11 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import xml from "xml";
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { createDefaultStyles } from "@file/styles/factory";
|
||||
import type { IContext } from "@file/xml-components";
|
||||
import { type XmlElement as Element, stringifyXmlable } from "@util/xml";
|
||||
|
||||
import { getFirstLevelElements, toJson } from "./util";
|
||||
|
||||
@@ -43,7 +42,7 @@ const nameOf = (style: Element): string | undefined => {
|
||||
const formatDefaultStyles = (context: IContext): ReadonlyMap<string, Element> =>
|
||||
new Map(
|
||||
Object.values(createDefaultStyles())
|
||||
.map((style) => toJson(xml(formatter.format(style, context))).elements![0])
|
||||
.map((style) => toJson(stringifyXmlable(formatter.format(style, context))).elements![0])
|
||||
// Rather than the document's defaults, which aren't a style
|
||||
.filter((style) => style.name === "w:style")
|
||||
.map((style) => [idOf(style), style]),
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { js2xml } from "xml-js";
|
||||
|
||||
import type { IViewWrapper } from "@file/document-wrapper";
|
||||
import type { File } from "@file/file";
|
||||
import { Paragraph, TextRun } from "@file/paragraph";
|
||||
import { stringifyElement } from "@util/xml";
|
||||
|
||||
import { findDrawingIds, renumberDrawingsAvoiding } from "./drawing-ids";
|
||||
import type { IPatch, TableRowsPatch } from "./from-docx";
|
||||
@@ -50,7 +50,7 @@ const tablesOf = (json: ReturnType<typeof toJson>): readonly (readonly (readonly
|
||||
t.elements!.filter((e) => e.name === "w:tr").map((r) => r.elements!.map((c) => traverse({ elements: [c] })[0]?.text ?? "")),
|
||||
);
|
||||
|
||||
const xmlOf = (json: ReturnType<typeof toJson>): string => js2xml(json);
|
||||
const xmlOf = (json: ReturnType<typeof toJson>): string => stringifyElement(json);
|
||||
|
||||
const ITEMS: TableRowsPatch = {
|
||||
type: PatchType.TABLE_ROWS,
|
||||
@@ -224,7 +224,7 @@ describe("patchTableRows", () => {
|
||||
|
||||
const [first, second] = json
|
||||
.elements![0].elements![0].elements!.filter((e) => e.name === "w:tr")
|
||||
.map((r) => js2xml({ elements: [r] }));
|
||||
.map((r) => stringifyElement({ elements: [r] }));
|
||||
expect(first).to.contain('w14:paraId="00000001"').and.contain('w14:paraId="00000003"').and.contain('<w:id w:val="7"/>');
|
||||
expect(first).to.contain('<w:bookmarkStart w:id="5" w:name="item"/>').and.contain('<w:bookmarkEnd w:id="5"/>');
|
||||
expect(second).not.to.match(/paraId|textId|w:id|bookmark/);
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import type { RenumberDrawings } from "./drawing-ids";
|
||||
import type { IPatch, TableRowsPatch } from "./from-docx";
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
*/
|
||||
// cspell:ignore hlink Hlink
|
||||
import type JSZip from "jszip";
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import { type ThemeColorValues, themeColorValues } from "@file/theme/color-scheme";
|
||||
import type { ThemeColorName } from "@file/theme/theme-color";
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import { resolveTarget } from "./drawing-patch";
|
||||
import { toJson } from "./util";
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { Element } from "xml-js";
|
||||
|
||||
import type { XmlElement as Element } from "@util/xml";
|
||||
|
||||
import { type IRenderedParagraphNode, renderParagraphNode } from "./run-renderer";
|
||||
|
||||
|
||||
+3
-4
@@ -3,11 +3,10 @@
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import xml from "xml";
|
||||
import { type Element, xml2js } from "xml-js";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { Text } from "@file/paragraph/run/run-components/text";
|
||||
import { type XmlElement as Element, parseXml, stringifyXmlable } from "@util/xml";
|
||||
|
||||
const formatter = new Formatter();
|
||||
|
||||
@@ -27,7 +26,7 @@ const formatter = new Formatter();
|
||||
* ```
|
||||
*/
|
||||
export const toJson = (xmlData: string): Element => {
|
||||
const xmlObj = xml2js(xmlData, { compact: false, captureSpacesBetweenElements: true }) as Element;
|
||||
const xmlObj = parseXml(xmlData, { keepWhitespaceText: true });
|
||||
return xmlObj;
|
||||
};
|
||||
|
||||
@@ -49,7 +48,7 @@ export const toJson = (xmlData: string): Element => {
|
||||
*/
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
export const createTextElementContents = (text: string): Element[] => {
|
||||
const textJson = toJson(xml(formatter.format(new Text({ text }))));
|
||||
const textJson = toJson(stringifyXmlable(formatter.format(new Text({ text }))));
|
||||
|
||||
return textJson.elements![0].elements ?? [];
|
||||
};
|
||||
|
||||
+4
-4
@@ -8,7 +8,6 @@
|
||||
// cspell:ignore IHDR IDAT IEND
|
||||
import JSZip from "jszip";
|
||||
import { deflateSync } from "node:zlib";
|
||||
import xml from "xml";
|
||||
|
||||
import { Formatter } from "@export/formatter";
|
||||
import { Packer } from "@export/packer/packer";
|
||||
@@ -16,6 +15,7 @@ import { File } from "@file/file";
|
||||
import type { Paragraph } from "@file/paragraph";
|
||||
import type { Table } from "@file/table";
|
||||
import type { IContext } from "@file/xml-components";
|
||||
import { stringifyXmlable } from "@util/xml";
|
||||
|
||||
/**
|
||||
* Written content with its ids made the same each time: relationships', bookmarks', tracked changes' and drawings'
|
||||
@@ -37,7 +37,7 @@ const contextOf = (): IContext => {
|
||||
/** Paragraphs and tables written as WordprocessingML, in one document */
|
||||
export const written = (children: readonly (Paragraph | Table)[]): string => {
|
||||
const context = contextOf();
|
||||
return children.map((child) => xml(new Formatter().format(child, context))).join("");
|
||||
return children.map((child) => stringifyXmlable(new Formatter().format(child, context))).join("");
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -53,10 +53,10 @@ export const formattedWithNotes = (
|
||||
children: readonly (Paragraph | Table)[],
|
||||
): { readonly body: string; readonly footnotes: string; readonly endnotes: string } => {
|
||||
const context = contextOf();
|
||||
const body = children.map((child) => xml(new Formatter().format(child, context))).join("");
|
||||
const body = children.map((child) => stringifyXmlable(new Formatter().format(child, context))).join("");
|
||||
const notesOf = (wrapper: typeof context.file.FootNotes | typeof context.file.Endnotes, kind: string): string =>
|
||||
[
|
||||
...xml(new Formatter().format(wrapper.View, { ...context, viewWrapper: wrapper })).matchAll(
|
||||
...stringifyXmlable(new Formatter().format(wrapper.View, { ...context, viewWrapper: wrapper })).matchAll(
|
||||
new RegExp(`<w:${kind} w:id="\\d+">.*?</w:${kind}>`, "g"),
|
||||
),
|
||||
]
|
||||
|
||||
@@ -9,3 +9,4 @@
|
||||
export * from "./convenience-functions";
|
||||
export * from "./values";
|
||||
export type * from "./output-type";
|
||||
export type * from "./xml/types";
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
import JSZip from "jszip";
|
||||
import type { ImportGlobFunction } from "vite";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseXml } from "./parse";
|
||||
import { stringifyElement } from "./stringify";
|
||||
import type { XmlElement } from "./types";
|
||||
|
||||
/**
|
||||
* Checks parseXml and stringifyElement against every XML part in the repository: the parts of each Word document, such
|
||||
* as those Word saved for the layout probes, and the OOXML schemas. jsdom's DOMParser, a separate XML parser, says what
|
||||
* each part holds, so a mistake parseXml and stringifyElement make alike still shows.
|
||||
*/
|
||||
|
||||
declare global {
|
||||
// Vite's own types for import.meta, vite/client, would type every "?raw" import, which other specs expect not to be
|
||||
// typed
|
||||
// eslint-disable-next-line @typescript-eslint/consistent-type-definitions
|
||||
interface ImportMeta {
|
||||
readonly glob: ImportGlobFunction;
|
||||
}
|
||||
}
|
||||
|
||||
// Vite gives each document as a data URL, and each schema as text
|
||||
const documents = import.meta.glob<string>(["/demo/assets/*.{docx,dotx}", "/scripts/layout-probes/**/*.docx"], {
|
||||
query: "?inline",
|
||||
import: "default",
|
||||
});
|
||||
const texts = import.meta.glob<string>(["/ooxml-schemas/**/*.xsd", "/demo/assets/*.xml"], {
|
||||
query: "?raw",
|
||||
import: "default",
|
||||
eager: true,
|
||||
});
|
||||
|
||||
/**
|
||||
* The largest part read. The parts over it, a dozen of the layout probes' documents, each repeat one run thousands of
|
||||
* times to measure Word's character widths. They hold nothing the smaller parts don't, and jsdom takes seconds over each.
|
||||
*/
|
||||
const MAX_PART_LENGTH = 1_000_000;
|
||||
|
||||
const partsOf = async (dataUrl: string): Promise<ReadonlyMap<string, string>> => {
|
||||
const zip = await JSZip.loadAsync(dataUrl.slice(dataUrl.indexOf(",") + 1), { base64: true });
|
||||
const names = Object.keys(zip.files).filter((name) => name.endsWith(".xml") || name.endsWith(".rels"));
|
||||
const parts = await Promise.all(names.map(async (name) => [name, await zip.file(name)!.async("string")] as const));
|
||||
return new Map(parts.filter(([, xml]) => xml.length <= MAX_PART_LENGTH));
|
||||
};
|
||||
|
||||
/** A node of the DOM as parseXml reads it */
|
||||
const fromDom = (node: Node): XmlElement | undefined => {
|
||||
switch (node.nodeType) {
|
||||
case Node.ELEMENT_NODE: {
|
||||
const element = node as Element;
|
||||
const attributes = Object.fromEntries([...element.attributes].map(({ name, value }) => [name, value]));
|
||||
const elements = [...element.childNodes].map(fromDom).filter((child) => child !== undefined);
|
||||
return {
|
||||
type: "element",
|
||||
name: element.tagName,
|
||||
...(Object.keys(attributes).length > 0 ? { attributes } : {}),
|
||||
...(elements.length > 0 ? { elements } : {}),
|
||||
};
|
||||
}
|
||||
case Node.TEXT_NODE:
|
||||
return { type: "text", text: (node as Text).data };
|
||||
case Node.CDATA_SECTION_NODE:
|
||||
return (node as CDATASection).data === "" ? undefined : { type: "cdata", cdata: (node as CDATASection).data };
|
||||
case Node.COMMENT_NODE:
|
||||
return (node as Comment).data === "" ? undefined : { type: "comment", comment: (node as Comment).data };
|
||||
case Node.PROCESSING_INSTRUCTION_NODE:
|
||||
return { type: "instruction", name: (node as ProcessingInstruction).target, instruction: (node as ProcessingInstruction).data };
|
||||
default:
|
||||
return { type: "doctype" };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* A node with each line break as "\n". XML parsers such as jsdom's read "\r\n" as "\n", but parseXml keeps it, as
|
||||
* xml-js did, so that patchDocument writes a template's text back as it was.
|
||||
*/
|
||||
const withLineFeeds = (node: XmlElement): XmlElement => {
|
||||
const lineFeeds = (value: string): string => value.replace(/\r\n?/g, "\n");
|
||||
switch (node.type) {
|
||||
case "element":
|
||||
return {
|
||||
...node,
|
||||
...(node.attributes
|
||||
? {
|
||||
attributes: Object.fromEntries(
|
||||
Object.entries(node.attributes).map(([key, value]) => [key, lineFeeds(String(value))]),
|
||||
),
|
||||
}
|
||||
: {}),
|
||||
...(node.elements ? { elements: node.elements.map(withLineFeeds) } : {}),
|
||||
};
|
||||
case "text":
|
||||
return { ...node, text: lineFeeds(String(node.text)) };
|
||||
case "cdata":
|
||||
return { ...node, cdata: lineFeeds(node.cdata!) };
|
||||
case "comment":
|
||||
return { ...node, comment: lineFeeds(node.comment!) };
|
||||
case "instruction":
|
||||
return { ...node, instruction: lineFeeds(node.instruction!) };
|
||||
default:
|
||||
// The DOM keeps a DOCTYPE's name and identifiers, not its text
|
||||
return { type: node.type };
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* The nodes of a document as the DOM has them: without the declaration, which the DOM has no node for, or the whitespace
|
||||
* between the top-level nodes
|
||||
*/
|
||||
const comparable = (document: XmlElement): readonly XmlElement[] =>
|
||||
(document.elements ?? []).filter(({ type }) => type !== "text").map(withLineFeeds);
|
||||
|
||||
const check = (xml: string, part: string): void => {
|
||||
const dom = new DOMParser().parseFromString(xml, "application/xml");
|
||||
expect(dom.getElementsByTagName("parsererror"), `jsdom can't read ${part}`).to.have.length(0);
|
||||
|
||||
const parsed = parseXml(xml, { keepWhitespaceText: true });
|
||||
expect(comparable(parsed), part).to.deep.equal([...dom.childNodes].map(fromDom));
|
||||
expect(parseXml(stringifyElement(parsed), { keepWhitespaceText: true }), `${part}, written and read again`).to.deep.equal(parsed);
|
||||
};
|
||||
|
||||
describe("parseXml and stringifyElement with the repository's XML", () => {
|
||||
describe("documents", () => {
|
||||
for (const [path, load] of Object.entries(documents)) {
|
||||
it(`should read and write each part of ${path} as jsdom reads it`, async () => {
|
||||
for (const [name, xml] of await partsOf(await load())) {
|
||||
check(xml, name);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe("schemas", () => {
|
||||
for (const [path, xml] of Object.entries(texts)) {
|
||||
it(`should read and write ${path} as jsdom reads it`, () => {
|
||||
check(xml, path);
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Reading and writing XML.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
export * from "./parse";
|
||||
export * from "./stringify";
|
||||
export type * from "./types";
|
||||
@@ -0,0 +1,177 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { parseXml } from "./parse";
|
||||
|
||||
describe("parseXml", () => {
|
||||
describe("the document", () => {
|
||||
it("should read the declaration's attributes, in either quotes, before the nodes", () => {
|
||||
const document = parseXml(`<?xml version="1.0" encoding='UTF-8' standalone="yes"?><a/>`);
|
||||
expect(document).to.deep.equal({
|
||||
declaration: { attributes: { version: "1.0", encoding: "UTF-8", standalone: "yes" } },
|
||||
elements: [{ type: "element", name: "a" }],
|
||||
});
|
||||
expect(Object.keys(document)).to.deep.equal(["declaration", "elements"]);
|
||||
});
|
||||
|
||||
it("should read a declaration without attributes", () => {
|
||||
expect(parseXml("<?xml?><a/>")).to.deep.equal({ declaration: {}, elements: [{ type: "element", name: "a" }] });
|
||||
});
|
||||
|
||||
it("should read nothing from an empty string", () => {
|
||||
expect(parseXml("")).to.deep.equal({});
|
||||
});
|
||||
|
||||
it("should skip a byte order mark and the whitespace before the first tag", () => {
|
||||
expect(parseXml("\uFEFF \r\n<a/>", { keepWhitespaceText: true })).to.deep.equal({ elements: [{ type: "element", name: "a" }] });
|
||||
});
|
||||
|
||||
it("should read elements one after another at the top level", () => {
|
||||
expect(parseXml("<a/><b/>")).to.deep.equal({
|
||||
elements: [
|
||||
{ type: "element", name: "a" },
|
||||
{ type: "element", name: "b" },
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("elements", () => {
|
||||
it("should read nested elements and their attributes", () => {
|
||||
expect(parseXml(`<w:p w14:paraId="1A"><w:r><w:t xml:space='preserve'>Hi</w:t></w:r><w:r/></w:p>`)).to.deep.equal({
|
||||
elements: [
|
||||
{
|
||||
type: "element",
|
||||
name: "w:p",
|
||||
attributes: { "w14:paraId": "1A" },
|
||||
elements: [
|
||||
{
|
||||
type: "element",
|
||||
name: "w:r",
|
||||
elements: [
|
||||
{
|
||||
type: "element",
|
||||
name: "w:t",
|
||||
attributes: { "xml:space": "preserve" },
|
||||
elements: [{ type: "text", text: "Hi" }],
|
||||
},
|
||||
],
|
||||
},
|
||||
{ type: "element", name: "w:r" },
|
||||
],
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
it("should allow whitespace between attributes, around their equals signs and in tags", () => {
|
||||
expect(parseXml(`<a\n b = "1"\tc='2'\n/><d ></d >`).elements).to.deep.equal([
|
||||
{ type: "element", name: "a", attributes: { b: "1", c: "2" } },
|
||||
{ type: "element", name: "d" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should keep the first of attributes with the same name", () => {
|
||||
expect(parseXml(`<a b="1" b="2"/>`).elements![0].attributes).to.deep.equal({ b: "1" });
|
||||
});
|
||||
|
||||
it("should decode entities in attributes, and keep their whitespace", () => {
|
||||
expect(parseXml(`<a b="&"<\n\tA"/>`).elements![0].attributes).to.deep.equal({ b: '&"<\n\tA' });
|
||||
});
|
||||
|
||||
it("should read an attribute named __proto__ as an attribute, not the prototype", () => {
|
||||
const { attributes } = parseXml(`<a __proto__="x" constructor="y"/>`).elements![0];
|
||||
expect(Object.keys(attributes!)).to.deep.equal(["__proto__", "constructor"]);
|
||||
expect(Object.getPrototypeOf(attributes)).to.equal(Object.prototype);
|
||||
});
|
||||
|
||||
it("should throw for elements that aren't well formed", () => {
|
||||
expect(() => parseXml("<a>")).to.throw("<a> isn't closed");
|
||||
expect(() => parseXml("<a")).to.throw("<a> that isn't closed");
|
||||
expect(() => parseXml(`<a b="1"`)).to.throw("<a> that isn't closed");
|
||||
expect(() => parseXml("<>")).to.throw("tag without a name");
|
||||
expect(() => parseXml("<a><b></a>")).to.throw("closing tag </a> doesn't match <b>");
|
||||
expect(() => parseXml("</a>")).to.throw("closing tag </a> doesn't match <>");
|
||||
expect(() => parseXml("<a></a")).to.throw("closing tag that isn't closed");
|
||||
});
|
||||
|
||||
it("should throw for attributes that aren't well formed", () => {
|
||||
expect(() => parseXml("<a b>")).to.throw("attribute of <a> without a value");
|
||||
expect(() => parseXml(`<a b c="1">`)).to.throw("attribute of <a> without a value");
|
||||
expect(() => parseXml(`<a ="1">`)).to.throw("attribute of <a> without a value");
|
||||
expect(() => parseXml("<a b=1/>")).to.throw("value of b on <a> isn't quoted");
|
||||
expect(() => parseXml(`<a b="1/>`)).to.throw("value of b on <a> isn't closed");
|
||||
});
|
||||
});
|
||||
|
||||
describe("text", () => {
|
||||
it("should decode the entities XML predefines and character references", () => {
|
||||
expect(parseXml("<a>&<>"'ABC😀</a>").elements![0].elements).to.deep.equal([
|
||||
{ type: "text", text: `&<>"'ABC\u{1F600}` },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should throw for an entity XML doesn't predefine, or a character reference to no character", () => {
|
||||
expect(() => parseXml("<a> </a>")).to.throw('unknown entity " "');
|
||||
expect(() => parseXml("<a>�</a>")).to.throw('unknown entity "�"');
|
||||
expect(() => parseXml("<a>�</a>")).to.throw('unknown entity "�"');
|
||||
expect(() => parseXml("<a>&#xZ;</a>")).to.throw('unknown entity "&#xZ;"');
|
||||
});
|
||||
|
||||
it("should throw for an & that starts no entity", () => {
|
||||
expect(() => parseXml("<a>Fish & chips</a>")).to.throw('"&" that starts no entity');
|
||||
});
|
||||
|
||||
it("should leave out text that is only whitespace, unless told to keep it", () => {
|
||||
const xml = `<?xml version="1.0"?>\r\n<a> <b/>\n</a>\n`;
|
||||
expect(parseXml(xml).elements).to.deep.equal([{ type: "element", name: "a", elements: [{ type: "element", name: "b" }] }]);
|
||||
expect(parseXml(xml, { keepWhitespaceText: true }).elements).to.deep.equal([
|
||||
{ type: "text", text: "\r\n" },
|
||||
{
|
||||
type: "element",
|
||||
name: "a",
|
||||
elements: [
|
||||
{ type: "text", text: " " },
|
||||
{ type: "element", name: "b" },
|
||||
{ type: "text", text: "\n" },
|
||||
],
|
||||
},
|
||||
{ type: "text", text: "\n" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should throw for text outside of the root element", () => {
|
||||
expect(() => parseXml("text<a/>")).to.throw('text outside of the root element, "text"');
|
||||
expect(() => parseXml("<a/>text")).to.throw('text outside of the root element, "text"');
|
||||
});
|
||||
});
|
||||
|
||||
describe("other nodes", () => {
|
||||
it("should read processing instructions, with and without a body", () => {
|
||||
expect(parseXml(`<?mso-application progid="Word.Document"?><a><?pi?></a>`).elements).to.deep.equal([
|
||||
{ type: "instruction", name: "mso-application", instruction: 'progid="Word.Document"' },
|
||||
{ type: "element", name: "a", elements: [{ type: "instruction", name: "pi", instruction: "" }] },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should read comments and CDATA sections, leaving out empty ones", () => {
|
||||
expect(parseXml("<a><!-- c --><!----><![CDATA[x<y&]]><![CDATA[]]></a>").elements![0].elements).to.deep.equal([
|
||||
{ type: "comment", comment: " c " },
|
||||
{ type: "cdata", cdata: "x<y&" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should read a DOCTYPE to its end, past the > and ] in its internal subset and quotes", () => {
|
||||
expect(parseXml(`<!DOCTYPE a [ <!ENTITY x "y>"> <!ENTITY z ']'> ]><a/>`).elements).to.deep.equal([
|
||||
{ type: "doctype", doctype: `a [ <!ENTITY x "y>"> <!ENTITY z ']'> ]` },
|
||||
{ type: "element", name: "a" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("should throw for nodes that aren't closed", () => {
|
||||
expect(() => parseXml("<?xml version")).to.throw("processing instruction that isn't closed");
|
||||
expect(() => parseXml("<a><!-- c")).to.throw("comment that isn't closed");
|
||||
expect(() => parseXml("<a><![CDATA[x")).to.throw("CDATA section that isn't closed");
|
||||
expect(() => parseXml("<!DOCTYPE a [ > ")).to.throw("DOCTYPE that isn't closed");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,263 @@
|
||||
/**
|
||||
* Reads XML into an {@link XmlElement} tree.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { XmlAttributes, XmlDeclarationAttributes, XmlElement } from "./types";
|
||||
|
||||
/**
|
||||
* Options for {@link parseXml}.
|
||||
*/
|
||||
export type ParseXmlOptions = {
|
||||
/**
|
||||
* Keep text that is only whitespace, such as the space in `<w:t xml:space="preserve"> </w:t>` or the line breaks
|
||||
* between elements. Without it, such text is left out.
|
||||
*/
|
||||
readonly keepWhitespaceText?: boolean;
|
||||
};
|
||||
|
||||
const PREDEFINED_ENTITIES: ReadonlyMap<string, string> = new Map([
|
||||
["amp", "&"],
|
||||
["lt", "<"],
|
||||
["gt", ">"],
|
||||
["quot", '"'],
|
||||
["apos", "'"], // cspell:words apos
|
||||
]);
|
||||
|
||||
const ENTITY_REFERENCE = /&([^;]*);?/g;
|
||||
|
||||
/**
|
||||
* Decodes the five entities XML predefines and character references, such as ` `. XML that declares entities of
|
||||
* its own in a DTD is not supported, so that no input can expand into more than it holds.
|
||||
*/
|
||||
const decodeEntities = (raw: string): string =>
|
||||
raw.indexOf("&") === -1
|
||||
? raw
|
||||
: raw.replace(ENTITY_REFERENCE, (reference: string, name: string) => {
|
||||
if (!reference.endsWith(";")) {
|
||||
throw new Error(`Invalid XML: "&" that starts no entity, in "${raw}"`);
|
||||
}
|
||||
const predefined = PREDEFINED_ENTITIES.get(name);
|
||||
if (predefined !== undefined) {
|
||||
return predefined;
|
||||
}
|
||||
const codePoint = /^#x[0-9a-f]+$/i.test(name)
|
||||
? parseInt(name.slice(2), 16)
|
||||
: /^#[0-9]+$/.test(name)
|
||||
? parseInt(name.slice(1), 10)
|
||||
: Number.NaN;
|
||||
if (!(codePoint > 0 && codePoint <= 0x10ffff)) {
|
||||
throw new Error(`Invalid XML: unknown entity "${reference}"`);
|
||||
}
|
||||
return String.fromCodePoint(codePoint);
|
||||
});
|
||||
|
||||
const isWhitespace = (char: string): boolean => char === " " || char === "\n" || char === "\t" || char === "\r";
|
||||
|
||||
const DECLARATION_ATTRIBUTE = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g;
|
||||
|
||||
const parseDeclarationAttributes = (body: string): XmlDeclarationAttributes =>
|
||||
Object.fromEntries(
|
||||
[...body.matchAll(DECLARATION_ATTRIBUTE)].map(([, name, doubleQuoted, singleQuoted]) => [name, doubleQuoted ?? singleQuoted]),
|
||||
);
|
||||
|
||||
/**
|
||||
* Reads XML into a tree of {@link XmlElement}s, the shape xml-js gave for `xml2js(text)`.
|
||||
*
|
||||
* Throws on XML that isn't well formed, such as an element that isn't closed or an entity XML doesn't predefine.
|
||||
*
|
||||
* @param text - The XML
|
||||
* @param options - Whether to keep text that is only whitespace
|
||||
* @returns The document, with its declaration and the nodes at its top level
|
||||
*/
|
||||
export const parseXml = (text: string, { keepWhitespaceText = false }: ParseXmlOptions = {}): XmlElement => {
|
||||
// The tree is built in place, as a document's body can have thousands of children
|
||||
const document: XmlElement = {};
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const open: XmlElement[] = [];
|
||||
let position = text.charCodeAt(0) === 0xfeff ? 1 : 0;
|
||||
|
||||
// Whitespace before the first tag isn't part of the document
|
||||
while (position < text.length && isWhitespace(text[position])) {
|
||||
position++;
|
||||
}
|
||||
|
||||
const append = (node: XmlElement): void => {
|
||||
const parent = open.length === 0 ? document : open[open.length - 1];
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
(parent.elements ??= []).push(node);
|
||||
};
|
||||
|
||||
const appendText = (raw: string): void => {
|
||||
if (raw.trim() === "") {
|
||||
if (raw !== "" && keepWhitespaceText) {
|
||||
append({ type: "text", text: raw });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (open.length === 0) {
|
||||
throw new Error(`Invalid XML: text outside of the root element, "${raw.trim()}"`);
|
||||
}
|
||||
append({ type: "text", text: decodeEntities(raw) });
|
||||
};
|
||||
|
||||
const indexOfOrThrow = (search: string, from: number, what: string): number => {
|
||||
const index = text.indexOf(search, from);
|
||||
if (index === -1) {
|
||||
throw new Error(`Invalid XML: ${what} that isn't closed`);
|
||||
}
|
||||
return index;
|
||||
};
|
||||
|
||||
while (position < text.length) {
|
||||
const tagStart = text.indexOf("<", position);
|
||||
appendText(text.slice(position, tagStart === -1 ? text.length : tagStart));
|
||||
if (tagStart === -1) {
|
||||
break;
|
||||
}
|
||||
|
||||
if (text.startsWith("<?", tagStart)) {
|
||||
const end = indexOfOrThrow("?>", tagStart + 2, "processing instruction");
|
||||
const content = text.slice(tagStart + 2, end);
|
||||
const nameEnd = content.search(/\s/);
|
||||
const name = nameEnd === -1 ? content : content.slice(0, nameEnd);
|
||||
const body = nameEnd === -1 ? "" : content.slice(nameEnd).trimStart();
|
||||
if (name.toLowerCase() === "xml") {
|
||||
const attributes = parseDeclarationAttributes(body);
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
document.declaration = Object.keys(attributes).length > 0 ? { attributes } : {};
|
||||
} else {
|
||||
append({ type: "instruction", name, instruction: body });
|
||||
}
|
||||
position = end + 2;
|
||||
} else if (text.startsWith("<!--", tagStart)) {
|
||||
const end = indexOfOrThrow("-->", tagStart + 4, "comment");
|
||||
const comment = text.slice(tagStart + 4, end);
|
||||
if (comment !== "") {
|
||||
append({ type: "comment", comment });
|
||||
}
|
||||
position = end + 3;
|
||||
} else if (text.startsWith("<![CDATA[", tagStart)) {
|
||||
const end = indexOfOrThrow("]]>", tagStart + 9, "CDATA section");
|
||||
const cdata = text.slice(tagStart + 9, end);
|
||||
if (cdata !== "") {
|
||||
append({ type: "cdata", cdata });
|
||||
}
|
||||
position = end + 3;
|
||||
} else if (text.startsWith("<!DOCTYPE", tagStart)) {
|
||||
// The DOCTYPE ends at the first ">" that isn't in its internal subset, between "[" and "]", or quoted
|
||||
let end = tagStart + 9;
|
||||
let quote: string | undefined;
|
||||
let inSubset = false;
|
||||
for (; end < text.length; end++) {
|
||||
const char = text[end];
|
||||
if (quote !== undefined) {
|
||||
quote = char === quote ? undefined : quote;
|
||||
} else if (char === '"' || char === "'") {
|
||||
quote = char;
|
||||
} else if (char === "[") {
|
||||
inSubset = true;
|
||||
} else if (char === "]") {
|
||||
inSubset = false;
|
||||
} else if (char === ">" && !inSubset) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (end === text.length) {
|
||||
throw new Error("Invalid XML: DOCTYPE that isn't closed");
|
||||
}
|
||||
append({ type: "doctype", doctype: text.slice(tagStart + 9, end).replace(/^ /, "") });
|
||||
position = end + 1;
|
||||
} else if (text.startsWith("</", tagStart)) {
|
||||
const end = indexOfOrThrow(">", tagStart + 2, "closing tag");
|
||||
const name = text.slice(tagStart + 2, end).trimEnd();
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
const element = open.pop();
|
||||
if (element?.name !== name) {
|
||||
throw new Error(`Invalid XML: closing tag </${name}> doesn't match <${element?.name ?? ""}>`);
|
||||
}
|
||||
position = end + 1;
|
||||
} else {
|
||||
position = parseStartTag(text, tagStart + 1, (element, selfClosing) => {
|
||||
append(element);
|
||||
if (!selfClosing) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
open.push(element);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (open.length > 0) {
|
||||
throw new Error(`Invalid XML: <${open[open.length - 1].name}> isn't closed`);
|
||||
}
|
||||
|
||||
// xml-js gave the declaration before the nodes
|
||||
const { elements, ...rest } = document;
|
||||
return elements === undefined ? rest : { ...rest, elements };
|
||||
};
|
||||
|
||||
/**
|
||||
* Reads a start tag from just after its "<", such as `w:p w14:paraId="1A2B3C4D">` or `w:br/>`.
|
||||
*
|
||||
* @returns The position just after the tag's ">"
|
||||
*/
|
||||
const parseStartTag = (text: string, from: number, onElement: (element: XmlElement, selfClosing: boolean) => void): number => {
|
||||
let nameEnd = from;
|
||||
while (nameEnd < text.length && !isWhitespace(text[nameEnd]) && text[nameEnd] !== "/" && text[nameEnd] !== ">") {
|
||||
nameEnd++;
|
||||
}
|
||||
const name = text.slice(from, nameEnd);
|
||||
if (name === "") {
|
||||
throw new Error("Invalid XML: tag without a name");
|
||||
}
|
||||
|
||||
// Entries, not an object, so that an attribute such as __proto__ is one of them rather than the object's prototype
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const attributes: (readonly [string, string])[] = [];
|
||||
let position = nameEnd;
|
||||
for (;;) {
|
||||
while (position < text.length && isWhitespace(text[position])) {
|
||||
position++;
|
||||
}
|
||||
if (position >= text.length) {
|
||||
throw new Error(`Invalid XML: <${name}> that isn't closed`);
|
||||
}
|
||||
if (text[position] === ">" || text.startsWith("/>", position)) {
|
||||
const selfClosing = text[position] === "/";
|
||||
onElement(
|
||||
{
|
||||
type: "element",
|
||||
name,
|
||||
...(attributes.length > 0 ? { attributes: Object.fromEntries(attributes) as XmlAttributes } : {}),
|
||||
},
|
||||
selfClosing,
|
||||
);
|
||||
return position + (selfClosing ? 2 : 1);
|
||||
}
|
||||
|
||||
const equals = text.indexOf("=", position);
|
||||
const attributeName = text.slice(position, equals === -1 ? text.length : equals).trimEnd();
|
||||
if (equals === -1 || attributeName === "" || /[\s/>]/.test(attributeName)) {
|
||||
throw new Error(`Invalid XML: attribute of <${name}> without a value`);
|
||||
}
|
||||
let valueStart = equals + 1;
|
||||
while (valueStart < text.length && isWhitespace(text[valueStart])) {
|
||||
valueStart++;
|
||||
}
|
||||
const quote = text[valueStart];
|
||||
if (quote !== '"' && quote !== "'") {
|
||||
throw new Error(`Invalid XML: value of ${attributeName} on <${name}> isn't quoted`);
|
||||
}
|
||||
const valueEnd = text.indexOf(quote, valueStart + 1);
|
||||
if (valueEnd === -1) {
|
||||
throw new Error(`Invalid XML: value of ${attributeName} on <${name}> isn't closed`);
|
||||
}
|
||||
// Like xml-js, the first of attributes with the same name is kept
|
||||
if (!attributes.some(([existing]) => existing === attributeName)) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
attributes.push([attributeName, decodeEntities(text.slice(valueStart + 1, valueEnd))]);
|
||||
}
|
||||
position = valueEnd + 1;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,136 @@
|
||||
// cspell:words apos
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { stringifyElement, stringifyXmlable } from "./stringify";
|
||||
import type { XmlElement } from "./types";
|
||||
|
||||
describe("stringifyXmlable", () => {
|
||||
it("should write elements with attributes, children and text", () => {
|
||||
expect(
|
||||
stringifyXmlable({
|
||||
"w:p": [
|
||||
{ _attr: { "w14:paraId": "1A" } },
|
||||
{ "w:r": [{ "w:t": [{ _attr: { "xml:space": "preserve" } }, "Hi"] }] },
|
||||
{ "w:r": {} },
|
||||
],
|
||||
}),
|
||||
).to.equal('<w:p w14:paraId="1A"><w:r><w:t xml:space="preserve">Hi</w:t></w:r><w:r/></w:p>');
|
||||
});
|
||||
|
||||
it("should write an element's value, whatever its type", () => {
|
||||
expect(stringifyXmlable({ a: "text" })).to.equal("<a>text</a>");
|
||||
expect(stringifyXmlable({ a: 5 })).to.equal("<a>5</a>");
|
||||
expect(stringifyXmlable({ a: true })).to.equal("<a>true</a>");
|
||||
expect(stringifyXmlable({ a: "" })).to.equal("<a></a>");
|
||||
expect(stringifyXmlable({ a: undefined })).to.equal("<a></a>");
|
||||
expect(stringifyXmlable({ a: null })).to.equal("<a/>");
|
||||
expect(stringifyXmlable({ a: [] })).to.equal("<a></a>");
|
||||
expect(stringifyXmlable({ a: [5] })).to.equal("<a>5</a>");
|
||||
expect(stringifyXmlable({ a: { _attr: { b: 1, c: false, d: "x" } } })).to.equal('<a b="1" c="false" d="x"/>');
|
||||
expect(stringifyXmlable({})).to.equal("");
|
||||
});
|
||||
|
||||
it("should escape text and attributes", () => {
|
||||
expect(stringifyXmlable({ a: [{ _attr: { b: `&"'<>` } }, `&"'<>`] })).to.equal(
|
||||
'<a b="&"'<>">&"'<></a>',
|
||||
);
|
||||
});
|
||||
|
||||
it("should write CDATA, splitting it at each ]]>", () => {
|
||||
expect(stringifyXmlable({ a: { _cdata: "x]]>y" } })).to.equal("<a><![CDATA[x]]]]><![CDATA[>y]]></a>");
|
||||
});
|
||||
|
||||
it("should let text take the place of what came before it, as the xml package did", () => {
|
||||
expect(stringifyXmlable({ a: [{ b: {} }, "text"] })).to.equal("<a>text</a>");
|
||||
expect(stringifyXmlable({ a: ["one", "two"] })).to.equal("<a>two</a>");
|
||||
});
|
||||
|
||||
it("should write a declaration first", () => {
|
||||
expect(stringifyXmlable({ a: {} }, { declaration: { standalone: "yes", encoding: "UTF-8" } })).to.equal(
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?><a/>',
|
||||
);
|
||||
expect(stringifyXmlable({ a: {} }, { declaration: {} })).to.equal('<?xml version="1.0" encoding="UTF-8"?><a/>');
|
||||
});
|
||||
|
||||
it("should write several objects one after another", () => {
|
||||
expect(stringifyXmlable([{ a: {} }, { b: "x" }])).to.equal("<a/><b>x</b>");
|
||||
});
|
||||
|
||||
it("should indent each level, as the xml package did", () => {
|
||||
expect(
|
||||
stringifyXmlable(
|
||||
{ a: [{ _attr: { x: 1 } }, { b: [{ c: "text" }, { d: {} }] }, { e: [] }] },
|
||||
{ indent: " ", declaration: { standalone: "yes" } },
|
||||
),
|
||||
).to.equal(
|
||||
[
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>',
|
||||
'<a x="1">',
|
||||
" <b>",
|
||||
" <c>text</c>",
|
||||
" <d/>",
|
||||
" </b>",
|
||||
" <e>",
|
||||
" </e>",
|
||||
"</a>",
|
||||
].join("\n"),
|
||||
);
|
||||
expect(stringifyXmlable([{ a: {} }, { b: "x" }], { indent: " " })).to.equal("<a/>\n<b>x</b>");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stringifyElement", () => {
|
||||
it("should write a document's declaration and nodes", () => {
|
||||
const document: XmlElement = {
|
||||
declaration: { attributes: { version: "1.0", standalone: "yes" } },
|
||||
elements: [
|
||||
{ type: "instruction", name: "mso-application", instruction: 'progid="Word.Document"' },
|
||||
{ type: "doctype", doctype: "a" },
|
||||
{
|
||||
type: "element",
|
||||
name: "a",
|
||||
attributes: { b: "1", c: 2, d: undefined },
|
||||
elements: [
|
||||
{ type: "element", name: "empty" },
|
||||
{ type: "element", name: "w:t", attributes: { "xml:space": "preserve" } },
|
||||
{ type: "text", text: 5 },
|
||||
{ type: "comment", comment: " c " },
|
||||
{ type: "cdata", cdata: "x]]>y" },
|
||||
{ type: "instruction", name: "pi" },
|
||||
{ type: "element", name: "children", elements: [{ type: "text", text: "t" }] },
|
||||
{ type: "unknown" },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
expect(stringifyElement(document)).to.equal(
|
||||
'<?xml version="1.0" standalone="yes"?><?mso-application progid="Word.Document"?><!DOCTYPE a><a b="1" c="2">' +
|
||||
'<empty/><w:t xml:space="preserve"></w:t>5<!-- c --><![CDATA[x]]]]><![CDATA[>y]]><?pi?><children>t</children></a>',
|
||||
);
|
||||
});
|
||||
|
||||
it("should escape text and attributes, so that what is read is written back as it was", () => {
|
||||
expect(
|
||||
stringifyElement({
|
||||
elements: [
|
||||
{
|
||||
type: "element",
|
||||
name: "a",
|
||||
attributes: { b: `& &"'<>` },
|
||||
elements: [{ type: "text", text: `& &"'<>` }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
).to.equal(`<a b="&amp; &"'<>">&amp; &"'<></a>`);
|
||||
});
|
||||
|
||||
it("should leave out attributes without a value", () => {
|
||||
expect(stringifyElement({ elements: [{ type: "element", name: "a", attributes: { b: null as unknown as string } }] })).to.equal(
|
||||
"<a/>",
|
||||
);
|
||||
});
|
||||
|
||||
it("should write nothing for an empty document", () => {
|
||||
expect(stringifyElement({})).to.equal("");
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* Writes XML, from the objects docx's `Formatter` makes or from an {@link XmlElement} tree.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
import type { IXmlableObject } from "@file/xml-components/xmlable-object";
|
||||
|
||||
import type { XmlElement } from "./types";
|
||||
|
||||
const ESCAPES: ReadonlyMap<string, string> = new Map([
|
||||
["&", "&"],
|
||||
['"', """],
|
||||
["'", "'"], // cspell:words apos
|
||||
["<", "<"],
|
||||
[">", ">"],
|
||||
]);
|
||||
|
||||
const escapeAll = (value: string): string => value.replace(/[&"'<>]/g, (char) => ESCAPES.get(char)!);
|
||||
|
||||
const escapeText = (value: string): string => value.replace(/[&<>]/g, (char) => ESCAPES.get(char)!);
|
||||
|
||||
/**
|
||||
* Escapes a value the way the xml package did, leaving values that aren't strings, such as numbers, as they are.
|
||||
*/
|
||||
const escapeValue = <T>(value: T): T | string => (typeof value === "string" ? escapeAll(value) : value);
|
||||
|
||||
/**
|
||||
* Options for {@link stringifyXmlable}.
|
||||
*/
|
||||
export type StringifyXmlableOptions = {
|
||||
/** What to indent each level with, such as two spaces. Without it, the XML is written on one line. */
|
||||
readonly indent?: string;
|
||||
/** Write an XML declaration first, with these attributes. */
|
||||
readonly declaration?: { readonly encoding?: string; readonly standalone?: string };
|
||||
};
|
||||
|
||||
type ResolvedContent = ResolvedElement | string | number | boolean | undefined;
|
||||
|
||||
type ResolvedElement = {
|
||||
readonly name: string | undefined;
|
||||
readonly attributes: readonly string[];
|
||||
readonly content: readonly ResolvedContent[];
|
||||
readonly indents: string;
|
||||
};
|
||||
|
||||
/**
|
||||
* Works out an element's tag, attributes and content, as the xml package did, quirks and all, so that docx writes the
|
||||
* same XML byte for byte.
|
||||
*/
|
||||
const resolve = (data: object, indent: string, depth: number): ResolvedElement => {
|
||||
// An empty object has no name, and writes nothing
|
||||
const name = Object.keys(data)[0] as string | undefined;
|
||||
const values: unknown = name === undefined ? undefined : (data as Record<string, unknown>)[name];
|
||||
|
||||
// Built in place, as an element of a document's body can have thousands of children
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const attributes: string[] = [];
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const content: ResolvedContent[] = [];
|
||||
const addAttributes = (attr: Readonly<Record<string, unknown>>): void => {
|
||||
for (const [key, value] of Object.entries(attr)) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
attributes.push(`${key}="${String(escapeValue(value))}"`);
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof values === "object") {
|
||||
if (values !== null) {
|
||||
const { _attr: attr, _cdata: cdata } = values as { readonly _attr?: Record<string, unknown>; readonly _cdata?: string };
|
||||
if (attr) {
|
||||
addAttributes(attr);
|
||||
}
|
||||
if (cdata) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
content.push(`<![CDATA[${cdata.replace(/\]\]>/g, "]]]]><![CDATA[>")}]]>`);
|
||||
}
|
||||
if (Array.isArray(values)) {
|
||||
let isStringContent = false;
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
content.push("");
|
||||
for (const value of values) {
|
||||
if (typeof value === "object") {
|
||||
if (Object.keys(value)[0] === "_attr") {
|
||||
addAttributes((value as { readonly _attr: Record<string, unknown> })._attr);
|
||||
} else {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
content.push(resolve(value as object, indent, depth + 1));
|
||||
}
|
||||
} else {
|
||||
// Text takes the place of whatever came before it, as it did in the xml package
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
content.pop();
|
||||
isStringContent = true;
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
content.push(escapeValue(value as string));
|
||||
}
|
||||
}
|
||||
if (!isStringContent) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
content.push("");
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
content.push(escapeValue(values as string | number | boolean | undefined));
|
||||
}
|
||||
|
||||
return { name, attributes, content, indents: depth > 1 ? indent.repeat(depth - 1) : "" };
|
||||
};
|
||||
|
||||
const format = (element: ResolvedElement | string | number | boolean, indent: string, isLast: boolean): string => {
|
||||
if (typeof element !== "object") {
|
||||
return String(element);
|
||||
}
|
||||
const { name, attributes, content, indents } = element;
|
||||
const { length } = content;
|
||||
const open =
|
||||
indents +
|
||||
(name ? `<${name}` : "") +
|
||||
(attributes.length > 0 ? ` ${attributes.join(" ")}` : "") +
|
||||
(length > 0 ? (name ? ">" : "") : "/>") +
|
||||
(indent && length > 1 ? "\n" : "");
|
||||
if (length === 0) {
|
||||
return open + (indent ? "\n" : "");
|
||||
}
|
||||
const children = content.map((child) => (child === undefined ? "" : format(child, indent, false))).join("");
|
||||
return open + children + (length > 1 ? indents : "") + (name ? `</${name}>` : "") + (indent && !isLast ? "\n" : "");
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes the XML of an object from docx's `Formatter`, such as `{ "w:b": { _attr: { "w:val": false } } }`,
|
||||
* as the xml package did.
|
||||
*
|
||||
* @param input - The object, or several to write one after another
|
||||
* @param options - How to indent, and the XML declaration to write first
|
||||
* @returns The XML
|
||||
*/
|
||||
export const stringifyXmlable = (
|
||||
input: IXmlableObject | readonly IXmlableObject[],
|
||||
{ indent = "", declaration }: StringifyXmlableOptions = {},
|
||||
): string => {
|
||||
const items = Array.isArray(input) ? input : [input];
|
||||
const startDepth = indent ? 1 : 0;
|
||||
const standalone = declaration?.standalone ? ` standalone="${escapeAll(declaration.standalone)}"` : "";
|
||||
const declarationXml =
|
||||
declaration === undefined
|
||||
? ""
|
||||
: `<?xml version="1.0" encoding="${escapeAll(declaration.encoding || "UTF-8")}"${standalone}?>${indent ? "\n" : ""}`;
|
||||
return declarationXml + items.map((item, i) => format(resolve(item, indent, startDepth), indent, i === items.length - 1)).join("");
|
||||
};
|
||||
|
||||
const stringifyAttributes = (attributes: XmlElement["attributes"]): string =>
|
||||
Object.entries(attributes ?? {})
|
||||
.flatMap(([key, value]) => (value === undefined || value === null ? [] : [` ${key}="${escapeAll(String(value))}"`]))
|
||||
.join("");
|
||||
|
||||
const stringifyNode = (node: XmlElement): string => {
|
||||
switch (node.type) {
|
||||
case "element": {
|
||||
const elements = node.elements ?? [];
|
||||
const open = `<${node.name}${stringifyAttributes(node.attributes)}`;
|
||||
// An empty element that preserves its whitespace is written with both tags, as xml-js did
|
||||
return elements.length > 0 || node.attributes?.["xml:space"] === "preserve"
|
||||
? `${open}>${elements.map(stringifyNode).join("")}</${node.name}>`
|
||||
: `${open}/>`;
|
||||
}
|
||||
case "text":
|
||||
return escapeText(String(node.text));
|
||||
case "cdata":
|
||||
return `<![CDATA[${String(node.cdata).replace(/\]\]>/g, "]]]]><![CDATA[>")}]]>`;
|
||||
case "comment":
|
||||
return `<!--${node.comment}-->`;
|
||||
case "doctype":
|
||||
return `<!DOCTYPE ${node.doctype}>`;
|
||||
case "instruction":
|
||||
return `<?${node.name}${node.instruction ? ` ${node.instruction}` : ""}?>`;
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Writes the XML of an {@link XmlElement} tree, such as one from {@link parseXml}.
|
||||
*
|
||||
* @param document - The document, with its declaration and the nodes at its top level
|
||||
* @returns The XML
|
||||
*/
|
||||
export const stringifyElement = (document: XmlElement): string =>
|
||||
(document.declaration ? `<?xml${stringifyAttributes(document.declaration.attributes)}?>` : "") +
|
||||
(document.elements ?? []).map(stringifyNode).join("");
|
||||
@@ -0,0 +1,47 @@
|
||||
/**
|
||||
* The tree that docx reads XML into, such as the parts of a document it patches or the XML given to
|
||||
* `convertToXmlComponent`.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
/* eslint-disable functional/prefer-readonly-type -- Changes to a document, such as patches, are made to its tree in place */
|
||||
|
||||
/**
|
||||
* The attributes of an element, by name.
|
||||
*/
|
||||
export type XmlAttributes = Record<string, string | number | undefined>;
|
||||
|
||||
/**
|
||||
* The attributes of an XML declaration, such as `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`.
|
||||
*/
|
||||
export type XmlDeclarationAttributes = {
|
||||
version?: string | number;
|
||||
encoding?: string;
|
||||
standalone?: "yes" | "no";
|
||||
};
|
||||
|
||||
/**
|
||||
* A node of an XML document, or the document itself.
|
||||
*
|
||||
* It has the shape of xml-js's non-compact `Element`, which docx used before it read XML itself, so a tree from
|
||||
* xml-js can still be given wherever docx takes one. `type` says which of the other fields the node has:
|
||||
*
|
||||
* - The document has no `type`. It has its `declaration`, if it has one, and the nodes at its top level in `elements`.
|
||||
* - `"element"` has its `name`, and its `attributes` and `elements` if it has any.
|
||||
* - `"text"` has its `text`, with entities such as `&` decoded.
|
||||
* - `"cdata"`, `"comment"` and `"doctype"` have their content in the field of their name.
|
||||
* - `"instruction"`, a processing instruction such as `<?mso-application progid="Word.Document"?>`, has its `name`
|
||||
* and the rest in `instruction`.
|
||||
*/
|
||||
export type XmlElement = {
|
||||
declaration?: { attributes?: XmlDeclarationAttributes };
|
||||
instruction?: string;
|
||||
attributes?: XmlAttributes;
|
||||
cdata?: string;
|
||||
doctype?: string;
|
||||
comment?: string;
|
||||
text?: string | number | boolean;
|
||||
type?: string;
|
||||
name?: string;
|
||||
elements?: XmlElement[];
|
||||
};
|
||||
@@ -34,6 +34,8 @@ export default defineConfig({
|
||||
protocolImports: true,
|
||||
}),
|
||||
],
|
||||
// Lets specs import Word documents with ?inline, such as the corpus src/util/xml reads
|
||||
assetsInclude: ["**/*.docx", "**/*.dotx"],
|
||||
resolve: {
|
||||
tsconfigPaths: true,
|
||||
alias: {
|
||||
|
||||
Reference in New Issue
Block a user