@folijs/docx 0.4.0 → 0.6.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 +59 -0
- package/README.md +95 -15
- package/dist/export/balance.d.ts +17 -0
- package/dist/export/balance.d.ts.map +1 -0
- package/dist/export/balance.js +111 -0
- package/dist/export/balance.js.map +1 -0
- package/dist/export/content.d.ts +7 -0
- package/dist/export/content.d.ts.map +1 -1
- package/dist/export/content.js +185 -14
- package/dist/export/content.js.map +1 -1
- package/dist/export/controls.d.ts +18 -0
- package/dist/export/controls.d.ts.map +1 -0
- package/dist/export/controls.js +232 -0
- package/dist/export/controls.js.map +1 -0
- package/dist/export/index.d.ts +6 -1
- package/dist/export/index.d.ts.map +1 -1
- package/dist/export/index.js +277 -28
- package/dist/export/index.js.map +1 -1
- package/dist/export/parts.d.ts +9 -1
- package/dist/export/parts.d.ts.map +1 -1
- package/dist/export/parts.js +69 -2
- package/dist/export/parts.js.map +1 -1
- package/dist/export/pictures.d.ts +54 -0
- package/dist/export/pictures.d.ts.map +1 -0
- package/dist/export/pictures.js +359 -0
- package/dist/export/pictures.js.map +1 -0
- package/dist/export/properties.d.ts +11 -1
- package/dist/export/properties.d.ts.map +1 -1
- package/dist/export/properties.js +57 -3
- package/dist/export/properties.js.map +1 -1
- package/dist/export/tables.d.ts +27 -0
- package/dist/export/tables.d.ts.map +1 -0
- package/dist/export/tables.js +344 -0
- package/dist/export/tables.js.map +1 -0
- package/dist/images.d.ts +21 -0
- package/dist/images.d.ts.map +1 -0
- package/dist/images.js +53 -0
- package/dist/images.js.map +1 -0
- package/dist/import/content.d.ts +15 -1
- package/dist/import/content.d.ts.map +1 -1
- package/dist/import/content.js +357 -15
- package/dist/import/content.js.map +1 -1
- package/dist/import/controls.d.ts +14 -0
- package/dist/import/controls.d.ts.map +1 -0
- package/dist/import/controls.js +123 -0
- package/dist/import/controls.js.map +1 -0
- package/dist/import/index.d.ts +10 -2
- package/dist/import/index.d.ts.map +1 -1
- package/dist/import/index.js +76 -13
- package/dist/import/index.js.map +1 -1
- package/dist/import/ooxml.d.ts +4 -0
- package/dist/import/ooxml.d.ts.map +1 -1
- package/dist/import/ooxml.js +4 -0
- package/dist/import/ooxml.js.map +1 -1
- package/dist/import/parts.d.ts.map +1 -1
- package/dist/import/parts.js +8 -1
- package/dist/import/parts.js.map +1 -1
- package/dist/import/pictures.d.ts +34 -0
- package/dist/import/pictures.d.ts.map +1 -0
- package/dist/import/pictures.js +147 -0
- package/dist/import/pictures.js.map +1 -0
- package/dist/import/properties.d.ts +2 -0
- package/dist/import/properties.d.ts.map +1 -1
- package/dist/import/properties.js +55 -0
- package/dist/import/properties.js.map +1 -1
- package/dist/import/report.d.ts +6 -0
- package/dist/import/report.d.ts.map +1 -1
- package/dist/import/report.js +5 -0
- package/dist/import/report.js.map +1 -1
- package/dist/import/stories.d.ts +19 -0
- package/dist/import/stories.d.ts.map +1 -0
- package/dist/import/stories.js +119 -0
- package/dist/import/stories.js.map +1 -0
- package/dist/import/tables.d.ts +31 -0
- package/dist/import/tables.d.ts.map +1 -0
- package/dist/import/tables.js +236 -0
- package/dist/import/tables.js.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/settings.d.ts +18 -4
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +173 -26
- package/dist/settings.js.map +1 -1
- package/package.json +3 -3
- package/src/export/balance.ts +113 -0
- package/src/export/content.ts +240 -15
- package/src/export/controls.ts +259 -0
- package/src/export/index.ts +357 -32
- package/src/export/parts.ts +94 -2
- package/src/export/pictures.ts +411 -0
- package/src/export/properties.ts +69 -3
- package/src/export/tables.ts +386 -0
- package/src/images.ts +60 -0
- package/src/import/content.ts +365 -17
- package/src/import/controls.ts +137 -0
- package/src/import/index.ts +87 -12
- package/src/import/ooxml.ts +4 -0
- package/src/import/parts.ts +14 -1
- package/src/import/pictures.ts +176 -0
- package/src/import/properties.ts +59 -0
- package/src/import/report.ts +11 -0
- package/src/import/stories.ts +122 -0
- package/src/import/tables.ts +267 -0
- package/src/index.ts +1 -0
- package/src/settings.ts +191 -27
package/src/export/index.ts
CHANGED
|
@@ -5,20 +5,34 @@
|
|
|
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 FoliDocument,
|
|
11
|
+
type NodeJSON,
|
|
12
|
+
parseDocument,
|
|
13
|
+
type ResourceJSON,
|
|
14
|
+
type SectionJSON,
|
|
15
|
+
type StoryJSON,
|
|
16
|
+
} from "@folijs/core";
|
|
17
|
+
import { controlsUsed, noteIds, packageStories } from "../import/index.js";
|
|
18
|
+
import { child, isW, REL, W } from "../import/ooxml.js";
|
|
10
19
|
import { DocxError, type DocxPackage, type NewPart } from "../package.js";
|
|
11
|
-
import { newSettingsXml, withTrackRevisions } from "../settings.js";
|
|
20
|
+
import { newSettingsXml, withSettings, withTrackRevisions } from "../settings.js";
|
|
21
|
+
import { parseXml, type XmlElement } from "../xml.js";
|
|
12
22
|
import { deflateEntry, writeZip } from "../zip.js";
|
|
23
|
+
import { balanced } from "./balance.js";
|
|
13
24
|
import { blocksXml, type WriteContext } from "./content.js";
|
|
14
25
|
import {
|
|
15
26
|
commentsExtendedXml,
|
|
16
27
|
commentsXml,
|
|
28
|
+
notesXml,
|
|
17
29
|
numberingXml,
|
|
18
30
|
type OriginalPart,
|
|
19
31
|
stylesXml,
|
|
32
|
+
wrapPart,
|
|
20
33
|
} from "./parts.js";
|
|
21
|
-
import {
|
|
34
|
+
import { drawingXml, Media, pictureBytes } from "./pictures.js";
|
|
35
|
+
import { same, sectionXml } from "./properties.js";
|
|
22
36
|
import {
|
|
23
37
|
DEFAULT_NAMESPACES,
|
|
24
38
|
escapeAttribute,
|
|
@@ -35,6 +49,10 @@ const CT = {
|
|
|
35
49
|
commentsExtended:
|
|
36
50
|
"application/vnd.openxmlformats-officedocument.wordprocessingml.commentsExtended+xml",
|
|
37
51
|
settings: "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml",
|
|
52
|
+
header: "application/vnd.openxmlformats-officedocument.wordprocessingml.header+xml",
|
|
53
|
+
footer: "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml",
|
|
54
|
+
footnotes: "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml",
|
|
55
|
+
endnotes: "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml",
|
|
38
56
|
rels: "application/vnd.openxmlformats-package.relationships+xml",
|
|
39
57
|
};
|
|
40
58
|
|
|
@@ -45,17 +63,51 @@ class Relationships {
|
|
|
45
63
|
readonly added: { id: string; type: string; target: string; external: boolean }[] = [];
|
|
46
64
|
readonly #ids: Set<string>;
|
|
47
65
|
readonly #byTarget = new Map<string, string>();
|
|
48
|
-
readonly #existing: ReadonlyMap<
|
|
66
|
+
readonly #existing: ReadonlyMap<
|
|
67
|
+
string,
|
|
68
|
+
{ type: string; target: string; external: boolean; partName?: string }
|
|
69
|
+
>;
|
|
70
|
+
/** The part each internal relationship points to (resolved, as the package resolves it). */
|
|
71
|
+
readonly #parts = new Map<string, string>();
|
|
49
72
|
|
|
50
73
|
constructor(
|
|
51
|
-
existing: readonly {
|
|
74
|
+
existing: readonly {
|
|
75
|
+
id: string;
|
|
76
|
+
type: string;
|
|
77
|
+
target: string;
|
|
78
|
+
external: boolean;
|
|
79
|
+
partName?: string;
|
|
80
|
+
}[],
|
|
52
81
|
) {
|
|
53
82
|
this.#existing = new Map(existing.map((r) => [r.id, r]));
|
|
83
|
+
for (const r of existing) if (!r.external && r.partName) this.#parts.set(r.id, r.partName);
|
|
54
84
|
this.#ids = new Set(existing.map((r) => r.id));
|
|
55
85
|
for (const r of existing)
|
|
56
86
|
if (r.type === REL.hyperlink && r.external) this.#byTarget.set(r.target, r.id);
|
|
57
87
|
}
|
|
58
88
|
|
|
89
|
+
/** The part relationship `id` points to (one it had, or one added), if internal. */
|
|
90
|
+
target(id: string): string | undefined {
|
|
91
|
+
return this.#parts.get(id);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* The relationship to image part `part` (absolute; `target` as this part refers to it):
|
|
96
|
+
* `current` when it is one, else a known or new one. Compared by part, not by the target's
|
|
97
|
+
* text (`/word/media/x.png`, `./media/x.png` and `media/x.png` are one part).
|
|
98
|
+
*/
|
|
99
|
+
image(part: string, target: string, current: string | undefined): string {
|
|
100
|
+
const isImage = (id: string) => {
|
|
101
|
+
const r = this.#existing.get(id) ?? this.added.find((a) => a.id === id);
|
|
102
|
+
return r?.type === REL_IMAGE && this.#parts.get(id)?.toLowerCase() === part.toLowerCase();
|
|
103
|
+
};
|
|
104
|
+
if (current !== undefined && isImage(current)) return current;
|
|
105
|
+
for (const id of this.#parts.keys()) if (isImage(id)) return id;
|
|
106
|
+
const id = this.add(REL_IMAGE, target, false);
|
|
107
|
+
this.#parts.set(id, part);
|
|
108
|
+
return id;
|
|
109
|
+
}
|
|
110
|
+
|
|
59
111
|
hyperlink(href: string, id: string | undefined): string {
|
|
60
112
|
const own = id === undefined ? undefined : this.#existing.get(id);
|
|
61
113
|
if (own && own.type === REL.hyperlink && own.target === href) return id as string;
|
|
@@ -64,10 +116,13 @@ class Relationships {
|
|
|
64
116
|
return this.add(REL.hyperlink, href, true);
|
|
65
117
|
}
|
|
66
118
|
|
|
67
|
-
|
|
119
|
+
/** Adds a relationship; `wanted` is its id (a story's), refused if another has it. */
|
|
120
|
+
add(type: string, target: string, external: boolean, wanted?: string): string {
|
|
121
|
+
if (wanted !== undefined && this.#ids.has(wanted))
|
|
122
|
+
throw new DocxError(`Relationship id ${wanted} is already in use`);
|
|
68
123
|
let n = this.#ids.size + 1;
|
|
69
124
|
while (this.#ids.has(`rId${n}`)) n++;
|
|
70
|
-
const id = `rId${n}`;
|
|
125
|
+
const id = wanted ?? `rId${n}`;
|
|
71
126
|
this.#ids.add(id);
|
|
72
127
|
this.added.push({ id, type, target, external });
|
|
73
128
|
if (type === REL.hyperlink && external) this.#byTarget.set(target, id);
|
|
@@ -91,8 +146,29 @@ class Relationships {
|
|
|
91
146
|
}
|
|
92
147
|
}
|
|
93
148
|
|
|
94
|
-
|
|
95
|
-
|
|
149
|
+
const REL_IMAGE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
|
|
150
|
+
|
|
151
|
+
function contextFor(
|
|
152
|
+
namespaces: Namespaces,
|
|
153
|
+
relationships: Relationships,
|
|
154
|
+
media: Media,
|
|
155
|
+
source: string,
|
|
156
|
+
): WriteContext {
|
|
157
|
+
return {
|
|
158
|
+
namespaces,
|
|
159
|
+
controls: media.controls,
|
|
160
|
+
hyperlink: (href, id) => relationships.hyperlink(href, id),
|
|
161
|
+
picture: (attrs) =>
|
|
162
|
+
drawingXml(
|
|
163
|
+
attrs,
|
|
164
|
+
{
|
|
165
|
+
image: (part, current) => relationships.image(part, relative(source, part), current),
|
|
166
|
+
target: (id) => relationships.target(id),
|
|
167
|
+
},
|
|
168
|
+
namespaces,
|
|
169
|
+
media,
|
|
170
|
+
),
|
|
171
|
+
};
|
|
96
172
|
}
|
|
97
173
|
|
|
98
174
|
/** `/word/_rels/document.xml.rels` for `/word/document.xml`. */
|
|
@@ -113,6 +189,14 @@ export interface ExportOptions {
|
|
|
113
189
|
* original package has it (off in a new one).
|
|
114
190
|
*/
|
|
115
191
|
trackRevisions?: boolean;
|
|
192
|
+
/**
|
|
193
|
+
* The bytes of a picture's image the package does not hold and its resource gives no `data:`
|
|
194
|
+
* URL for (an app's upload, by its URL). Undefined: the export fails, never drops it.
|
|
195
|
+
*/
|
|
196
|
+
resource?: (
|
|
197
|
+
key: string,
|
|
198
|
+
resource: ResourceJSON,
|
|
199
|
+
) => Promise<Uint8Array | undefined> | Uint8Array | undefined;
|
|
116
200
|
}
|
|
117
201
|
|
|
118
202
|
/**
|
|
@@ -124,8 +208,94 @@ export async function exportDocx(
|
|
|
124
208
|
original?: DocxPackage,
|
|
125
209
|
options: ExportOptions = {},
|
|
126
210
|
): Promise<Uint8Array> {
|
|
127
|
-
const doc = withThreadIds(parseDocument(document), original);
|
|
128
|
-
|
|
211
|
+
const doc = balanced(withThreadIds(parseDocument(document), original), original);
|
|
212
|
+
// Before the app is asked for any picture's bytes.
|
|
213
|
+
const reference = original ? undefined : packageReference(doc);
|
|
214
|
+
if (reference) {
|
|
215
|
+
throw new DocxError(
|
|
216
|
+
`The document refers to a part of its original package (${reference}): export it with that package`,
|
|
217
|
+
);
|
|
218
|
+
}
|
|
219
|
+
const referenced = noteReferences(doc);
|
|
220
|
+
const read =
|
|
221
|
+
original && (doc.stories || referenced.modeled.size)
|
|
222
|
+
? packageStories(original)
|
|
223
|
+
: { stories: {}, controls: new Map<string, ControlJSON>() };
|
|
224
|
+
const originals: Readonly<Record<string, StoryJSON>> = read.stories;
|
|
225
|
+
// A story is unchanged if its tree is, and the controls in it say what they said.
|
|
226
|
+
const unchanged = (id: string) =>
|
|
227
|
+
Object.hasOwn(originals, id) &&
|
|
228
|
+
same(doc.stories?.[id], originals[id]) &&
|
|
229
|
+
[...controlsUsed(doc.stories?.[id])].every((c) =>
|
|
230
|
+
same(doc.controls?.[c], read.controls.get(c)),
|
|
231
|
+
);
|
|
232
|
+
// Notes the model does not hold (an unknown `w:type`) stay in their part: they count too.
|
|
233
|
+
const inPart = original && referenced.modeled.size ? noteIds(original) : new Set<string>();
|
|
234
|
+
for (const key of referenced.modeled)
|
|
235
|
+
if (!Object.hasOwn(doc.stories ?? {}, key) && !inPart.has(key))
|
|
236
|
+
throw new DocxError(`A note reference has no note: ${key.slice(0, 64)}`);
|
|
237
|
+
// The parts written from the model: their drawings are the document's own.
|
|
238
|
+
const rewritten = original
|
|
239
|
+
? [
|
|
240
|
+
original.mainDocument,
|
|
241
|
+
...original
|
|
242
|
+
.relationships(original.mainDocument)
|
|
243
|
+
.filter(
|
|
244
|
+
(r) =>
|
|
245
|
+
r.partName &&
|
|
246
|
+
(r.type === REL.comments ||
|
|
247
|
+
(doc.stories && Object.hasOwn(doc.stories, r.id) && !unchanged(r.id))),
|
|
248
|
+
)
|
|
249
|
+
.map((r) => r.partName as string),
|
|
250
|
+
]
|
|
251
|
+
: [];
|
|
252
|
+
const bytes = await pictureBytes(doc, original, options.resource);
|
|
253
|
+
const media = new Media(doc, original, bytes, rewritten);
|
|
254
|
+
return original
|
|
255
|
+
? intoPackage(doc, original, originals, unchanged, referenced.isReferenced, options, media)
|
|
256
|
+
: newPackage(doc, referenced.isReferenced, options, media);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* The notes the document refers to, as story ids: `modeled` by `noteReference` nodes. `isReferenced`
|
|
261
|
+
* also says yes to every note of a kind that verbatim XML refers to: which one it means is not
|
|
262
|
+
* worth guessing, and removing a note still referred to makes Word refuse the file.
|
|
263
|
+
*/
|
|
264
|
+
function noteReferences(doc: FoliDocument): {
|
|
265
|
+
modeled: Set<string>;
|
|
266
|
+
isReferenced: (key: string) => boolean;
|
|
267
|
+
} {
|
|
268
|
+
const modeled = new Set<string>();
|
|
269
|
+
const verbatim = new Set<string>();
|
|
270
|
+
JSON.stringify([doc.content, doc.comments, doc.stories], (key, value) => {
|
|
271
|
+
if (key === "xml" && typeof value === "string")
|
|
272
|
+
for (const [, kind] of value.matchAll(/(foot|end)noteReference/g))
|
|
273
|
+
verbatim.add(`${kind}note`);
|
|
274
|
+
const node = value as { type?: unknown; attrs?: { story?: unknown } } | null;
|
|
275
|
+
if (node?.type === "noteReference" && typeof node.attrs?.story === "string")
|
|
276
|
+
modeled.add(node.attrs.story);
|
|
277
|
+
return value;
|
|
278
|
+
});
|
|
279
|
+
return {
|
|
280
|
+
modeled,
|
|
281
|
+
isReferenced: (key) => modeled.has(key) || verbatim.has(key.split(":")[0] as string),
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/** `text` if it is a well-formed part whose `w:` content is WordprocessingML; DocxError if not. */
|
|
286
|
+
function checkedPart(name: string, text: string): string {
|
|
287
|
+
let root: XmlElement;
|
|
288
|
+
try {
|
|
289
|
+
root = parseXml(text).root;
|
|
290
|
+
} catch (error) {
|
|
291
|
+
throw new DocxError(`${name}: its namespaces do not fit what is written: ${error}`, {
|
|
292
|
+
cause: error,
|
|
293
|
+
});
|
|
294
|
+
}
|
|
295
|
+
for (const child of root.children)
|
|
296
|
+
if (child.kind === "element" && child.prefix === "w" && child.ns !== W)
|
|
297
|
+
throw new DocxError(`${name}: its w: prefix is not WordprocessingML`);
|
|
298
|
+
return text;
|
|
129
299
|
}
|
|
130
300
|
|
|
131
301
|
const PARA_ID = "w14:paraId";
|
|
@@ -188,10 +358,31 @@ function withThreadIds(doc: FoliDocument, pkg: DocxPackage | undefined): FoliDoc
|
|
|
188
358
|
return copy;
|
|
189
359
|
}
|
|
190
360
|
|
|
361
|
+
/** A free name for a new part: `/word/header1.xml`, `/word/header2.xml`… */
|
|
362
|
+
function freePart(stem: string, taken: (name: string) => boolean): string {
|
|
363
|
+
let n = 1;
|
|
364
|
+
while (taken(`/word/${stem}${n}.xml`)) n++;
|
|
365
|
+
return `/word/${stem}${n}.xml`;
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
const HEADER_FOOTER = {
|
|
369
|
+
header: { root: "w:hdr", rel: REL.header, contentType: CT.header },
|
|
370
|
+
footer: { root: "w:ftr", rel: REL.footer, contentType: CT.footer },
|
|
371
|
+
} as const;
|
|
372
|
+
const NOTES = {
|
|
373
|
+
footnote: { rel: REL.footnotes, contentType: CT.footnotes, name: "/word/footnotes.xml" },
|
|
374
|
+
endnote: { rel: REL.endnotes, contentType: CT.endnotes, name: "/word/endnotes.xml" },
|
|
375
|
+
} as const;
|
|
376
|
+
const NOTE_KINDS = ["footnote", "endnote"] as const;
|
|
377
|
+
|
|
191
378
|
async function intoPackage(
|
|
192
379
|
doc: FoliDocument,
|
|
193
380
|
pkg: DocxPackage,
|
|
381
|
+
originals: Readonly<Record<string, StoryJSON>>,
|
|
382
|
+
unchanged: (id: string) => boolean,
|
|
383
|
+
isReferenced: (key: string) => boolean,
|
|
194
384
|
options: ExportOptions,
|
|
385
|
+
media: Media,
|
|
195
386
|
): Promise<Uint8Array> {
|
|
196
387
|
const mainName = pkg.mainDocument;
|
|
197
388
|
const main = pkg.xml(mainName);
|
|
@@ -199,7 +390,7 @@ async function intoPackage(
|
|
|
199
390
|
if (!body) throw new DocxError(`${mainName}: no w:body`);
|
|
200
391
|
const namespaces = namespacesOf(main.root, main.source);
|
|
201
392
|
const rels = new Relationships(pkg.relationships(mainName));
|
|
202
|
-
const context = contextFor(namespaces, rels);
|
|
393
|
+
const context = contextFor(namespaces, rels, media, mainName);
|
|
203
394
|
|
|
204
395
|
const content = blocksXml(doc.content.content ?? [], context) + bodySection(doc, namespaces);
|
|
205
396
|
const documentXml =
|
|
@@ -277,7 +468,8 @@ async function intoPackage(
|
|
|
277
468
|
REL.comments,
|
|
278
469
|
"/word/comments.xml",
|
|
279
470
|
CT.comments,
|
|
280
|
-
(o, ns) =>
|
|
471
|
+
(o, ns) =>
|
|
472
|
+
commentsXml(doc, o, contextFor(ns, commentRels, media, commentsName ?? "/word/comments.xml")),
|
|
281
473
|
doc.comments.length > 0,
|
|
282
474
|
);
|
|
283
475
|
if (comments && commentRels.added.length) writeRelationships(comments, commentRels);
|
|
@@ -292,18 +484,90 @@ async function intoPackage(
|
|
|
292
484
|
);
|
|
293
485
|
}
|
|
294
486
|
|
|
487
|
+
// Stories: none in the document (schema v4, or none read) leaves their parts as they are.
|
|
488
|
+
const stories = doc.stories ?? {};
|
|
489
|
+
const ownRelationships = (name: string, existing: boolean) =>
|
|
490
|
+
new Relationships(existing ? pkg.relationships(name) : []);
|
|
491
|
+
const newNames = new Set<string>();
|
|
492
|
+
const writtenStories = new Map<string, string>();
|
|
493
|
+
for (const [id, story] of Object.entries(stories)) {
|
|
494
|
+
if (story.kind !== "header" && story.kind !== "footer") continue;
|
|
495
|
+
const { root, rel, contentType } = HEADER_FOOTER[story.kind];
|
|
496
|
+
const related = pkg.relationships(mainName).find((r) => r.id === id);
|
|
497
|
+
// Only a part this story was read from: an id can name any relationship of the package.
|
|
498
|
+
if (related && (related.type !== rel || !Object.hasOwn(originals, id)))
|
|
499
|
+
throw new DocxError(`Story ${id.slice(0, 64)} has the id of another relationship`);
|
|
500
|
+
if (!related && !/^[A-Za-z_][\w.-]*$/.test(id))
|
|
501
|
+
throw new DocxError(`Not a relationship id: ${id.slice(0, 64)}`);
|
|
502
|
+
const existing = related?.partName ? pkg.part(related.partName) : undefined;
|
|
503
|
+
if (existing && unchanged(id)) continue;
|
|
504
|
+
const name = existing?.name ?? freePart(story.kind, (n) => !!pkg.part(n) || newNames.has(n));
|
|
505
|
+
const xml = existing ? pkg.xml(existing.name) : undefined;
|
|
506
|
+
const ns = xml ? namespacesOf(xml.root, xml.source) : namespaces;
|
|
507
|
+
const partRels = ownRelationships(name, !!existing);
|
|
508
|
+
const inner = blocksXml(story.content.content ?? [], contextFor(ns, partRels, media, name));
|
|
509
|
+
const text = checkedPart(
|
|
510
|
+
name,
|
|
511
|
+
wrapPart(xml && { root: xml.root, source: xml.source }, root, ns, inner),
|
|
512
|
+
);
|
|
513
|
+
// Two relationships can share a part: both stories must then say the same.
|
|
514
|
+
const earlier = writtenStories.get(name);
|
|
515
|
+
if (earlier !== undefined && earlier !== text)
|
|
516
|
+
throw new DocxError(`${name} is shared by stories that differ`);
|
|
517
|
+
writtenStories.set(name, text);
|
|
518
|
+
if (existing) set(name, text);
|
|
519
|
+
else {
|
|
520
|
+
newNames.add(name);
|
|
521
|
+
add.push({ name, data: encoder.encode(text), contentType });
|
|
522
|
+
rels.add(rel, relative(mainName, name), false, id);
|
|
523
|
+
}
|
|
524
|
+
if (partRels.added.length) writeRelationships(name, partRels);
|
|
525
|
+
}
|
|
526
|
+
for (const kind of NOTE_KINDS) {
|
|
527
|
+
const { rel, contentType, name: defaultName } = NOTES[kind];
|
|
528
|
+
const name = pkg.relationships(mainName).find((r) => r.type === rel)?.partName;
|
|
529
|
+
const held = Object.values(stories).some((s) => s.kind === kind);
|
|
530
|
+
if (!name && !held) continue;
|
|
531
|
+
if (name && !doc.stories) continue;
|
|
532
|
+
const target = name ?? defaultName;
|
|
533
|
+
if (name && !isW(pkg.xml(name).root, `${kind}s`)) {
|
|
534
|
+
if (held) throw new DocxError(`${name} is not a ${kind}s part`);
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
const partRels = ownRelationships(target, !!name);
|
|
538
|
+
const write = (o: OriginalPart | undefined, ns: Namespaces) =>
|
|
539
|
+
checkedPart(
|
|
540
|
+
target,
|
|
541
|
+
notesXml(kind, stories, originals, unchanged, isReferenced, o, {
|
|
542
|
+
...contextFor(ns, partRels, media, target),
|
|
543
|
+
note: kind,
|
|
544
|
+
}),
|
|
545
|
+
);
|
|
546
|
+
part(rel, defaultName, contentType, write, held);
|
|
547
|
+
if (partRels.added.length) writeRelationships(target, partRels);
|
|
548
|
+
}
|
|
549
|
+
|
|
295
550
|
const { trackRevisions } = options;
|
|
296
|
-
|
|
551
|
+
const { settings } = doc;
|
|
552
|
+
if (trackRevisions !== undefined || settings) {
|
|
297
553
|
part(
|
|
298
554
|
REL.settings,
|
|
299
555
|
"/word/settings.xml",
|
|
300
556
|
CT.settings,
|
|
301
|
-
(o) =>
|
|
302
|
-
|
|
557
|
+
(o) => {
|
|
558
|
+
if (!o) return newSettingsXml(!!trackRevisions, settings);
|
|
559
|
+
const source =
|
|
560
|
+
trackRevisions === undefined
|
|
561
|
+
? o.source
|
|
562
|
+
: withTrackRevisions(o.source, o.root, trackRevisions);
|
|
563
|
+
return settings ? withSettings(source, parseXml(source).root, settings) : source;
|
|
564
|
+
},
|
|
565
|
+
!!trackRevisions || !!settings,
|
|
303
566
|
);
|
|
304
567
|
}
|
|
305
568
|
|
|
306
569
|
if (rels.added.length) writeRelationships(mainName, rels);
|
|
570
|
+
add.push(...media.added);
|
|
307
571
|
return pkg.write(replace, add);
|
|
308
572
|
|
|
309
573
|
function writeRelationships(source: string, relationships: Relationships): void {
|
|
@@ -352,15 +616,14 @@ function changedThreads(doc: FoliDocument, pkg: DocxPackage): boolean {
|
|
|
352
616
|
}
|
|
353
617
|
|
|
354
618
|
/** A new package: content types, relationships, the document and the parts it needs. */
|
|
355
|
-
async function newPackage(
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
}
|
|
619
|
+
async function newPackage(
|
|
620
|
+
doc: FoliDocument,
|
|
621
|
+
isReferenced: (key: string) => boolean,
|
|
622
|
+
options: ExportOptions,
|
|
623
|
+
media: Media,
|
|
624
|
+
): Promise<Uint8Array> {
|
|
362
625
|
const rels = new Relationships([]);
|
|
363
|
-
const context = contextFor(DEFAULT_NAMESPACES, rels);
|
|
626
|
+
const context = contextFor(DEFAULT_NAMESPACES, rels, media, "/word/document.xml");
|
|
364
627
|
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>`;
|
|
365
628
|
const parts: { name: string; text: string; contentType: string }[] = [
|
|
366
629
|
{ name: "/word/document.xml", text: main, contentType: CT.main },
|
|
@@ -378,13 +641,62 @@ async function newPackage(doc: FoliDocument, options: ExportOptions): Promise<Ui
|
|
|
378
641
|
numberingXml(doc, undefined, DEFAULT_NAMESPACES),
|
|
379
642
|
);
|
|
380
643
|
}
|
|
644
|
+
for (const [id, story] of Object.entries(doc.stories ?? {})) {
|
|
645
|
+
if (story.kind !== "header" && story.kind !== "footer") continue;
|
|
646
|
+
if (!/^[A-Za-z_][\w.-]*$/.test(id))
|
|
647
|
+
throw new DocxError(`Not a relationship id: ${id.slice(0, 64)}`);
|
|
648
|
+
const { root, rel, contentType } = HEADER_FOOTER[story.kind];
|
|
649
|
+
const name = freePart(story.kind, (n) => parts.some((p) => p.name === n));
|
|
650
|
+
const partRels = new Relationships([]);
|
|
651
|
+
const inner = blocksXml(
|
|
652
|
+
story.content.content ?? [],
|
|
653
|
+
contextFor(DEFAULT_NAMESPACES, partRels, media, name),
|
|
654
|
+
);
|
|
655
|
+
parts.push({
|
|
656
|
+
name,
|
|
657
|
+
text: wrapPart(undefined, root, DEFAULT_NAMESPACES, inner),
|
|
658
|
+
contentType,
|
|
659
|
+
});
|
|
660
|
+
rels.add(rel, relative("/word/document.xml", name), false, id);
|
|
661
|
+
if (partRels.added.length)
|
|
662
|
+
parts.push({
|
|
663
|
+
name: relationshipsPartName(name),
|
|
664
|
+
text: partRels.xml(undefined),
|
|
665
|
+
contentType: CT.rels,
|
|
666
|
+
});
|
|
667
|
+
}
|
|
668
|
+
for (const kind of NOTE_KINDS) {
|
|
669
|
+
const stories = doc.stories ?? {};
|
|
670
|
+
if (!Object.values(stories).some((s) => s.kind === kind)) continue;
|
|
671
|
+
const { rel, contentType, name } = NOTES[kind];
|
|
672
|
+
const partRels = new Relationships([]);
|
|
673
|
+
add(
|
|
674
|
+
name,
|
|
675
|
+
rel,
|
|
676
|
+
contentType,
|
|
677
|
+
notesXml(kind, stories, {}, () => false, isReferenced, undefined, {
|
|
678
|
+
...contextFor(DEFAULT_NAMESPACES, partRels, media, name),
|
|
679
|
+
note: kind,
|
|
680
|
+
}),
|
|
681
|
+
);
|
|
682
|
+
if (partRels.added.length)
|
|
683
|
+
parts.push({
|
|
684
|
+
name: relationshipsPartName(name),
|
|
685
|
+
text: partRels.xml(undefined),
|
|
686
|
+
contentType: CT.rels,
|
|
687
|
+
});
|
|
688
|
+
}
|
|
381
689
|
if (doc.comments.length) {
|
|
382
690
|
const commentRels = new Relationships([]);
|
|
383
691
|
add(
|
|
384
692
|
"/word/comments.xml",
|
|
385
693
|
REL.comments,
|
|
386
694
|
CT.comments,
|
|
387
|
-
commentsXml(
|
|
695
|
+
commentsXml(
|
|
696
|
+
doc,
|
|
697
|
+
undefined,
|
|
698
|
+
contextFor(DEFAULT_NAMESPACES, commentRels, media, "/word/comments.xml"),
|
|
699
|
+
),
|
|
388
700
|
);
|
|
389
701
|
if (commentRels.added.length)
|
|
390
702
|
parts.push({
|
|
@@ -401,14 +713,19 @@ async function newPackage(doc: FoliDocument, options: ExportOptions): Promise<Ui
|
|
|
401
713
|
);
|
|
402
714
|
}
|
|
403
715
|
}
|
|
404
|
-
if (options.trackRevisions)
|
|
405
|
-
add(
|
|
716
|
+
if (options.trackRevisions || doc.settings)
|
|
717
|
+
add(
|
|
718
|
+
"/word/settings.xml",
|
|
719
|
+
REL.settings,
|
|
720
|
+
CT.settings,
|
|
721
|
+
newSettingsXml(!!options.trackRevisions, doc.settings),
|
|
722
|
+
);
|
|
406
723
|
parts.push({
|
|
407
724
|
name: "/word/_rels/document.xml.rels",
|
|
408
725
|
text: rels.xml(undefined),
|
|
409
726
|
contentType: CT.rels,
|
|
410
727
|
});
|
|
411
|
-
const overrides = parts
|
|
728
|
+
const overrides = [...parts, ...media.added]
|
|
412
729
|
.filter((p) => p.contentType !== CT.rels)
|
|
413
730
|
.map((p) => `<Override PartName="${p.name}" ContentType="${p.contentType}"/>`)
|
|
414
731
|
.join("");
|
|
@@ -425,6 +742,7 @@ async function newPackage(doc: FoliDocument, options: ExportOptions): Promise<Ui
|
|
|
425
742
|
];
|
|
426
743
|
const entries = [];
|
|
427
744
|
for (const [name, text] of files) entries.push(await deflateEntry(name, encoder.encode(text)));
|
|
745
|
+
for (const part of media.added) entries.push(await deflateEntry(part.name.slice(1), part.data));
|
|
428
746
|
return writeZip(entries);
|
|
429
747
|
}
|
|
430
748
|
|
|
@@ -442,11 +760,18 @@ function bodySection(doc: FoliDocument, namespaces: Namespaces): string {
|
|
|
442
760
|
function packageReference(doc: FoliDocument): string | undefined {
|
|
443
761
|
const sections = [doc.section, ...(doc.content.content ?? []).map((b) => b.attrs?.section)];
|
|
444
762
|
for (const s of sections) {
|
|
445
|
-
const section = s as
|
|
446
|
-
|
|
763
|
+
const section = s as
|
|
764
|
+
| { headers?: Record<string, string>; footers?: Record<string, string> }
|
|
765
|
+
| undefined;
|
|
766
|
+
const ids = [
|
|
767
|
+
...Object.values(section?.headers ?? {}),
|
|
768
|
+
...Object.values(section?.footers ?? {}),
|
|
769
|
+
];
|
|
770
|
+
if (ids.some((id) => !doc.stories || !Object.hasOwn(doc.stories, id)))
|
|
771
|
+
return "a header or footer";
|
|
447
772
|
}
|
|
448
773
|
let found: string | undefined;
|
|
449
|
-
JSON.stringify([doc.content, doc.comments], (key, value) => {
|
|
774
|
+
JSON.stringify([doc.content, doc.comments, doc.stories], (key, value) => {
|
|
450
775
|
if (!found && key === "xml" && typeof value === "string" && /\sr:[A-Za-z]+="/.test(value))
|
|
451
776
|
found = "content kept verbatim";
|
|
452
777
|
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,9 +25,12 @@ 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";
|
|
29
|
+
import { DocxError } from "../package.js";
|
|
27
30
|
import type { XmlElement, XmlNode } from "../xml.js";
|
|
28
31
|
import { blocksXml, type WriteContext } from "./content.js";
|
|
29
32
|
import { paragraphPropertiesXml, runPropertiesXml, same } from "./properties.js";
|
|
33
|
+
import { stylePartsXml } from "./tables.js";
|
|
30
34
|
import {
|
|
31
35
|
attributesOf,
|
|
32
36
|
el,
|
|
@@ -73,7 +77,7 @@ function childSource(
|
|
|
73
77
|
}
|
|
74
78
|
|
|
75
79
|
/** A part's text: the original's prolog and root around `children`, or a new root. */
|
|
76
|
-
function wrapPart(
|
|
80
|
+
export function wrapPart(
|
|
77
81
|
part: OriginalPart | undefined,
|
|
78
82
|
rootName: string,
|
|
79
83
|
ns: Namespaces,
|
|
@@ -187,6 +191,18 @@ function styleXml(style: StyleJSON, ns: Namespaces): string {
|
|
|
187
191
|
if (reread && same(normalizeStyle(style), normalizeStyle(reread))) return style.ext as string;
|
|
188
192
|
}
|
|
189
193
|
const reread = o ? styleOf(o.element, reading(o.source)) : undefined;
|
|
194
|
+
// A table style read from the file has its parts written as read (`w:tblPr`… kept): a change
|
|
195
|
+
// would be lost. A new one (Word's Table Grid, added by a command) is written from the model,
|
|
196
|
+
// without conditional formats.
|
|
197
|
+
for (const key of o
|
|
198
|
+
? (["table", "row", "cell", "conditions"] as const)
|
|
199
|
+
: (["conditions"] as const)) {
|
|
200
|
+
if (!same(style[key], reread?.[key])) {
|
|
201
|
+
throw new DocxError(
|
|
202
|
+
`Style ${style.id}: a changed table style (${key}) cannot be exported yet`,
|
|
203
|
+
);
|
|
204
|
+
}
|
|
205
|
+
}
|
|
190
206
|
const generated = new Map<string, string>([
|
|
191
207
|
["name", val("name", style.name)],
|
|
192
208
|
["basedOn", val("basedOn", style.basedOn)],
|
|
@@ -208,6 +224,7 @@ function styleXml(style: StyleJSON, ns: Namespaces): string {
|
|
|
208
224
|
"rPr",
|
|
209
225
|
runPropertiesXml(style.run ?? [], childSource(o, "rPr"), ns, "w:rPr", false, undefined, true),
|
|
210
226
|
],
|
|
227
|
+
...(o ? [] : Object.entries(stylePartsXml(style, ns))),
|
|
211
228
|
]);
|
|
212
229
|
const children = merged(STYLE_ORDER, new Set(generated.keys()), generated, o);
|
|
213
230
|
const open =
|
|
@@ -520,6 +537,81 @@ export function commentsXml(
|
|
|
520
537
|
return wrapPart(part, "w:comments", context.namespaces, body + added);
|
|
521
538
|
}
|
|
522
539
|
|
|
540
|
+
/**
|
|
541
|
+
* The separators a new notes part starts with, as Word writes them (unless it has its own): single
|
|
542
|
+
* spaced, nothing after.
|
|
543
|
+
*/
|
|
544
|
+
const noteSeparators = (
|
|
545
|
+
kind: "footnote" | "endnote",
|
|
546
|
+
stories: Readonly<Record<string, StoryJSON>>,
|
|
547
|
+
) =>
|
|
548
|
+
(Object.hasOwn(stories, `${kind}:-1`)
|
|
549
|
+
? ""
|
|
550
|
+
: `<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}>`) +
|
|
551
|
+
(Object.hasOwn(stories, `${kind}:0`)
|
|
552
|
+
? ""
|
|
553
|
+
: `<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}>`);
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* A footnotes or endnotes part: a note unchanged from `originals` keeps its bytes, a changed one
|
|
557
|
+
* is written from its story, and new ones go at the end. One whose story is gone is removed,
|
|
558
|
+
* unless Word needs it: a separator, or a note something still refers to (`isReferenced`).
|
|
559
|
+
*/
|
|
560
|
+
export function notesXml(
|
|
561
|
+
kind: "footnote" | "endnote",
|
|
562
|
+
stories: Readonly<Record<string, StoryJSON>>,
|
|
563
|
+
originals: Readonly<Record<string, StoryJSON>>,
|
|
564
|
+
unchanged: (key: string) => boolean,
|
|
565
|
+
isReferenced: (key: string) => boolean,
|
|
566
|
+
part: OriginalPart | undefined,
|
|
567
|
+
context: WriteContext,
|
|
568
|
+
): string {
|
|
569
|
+
const write = (key: string, story: StoryJSON) => {
|
|
570
|
+
if (!new RegExp(`^${kind}:-?\\d+$`).test(key))
|
|
571
|
+
throw new DocxError(`Not the id of a ${kind}: ${key.slice(0, 64)}`);
|
|
572
|
+
const type = story.noteType ? ` w:type="${story.noteType}"` : "";
|
|
573
|
+
if (story.ext) {
|
|
574
|
+
// The element it was read from must be this note: a copy would repeat another's id.
|
|
575
|
+
const { element } = fragment(story.ext.replace(/\/?>$/, "/>"), context.namespaces, kind);
|
|
576
|
+
if (
|
|
577
|
+
integer(attr(element, "id")) !== Number(key.slice(kind.length + 1)) ||
|
|
578
|
+
attr(element, "type") !== story.noteType
|
|
579
|
+
)
|
|
580
|
+
throw new DocxError(`The start tag kept for ${key.slice(0, 64)} is another note's`);
|
|
581
|
+
}
|
|
582
|
+
const start =
|
|
583
|
+
story.ext?.replace(/\/>$/, ">") ?? `<w:${kind}${type} w:id="${key.slice(kind.length + 1)}">`;
|
|
584
|
+
return `${start}${blocksXml(story.content.content ?? [], context)}</w:${kind}>`;
|
|
585
|
+
};
|
|
586
|
+
const seen = new Set<string>();
|
|
587
|
+
const held = part ? notesOf(part.root, kind) : new Map<string, XmlElement>();
|
|
588
|
+
const keyOf = new Map([...held].map(([key, el]) => [el, key]));
|
|
589
|
+
const body = rebuild<string>(
|
|
590
|
+
part,
|
|
591
|
+
(child) => {
|
|
592
|
+
const key = keyOf.get(child);
|
|
593
|
+
if (key === undefined) return undefined;
|
|
594
|
+
seen.add(key);
|
|
595
|
+
if (!Object.hasOwn(stories, key)) {
|
|
596
|
+
const original = originals[key];
|
|
597
|
+
const needed =
|
|
598
|
+
!original || (original.noteType ?? "normal") !== "normal" || isReferenced(key);
|
|
599
|
+
return needed ? undefined : null;
|
|
600
|
+
}
|
|
601
|
+
const story = stories[key] as StoryJSON;
|
|
602
|
+
return story && unchanged(key) ? undefined : key;
|
|
603
|
+
},
|
|
604
|
+
(key) => write(key, stories[key] as StoryJSON),
|
|
605
|
+
[],
|
|
606
|
+
);
|
|
607
|
+
const added = Object.entries(stories)
|
|
608
|
+
.filter(([key, story]) => story.kind === kind && !seen.has(key))
|
|
609
|
+
.map(([key, story]) => write(key, story))
|
|
610
|
+
.join("");
|
|
611
|
+
const separators = part ? "" : noteSeparators(kind, stories);
|
|
612
|
+
return wrapPart(part, `w:${kind}s`, context.namespaces, separators + body + added);
|
|
613
|
+
}
|
|
614
|
+
|
|
523
615
|
/**
|
|
524
616
|
* `commentsExtended.xml` for the comments' replies and resolved state, keyed by the `w14:paraId`
|
|
525
617
|
* of each comment's last paragraph (comments without one cannot be listed).
|