@folijs/docx 0.5.0 → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +157 -0
- package/README.md +54 -17
- package/dist/custom.d.ts +2 -0
- package/dist/custom.d.ts.map +1 -0
- package/dist/custom.js +216 -0
- package/dist/custom.js.map +1 -0
- package/dist/export/balance.d.ts +2 -0
- package/dist/export/balance.d.ts.map +1 -0
- package/dist/export/balance.js +112 -0
- package/dist/export/balance.js.map +1 -0
- package/dist/export/content.d.ts +1 -14
- package/dist/export/content.d.ts.map +1 -1
- package/dist/export/content.js +157 -22
- package/dist/export/content.js.map +1 -1
- package/dist/export/controls.d.ts +2 -0
- package/dist/export/controls.d.ts.map +1 -0
- package/dist/export/controls.js +233 -0
- package/dist/export/controls.js.map +1 -0
- package/dist/export/index.d.ts +8 -2
- package/dist/export/index.d.ts.map +1 -1
- package/dist/export/index.js +218 -18
- package/dist/export/index.js.map +1 -1
- package/dist/export/parts.d.ts +1 -16
- package/dist/export/parts.d.ts.map +1 -1
- package/dist/export/parts.js +79 -11
- package/dist/export/parts.js.map +1 -1
- package/dist/export/pictures.d.ts +0 -42
- package/dist/export/pictures.d.ts.map +1 -1
- package/dist/export/pictures.js +24 -4
- package/dist/export/pictures.js.map +1 -1
- package/dist/export/properties.d.ts +1 -41
- package/dist/export/properties.d.ts.map +1 -1
- package/dist/export/properties.js +74 -15
- package/dist/export/properties.js.map +1 -1
- package/dist/export/tables.d.ts +0 -19
- package/dist/export/tables.d.ts.map +1 -1
- package/dist/export/tables.js +15 -3
- package/dist/export/tables.js.map +1 -1
- package/dist/export/xmlout.d.ts +1 -61
- package/dist/export/xmlout.d.ts.map +1 -1
- package/dist/export/xmlout.js +34 -7
- package/dist/export/xmlout.js.map +1 -1
- package/dist/import/content.d.ts +1 -33
- package/dist/import/content.d.ts.map +1 -1
- package/dist/import/content.js +208 -17
- package/dist/import/content.js.map +1 -1
- package/dist/import/controls.d.ts +2 -0
- package/dist/import/controls.d.ts.map +1 -0
- package/dist/import/controls.js +121 -0
- package/dist/import/controls.js.map +1 -0
- package/dist/import/index.d.ts +1 -1
- package/dist/import/index.d.ts.map +1 -1
- package/dist/import/index.js +82 -14
- package/dist/import/index.js.map +1 -1
- package/dist/import/ooxml.d.ts +1 -37
- package/dist/import/ooxml.d.ts.map +1 -1
- package/dist/import/ooxml.js +44 -8
- package/dist/import/ooxml.js.map +1 -1
- package/dist/import/parts.d.ts +1 -33
- package/dist/import/parts.d.ts.map +1 -1
- package/dist/import/parts.js +36 -10
- package/dist/import/parts.js.map +1 -1
- package/dist/import/pictures.d.ts +1 -33
- package/dist/import/pictures.d.ts.map +1 -1
- package/dist/import/pictures.js +7 -1
- package/dist/import/pictures.js.map +1 -1
- package/dist/import/properties.d.ts +1 -43
- package/dist/import/properties.d.ts.map +1 -1
- package/dist/import/properties.js +84 -6
- package/dist/import/properties.js.map +1 -1
- package/dist/import/report.d.ts +0 -10
- package/dist/import/report.d.ts.map +1 -1
- package/dist/import/report.js +1 -0
- package/dist/import/report.js.map +1 -1
- package/dist/import/stories.d.ts +2 -0
- package/dist/import/stories.d.ts.map +1 -0
- package/dist/import/stories.js +131 -0
- package/dist/import/stories.js.map +1 -0
- package/dist/import/tables.d.ts +0 -24
- package/dist/import/tables.d.ts.map +1 -1
- package/dist/import/tables.js +25 -6
- package/dist/import/tables.js.map +1 -1
- package/dist/package.d.ts +8 -4
- package/dist/package.d.ts.map +1 -1
- package/dist/package.js +38 -4
- package/dist/package.js.map +1 -1
- package/dist/settings.d.ts +1 -7
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +186 -26
- package/dist/settings.js.map +1 -1
- package/dist/xml.d.ts +8 -0
- package/dist/xml.d.ts.map +1 -1
- package/dist/xml.js +30 -2
- package/dist/xml.js.map +1 -1
- package/dist/zip.d.ts +0 -47
- package/dist/zip.d.ts.map +1 -1
- package/dist/zip.js +11 -2
- package/dist/zip.js.map +1 -1
- package/package.json +6 -5
- package/src/custom.ts +254 -0
- package/src/export/balance.ts +114 -0
- package/src/export/content.ts +203 -19
- package/src/export/controls.ts +260 -0
- package/src/export/index.ts +268 -20
- package/src/export/parts.ts +102 -10
- package/src/export/pictures.ts +21 -5
- package/src/export/properties.ts +90 -18
- package/src/export/tables.ts +15 -3
- package/src/export/xmlout.ts +36 -7
- package/src/import/content.ts +219 -17
- package/src/import/controls.ts +141 -0
- package/src/import/index.ts +103 -22
- package/src/import/ooxml.ts +44 -8
- package/src/import/parts.ts +44 -19
- package/src/import/pictures.ts +8 -1
- package/src/import/properties.ts +90 -6
- package/src/import/report.ts +1 -0
- package/src/import/stories.ts +134 -0
- package/src/import/tables.ts +25 -6
- package/src/package.ts +56 -6
- package/src/settings.ts +204 -27
- package/src/xml.ts +42 -2
- package/src/zip.ts +17 -5
package/src/export/index.ts
CHANGED
|
@@ -5,21 +5,37 @@
|
|
|
5
5
|
* byte for byte. Without a package, a new one is made.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import {
|
|
9
|
-
|
|
8
|
+
import {
|
|
9
|
+
type ControlJSON,
|
|
10
|
+
type Extension,
|
|
11
|
+
type FoliDocument,
|
|
12
|
+
type NodeJSON,
|
|
13
|
+
parseDocument,
|
|
14
|
+
type ResourceJSON,
|
|
15
|
+
type SectionJSON,
|
|
16
|
+
type StoryJSON,
|
|
17
|
+
} from "@folijs/core";
|
|
18
|
+
import { customToWord } from "../custom.js";
|
|
19
|
+
import { controlsUsed, packageStories } from "../import/index.js";
|
|
20
|
+
import { child, isW, REL, W } from "../import/ooxml.js";
|
|
21
|
+
import { noteIds } from "../import/stories.js";
|
|
10
22
|
import { DocxError, type DocxPackage, type NewPart } from "../package.js";
|
|
11
|
-
import { newSettingsXml, withTrackRevisions } from "../settings.js";
|
|
23
|
+
import { newSettingsXml, withSettings, withTrackRevisions } from "../settings.js";
|
|
24
|
+
import { parseXml, type XmlElement } from "../xml.js";
|
|
12
25
|
import { deflateEntry, writeZip } from "../zip.js";
|
|
26
|
+
import { balanced } from "./balance.js";
|
|
13
27
|
import { blocksXml, type WriteContext } from "./content.js";
|
|
14
28
|
import {
|
|
15
29
|
commentsExtendedXml,
|
|
16
30
|
commentsXml,
|
|
31
|
+
notesXml,
|
|
17
32
|
numberingXml,
|
|
18
33
|
type OriginalPart,
|
|
19
34
|
stylesXml,
|
|
35
|
+
wrapPart,
|
|
20
36
|
} from "./parts.js";
|
|
21
37
|
import { drawingXml, Media, pictureBytes } from "./pictures.js";
|
|
22
|
-
import { sectionXml } from "./properties.js";
|
|
38
|
+
import { same, sectionXml } from "./properties.js";
|
|
23
39
|
import {
|
|
24
40
|
DEFAULT_NAMESPACES,
|
|
25
41
|
escapeAttribute,
|
|
@@ -36,6 +52,10 @@ const CT = {
|
|
|
36
52
|
commentsExtended:
|
|
37
53
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml",
|
|
38
54
|
settings: "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml",
|
|
55
|
+
header: "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
|
|
56
|
+
footer: "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
|
|
57
|
+
footnotes: "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml",
|
|
58
|
+
endnotes: "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml",
|
|
39
59
|
rels: "application/vnd.openxmlformats-package.relationships+xml",
|
|
40
60
|
};
|
|
41
61
|
|
|
@@ -99,10 +119,13 @@ class Relationships {
|
|
|
99
119
|
return this.add(REL.hyperlink, href, true);
|
|
100
120
|
}
|
|
101
121
|
|
|
102
|
-
|
|
122
|
+
/** Adds a relationship; `wanted` is its id (a story's), refused if another has it. */
|
|
123
|
+
add(type: string, target: string, external: boolean, wanted?: string): string {
|
|
124
|
+
if (wanted !== undefined && this.#ids.has(wanted))
|
|
125
|
+
throw new DocxError(`Relationship id ${wanted} is already in use`);
|
|
103
126
|
let n = this.#ids.size + 1;
|
|
104
127
|
while (this.#ids.has(`rId${n}`)) n++;
|
|
105
|
-
const id = `rId${n}`;
|
|
128
|
+
const id = wanted ?? `rId${n}`;
|
|
106
129
|
this.#ids.add(id);
|
|
107
130
|
this.added.push({ id, type, target, external });
|
|
108
131
|
if (type === REL.hyperlink && external) this.#byTarget.set(target, id);
|
|
@@ -136,6 +159,7 @@ function contextFor(
|
|
|
136
159
|
): WriteContext {
|
|
137
160
|
return {
|
|
138
161
|
namespaces,
|
|
162
|
+
controls: media.controls,
|
|
139
163
|
hyperlink: (href, id) => relationships.hyperlink(href, id),
|
|
140
164
|
picture: (attrs) =>
|
|
141
165
|
drawingXml(
|
|
@@ -176,6 +200,12 @@ export interface ExportOptions {
|
|
|
176
200
|
key: string,
|
|
177
201
|
resource: ResourceJSON,
|
|
178
202
|
) => Promise<Uint8Array | undefined> | Uint8Array | undefined;
|
|
203
|
+
/**
|
|
204
|
+
* The custom node and mark types the document may hold (ADR-0008): validated by them, and a
|
|
205
|
+
* node's text in its content control is their `text(attrs)`. A custom type none declares is
|
|
206
|
+
* written as it was read (a `.docx` control's text, else `[type]`).
|
|
207
|
+
*/
|
|
208
|
+
extensions?: readonly Extension[];
|
|
179
209
|
}
|
|
180
210
|
|
|
181
211
|
/**
|
|
@@ -186,8 +216,10 @@ export async function exportDocx(
|
|
|
186
216
|
document: FoliDocument,
|
|
187
217
|
original?: DocxPackage,
|
|
188
218
|
options: ExportOptions = {},
|
|
189
|
-
): Promise<Uint8Array
|
|
190
|
-
|
|
219
|
+
): Promise<Uint8Array<ArrayBuffer>> {
|
|
220
|
+
// Custom nodes and marks become tagged content controls first (ADR-0008).
|
|
221
|
+
const parsed = parseDocument(document, { extensions: options.extensions ?? [] });
|
|
222
|
+
const doc = balanced(withThreadIds(customToWord(parsed, options.extensions), original), original);
|
|
191
223
|
// Before the app is asked for any picture's bytes.
|
|
192
224
|
const reference = original ? undefined : packageReference(doc);
|
|
193
225
|
if (reference) {
|
|
@@ -195,19 +227,86 @@ export async function exportDocx(
|
|
|
195
227
|
`The document refers to a part of its original package (${reference}): export it with that package`,
|
|
196
228
|
);
|
|
197
229
|
}
|
|
230
|
+
const referenced = noteReferences(doc);
|
|
231
|
+
const read =
|
|
232
|
+
original && (doc.stories || referenced.modeled.size)
|
|
233
|
+
? packageStories(original)
|
|
234
|
+
: { stories: {}, controls: new Map<string, ControlJSON>() };
|
|
235
|
+
const originals: Readonly<Record<string, StoryJSON>> = read.stories;
|
|
236
|
+
// A story is unchanged if its tree is, and the controls in it say what they said.
|
|
237
|
+
const unchanged = (id: string) =>
|
|
238
|
+
Object.hasOwn(originals, id) &&
|
|
239
|
+
same(doc.stories?.[id], originals[id]) &&
|
|
240
|
+
[...controlsUsed(doc.stories?.[id])].every((c) =>
|
|
241
|
+
same(doc.controls?.[c], read.controls.get(c)),
|
|
242
|
+
);
|
|
243
|
+
// Notes the model does not hold (an unknown `w:type`) stay in their part: they count too.
|
|
244
|
+
const inPart = original && referenced.modeled.size ? noteIds(original) : new Set<string>();
|
|
245
|
+
for (const key of referenced.modeled)
|
|
246
|
+
if (!Object.hasOwn(doc.stories ?? {}, key) && !inPart.has(key))
|
|
247
|
+
throw new DocxError(`A note reference has no note: ${key.slice(0, 64)}`);
|
|
198
248
|
// The parts written from the model: their drawings are the document's own.
|
|
199
249
|
const rewritten = original
|
|
200
250
|
? [
|
|
201
251
|
original.mainDocument,
|
|
202
252
|
...original
|
|
203
253
|
.relationships(original.mainDocument)
|
|
204
|
-
.filter(
|
|
254
|
+
.filter(
|
|
255
|
+
(r) =>
|
|
256
|
+
r.partName &&
|
|
257
|
+
(r.type === REL.comments ||
|
|
258
|
+
(doc.stories && Object.hasOwn(doc.stories, r.id) && !unchanged(r.id))),
|
|
259
|
+
)
|
|
205
260
|
.map((r) => r.partName as string),
|
|
206
261
|
]
|
|
207
262
|
: [];
|
|
208
263
|
const bytes = await pictureBytes(doc, original, options.resource);
|
|
209
264
|
const media = new Media(doc, original, bytes, rewritten);
|
|
210
|
-
return original
|
|
265
|
+
return original
|
|
266
|
+
? intoPackage(doc, original, originals, unchanged, referenced.isReferenced, options, media)
|
|
267
|
+
: newPackage(doc, referenced.isReferenced, options, media);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* The notes the document refers to, as story ids: `modeled` by `noteReference` nodes. `isReferenced`
|
|
272
|
+
* also says yes to every note of a kind that verbatim XML refers to: which one it means is not
|
|
273
|
+
* worth guessing, and removing a note still referred to makes Word refuse the file.
|
|
274
|
+
*/
|
|
275
|
+
function noteReferences(doc: FoliDocument): {
|
|
276
|
+
modeled: Set<string>;
|
|
277
|
+
isReferenced: (key: string) => boolean;
|
|
278
|
+
} {
|
|
279
|
+
const modeled = new Set<string>();
|
|
280
|
+
const verbatim = new Set<string>();
|
|
281
|
+
JSON.stringify([doc.content, doc.comments, doc.stories], (key, value) => {
|
|
282
|
+
if (key === "xml" && typeof value === "string")
|
|
283
|
+
for (const [, kind] of value.matchAll(/(foot|end)noteReference/g))
|
|
284
|
+
verbatim.add(`${kind}note`);
|
|
285
|
+
const node = value as { type?: unknown; attrs?: { story?: unknown } } | null;
|
|
286
|
+
if (node?.type === "noteReference" && typeof node.attrs?.story === "string")
|
|
287
|
+
modeled.add(node.attrs.story);
|
|
288
|
+
return value;
|
|
289
|
+
});
|
|
290
|
+
return {
|
|
291
|
+
modeled,
|
|
292
|
+
isReferenced: (key) => modeled.has(key) || verbatim.has(key.split(":")[0] as string),
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** `text` if it is a well-formed part whose `w:` content is WordprocessingML; DocxError if not. */
|
|
297
|
+
function checkedPart(name: string, text: string): string {
|
|
298
|
+
let root: XmlElement;
|
|
299
|
+
try {
|
|
300
|
+
root = parseXml(text).root;
|
|
301
|
+
} catch (error) {
|
|
302
|
+
throw new DocxError(`${name}: its namespaces do not fit what is written: ${error}`, {
|
|
303
|
+
cause: error,
|
|
304
|
+
});
|
|
305
|
+
}
|
|
306
|
+
for (const child of root.children)
|
|
307
|
+
if (child.kind === "element" && child.prefix === "w" && child.ns !== W)
|
|
308
|
+
throw new DocxError(`${name}: its w: prefix is not WordprocessingML`);
|
|
309
|
+
return text;
|
|
211
310
|
}
|
|
212
311
|
|
|
213
312
|
const PARA_ID = "w14:paraId";
|
|
@@ -270,12 +369,32 @@ function withThreadIds(doc: FoliDocument, pkg: DocxPackage | undefined): FoliDoc
|
|
|
270
369
|
return copy;
|
|
271
370
|
}
|
|
272
371
|
|
|
372
|
+
/** A free name for a new part: `/word/header1.xml`, `/word/header2.xml`… */
|
|
373
|
+
function freePart(stem: string, taken: (name: string) => boolean): string {
|
|
374
|
+
let n = 1;
|
|
375
|
+
while (taken(`/word/${stem}${n}.xml`)) n++;
|
|
376
|
+
return `/word/${stem}${n}.xml`;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const HEADER_FOOTER = {
|
|
380
|
+
header: { root: "w:hdr", rel: REL.header, contentType: CT.header },
|
|
381
|
+
footer: { root: "w:ftr", rel: REL.footer, contentType: CT.footer },
|
|
382
|
+
} as const;
|
|
383
|
+
const NOTES = {
|
|
384
|
+
footnote: { rel: REL.footnotes, contentType: CT.footnotes, name: "/word/footnotes.xml" },
|
|
385
|
+
endnote: { rel: REL.endnotes, contentType: CT.endnotes, name: "/word/endnotes.xml" },
|
|
386
|
+
} as const;
|
|
387
|
+
const NOTE_KINDS = ["footnote", "endnote"] as const;
|
|
388
|
+
|
|
273
389
|
async function intoPackage(
|
|
274
390
|
doc: FoliDocument,
|
|
275
391
|
pkg: DocxPackage,
|
|
392
|
+
originals: Readonly<Record<string, StoryJSON>>,
|
|
393
|
+
unchanged: (id: string) => boolean,
|
|
394
|
+
isReferenced: (key: string) => boolean,
|
|
276
395
|
options: ExportOptions,
|
|
277
396
|
media: Media,
|
|
278
|
-
): Promise<Uint8Array
|
|
397
|
+
): Promise<Uint8Array<ArrayBuffer>> {
|
|
279
398
|
const mainName = pkg.mainDocument;
|
|
280
399
|
const main = pkg.xml(mainName);
|
|
281
400
|
const body = child(main.root, "body");
|
|
@@ -376,14 +495,85 @@ async function intoPackage(
|
|
|
376
495
|
);
|
|
377
496
|
}
|
|
378
497
|
|
|
498
|
+
// Stories: none in the document (schema v4, or none read) leaves their parts as they are.
|
|
499
|
+
const stories = doc.stories ?? {};
|
|
500
|
+
const ownRelationships = (name: string, existing: boolean) =>
|
|
501
|
+
new Relationships(existing ? pkg.relationships(name) : []);
|
|
502
|
+
const newNames = new Set<string>();
|
|
503
|
+
const writtenStories = new Map<string, string>();
|
|
504
|
+
for (const [id, story] of Object.entries(stories)) {
|
|
505
|
+
if (story.kind !== "header" && story.kind !== "footer") continue;
|
|
506
|
+
const { root, rel, contentType } = HEADER_FOOTER[story.kind];
|
|
507
|
+
const related = pkg.relationships(mainName).find((r) => r.id === id);
|
|
508
|
+
// Only a part this story was read from: an id can name any relationship of the package.
|
|
509
|
+
if (related && (related.type !== rel || !Object.hasOwn(originals, id)))
|
|
510
|
+
throw new DocxError(`Story ${id.slice(0, 64)} has the id of another relationship`);
|
|
511
|
+
if (!related && !/^[A-Za-z_][\w.-]*$/.test(id))
|
|
512
|
+
throw new DocxError(`Not a relationship id: ${id.slice(0, 64)}`);
|
|
513
|
+
const existing = related?.partName ? pkg.part(related.partName) : undefined;
|
|
514
|
+
if (existing && unchanged(id)) continue;
|
|
515
|
+
const name = existing?.name ?? freePart(story.kind, (n) => !!pkg.part(n) || newNames.has(n));
|
|
516
|
+
const xml = existing ? pkg.xml(existing.name) : undefined;
|
|
517
|
+
const ns = xml ? namespacesOf(xml.root, xml.source) : namespaces;
|
|
518
|
+
const partRels = ownRelationships(name, !!existing);
|
|
519
|
+
const inner = blocksXml(story.content.content ?? [], contextFor(ns, partRels, media, name));
|
|
520
|
+
const text = checkedPart(
|
|
521
|
+
name,
|
|
522
|
+
wrapPart(xml && { root: xml.root, source: xml.source }, root, ns, inner),
|
|
523
|
+
);
|
|
524
|
+
// Two relationships can share a part: both stories must then say the same.
|
|
525
|
+
const earlier = writtenStories.get(name);
|
|
526
|
+
if (earlier !== undefined && earlier !== text)
|
|
527
|
+
throw new DocxError(`${name} is shared by stories that differ`);
|
|
528
|
+
writtenStories.set(name, text);
|
|
529
|
+
if (existing) set(name, text);
|
|
530
|
+
else {
|
|
531
|
+
newNames.add(name);
|
|
532
|
+
add.push({ name, data: encoder.encode(text), contentType });
|
|
533
|
+
rels.add(rel, relative(mainName, name), false, id);
|
|
534
|
+
}
|
|
535
|
+
if (partRels.added.length) writeRelationships(name, partRels);
|
|
536
|
+
}
|
|
537
|
+
for (const kind of NOTE_KINDS) {
|
|
538
|
+
const { rel, contentType, name: defaultName } = NOTES[kind];
|
|
539
|
+
const name = pkg.relationships(mainName).find((r) => r.type === rel)?.partName;
|
|
540
|
+
const held = Object.values(stories).some((s) => s.kind === kind);
|
|
541
|
+
if (!name && !held) continue;
|
|
542
|
+
if (name && !doc.stories) continue;
|
|
543
|
+
const target = name ?? defaultName;
|
|
544
|
+
if (name && !isW(pkg.xml(name).root, `${kind}s`)) {
|
|
545
|
+
if (held) throw new DocxError(`${name} is not a ${kind}s part`);
|
|
546
|
+
continue;
|
|
547
|
+
}
|
|
548
|
+
const partRels = ownRelationships(target, !!name);
|
|
549
|
+
const write = (o: OriginalPart | undefined, ns: Namespaces) =>
|
|
550
|
+
checkedPart(
|
|
551
|
+
target,
|
|
552
|
+
notesXml(kind, stories, originals, unchanged, isReferenced, o, {
|
|
553
|
+
...contextFor(ns, partRels, media, target),
|
|
554
|
+
note: kind,
|
|
555
|
+
}),
|
|
556
|
+
);
|
|
557
|
+
part(rel, defaultName, contentType, write, held);
|
|
558
|
+
if (partRels.added.length) writeRelationships(target, partRels);
|
|
559
|
+
}
|
|
560
|
+
|
|
379
561
|
const { trackRevisions } = options;
|
|
380
|
-
|
|
562
|
+
const { settings } = doc;
|
|
563
|
+
if (trackRevisions !== undefined || settings) {
|
|
381
564
|
part(
|
|
382
565
|
REL.settings,
|
|
383
566
|
"/word/settings.xml",
|
|
384
567
|
CT.settings,
|
|
385
|
-
(o) =>
|
|
386
|
-
|
|
568
|
+
(o) => {
|
|
569
|
+
if (!o) return newSettingsXml(!!trackRevisions, settings);
|
|
570
|
+
const source =
|
|
571
|
+
trackRevisions === undefined
|
|
572
|
+
? o.source
|
|
573
|
+
: withTrackRevisions(o.source, o.root, trackRevisions);
|
|
574
|
+
return settings ? withSettings(source, parseXml(source).root, settings) : source;
|
|
575
|
+
},
|
|
576
|
+
!!trackRevisions || !!settings,
|
|
387
577
|
);
|
|
388
578
|
}
|
|
389
579
|
|
|
@@ -439,9 +629,10 @@ function changedThreads(doc: FoliDocument, pkg: DocxPackage): boolean {
|
|
|
439
629
|
/** A new package: content types, relationships, the document and the parts it needs. */
|
|
440
630
|
async function newPackage(
|
|
441
631
|
doc: FoliDocument,
|
|
632
|
+
isReferenced: (key: string) => boolean,
|
|
442
633
|
options: ExportOptions,
|
|
443
634
|
media: Media,
|
|
444
|
-
): Promise<Uint8Array
|
|
635
|
+
): Promise<Uint8Array<ArrayBuffer>> {
|
|
445
636
|
const rels = new Relationships([]);
|
|
446
637
|
const context = contextFor(DEFAULT_NAMESPACES, rels, media, "/word/document.xml");
|
|
447
638
|
const main = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n<w:document ${NEW_ROOT_ATTRIBUTES}><w:body>${blocksXml(doc.content.content ?? [], context)}${bodySection(doc, DEFAULT_NAMESPACES)}</w:body></w:document>`;
|
|
@@ -461,6 +652,51 @@ async function newPackage(
|
|
|
461
652
|
numberingXml(doc, undefined, DEFAULT_NAMESPACES),
|
|
462
653
|
);
|
|
463
654
|
}
|
|
655
|
+
for (const [id, story] of Object.entries(doc.stories ?? {})) {
|
|
656
|
+
if (story.kind !== "header" && story.kind !== "footer") continue;
|
|
657
|
+
if (!/^[A-Za-z_][\w.-]*$/.test(id))
|
|
658
|
+
throw new DocxError(`Not a relationship id: ${id.slice(0, 64)}`);
|
|
659
|
+
const { root, rel, contentType } = HEADER_FOOTER[story.kind];
|
|
660
|
+
const name = freePart(story.kind, (n) => parts.some((p) => p.name === n));
|
|
661
|
+
const partRels = new Relationships([]);
|
|
662
|
+
const inner = blocksXml(
|
|
663
|
+
story.content.content ?? [],
|
|
664
|
+
contextFor(DEFAULT_NAMESPACES, partRels, media, name),
|
|
665
|
+
);
|
|
666
|
+
parts.push({
|
|
667
|
+
name,
|
|
668
|
+
text: wrapPart(undefined, root, DEFAULT_NAMESPACES, inner),
|
|
669
|
+
contentType,
|
|
670
|
+
});
|
|
671
|
+
rels.add(rel, relative("/word/document.xml", name), false, id);
|
|
672
|
+
if (partRels.added.length)
|
|
673
|
+
parts.push({
|
|
674
|
+
name: relationshipsPartName(name),
|
|
675
|
+
text: partRels.xml(undefined),
|
|
676
|
+
contentType: CT.rels,
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
for (const kind of NOTE_KINDS) {
|
|
680
|
+
const stories = doc.stories ?? {};
|
|
681
|
+
if (!Object.values(stories).some((s) => s.kind === kind)) continue;
|
|
682
|
+
const { rel, contentType, name } = NOTES[kind];
|
|
683
|
+
const partRels = new Relationships([]);
|
|
684
|
+
add(
|
|
685
|
+
name,
|
|
686
|
+
rel,
|
|
687
|
+
contentType,
|
|
688
|
+
notesXml(kind, stories, {}, () => false, isReferenced, undefined, {
|
|
689
|
+
...contextFor(DEFAULT_NAMESPACES, partRels, media, name),
|
|
690
|
+
note: kind,
|
|
691
|
+
}),
|
|
692
|
+
);
|
|
693
|
+
if (partRels.added.length)
|
|
694
|
+
parts.push({
|
|
695
|
+
name: relationshipsPartName(name),
|
|
696
|
+
text: partRels.xml(undefined),
|
|
697
|
+
contentType: CT.rels,
|
|
698
|
+
});
|
|
699
|
+
}
|
|
464
700
|
if (doc.comments.length) {
|
|
465
701
|
const commentRels = new Relationships([]);
|
|
466
702
|
add(
|
|
@@ -488,8 +724,13 @@ async function newPackage(
|
|
|
488
724
|
);
|
|
489
725
|
}
|
|
490
726
|
}
|
|
491
|
-
if (options.trackRevisions)
|
|
492
|
-
add(
|
|
727
|
+
if (options.trackRevisions || doc.settings)
|
|
728
|
+
add(
|
|
729
|
+
"/word/settings.xml",
|
|
730
|
+
REL.settings,
|
|
731
|
+
CT.settings,
|
|
732
|
+
newSettingsXml(!!options.trackRevisions, doc.settings),
|
|
733
|
+
);
|
|
493
734
|
parts.push({
|
|
494
735
|
name: "/word/_rels/document.xml.rels",
|
|
495
736
|
text: rels.xml(undefined),
|
|
@@ -530,11 +771,18 @@ function bodySection(doc: FoliDocument, namespaces: Namespaces): string {
|
|
|
530
771
|
function packageReference(doc: FoliDocument): string | undefined {
|
|
531
772
|
const sections = [doc.section, ...(doc.content.content ?? []).map((b) => b.attrs?.section)];
|
|
532
773
|
for (const s of sections) {
|
|
533
|
-
const section = s as
|
|
534
|
-
|
|
774
|
+
const section = s as
|
|
775
|
+
| { headers?: Record<string, string>; footers?: Record<string, string> }
|
|
776
|
+
| undefined;
|
|
777
|
+
const ids = [
|
|
778
|
+
...Object.values(section?.headers ?? {}),
|
|
779
|
+
...Object.values(section?.footers ?? {}),
|
|
780
|
+
];
|
|
781
|
+
if (ids.some((id) => !doc.stories || !Object.hasOwn(doc.stories, id)))
|
|
782
|
+
return "a header or footer";
|
|
535
783
|
}
|
|
536
784
|
let found: string | undefined;
|
|
537
|
-
JSON.stringify([doc.content, doc.comments], (key, value) => {
|
|
785
|
+
JSON.stringify([doc.content, doc.comments, doc.stories], (key, value) => {
|
|
538
786
|
if (!found && key === "xml" && typeof value === "string" && /\sr:[A-Za-z]+="/.test(value))
|
|
539
787
|
found = "content kept verbatim";
|
|
540
788
|
const link = value as {
|
package/src/export/parts.ts
CHANGED
|
@@ -12,9 +12,10 @@ import type {
|
|
|
12
12
|
FoliDocument,
|
|
13
13
|
NumberingInstanceJSON,
|
|
14
14
|
NumberingLevelJSON,
|
|
15
|
+
StoryJSON,
|
|
15
16
|
StyleJSON,
|
|
16
17
|
} from "@folijs/core";
|
|
17
|
-
import { attr, child, isW, W, W15 } from "../import/ooxml.js";
|
|
18
|
+
import { attr, child, integer, isW, W, W15 } from "../import/ooxml.js";
|
|
18
19
|
import {
|
|
19
20
|
abstractOf,
|
|
20
21
|
defaultsOf,
|
|
@@ -24,6 +25,7 @@ import {
|
|
|
24
25
|
usableStyle,
|
|
25
26
|
} from "../import/parts.js";
|
|
26
27
|
import { Recorder } from "../import/report.js";
|
|
28
|
+
import { notesOf } from "../import/stories.js";
|
|
27
29
|
import { DocxError } from "../package.js";
|
|
28
30
|
import type { XmlElement, XmlNode } from "../xml.js";
|
|
29
31
|
import { blocksXml, type WriteContext } from "./content.js";
|
|
@@ -41,6 +43,7 @@ import {
|
|
|
41
43
|
} from "./xmlout.js";
|
|
42
44
|
|
|
43
45
|
type Json = Record<string, unknown>;
|
|
46
|
+
/** @internal */
|
|
44
47
|
export interface OriginalPart {
|
|
45
48
|
readonly root: XmlElement;
|
|
46
49
|
readonly source: string;
|
|
@@ -74,8 +77,11 @@ function childSource(
|
|
|
74
77
|
return c && o ? o.source.slice(c.start, c.end) : undefined;
|
|
75
78
|
}
|
|
76
79
|
|
|
77
|
-
/**
|
|
78
|
-
|
|
80
|
+
/**
|
|
81
|
+
* A part's text: the original's prolog and root around `children`, or a new root.
|
|
82
|
+
* @internal
|
|
83
|
+
*/
|
|
84
|
+
export function wrapPart(
|
|
79
85
|
part: OriginalPart | undefined,
|
|
80
86
|
rootName: string,
|
|
81
87
|
ns: Namespaces,
|
|
@@ -182,19 +188,25 @@ const STYLE_ORDER = [
|
|
|
182
188
|
"tblStylePr",
|
|
183
189
|
];
|
|
184
190
|
|
|
191
|
+
const TABLE_STYLE_KEYS = ["table", "row", "cell", "conditions"] as const;
|
|
192
|
+
|
|
185
193
|
function styleXml(style: StyleJSON, ns: Namespaces): string {
|
|
186
194
|
const o = original(style.ext, ns);
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
195
|
+
let reread = o ? styleOf(o.element, reading(o.source)) : undefined;
|
|
196
|
+
// A schema 3 document (0.3.0, 0.4.0) kept a table style's parts in `ext` only: none of them
|
|
197
|
+
// in the model means they were never read, not removed, so they are written as read. Not
|
|
198
|
+
// gated on the version: a v3 document loaded and saved again says v5, and would then never
|
|
199
|
+
// export. An app that clears all four of a read style's parts gets them written as read (one
|
|
200
|
+
// part changed or left is compared, and refused when changed).
|
|
201
|
+
if (reread && TABLE_STYLE_KEYS.every((key) => style[key] === undefined)) {
|
|
202
|
+
reread = { ...reread };
|
|
203
|
+
for (const key of TABLE_STYLE_KEYS) delete reread[key];
|
|
190
204
|
}
|
|
191
|
-
|
|
205
|
+
if (reread && same(normalizeStyle(style), normalizeStyle(reread))) return style.ext as string;
|
|
192
206
|
// A table style read from the file has its parts written as read (`w:tblPr`… kept): a change
|
|
193
207
|
// would be lost. A new one (Word's Table Grid, added by a command) is written from the model,
|
|
194
208
|
// without conditional formats.
|
|
195
|
-
for (const key of o
|
|
196
|
-
? (["table", "row", "cell", "conditions"] as const)
|
|
197
|
-
: (["conditions"] as const)) {
|
|
209
|
+
for (const key of o ? TABLE_STYLE_KEYS : (["conditions"] as const)) {
|
|
198
210
|
if (!same(style[key], reread?.[key])) {
|
|
199
211
|
throw new DocxError(
|
|
200
212
|
`Style ${style.id}: a changed table style (${key}) cannot be exported yet`,
|
|
@@ -270,6 +282,7 @@ function defaultsXml(defaults: FoliDocument["defaults"], ns: Namespaces): string
|
|
|
270
282
|
return `<w:docDefaults${attributesOf(o)}>${rPr ? `<w:rPrDefault>${rPr}</w:rPrDefault>` : "<w:rPrDefault/>"}${pPr ? `<w:pPrDefault>${pPr}</w:pPrDefault>` : "<w:pPrDefault/>"}</w:docDefaults>`;
|
|
271
283
|
}
|
|
272
284
|
|
|
285
|
+
/** @internal */
|
|
273
286
|
export function stylesXml(
|
|
274
287
|
doc: FoliDocument,
|
|
275
288
|
part: OriginalPart | undefined,
|
|
@@ -412,6 +425,7 @@ function instanceXml(instance: NumberingInstanceJSON, ns: Namespaces): string {
|
|
|
412
425
|
return `${open}>${children}</w:num>`;
|
|
413
426
|
}
|
|
414
427
|
|
|
428
|
+
/** @internal */
|
|
415
429
|
export function numberingXml(
|
|
416
430
|
doc: FoliDocument,
|
|
417
431
|
part: OriginalPart | undefined,
|
|
@@ -510,6 +524,7 @@ function commentStart(comment: CommentJSON, ns: Namespaces): string {
|
|
|
510
524
|
}).replace(/\/>$/, ">");
|
|
511
525
|
}
|
|
512
526
|
|
|
527
|
+
/** @internal */
|
|
513
528
|
export function commentsXml(
|
|
514
529
|
doc: FoliDocument,
|
|
515
530
|
part: OriginalPart | undefined,
|
|
@@ -535,9 +550,86 @@ export function commentsXml(
|
|
|
535
550
|
return wrapPart(part, "w:comments", context.namespaces, body + added);
|
|
536
551
|
}
|
|
537
552
|
|
|
553
|
+
/**
|
|
554
|
+
* The separators a new notes part starts with, as Word writes them (unless it has its own): single
|
|
555
|
+
* spaced, nothing after.
|
|
556
|
+
*/
|
|
557
|
+
const noteSeparators = (
|
|
558
|
+
kind: "footnote" | "endnote",
|
|
559
|
+
stories: Readonly<Record<string, StoryJSON>>,
|
|
560
|
+
) =>
|
|
561
|
+
(Object.hasOwn(stories, `${kind}:-1`)
|
|
562
|
+
? ""
|
|
563
|
+
: `<w:${kind} w:type="separator" w:id="-1"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:separator/></w:r></w:p></w:${kind}>`) +
|
|
564
|
+
(Object.hasOwn(stories, `${kind}:0`)
|
|
565
|
+
? ""
|
|
566
|
+
: `<w:${kind} w:type="continuationSeparator" w:id="0"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></w:${kind}>`);
|
|
567
|
+
|
|
568
|
+
/**
|
|
569
|
+
* A footnotes or endnotes part: a note unchanged from `originals` keeps its bytes, a changed one
|
|
570
|
+
* is written from its story, and new ones go at the end. One whose story is gone is removed,
|
|
571
|
+
* unless Word needs it: a separator, or a note something still refers to (`isReferenced`).
|
|
572
|
+
* @internal
|
|
573
|
+
*/
|
|
574
|
+
export function notesXml(
|
|
575
|
+
kind: "footnote" | "endnote",
|
|
576
|
+
stories: Readonly<Record<string, StoryJSON>>,
|
|
577
|
+
originals: Readonly<Record<string, StoryJSON>>,
|
|
578
|
+
unchanged: (key: string) => boolean,
|
|
579
|
+
isReferenced: (key: string) => boolean,
|
|
580
|
+
part: OriginalPart | undefined,
|
|
581
|
+
context: WriteContext,
|
|
582
|
+
): string {
|
|
583
|
+
const write = (key: string, story: StoryJSON) => {
|
|
584
|
+
if (!new RegExp(`^${kind}:-?\\d+$`).test(key))
|
|
585
|
+
throw new DocxError(`Not the id of a ${kind}: ${key.slice(0, 64)}`);
|
|
586
|
+
const type = story.noteType ? ` w:type="${story.noteType}"` : "";
|
|
587
|
+
if (story.ext) {
|
|
588
|
+
// The element it was read from must be this note: a copy would repeat another's id.
|
|
589
|
+
const { element } = fragment(story.ext.replace(/\/?>$/, "/>"), context.namespaces, kind);
|
|
590
|
+
if (
|
|
591
|
+
integer(attr(element, "id")) !== Number(key.slice(kind.length + 1)) ||
|
|
592
|
+
attr(element, "type") !== story.noteType
|
|
593
|
+
)
|
|
594
|
+
throw new DocxError(`The start tag kept for ${key.slice(0, 64)} is another note's`);
|
|
595
|
+
}
|
|
596
|
+
const start =
|
|
597
|
+
story.ext?.replace(/\/>$/, ">") ?? `<w:${kind}${type} w:id="${key.slice(kind.length + 1)}">`;
|
|
598
|
+
return `${start}${blocksXml(story.content.content ?? [], context)}</w:${kind}>`;
|
|
599
|
+
};
|
|
600
|
+
const seen = new Set<string>();
|
|
601
|
+
const held = part ? notesOf(part.root, kind) : new Map<string, XmlElement>();
|
|
602
|
+
const keyOf = new Map([...held].map(([key, el]) => [el, key]));
|
|
603
|
+
const body = rebuild<string>(
|
|
604
|
+
part,
|
|
605
|
+
(child) => {
|
|
606
|
+
const key = keyOf.get(child);
|
|
607
|
+
if (key === undefined) return undefined;
|
|
608
|
+
seen.add(key);
|
|
609
|
+
if (!Object.hasOwn(stories, key)) {
|
|
610
|
+
const original = originals[key];
|
|
611
|
+
const needed =
|
|
612
|
+
!original || (original.noteType ?? "normal") !== "normal" || isReferenced(key);
|
|
613
|
+
return needed ? undefined : null;
|
|
614
|
+
}
|
|
615
|
+
const story = stories[key] as StoryJSON;
|
|
616
|
+
return story && unchanged(key) ? undefined : key;
|
|
617
|
+
},
|
|
618
|
+
(key) => write(key, stories[key] as StoryJSON),
|
|
619
|
+
[],
|
|
620
|
+
);
|
|
621
|
+
const added = Object.entries(stories)
|
|
622
|
+
.filter(([key, story]) => story.kind === kind && !seen.has(key))
|
|
623
|
+
.map(([key, story]) => write(key, story))
|
|
624
|
+
.join("");
|
|
625
|
+
const separators = part ? "" : noteSeparators(kind, stories);
|
|
626
|
+
return wrapPart(part, `w:${kind}s`, context.namespaces, separators + body + added);
|
|
627
|
+
}
|
|
628
|
+
|
|
538
629
|
/**
|
|
539
630
|
* `commentsExtended.xml` for the comments' replies and resolved state, keyed by the `w14:paraId`
|
|
540
631
|
* of each comment's last paragraph (comments without one cannot be listed).
|
|
632
|
+
* @internal
|
|
541
633
|
*/
|
|
542
634
|
export function commentsExtendedXml(doc: FoliDocument, part: OriginalPart | undefined): string {
|
|
543
635
|
const paraId = (c: CommentJSON) => {
|