mirror of
https://github.com/dolanmiu/docx.git
synced 2026-11-30 16:47:55 +01:00
fix: number drawing ids within each document when it is packed (#3946)
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createDrawingNumbering } from "./drawing-ids";
|
||||
|
||||
const idsOf = (xml: string, name: string): readonly number[] =>
|
||||
[...xml.matchAll(new RegExp(`<${name} id="(\\d+)"`, "g"))].map(([, id]) => Number(id));
|
||||
|
||||
const image = (id: number | string): string =>
|
||||
`<w:r><w:drawing><wp:inline distT="0"><wp:extent cx="1" cy="1"/><wp:docPr id="${id}" name=""/>` +
|
||||
`<a:graphic><a:graphicData><pic:pic><pic:nvPicPr><pic:cNvPr id="0" name=""/></pic:nvPicPr></pic:pic>` +
|
||||
`</a:graphicData></a:graphic></wp:inline></w:drawing></w:r>`;
|
||||
|
||||
// A group of two shapes and a connector that joins them, as docx/shapes writes it
|
||||
const group = (id: number, [first, second, connector]: readonly [number, number, number]): string =>
|
||||
`<w:r><w:drawing><wp:anchor distT="0"><wp:docPr id="${id}" name="Group"></wp:docPr><a:graphic><a:graphicData><wpg:wgp>` +
|
||||
`<wps:wsp><wps:cNvPr id="${first}" name="First"/></wps:wsp>` +
|
||||
`<wps:wsp><wps:cNvPr id="${second}" name="Second"/></wps:wsp>` +
|
||||
`<wps:wsp><wps:cNvPr id="${connector}" name="Connector"/><wps:cNvCnPr><a:stCxn id="${first}" idx="3"/><a:endCxn id="${second}" idx="1"/></wps:cNvCnPr></wps:wsp>` +
|
||||
`</wpg:wgp></a:graphicData></a:graphic></wp:anchor></w:drawing></w:r>`;
|
||||
|
||||
describe("createDrawingNumbering", () => {
|
||||
it("should number drawings from 1, in the order they are written", () => {
|
||||
const xml = createDrawingNumbering()(`<w:body><w:p>${image(40)}</w:p><w:p>${image(7)}${image(12)}</w:p></w:body>`);
|
||||
|
||||
expect(idsOf(xml, "wp:docPr")).to.deep.equal([1, 2, 3]);
|
||||
});
|
||||
|
||||
it("should carry on numbering in the parts after the first", () => {
|
||||
const numberDrawings = createDrawingNumbering();
|
||||
|
||||
expect(idsOf(numberDrawings(`<w:p>${image(40)}${image(41)}</w:p>`), "wp:docPr")).to.deep.equal([1, 2]);
|
||||
expect(idsOf(numberDrawings(`<w:p>${image(42)}</w:p>`), "wp:docPr")).to.deep.equal([3]);
|
||||
});
|
||||
|
||||
it("should start again from 1 for each document", () => {
|
||||
expect(idsOf(createDrawingNumbering()(image(40)), "wp:docPr")).to.deep.equal([1]);
|
||||
expect(idsOf(createDrawingNumbering()(image(41)), "wp:docPr")).to.deep.equal([1]);
|
||||
});
|
||||
|
||||
it("should give a drawing that is in the document twice different ids", () => {
|
||||
expect(idsOf(createDrawingNumbering()(`<w:p>${image(5)}${image(5)}</w:p>`), "wp:docPr")).to.deep.equal([1, 2]);
|
||||
});
|
||||
|
||||
it("should number the shapes in a drawing, and keep its connector joined to the same shapes", () => {
|
||||
const xml = createDrawingNumbering()(`<w:p>${image(9)}${group(20, [11, 12, 13])}</w:p>`);
|
||||
|
||||
expect(xml).to.contain('<wp:docPr id="2" name="Group"></wp:docPr>');
|
||||
expect(xml).to.contain('<wps:cNvPr id="3" name="First"/>');
|
||||
expect(xml).to.contain('<wps:cNvPr id="4" name="Second"/>');
|
||||
expect(xml).to.contain('<wps:cNvPr id="5" name="Connector"/><wps:cNvCnPr><a:stCxn id="3" idx="3"/><a:endCxn id="4" idx="1"/>');
|
||||
});
|
||||
|
||||
it("should keep a connector joined to shapes that come after it", () => {
|
||||
const connectorFirst = group(1, [2, 3, 4]).replace(
|
||||
/(<wpg:wgp>)(.*)(<wps:wsp><wps:cNvPr id="4".*<\/wps:wsp>)(<\/wpg:wgp>)/,
|
||||
"$1$3$2$4",
|
||||
);
|
||||
|
||||
const xml = createDrawingNumbering()(connectorFirst);
|
||||
|
||||
expect(xml).to.contain('<wps:cNvPr id="2" name="Connector"/><wps:cNvCnPr><a:stCxn id="3" idx="3"/><a:endCxn id="4" idx="1"/>');
|
||||
expect(xml).to.contain('<wps:cNvPr id="3" name="First"/>');
|
||||
expect(xml).to.contain('<wps:cNvPr id="4" name="Second"/>');
|
||||
});
|
||||
|
||||
it("should join a connector to a shape, not to a drawing that had the same id", () => {
|
||||
const xml = createDrawingNumbering()(group(2, [2, 3, 4]));
|
||||
|
||||
expect(idsOf(xml, "wp:docPr")).to.deep.equal([1]);
|
||||
expect(idsOf(xml, "wps:cNvPr")).to.deep.equal([2, 3, 4]);
|
||||
expect(xml).to.contain('<a:stCxn id="2" idx="3"/><a:endCxn id="3" idx="1"/>');
|
||||
});
|
||||
|
||||
it("should leave the end of a connector that joins no shape in its drawing", () => {
|
||||
const xml = createDrawingNumbering()(group(1, [2, 3, 4]).replace('<a:endCxn id="3"', '<a:endCxn id="30"'));
|
||||
|
||||
expect(xml).to.contain('<a:stCxn id="2" idx="3"/><a:endCxn id="30" idx="1"/>');
|
||||
});
|
||||
|
||||
it("should number a drawing in a shape's text box as a drawing of its own", () => {
|
||||
const textBox =
|
||||
`<w:r><w:drawing><wp:inline><wp:docPr id="50" name=""/><a:graphic><wps:wsp><wps:cNvPr id="51" name=""/>` +
|
||||
`<wps:txbx><w:txbxContent><w:p>${group(52, [53, 54, 55])}</w:p></w:txbxContent></wps:txbx>` +
|
||||
`<wps:cNvCnPr><a:stCxn id="51" idx="0"/></wps:cNvCnPr></wps:wsp></a:graphic></wp:inline></w:drawing></w:r>`;
|
||||
|
||||
const xml = createDrawingNumbering()(`<w:p>${textBox}${image(56)}</w:p>`);
|
||||
|
||||
expect(
|
||||
[...xml.matchAll(/<(wp:docPr|wps:cNvPr|a:stCxn|a:endCxn) id="(\d+)"/g)].map(([, name, id]) => `${name} ${id}`),
|
||||
).to.deep.equal([
|
||||
"wp:docPr 1",
|
||||
"wps:cNvPr 2",
|
||||
"wp:docPr 3",
|
||||
"wps:cNvPr 4",
|
||||
"wps:cNvPr 5",
|
||||
"wps:cNvPr 6",
|
||||
"a:stCxn 4",
|
||||
"a:endCxn 5",
|
||||
"a:stCxn 2",
|
||||
"wp:docPr 7",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should number the pictures and groups in a group, and leave the id 0 of a picture's own properties", () => {
|
||||
const pictures =
|
||||
`<w:r><w:drawing><wp:inline><wp:docPr id="8" name=""/><a:graphic><a:graphicData><wpg:wgp>` +
|
||||
`<wpg:grpSp><wpg:cNvPr id="9" name=""/><pic:pic><pic:nvPicPr><pic:cNvPr id="10" name=""/></pic:nvPicPr></pic:pic></wpg:grpSp>` +
|
||||
`</wpg:wgp></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>`;
|
||||
|
||||
const xml = createDrawingNumbering()(`<w:p>${image(7)}${pictures}</w:p>`);
|
||||
|
||||
expect(idsOf(xml, "wp:docPr")).to.deep.equal([1, 2]);
|
||||
expect(idsOf(xml, "wpg:cNvPr")).to.deep.equal([3]);
|
||||
expect(idsOf(xml, "pic:cNvPr")).to.deep.equal([0, 4]);
|
||||
});
|
||||
|
||||
it("should find an id that isn't the first attribute, in XML written across lines", () => {
|
||||
const xml = `<w:p>\n <w:r>\n <w:drawing>\n <wp:inline>\n <wp:docPr name="" id="9"/>\n </wp:inline>\n </w:drawing>\n </w:r>\n</w:p>`;
|
||||
|
||||
expect(createDrawingNumbering()(xml)).to.equal(xml.replace('id="9"', 'id="1"'));
|
||||
});
|
||||
|
||||
it("should change only the ids", () => {
|
||||
const xml = `<w:p>${image(9)}${group(20, [11, 12, 13])}</w:p>`;
|
||||
const withoutIds = (text: string): string => text.replace(/ id="\d+"/g, "");
|
||||
|
||||
expect(withoutIds(createDrawingNumbering()(xml))).to.equal(withoutIds(xml));
|
||||
});
|
||||
|
||||
it("should leave an id that isn't a number, ids outside drawings, and elements that only start with the same name", () => {
|
||||
const xml = `<w:p>${image("first")}<wps:cNvPr id="3" name=""/><wp:inlineThing><wp:docPrThing id="4"/></wp:inlineThing></w:p>`;
|
||||
|
||||
expect(createDrawingNumbering()(xml)).to.equal(xml);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Numbers the drawings of a document as it is packed.
|
||||
*
|
||||
* @module
|
||||
*/
|
||||
|
||||
// The tags of drawings, and of the elements in them that have ids: a drawing's own (`wp:docPr`), those of the shapes,
|
||||
// pictures and groups in it, and a connector's ends, which refer to the shapes it joins by their ids
|
||||
const TAG = /<(\/?)(wp:inline|wp:anchor|wp:docPr|wps:cNvPr|wpg:cNvPr|pic:cNvPr|a:stCxn|a:endCxn)(?=[\s/>])[^>]*>/g;
|
||||
const ID = /(\s)id="(\d+)"/;
|
||||
|
||||
/**
|
||||
* Creates a function that numbers the drawings in the parts of a document from 1, in the order they are written.
|
||||
*
|
||||
* Each drawing is given an id when it is created, from one counter for the whole process, so no two drawings share
|
||||
* one. Written as they are, the ids of a document would depend on the drawings created before it, and the same
|
||||
* document would be written differently each time. Word only needs the ids to be unique in the document, across all
|
||||
* of its parts, so the parts of a document are numbered by the same function, one after the other.
|
||||
*
|
||||
* Every drawing, and every shape, picture and group in it, is given the next id, even when the same drawing is in the
|
||||
* document twice, and a connector still joins the shapes it did. A picture's own `pic:cNvPr` keeps the id 0 it is
|
||||
* written with, as Word writes it: only its drawing's id needs to be unique.
|
||||
*
|
||||
* @returns A function that returns a part's XML with its drawings numbered after those of the parts before it
|
||||
*/
|
||||
export const createDrawingNumbering = (): ((xml: string) => string) => {
|
||||
let lastId = 0;
|
||||
|
||||
return (xml) => {
|
||||
// The new id of each tag that has one, by where the tag starts
|
||||
const newIds = new Map<number, number>();
|
||||
// The new ids of the shapes in each drawing the tags are in, by their old ids
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const drawings: Map<number, number>[] = [];
|
||||
// A connector can come before the shapes it joins, so its ends are numbered once every shape has been
|
||||
// eslint-disable-next-line functional/prefer-readonly-type
|
||||
const ends: { readonly offset: number; readonly shapes: ReadonlyMap<number, number>; readonly id: number }[] = [];
|
||||
|
||||
for (const { 0: tag, 1: closing, 2: name, index: offset } of xml.matchAll(TAG)) {
|
||||
if (name === "wp:inline" || name === "wp:anchor") {
|
||||
if (closing) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
drawings.pop();
|
||||
} else {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
drawings.push(new Map());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const shapes = drawings[drawings.length - 1];
|
||||
const id = Number(ID.exec(tag)?.[2]);
|
||||
if (closing || !shapes || !Number.isInteger(id) || (name === "pic:cNvPr" && id === 0)) {
|
||||
continue;
|
||||
}
|
||||
if (name === "a:stCxn" || name === "a:endCxn") {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
ends.push({ offset, shapes, id });
|
||||
continue;
|
||||
}
|
||||
lastId++;
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
newIds.set(offset, lastId);
|
||||
if (name !== "wp:docPr" && !shapes.has(id)) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
shapes.set(id, lastId);
|
||||
}
|
||||
}
|
||||
for (const { offset, shapes, id } of ends) {
|
||||
const shape = shapes.get(id);
|
||||
if (shape !== undefined) {
|
||||
// eslint-disable-next-line functional/immutable-data
|
||||
newIds.set(offset, shape);
|
||||
}
|
||||
}
|
||||
|
||||
return newIds.size === 0
|
||||
? xml
|
||||
: xml.replace(TAG, (tag: string, _closing: string, _name: string, offset: number) => {
|
||||
const id = newIds.get(offset);
|
||||
return id === undefined ? tag : tag.replace(ID, `$1id="${id}"`);
|
||||
});
|
||||
};
|
||||
};
|
||||
@@ -482,6 +482,46 @@ describe("Compiler", () => {
|
||||
expect(new Set(ids).size).to.equal(6);
|
||||
});
|
||||
|
||||
it("should number the drawings of a document from 1, across its parts, however many drawings were made before it", () => {
|
||||
// Each drawing takes its id from one counter for the whole process when it is created
|
||||
const image = (): Paragraph =>
|
||||
new Paragraph({
|
||||
children: [new ImageRun({ type: "png", data: Buffer.from("", "base64"), transformation: { width: 10, height: 10 } })],
|
||||
});
|
||||
const createFile = (): File =>
|
||||
new File({
|
||||
footnotes: { 1: { children: [image()] } },
|
||||
endnotes: { 1: { children: [image()] } },
|
||||
comments: { children: [{ id: 0, date: new Date("2026-01-01T00:00:00Z"), children: [image()] }] },
|
||||
sections: [
|
||||
{
|
||||
headers: { default: new Header({ children: [image()] }) },
|
||||
footers: { default: new Footer({ children: [image()] }) },
|
||||
children: [image(), image()],
|
||||
},
|
||||
],
|
||||
});
|
||||
const parts = [
|
||||
"word/document.xml",
|
||||
"word/header1.xml",
|
||||
"word/footer1.xml",
|
||||
"word/footnotes.xml",
|
||||
"word/endnotes.xml",
|
||||
"word/comments.xml",
|
||||
];
|
||||
const partsOf = (file: File): readonly string[] => {
|
||||
const zipFile = compile(file);
|
||||
return parts.map((path) => textOf(zipFile, path)!);
|
||||
};
|
||||
|
||||
const first = partsOf(createFile());
|
||||
const second = partsOf(createFile());
|
||||
|
||||
expect(second).to.deep.equal(first);
|
||||
const ids = first.map((xml) => [...xml.matchAll(/<wp:docPr id="(\d+)"/g)].map(([, id]) => Number(id)));
|
||||
expect(ids).to.deep.equal([[1, 2], [3], [4], [5], [6], [7]]);
|
||||
});
|
||||
|
||||
it("should write the same package when a document is packed again", () => {
|
||||
// Packing again used to repeat the lists, custom properties, links on pictures and relationships the first
|
||||
// pack wrote, which Word can't open. Apps pack again when a user downloads a document a second time
|
||||
|
||||
@@ -10,6 +10,7 @@ import { stringifyXmlable } from "@util/xml";
|
||||
import type { ZipFileData } from "@util/zip";
|
||||
|
||||
import { Formatter } from "../formatter";
|
||||
import { createDrawingNumbering } from "./drawing-ids";
|
||||
import { ImageReplacer } from "./image-replacer";
|
||||
import { NumberingReplacer } from "./numbering-replacer";
|
||||
import { type PackagePartFile, xmlifyPackageParts } from "./package-part-writer";
|
||||
@@ -238,6 +239,10 @@ export class Compiler {
|
||||
const footnoteRelationshipCount = file.FootNotes.Relationships.RelationshipCount + 1;
|
||||
const endnoteRelationshipCount = file.Endnotes.Relationships.RelationshipCount + 1;
|
||||
|
||||
// The drawings are numbered in the order the parts are written below, so their ids don't depend on the drawings
|
||||
// made before the document
|
||||
const numberDrawings = createDrawingNumbering();
|
||||
|
||||
const documentMediaDatas = this.imageReplacer.getMediaData(documentXmlData, file.Media);
|
||||
const commentMediaDatas = this.imageReplacer.getMediaData(commentXmlData, file.Media);
|
||||
const footnoteMediaDatas = this.imageReplacer.getMediaData(footnoteXmlData, file.Media);
|
||||
@@ -280,7 +285,11 @@ export class Compiler {
|
||||
},
|
||||
Document: {
|
||||
data: (() => {
|
||||
const xmlData = this.imageReplacer.replace(documentXmlData, documentMediaDatas, documentRelationshipCount);
|
||||
const xmlData = this.imageReplacer.replace(
|
||||
numberDrawings(documentXmlData),
|
||||
documentMediaDatas,
|
||||
documentRelationshipCount,
|
||||
);
|
||||
const referenedXmlData = this.numberingReplacer.replace(xmlData, file.Numbering.ConcreteNumbering);
|
||||
return referenedXmlData;
|
||||
})(),
|
||||
@@ -442,7 +451,7 @@ export class Compiler {
|
||||
);
|
||||
const mediaDatas = this.imageReplacer.getMediaData(tempXmlData, file.Media);
|
||||
// TODO: 0 needs to be changed when headers get relationships of their own
|
||||
const xmlData = this.imageReplacer.replace(tempXmlData, mediaDatas, 0);
|
||||
const xmlData = this.imageReplacer.replace(numberDrawings(tempXmlData), mediaDatas, 0);
|
||||
|
||||
const referenedXmlData = this.numberingReplacer.replace(xmlData, file.Numbering.ConcreteNumbering);
|
||||
|
||||
@@ -467,7 +476,7 @@ export class Compiler {
|
||||
);
|
||||
const mediaDatas = this.imageReplacer.getMediaData(tempXmlData, file.Media);
|
||||
// TODO: 0 needs to be changed when headers get relationships of their own
|
||||
const xmlData = this.imageReplacer.replace(tempXmlData, mediaDatas, 0);
|
||||
const xmlData = this.imageReplacer.replace(numberDrawings(tempXmlData), mediaDatas, 0);
|
||||
|
||||
const referenedXmlData = this.numberingReplacer.replace(xmlData, file.Numbering.ConcreteNumbering);
|
||||
|
||||
@@ -512,7 +521,11 @@ export class Compiler {
|
||||
},
|
||||
FootNotes: {
|
||||
data: (() => {
|
||||
const xmlData = this.imageReplacer.replace(footnoteXmlData, footnoteMediaDatas, footnoteRelationshipCount);
|
||||
const xmlData = this.imageReplacer.replace(
|
||||
numberDrawings(footnoteXmlData),
|
||||
footnoteMediaDatas,
|
||||
footnoteRelationshipCount,
|
||||
);
|
||||
const referenedXmlData = this.numberingReplacer.replace(xmlData, file.Numbering.ConcreteNumbering);
|
||||
return referenedXmlData;
|
||||
})(),
|
||||
@@ -547,7 +560,7 @@ export class Compiler {
|
||||
},
|
||||
Endnotes: {
|
||||
data: (() => {
|
||||
const xmlData = this.imageReplacer.replace(endnoteXmlData, endnoteMediaDatas, endnoteRelationshipCount);
|
||||
const xmlData = this.imageReplacer.replace(numberDrawings(endnoteXmlData), endnoteMediaDatas, endnoteRelationshipCount);
|
||||
const referenedXmlData = this.numberingReplacer.replace(xmlData, file.Numbering.ConcreteNumbering);
|
||||
return referenedXmlData;
|
||||
})(),
|
||||
@@ -602,7 +615,11 @@ export class Compiler {
|
||||
: {
|
||||
Comments: {
|
||||
data: (() => {
|
||||
const xmlData = this.imageReplacer.replace(commentXmlData, commentMediaDatas, commentRelationshipCount);
|
||||
const xmlData = this.imageReplacer.replace(
|
||||
numberDrawings(commentXmlData),
|
||||
commentMediaDatas,
|
||||
commentRelationshipCount,
|
||||
);
|
||||
const referenedXmlData = this.numberingReplacer.replace(xmlData, file.Numbering.ConcreteNumbering);
|
||||
return referenedXmlData;
|
||||
})(),
|
||||
|
||||
@@ -36,6 +36,10 @@ export type DocPropertiesOptions = {
|
||||
readonly description?: string;
|
||||
/** Title of the drawing element */
|
||||
readonly title?: string;
|
||||
/**
|
||||
* The drawing's id. Default is the next id no other drawing has. The Packer numbers the drawings of a document again
|
||||
* from 1, in the order they are written, so its drawing ids don't depend on the drawings made before it
|
||||
*/
|
||||
readonly id?: string;
|
||||
};
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ describe("ShapeCanvasRun", () => {
|
||||
expect(canvas).to.have.length(5);
|
||||
|
||||
const connector = canvas[4]["wps:wsp"];
|
||||
// Shapes are named as Word names them, after what they are and their id
|
||||
// Shapes are named as Word names them, after what they are and their place in the drawing
|
||||
expect(canvas[2]["wps:wsp"][0]).to.deep.equal({ "wps:cNvPr": { _attr: { id: 1, name: "Flow Chart Terminator 1" } } });
|
||||
expect(connector[0]).to.deep.equal({ "wps:cNvPr": { _attr: { id: 3, name: "Straight Connector 3" } } });
|
||||
expect(connector[1]).to.deep.equal({
|
||||
@@ -107,11 +107,15 @@ describe("ShapeCanvasRun", () => {
|
||||
]);
|
||||
// The background is decorative, so screen readers skip it
|
||||
const background = group[2]["wps:wsp"][0]["wps:cNvPr"];
|
||||
expect(background[0]).to.deep.equal({ _attr: { id: 8, name: "Canvas 8" } });
|
||||
expect(background[0]).to.deep.equal({ _attr: { id: 8, name: "Canvas" } });
|
||||
expect(background[1]).to.have.property("a:extLst");
|
||||
expect(JSON.stringify(group[2])).to.include("F2F2F2");
|
||||
// The shapes and connector are laid out again, with ids of their own
|
||||
expect(group.slice(3).map((child: IXmlableObject) => child["wps:wsp"][0]["wps:cNvPr"]._attr.id)).to.deep.equal([5, 6, 7]);
|
||||
// The shapes and connector are laid out again, with ids of their own and the names they have on the canvas
|
||||
expect(group.slice(3).map((child: IXmlableObject) => child["wps:wsp"][0]["wps:cNvPr"]._attr)).to.deep.equal([
|
||||
{ id: 5, name: "Rectangle 1" },
|
||||
{ id: 6, name: "Rectangle 2" },
|
||||
{ id: 7, name: "Straight Connector 3" },
|
||||
]);
|
||||
expect(group[5]["wps:wsp"][1]).to.deep.equal({
|
||||
"wps:cNvCnPr": [{ "a:stCxn": { _attr: { id: 5, idx: 3 } } }, { "a:endCxn": { _attr: { id: 6, idx: 1 } } }],
|
||||
});
|
||||
|
||||
@@ -164,7 +164,8 @@ export class ShapeCanvasRun extends Run {
|
||||
}
|
||||
|
||||
// Applications that can't draw canvases, such as Apple Pages, draw the same diagram as a group. Its shapes
|
||||
// have ids of their own, and a rectangle behind them draws the canvas's background and outline
|
||||
// have ids of their own, and the same names, and a rectangle behind them draws the canvas's background and
|
||||
// outline
|
||||
const { backgroundId } = fallback;
|
||||
const group = layoutShapeDrawing(fallback.nodes, { keepPositive: true, layout: options.layout, styles });
|
||||
const background: ShapeDrawingChildMediaData = {
|
||||
@@ -175,7 +176,7 @@ export class ShapeCanvasRun extends Run {
|
||||
fill: options.fill,
|
||||
line: options.line ?? "none",
|
||||
// Screen readers skip it: it is only the canvas's background
|
||||
nonVisualDrawingProperties: { id: backgroundId, name: `Canvas ${backgroundId}`, decorative: true },
|
||||
nonVisualDrawingProperties: { id: backgroundId, name: "Canvas", decorative: true },
|
||||
},
|
||||
};
|
||||
const groupReach = {
|
||||
|
||||
@@ -1235,6 +1235,36 @@ describe("drawingStyledParagraphs", () => {
|
||||
});
|
||||
|
||||
describe("createShapeDrawingNodes", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("should name the children after their place in the drawing, however many drawings were made before it", () => {
|
||||
let id = 100;
|
||||
vi.spyOn(convenienceFunctions, "docPropertiesUniqueNumericId").mockImplementation(() => ++id);
|
||||
|
||||
const { children } = layoutShapeDrawing(
|
||||
createShapeDrawingNodes([
|
||||
box("a", 0, 0),
|
||||
{ type: "group", children: [box("b", 200, 0)] },
|
||||
connect("a", "b", { route: "elbow", label: "Yes" }),
|
||||
]),
|
||||
);
|
||||
|
||||
// The ids come from the counter every drawing takes its id from, until the document numbers its drawings
|
||||
const group = children[1];
|
||||
expect(group.type === "group" && group.nonVisualDrawingProperties).to.include({ id: 102, name: "Group 2" });
|
||||
expect(group.type === "group" && dataOf(group.children[0]).nonVisualDrawingProperties).to.include({ id: 103, name: "Rectangle 3" });
|
||||
expect(children.map((child) => child.type !== "group" && dataOf(child).nonVisualDrawingProperties)).to.deep.equal([
|
||||
{ id: 101, name: "Rectangle 1", description: undefined, title: undefined, link: undefined, decorative: undefined },
|
||||
false,
|
||||
{ id: 104, name: "Elbow Connector 4", description: undefined, title: undefined, link: undefined, decorative: undefined },
|
||||
{ id: 105, name: "Text Box 5", description: undefined, title: undefined, link: undefined, decorative: undefined },
|
||||
]);
|
||||
const { start, end } = dataOf(children[2]).connections!;
|
||||
expect([start?.id, end?.id]).to.deep.equal([101, 103]);
|
||||
});
|
||||
|
||||
it("should give the children their ids once, so laying them out again keeps them", () => {
|
||||
const nodes = createShapeDrawingNodes([{ type: "rectangle", transformation: { width: 10, height: 10 } }]);
|
||||
const ids = (layout: ShapeDrawingLayout): readonly unknown[] =>
|
||||
|
||||
+52
-24
@@ -368,7 +368,8 @@ const shrink = ({ left, top, right, bottom }: Bounds, by: number): Bounds => ({
|
||||
const transformDirection = ({ a, b, c, d }: Matrix, { x, y }: Point): Point => ({ x: a * x + c * y, y: b * x + d * y });
|
||||
|
||||
/**
|
||||
* A name for a shape, as Word gives them: what it is, then its drawing id, such as "Rounded Rectangle 4".
|
||||
* A name for a shape, as Word gives them: what it is, then a number, such as "Rounded Rectangle 4". The number is the
|
||||
* shape's drawing id within its drawing, which counts from 1, so the same drawing has the same names in any document.
|
||||
*/
|
||||
const defaultName = (kind: string, drawingId: number): string =>
|
||||
`${kind.replace(/([a-z\d])([A-Z])/g, "$1 $2").replace(/^./, (first) => first.toUpperCase())} ${drawingId}`;
|
||||
@@ -452,31 +453,29 @@ const shapeSites = (options: ShapeChildOptions, width: number, height: number):
|
||||
/**
|
||||
* Gives the band and header of each lane of a layout drawing ids.
|
||||
*/
|
||||
const assignLaneIds = (layout?: ShapeLayout): readonly LaneIds[] =>
|
||||
layout?.type === "flow"
|
||||
? (layout.lanes ?? []).map(() => [docPropertiesUniqueNumericId(), docPropertiesUniqueNumericId()] as const)
|
||||
: [];
|
||||
const assignLaneIds = (nextId: () => number, layout?: ShapeLayout): readonly LaneIds[] =>
|
||||
layout?.type === "flow" ? (layout.lanes ?? []).map(() => [nextId(), nextId()] as const) : [];
|
||||
|
||||
/**
|
||||
* Gives every shape, picture, group, connector and label a drawing id, in the order they are written.
|
||||
*/
|
||||
const assignIds = (children: readonly IShapeGroupChildOptions[]): readonly Node[] =>
|
||||
const assignIds = (children: readonly IShapeGroupChildOptions[], nextId: () => number): readonly Node[] =>
|
||||
children.map((options): Node => {
|
||||
switch (options.type) {
|
||||
case "connector": {
|
||||
const drawingId = docPropertiesUniqueNumericId();
|
||||
return { kind: "connector", options, drawingId, labelId: options.label ? docPropertiesUniqueNumericId() : undefined };
|
||||
const drawingId = nextId();
|
||||
return { kind: "connector", options, drawingId, labelId: options.label ? nextId() : undefined };
|
||||
}
|
||||
case "picture":
|
||||
return { kind: "picture", options, drawingId: docPropertiesUniqueNumericId() };
|
||||
return { kind: "picture", options, drawingId: nextId() };
|
||||
case "group": {
|
||||
const drawingId = docPropertiesUniqueNumericId();
|
||||
const drawingId = nextId();
|
||||
// A group's lanes are drawn first, behind its children
|
||||
const laneIds = assignLaneIds(options.layout);
|
||||
return { kind: "group", options, drawingId, laneIds, children: assignIds(options.children) };
|
||||
const laneIds = assignLaneIds(nextId, options.layout);
|
||||
return { kind: "group", options, drawingId, laneIds, children: assignIds(options.children, nextId) };
|
||||
}
|
||||
default:
|
||||
return { kind: "shape", options, drawingId: docPropertiesUniqueNumericId() };
|
||||
return { kind: "shape", options, drawingId: nextId() };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1531,7 +1530,7 @@ const layoutGroup = (
|
||||
};
|
||||
};
|
||||
|
||||
const toMediaData = (child: LaidOutChild, shift: Point): ShapeDrawingChildMediaData => {
|
||||
const toMediaData = (child: LaidOutChild, shift: Point, drawingIds: readonly number[]): ShapeDrawingChildMediaData => {
|
||||
const x = Math.round(child.box.x + shift.x);
|
||||
const y = Math.round(child.box.y + shift.y);
|
||||
const width = Math.round(child.box.width);
|
||||
@@ -1543,19 +1542,39 @@ const toMediaData = (child: LaidOutChild, shift: Point): ShapeDrawingChildMediaD
|
||||
flip: child.flip,
|
||||
rotation: child.rotation ? child.rotation * 60000 : undefined,
|
||||
};
|
||||
const withDrawingId = <T extends { readonly id: number }>(properties: T): T => ({ ...properties, id: drawingIds[properties.id - 1] });
|
||||
switch (child.type) {
|
||||
case "wps":
|
||||
return { type: "wps", transformation, data: child.data };
|
||||
case "wps": {
|
||||
const { nonVisualDrawingProperties, connections } = child.data;
|
||||
return {
|
||||
type: "wps",
|
||||
transformation,
|
||||
data: {
|
||||
...child.data,
|
||||
...(nonVisualDrawingProperties && { nonVisualDrawingProperties: withDrawingId(nonVisualDrawingProperties) }),
|
||||
...(connections && {
|
||||
connections: {
|
||||
start: connections.start && withDrawingId(connections.start),
|
||||
end: connections.end && withDrawingId(connections.end),
|
||||
},
|
||||
}),
|
||||
},
|
||||
};
|
||||
}
|
||||
case "picture":
|
||||
return { type: "picture", transformation, data: child.data };
|
||||
return {
|
||||
type: "picture",
|
||||
transformation,
|
||||
data: { ...child.data, nonVisualDrawingProperties: withDrawingId(child.data.nonVisualDrawingProperties) },
|
||||
};
|
||||
default:
|
||||
return {
|
||||
type: "group",
|
||||
transformation,
|
||||
childOffset: child.childOffset,
|
||||
childExtent: child.childExtent,
|
||||
children: child.children.map((grandchild) => toMediaData(grandchild, { x: 0, y: 0 })),
|
||||
nonVisualDrawingProperties: child.nonVisualDrawingProperties,
|
||||
children: child.children.map((grandchild) => toMediaData(grandchild, { x: 0, y: 0 }, drawingIds)),
|
||||
nonVisualDrawingProperties: withDrawingId(child.nonVisualDrawingProperties),
|
||||
};
|
||||
}
|
||||
};
|
||||
@@ -1569,19 +1588,28 @@ export type ShapeDrawingNodes = {
|
||||
readonly ids: ReadonlySet<string>;
|
||||
/** The drawing ids of the band and header of each lane of the layout */
|
||||
readonly laneIds: readonly LaneIds[];
|
||||
/** The ids the drawing ids from 1 are written as, from the counter every drawing takes its id from */
|
||||
readonly drawingIds: readonly number[];
|
||||
};
|
||||
|
||||
/**
|
||||
* Gives the children of a group or canvas their drawing ids. Every shape, picture, group and connector identifies
|
||||
* itself with a cNvPr, which needs an id that is unique in the document.
|
||||
*
|
||||
* They are numbered from 1 within the drawing, and named after that number, so the same drawing has the same names in
|
||||
* any document. Each is written as an id from the counter every drawing takes its id from, so no two drawings share
|
||||
* one, and the Packer then numbers the drawings of the document from 1.
|
||||
*
|
||||
* @throws If two shapes or pictures have the same `id`
|
||||
*/
|
||||
export const createShapeDrawingNodes = (children: readonly IShapeGroupChildOptions[], layout?: ShapeLayout): ShapeDrawingNodes => {
|
||||
let count = 0;
|
||||
const nextId = (): number => ++count;
|
||||
// The lanes are drawn first, behind the children
|
||||
const laneIds = assignLaneIds(layout);
|
||||
const nodes = assignIds(children);
|
||||
return { nodes, ids: collectIds(nodes), laneIds };
|
||||
const laneIds = assignLaneIds(nextId, layout);
|
||||
const nodes = assignIds(children, nextId);
|
||||
const drawingIds = Array.from({ length: count }, () => docPropertiesUniqueNumericId());
|
||||
return { nodes, ids: collectIds(nodes), laneIds, drawingIds };
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -1602,7 +1630,7 @@ export const layoutShapeDrawing = (
|
||||
styles = WORD_DEFAULT_STYLES,
|
||||
}: { readonly keepPositive?: boolean; readonly layout?: ShapeLayout; readonly styles?: TextStyles } = {},
|
||||
): ShapeDrawingLayout => {
|
||||
const { nodes, ids, laneIds } = "nodes" in children ? children : createShapeDrawingNodes(children, shapeLayout);
|
||||
const { nodes, ids, laneIds, drawingIds } = "nodes" in children ? children : createShapeDrawingNodes(children, shapeLayout);
|
||||
const layout = layoutGroup(nodes, ids, styles, shapeLayout, laneIds);
|
||||
const shift = keepPositive ? { x: Math.max(0, -layout.reach.left), y: Math.max(0, -layout.reach.top) } : { x: 0, y: 0 };
|
||||
const move = ({ left, top, right, bottom }: Bounds): Bounds => ({
|
||||
@@ -1613,7 +1641,7 @@ export const layoutShapeDrawing = (
|
||||
});
|
||||
|
||||
return {
|
||||
children: layout.children.map((child) => toMediaData(child, shift)),
|
||||
children: layout.children.map((child) => toMediaData(child, shift, drawingIds)),
|
||||
bounds: move(layout.box),
|
||||
reach: move(layout.reach),
|
||||
};
|
||||
|
||||
@@ -122,7 +122,9 @@ export const docPropertiesUniqueNumericIdGen = (): UniqueNumericIdCreator => uni
|
||||
* Drawing IDs (`wp:docPr` and `wps:cNvPr`) must be unique within a document,
|
||||
* and Word reports unreadable content when two drawings share one. A drawing
|
||||
* is created before it belongs to a document, so all drawings draw from this
|
||||
* one counter rather than a generator per instance.
|
||||
* one counter rather than a generator per instance. The Packer numbers the
|
||||
* drawings of each document again from 1, so the ids it writes don't depend on
|
||||
* the drawings made before the document.
|
||||
*
|
||||
* @returns A number no earlier call has returned
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user