@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/content.ts
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
|
|
6
6
|
import type { MarkJSON, NodeJSON } from "@folijs/core";
|
|
7
7
|
import { DocxError } from "../package.js";
|
|
8
|
+
import type { ControlWriter } from "./controls.js";
|
|
8
9
|
import { paragraphPropertiesXml, runPropertiesXml, same } from "./properties.js";
|
|
9
10
|
import {
|
|
10
11
|
cellPropertiesXml,
|
|
@@ -13,8 +14,9 @@ import {
|
|
|
13
14
|
rowPropertiesXml,
|
|
14
15
|
tablePropertiesXml,
|
|
15
16
|
} from "./tables.js";
|
|
16
|
-
import { bagXml, el, escapeText, fragment, type Namespaces } from "./xmlout.js";
|
|
17
|
+
import { bagXml, el, escapeAttribute, escapeText, fragment, type Namespaces } from "./xmlout.js";
|
|
17
18
|
|
|
19
|
+
/** @internal */
|
|
18
20
|
export interface WriteContext {
|
|
19
21
|
readonly namespaces: Namespaces;
|
|
20
22
|
/**
|
|
@@ -24,6 +26,10 @@ export interface WriteContext {
|
|
|
24
26
|
readonly hyperlink: (href: string, id: string | undefined) => string;
|
|
25
27
|
/** A picture's `w:drawing` (its image related to the part, its media part allocated). */
|
|
26
28
|
readonly picture: (attrs: Record<string, unknown>) => string;
|
|
29
|
+
/** The kind of note being written: what its `noteMark` is. */
|
|
30
|
+
readonly note?: "footnote" | "endnote";
|
|
31
|
+
/** The document's content controls. */
|
|
32
|
+
readonly controls: ControlWriter;
|
|
27
33
|
}
|
|
28
34
|
|
|
29
35
|
type Json = Record<string, unknown>;
|
|
@@ -35,15 +41,37 @@ function verbatim(xml: unknown, context: WriteContext): string {
|
|
|
35
41
|
return text;
|
|
36
42
|
}
|
|
37
43
|
|
|
44
|
+
/** A control around `inner` (`w:sdtPr`, `w:sdtEndPr`, then the content, as `w:sdt` requires). */
|
|
45
|
+
function controlXml(id: string, inner: string, context: WriteContext): string {
|
|
46
|
+
const { properties } = context.controls.parts(id, context.namespaces);
|
|
47
|
+
return `<w:sdt>${properties}<w:sdtContent>${inner}</w:sdtContent></w:sdt>`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `items` written by `write`, the runs of them in one control (at `depth`) inside it. */
|
|
51
|
+
function inControls(
|
|
52
|
+
items: readonly NodeJSON[],
|
|
53
|
+
depth: number,
|
|
54
|
+
context: WriteContext,
|
|
55
|
+
write: (item: NodeJSON) => string,
|
|
56
|
+
): string {
|
|
57
|
+
return grouped(
|
|
58
|
+
items,
|
|
59
|
+
(n) => (n.attrs?.controls as string[] | undefined)?.[depth],
|
|
60
|
+
(group, id) =>
|
|
61
|
+
id === undefined
|
|
62
|
+
? group.map(write).join("")
|
|
63
|
+
: controlXml(id as string, inControls(group, depth + 1, context, write), context),
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** @internal */
|
|
38
68
|
export function blocksXml(blocks: readonly NodeJSON[], context: WriteContext): string {
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
if (block.type === "
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
}
|
|
46
|
-
return out;
|
|
69
|
+
return inControls(blocks, 0, context, (block) => {
|
|
70
|
+
if (block.type === "paragraph") return paragraphXml(block, context);
|
|
71
|
+
if (block.type === "opaqueBlock") return verbatim(block.attrs?.xml, context);
|
|
72
|
+
if (block.type === "table") return tableXml(block, context);
|
|
73
|
+
return notYet(block);
|
|
74
|
+
});
|
|
47
75
|
}
|
|
48
76
|
|
|
49
77
|
/** A table: its properties, its grid, then each row's exceptions, properties and cells. */
|
|
@@ -51,15 +79,14 @@ function tableXml(table: NodeJSON, context: WriteContext): string {
|
|
|
51
79
|
const ns = context.namespaces;
|
|
52
80
|
const attrs = (table.attrs ?? {}) as Json;
|
|
53
81
|
let out = `<w:tbl>${tablePropertiesXml(attrs, ns)}${gridXml(attrs, ns)}`;
|
|
54
|
-
|
|
82
|
+
out += inControls(table.content ?? [], 0, context, (row) => {
|
|
55
83
|
const r = (row.attrs ?? {}) as Json;
|
|
56
|
-
|
|
57
|
-
for (const cell of row.content ?? []) {
|
|
84
|
+
const cells = inControls(row.content ?? [], 0, context, (cell) => {
|
|
58
85
|
const c = (cell.attrs ?? {}) as Json;
|
|
59
|
-
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
}
|
|
86
|
+
return `<w:tc>${cellPropertiesXml(c, ns)}${blocksXml(cell.content ?? [], context)}</w:tc>`;
|
|
87
|
+
});
|
|
88
|
+
return `<w:tr${bagXml(r.attributes, ns)}>${exceptionsXml(r.exceptions, ns)}${rowPropertiesXml(r, ns)}${cells}</w:tr>`;
|
|
89
|
+
});
|
|
63
90
|
return `${out}</w:tbl>`;
|
|
64
91
|
}
|
|
65
92
|
|
|
@@ -68,6 +95,7 @@ function notYet(node: NodeJSON): never {
|
|
|
68
95
|
throw new DocxError(`A ${node.type} cannot be exported to .docx yet`);
|
|
69
96
|
}
|
|
70
97
|
|
|
98
|
+
/** @internal */
|
|
71
99
|
export function paragraphXml(p: NodeJSON, context: WriteContext): string {
|
|
72
100
|
const attrs = (p.attrs ?? {}) as Json;
|
|
73
101
|
const own = bagXml(attrs.attributes, context.namespaces);
|
|
@@ -95,8 +123,113 @@ function grouped(
|
|
|
95
123
|
return out;
|
|
96
124
|
}
|
|
97
125
|
|
|
126
|
+
/** An element already written, standing in the inline content while runs are grouped. */
|
|
127
|
+
const ELEMENT = "#element";
|
|
128
|
+
|
|
129
|
+
/** Where the node matching the opening one at `from` is, by nesting; -1 if none. */
|
|
130
|
+
function closing(
|
|
131
|
+
nodes: readonly NodeJSON[],
|
|
132
|
+
from: number,
|
|
133
|
+
opens: (n: NodeJSON) => boolean,
|
|
134
|
+
closes: (n: NodeJSON) => boolean,
|
|
135
|
+
): number {
|
|
136
|
+
let depth = 0;
|
|
137
|
+
for (let i = from; i < nodes.length; i++) {
|
|
138
|
+
const node = nodes[i] as NodeJSON;
|
|
139
|
+
if (opens(node)) depth++;
|
|
140
|
+
else if (closes(node) && --depth === 0) return i;
|
|
141
|
+
}
|
|
142
|
+
return -1;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** A field read from `w:fldSimple`, written as one: start, its code, a separator, the result. */
|
|
146
|
+
function simpleFieldXml(
|
|
147
|
+
inner: readonly NodeJSON[],
|
|
148
|
+
context: WriteContext,
|
|
149
|
+
deleted: boolean,
|
|
150
|
+
): string | undefined {
|
|
151
|
+
const start = inner[0] as NodeJSON;
|
|
152
|
+
const code = inner[1];
|
|
153
|
+
if (code?.type !== "fieldCode" || inner[2]?.type !== "fieldSeparator") return undefined;
|
|
154
|
+
const instruction = String(code.attrs?.text ?? "");
|
|
155
|
+
const ext = start.attrs?.ext as string | undefined;
|
|
156
|
+
let open = `<w:fldSimple w:instr="${escapeAttribute(instruction)}">`;
|
|
157
|
+
if (ext) {
|
|
158
|
+
const { element, source } = fragment(`${ext}</w:fldSimple>`, context.namespaces, "fldSimple");
|
|
159
|
+
const others = element.attributes
|
|
160
|
+
.filter((a) => a.name !== "w:instr")
|
|
161
|
+
.map((a) => ` ${source.slice(a.start, a.end)}`)
|
|
162
|
+
.join("");
|
|
163
|
+
const same = element.attributes.find((a) => a.name === "w:instr")?.value === instruction;
|
|
164
|
+
open = same ? ext : `<w:fldSimple w:instr="${escapeAttribute(instruction)}"${others}>`;
|
|
165
|
+
}
|
|
166
|
+
return `${open}${inlinesXml(inner.slice(3), context, deleted)}</w:fldSimple>`;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** The hyperlink and tracked changes `a` and `b` both have: they go around the whole element. */
|
|
170
|
+
function sharedStructure(a: NodeJSON, b: NodeJSON): MarkJSON[] {
|
|
171
|
+
return (a.marks ?? []).filter(
|
|
172
|
+
(m) => STRUCTURE.has(m.type) && (b.marks ?? []).some((other) => same(m, other)),
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Inline content: inline controls and simple fields as the elements around what they hold, inside
|
|
178
|
+
* the hyperlink and tracked changes around both their ends (ends whose partner is gone are
|
|
179
|
+
* dropped, their content kept); the rest in runs. `deleted`: inside a tracked deletion.
|
|
180
|
+
*/
|
|
181
|
+
function inlinesXml(nodes: readonly NodeJSON[], context: WriteContext, deleted = false): string {
|
|
182
|
+
const out: NodeJSON[] = [];
|
|
183
|
+
for (let i = 0; i < nodes.length; i++) {
|
|
184
|
+
const node = nodes[i] as NodeJSON;
|
|
185
|
+
const control = node.type === "controlStart";
|
|
186
|
+
const field = node.type === "fieldStart" && !!node.attrs?.simple;
|
|
187
|
+
const id = node.attrs?.id;
|
|
188
|
+
const end =
|
|
189
|
+
!control && !field
|
|
190
|
+
? -1
|
|
191
|
+
: closing(
|
|
192
|
+
nodes,
|
|
193
|
+
i,
|
|
194
|
+
(n) =>
|
|
195
|
+
control ? n.type === "controlStart" && n.attrs?.id === id : n.type === "fieldStart",
|
|
196
|
+
(n) =>
|
|
197
|
+
control ? n.type === "controlEnd" && n.attrs?.id === id : n.type === "fieldEnd",
|
|
198
|
+
);
|
|
199
|
+
if (end < 0) {
|
|
200
|
+
out.push(node);
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const shared = sharedStructure(node, nodes[end] as NodeJSON);
|
|
204
|
+
const without = (n: NodeJSON): NodeJSON => {
|
|
205
|
+
const marks = (n.marks ?? []).filter((m) => !shared.some((s) => same(m, s)));
|
|
206
|
+
const { marks: _marks, ...rest } = n;
|
|
207
|
+
return marks.length ? { ...rest, marks } : rest;
|
|
208
|
+
};
|
|
209
|
+
const gone = deleted || shared.some((m) => m.type === "deletion");
|
|
210
|
+
const xml = control
|
|
211
|
+
? controlXml(
|
|
212
|
+
String(id),
|
|
213
|
+
inlinesXml(nodes.slice(i + 1, end).map(without), context, gone),
|
|
214
|
+
context,
|
|
215
|
+
)
|
|
216
|
+
: simpleFieldXml(nodes.slice(i, end).map(without), context, gone);
|
|
217
|
+
if (xml === undefined) {
|
|
218
|
+
out.push(node);
|
|
219
|
+
continue;
|
|
220
|
+
}
|
|
221
|
+
out.push({ type: ELEMENT, attrs: { xml }, ...(shared.length ? { marks: shared } : {}) });
|
|
222
|
+
i = end;
|
|
223
|
+
}
|
|
224
|
+
return plainInlinesXml(out, context, deleted);
|
|
225
|
+
}
|
|
226
|
+
|
|
98
227
|
/** Hyperlinks outermost, then insertions (or move destinations), then deletions (or move sources). */
|
|
99
|
-
function
|
|
228
|
+
function plainInlinesXml(
|
|
229
|
+
nodes: readonly NodeJSON[],
|
|
230
|
+
context: WriteContext,
|
|
231
|
+
outerDeleted: boolean,
|
|
232
|
+
): string {
|
|
100
233
|
return grouped(
|
|
101
234
|
nodes,
|
|
102
235
|
(n) => markOf(n, "link"),
|
|
@@ -117,7 +250,7 @@ function inlinesXml(nodes: readonly NodeJSON[], context: WriteContext): string {
|
|
|
117
250
|
del as MarkJSON | undefined,
|
|
118
251
|
"del",
|
|
119
252
|
"moveFrom",
|
|
120
|
-
runsXml(g2, !!del, context),
|
|
253
|
+
runsXml(g2, !!del || outerDeleted, context),
|
|
121
254
|
context,
|
|
122
255
|
),
|
|
123
256
|
),
|
|
@@ -175,7 +308,13 @@ function inRun(node: NodeJSON): boolean {
|
|
|
175
308
|
"pageBreak",
|
|
176
309
|
"columnBreak",
|
|
177
310
|
"commentReference",
|
|
311
|
+
"noteReference",
|
|
312
|
+
"noteMark",
|
|
178
313
|
"picture",
|
|
314
|
+
"fieldStart",
|
|
315
|
+
"fieldCode",
|
|
316
|
+
"fieldSeparator",
|
|
317
|
+
"fieldEnd",
|
|
179
318
|
].includes(node.type);
|
|
180
319
|
}
|
|
181
320
|
|
|
@@ -218,13 +357,32 @@ function markerXml(node: NodeJSON, context: WriteContext): string {
|
|
|
218
357
|
return tag("w:commentRangeStart", { "w:id": String(a.id) });
|
|
219
358
|
case "commentEnd":
|
|
220
359
|
return tag("w:commentRangeEnd", { "w:id": String(a.id) });
|
|
360
|
+
case ELEMENT:
|
|
361
|
+
return String(a.xml);
|
|
221
362
|
case "opaqueInline":
|
|
222
363
|
return verbatim(a.xml, context);
|
|
364
|
+
// Their partner is gone (an edit): the content around them stays.
|
|
365
|
+
case "controlStart":
|
|
366
|
+
case "controlEnd":
|
|
367
|
+
return "";
|
|
223
368
|
default:
|
|
224
369
|
return notYet(node);
|
|
225
370
|
}
|
|
226
371
|
}
|
|
227
372
|
|
|
373
|
+
/** A `w:fldChar`: the element as read if it holds more than the model does. */
|
|
374
|
+
function fieldCharXml(type: string, a: Json, context: WriteContext): string {
|
|
375
|
+
// A simple field's `ext` is its start tag: this one has lost its shape, and is written plain.
|
|
376
|
+
if (a.ext && !a.simple) return verbatim(a.ext, context);
|
|
377
|
+
const flag = (value: unknown) =>
|
|
378
|
+
value === null || value === undefined ? undefined : value ? "1" : "0";
|
|
379
|
+
return el("w:fldChar", {
|
|
380
|
+
"w:fldCharType": type,
|
|
381
|
+
"w:dirty": flag(a.dirty),
|
|
382
|
+
"w:fldLock": flag(a.locked),
|
|
383
|
+
});
|
|
384
|
+
}
|
|
385
|
+
|
|
228
386
|
/**
|
|
229
387
|
* Text as `w:t` (or `w:delText`), with tabs and Word's special hyphens as their elements, and
|
|
230
388
|
* line ends and vertical tabs (Office's line break in pasted text) as breaks.
|
|
@@ -263,11 +421,37 @@ function runContentXml(node: NodeJSON, deleted: boolean, context: WriteContext):
|
|
|
263
421
|
return el("w:br", { "w:type": "column" });
|
|
264
422
|
case "commentReference":
|
|
265
423
|
return `${el("w:commentReference", { "w:id": String(a.id) }).slice(0, -2)}${bagXml(a.attributes, context.namespaces, ["w:id"])}/>`;
|
|
424
|
+
case "noteReference": {
|
|
425
|
+
const [kind, id] = String(a.story).split(/:(.*)/s) as [string, string];
|
|
426
|
+
if ((kind !== "footnote" && kind !== "endnote") || !/^-?\d+$/.test(id ?? ""))
|
|
427
|
+
throw new DocxError(`Not a note's id: ${String(a.story).slice(0, 64)}`);
|
|
428
|
+
const known = ["w:customMarkFollows", "w:id"];
|
|
429
|
+
const open = el(`w:${kind}Reference`, {
|
|
430
|
+
"w:customMarkFollows": a.customMark === undefined ? undefined : a.customMark ? "1" : "0",
|
|
431
|
+
"w:id": id,
|
|
432
|
+
}).slice(0, -2);
|
|
433
|
+
return `${open}${bagXml(a.attributes, context.namespaces, known)}/>`;
|
|
434
|
+
}
|
|
435
|
+
case "noteMark":
|
|
436
|
+
return context.note ? `<w:${context.note}Ref/>` : notYet(node);
|
|
437
|
+
case "fieldStart":
|
|
438
|
+
return fieldCharXml("begin", a, context);
|
|
439
|
+
case "fieldSeparator":
|
|
440
|
+
return fieldCharXml("separate", a, context);
|
|
441
|
+
case "fieldEnd":
|
|
442
|
+
return fieldCharXml("end", a, context);
|
|
443
|
+
case "fieldCode": {
|
|
444
|
+
const name = deleted ? "w:delInstrText" : "w:instrText";
|
|
445
|
+
const value = String(a.text ?? "");
|
|
446
|
+
const preserve = /^\s|\s$/.test(value) ? ' xml:space="preserve"' : "";
|
|
447
|
+
const bag = bagXml(a.attributes, context.namespaces, ["xml:space"]);
|
|
448
|
+
return `<${name}${preserve}${bag}>${escapeText(value)}</${name}>`;
|
|
449
|
+
}
|
|
266
450
|
case "opaqueInline":
|
|
267
451
|
return verbatim(a.xml, context);
|
|
268
452
|
case "picture":
|
|
269
453
|
return context.picture(a);
|
|
270
454
|
default:
|
|
271
|
-
return
|
|
455
|
+
return notYet(node);
|
|
272
456
|
}
|
|
273
457
|
}
|
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Content controls written back (ADR-0007). A control keeps the `w:sdtPr` and `w:sdtEndPr` it was
|
|
3
|
+
* read from: what changed is patched child by child, the rest stays byte for byte. A new control
|
|
4
|
+
* gets a whole `w:sdtPr`. A control written twice (an edit split it) gets a new `w:id` the second
|
|
5
|
+
* time; a copy carries none (core drops it), and Word gives it one.
|
|
6
|
+
*/
|
|
7
|
+
import type { ControlJSON } from "@folijs/core";
|
|
8
|
+
import { controlProperties } from "../import/controls.js";
|
|
9
|
+
import { child, elements, W14, W15 } from "../import/ooxml.js";
|
|
10
|
+
import { Recorder } from "../import/report.js";
|
|
11
|
+
import { DocxError } from "../package.js";
|
|
12
|
+
import type { XmlElement } from "../xml.js";
|
|
13
|
+
import { same } from "./properties.js";
|
|
14
|
+
import { el, escapeAttribute, fragment, type Namespaces, val } from "./xmlout.js";
|
|
15
|
+
|
|
16
|
+
/** `w:sdtPr`'s children in the order the schema gives them; the kind's element comes after. */
|
|
17
|
+
const ORDER = [
|
|
18
|
+
"rPr",
|
|
19
|
+
"alias",
|
|
20
|
+
"tag",
|
|
21
|
+
"id",
|
|
22
|
+
"lock",
|
|
23
|
+
"placeholder",
|
|
24
|
+
"temporary",
|
|
25
|
+
"showingPlcHdr",
|
|
26
|
+
"dataBinding",
|
|
27
|
+
"label",
|
|
28
|
+
"tabIndex",
|
|
29
|
+
];
|
|
30
|
+
const ID = /(<[\w.-]+:id\b[^>]*?[\w.-]+:val=")(-?\d+)(")/;
|
|
31
|
+
|
|
32
|
+
interface Edit {
|
|
33
|
+
from: number;
|
|
34
|
+
to: number;
|
|
35
|
+
text: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const itemsXml = (items: NonNullable<ControlJSON["items"]>) =>
|
|
39
|
+
items
|
|
40
|
+
.map((item) =>
|
|
41
|
+
el("w:listItem", {
|
|
42
|
+
"w:displayText": item.display ?? item.value,
|
|
43
|
+
"w:value": item.value,
|
|
44
|
+
}),
|
|
45
|
+
)
|
|
46
|
+
.join("");
|
|
47
|
+
|
|
48
|
+
/** An extension's element, its namespace declared on it where the part does not. */
|
|
49
|
+
const extension = (prefix: "w14" | "w15", uri: string, ns: Namespaces) =>
|
|
50
|
+
ns.prefixes.has(prefix) ? {} : { [`xmlns:${prefix}`]: uri };
|
|
51
|
+
|
|
52
|
+
/** The element of a control's kind, as Word writes it. */
|
|
53
|
+
function kindXml(control: ControlJSON, ns: Namespaces): string {
|
|
54
|
+
switch (control.kind) {
|
|
55
|
+
case "text":
|
|
56
|
+
return el("w:text", control.multiLine ? { "w:multiLine": "1" } : {});
|
|
57
|
+
case "dropDown":
|
|
58
|
+
return el("w:dropDownList", {}, itemsXml(control.items ?? []));
|
|
59
|
+
case "comboBox":
|
|
60
|
+
return el("w:comboBox", {}, itemsXml(control.items ?? []));
|
|
61
|
+
case "date":
|
|
62
|
+
return el(
|
|
63
|
+
"w:date",
|
|
64
|
+
{ "w:fullDate": control.date },
|
|
65
|
+
val("dateFormat", control.dateFormat ?? "d MMMM yyyy") +
|
|
66
|
+
val("lid", "en-US") +
|
|
67
|
+
val("storeMappedDataAs", "dateTime") +
|
|
68
|
+
val("calendar", "gregorian"),
|
|
69
|
+
);
|
|
70
|
+
case "checkbox": {
|
|
71
|
+
const glyph = (name: string, state: ControlJSON["checkedState"], code: string) =>
|
|
72
|
+
el(`w14:${name}`, {
|
|
73
|
+
"w14:val": state?.value ?? code,
|
|
74
|
+
"w14:font": state?.font ?? "MS Gothic",
|
|
75
|
+
});
|
|
76
|
+
return el(
|
|
77
|
+
"w14:checkbox",
|
|
78
|
+
extension("w14", W14, ns),
|
|
79
|
+
el("w14:checked", { "w14:val": control.checked ? "1" : "0" }) +
|
|
80
|
+
glyph("checkedState", control.checkedState, "2612") +
|
|
81
|
+
glyph("uncheckedState", control.uncheckedState, "2610"),
|
|
82
|
+
);
|
|
83
|
+
}
|
|
84
|
+
case "picture":
|
|
85
|
+
return el("w:picture");
|
|
86
|
+
case "repeating":
|
|
87
|
+
return el("w15:repeatingSection", extension("w15", W15, ns));
|
|
88
|
+
case "repeatingItem":
|
|
89
|
+
return el("w15:repeatingSectionItem", extension("w15", W15, ns));
|
|
90
|
+
default:
|
|
91
|
+
return "";
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** The whole `w:sdtPr` of a control that has none yet. */
|
|
96
|
+
function newProperties(control: ControlJSON, id: number, ns: Namespaces): string {
|
|
97
|
+
const { placeholder } = control;
|
|
98
|
+
return el(
|
|
99
|
+
"w:sdtPr",
|
|
100
|
+
{},
|
|
101
|
+
val("alias", control.alias) +
|
|
102
|
+
val("tag", control.tag) +
|
|
103
|
+
val("id", id) +
|
|
104
|
+
val("lock", control.lock) +
|
|
105
|
+
(placeholder?.docPart ? el("w:placeholder", {}, val("docPart", placeholder.docPart)) : "") +
|
|
106
|
+
(placeholder?.showing ? el("w:showingPlcHdr") : "") +
|
|
107
|
+
kindXml(control, ns),
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** The kept `w:sdtPr` with what `control` says differently written into it. */
|
|
112
|
+
function patched(source: string, pr: XmlElement, control: ControlJSON, kept: ControlJSON): string {
|
|
113
|
+
const edits: Edit[] = [];
|
|
114
|
+
const children = elements(pr);
|
|
115
|
+
const prefix = pr.name.includes(":") ? `${pr.name.split(":")[0]}:` : "";
|
|
116
|
+
const named = (local: string) => children.find((c) => c.ns === pr.ns && c.local === local);
|
|
117
|
+
/** Where a new child goes: before the first that comes after it. */
|
|
118
|
+
const insertAt = (local: string) => {
|
|
119
|
+
const rank = ORDER.indexOf(local);
|
|
120
|
+
const next = children.find((c) => {
|
|
121
|
+
const at = c.ns === pr.ns ? ORDER.indexOf(c.local) : -1;
|
|
122
|
+
return at < 0 || at > rank;
|
|
123
|
+
});
|
|
124
|
+
return next ? next.start : pr.closeStart;
|
|
125
|
+
};
|
|
126
|
+
const child1 = (local: string, value: string | undefined) => {
|
|
127
|
+
const old = named(local);
|
|
128
|
+
const xml = value === undefined ? "" : el(`${prefix}${local}`, { [`${prefix}val`]: value });
|
|
129
|
+
if (old) edits.push({ from: old.start, to: old.end, text: xml });
|
|
130
|
+
else if (xml) {
|
|
131
|
+
const at = insertAt(local);
|
|
132
|
+
edits.push({ from: at, to: at, text: xml });
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
const isEmptyTag = (element: XmlElement) => element.openEnd === element.end;
|
|
136
|
+
/** `element`'s start tag with attribute `name` set, or gone. */
|
|
137
|
+
const withAttribute = (element: XmlElement, name: string, value: string | undefined) => {
|
|
138
|
+
const end = isEmptyTag(element) ? element.openEnd - 2 : element.openEnd - 1;
|
|
139
|
+
let tag = source.slice(element.start, end);
|
|
140
|
+
tag = tag.replace(new RegExp(`\\s${name}\\s*=\\s*("[^"]*"|'[^']*')`), "");
|
|
141
|
+
if (value !== undefined) tag += ` ${name}="${escapeAttribute(value)}"`;
|
|
142
|
+
edits.push({ from: element.start, to: end, text: tag });
|
|
143
|
+
};
|
|
144
|
+
/** `element` holding `inner` in place of its children (none: `inner` goes first among them). */
|
|
145
|
+
const withChildren = (element: XmlElement, inner: string, replace = true) => {
|
|
146
|
+
if (isEmptyTag(element))
|
|
147
|
+
edits.push({
|
|
148
|
+
from: element.openEnd - 2,
|
|
149
|
+
to: element.end,
|
|
150
|
+
text: `>${inner}</${element.name}>`,
|
|
151
|
+
});
|
|
152
|
+
else
|
|
153
|
+
edits.push({
|
|
154
|
+
from: element.openEnd,
|
|
155
|
+
to: replace ? element.closeStart : element.openEnd,
|
|
156
|
+
text: inner,
|
|
157
|
+
});
|
|
158
|
+
};
|
|
159
|
+
if (control.kind !== kept.kind) throw new DocxError("A content control cannot change kind");
|
|
160
|
+
if (control.alias !== kept.alias) child1("alias", control.alias);
|
|
161
|
+
if (control.tag !== kept.tag) child1("tag", control.tag);
|
|
162
|
+
if (control.lock !== kept.lock) child1("lock", control.lock);
|
|
163
|
+
const showing = control.placeholder?.showing === true;
|
|
164
|
+
if (showing !== (kept.placeholder?.showing === true)) {
|
|
165
|
+
const old = named("showingPlcHdr");
|
|
166
|
+
if (old) edits.push({ from: old.start, to: old.end, text: showing ? `<${old.name}/>` : "" });
|
|
167
|
+
else {
|
|
168
|
+
const at = insertAt("showingPlcHdr");
|
|
169
|
+
edits.push({ from: at, to: at, text: `<${prefix}showingPlcHdr/>` });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
const list = named("dropDownList") ?? named("comboBox");
|
|
173
|
+
if (list && !same(control.items, kept.items)) withChildren(list, itemsXml(control.items ?? []));
|
|
174
|
+
const date = named("date");
|
|
175
|
+
if (date) {
|
|
176
|
+
if (control.date !== kept.date) withAttribute(date, `${prefix}fullDate`, control.date);
|
|
177
|
+
if (control.dateFormat !== kept.dateFormat) {
|
|
178
|
+
const format = child(date, "dateFormat");
|
|
179
|
+
const xml = el(`${prefix}dateFormat`, { [`${prefix}val`]: control.dateFormat });
|
|
180
|
+
if (format) edits.push({ from: format.start, to: format.end, text: xml });
|
|
181
|
+
else withChildren(date, xml, false);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const text = named("text");
|
|
185
|
+
if (text && (control.multiLine ?? false) !== (kept.multiLine ?? false))
|
|
186
|
+
withAttribute(text, `${prefix}multiLine`, control.multiLine ? "1" : undefined);
|
|
187
|
+
const box = children.find((c) => c.ns === W14 && c.local === "checkbox");
|
|
188
|
+
if (box && (control.checked ?? false) !== (kept.checked ?? false)) {
|
|
189
|
+
const checked = elements(box).find((c) => c.ns === W14 && c.local === "checked");
|
|
190
|
+
const name = checked?.name ?? box.name.replace("checkbox", "checked");
|
|
191
|
+
const boxPrefix = name.slice(0, name.indexOf(":") + 1);
|
|
192
|
+
const xml = el(name, { [`${boxPrefix}val`]: control.checked ? "1" : "0" });
|
|
193
|
+
if (checked) edits.push({ from: checked.start, to: checked.end, text: xml });
|
|
194
|
+
else withChildren(box, xml, false);
|
|
195
|
+
}
|
|
196
|
+
let out = source.slice(pr.start, pr.end);
|
|
197
|
+
// From the end; of two put at one place, the first made ends up first.
|
|
198
|
+
const order = edits.map((edit, i) => ({ edit, i }));
|
|
199
|
+
order.sort((a, b) => b.edit.from - a.edit.from || b.edit.to - a.edit.to || b.i - a.i);
|
|
200
|
+
for (const { edit } of order)
|
|
201
|
+
out = out.slice(0, edit.from - pr.start) + edit.text + out.slice(edit.to - pr.start);
|
|
202
|
+
return out;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** @internal */
|
|
206
|
+
export class ControlWriter {
|
|
207
|
+
readonly #written = new Set<string>();
|
|
208
|
+
/** Every `w:id` the document's controls hold. */
|
|
209
|
+
readonly #held = new Set<string>();
|
|
210
|
+
/** Above any id Word gives. */
|
|
211
|
+
#nextId = 2_000_000_000;
|
|
212
|
+
|
|
213
|
+
constructor(readonly controls: Readonly<Record<string, ControlJSON>>) {
|
|
214
|
+
for (const control of Object.values(controls)) {
|
|
215
|
+
const id = control.ext && ID.exec(control.ext)?.[2];
|
|
216
|
+
if (id) this.#held.add(id);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
#freshId(): number {
|
|
221
|
+
while (this.#held.has(String(this.#nextId))) this.#nextId++;
|
|
222
|
+
return this.#nextId++;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** What goes before a control's content, in the order `w:sdt` requires. */
|
|
226
|
+
parts(id: string, ns: Namespaces): { properties: string } {
|
|
227
|
+
if (!Object.hasOwn(this.controls, id))
|
|
228
|
+
throw new DocxError(`Content control ${id.slice(0, 64)} has no properties`);
|
|
229
|
+
const control = this.controls[id] as ControlJSON;
|
|
230
|
+
let properties = control.ext
|
|
231
|
+
? this.#kept(control, ns)
|
|
232
|
+
: newProperties(control, this.#freshId(), ns);
|
|
233
|
+
// The same control written twice: an edit has separated its parts, and ids are unique.
|
|
234
|
+
if (this.#written.has(id))
|
|
235
|
+
properties = properties.replace(
|
|
236
|
+
ID,
|
|
237
|
+
(_, start, _id, end) => `${start}${this.#freshId()}${end}`,
|
|
238
|
+
);
|
|
239
|
+
this.#written.add(id);
|
|
240
|
+
return { properties };
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
#kept(control: ControlJSON, ns: Namespaces): string {
|
|
244
|
+
const { element, source } = fragment(control.ext as string, ns, "sdt");
|
|
245
|
+
const pr = child(element, "sdtPr");
|
|
246
|
+
const reread = controlProperties(element, { source, report: new Recorder() });
|
|
247
|
+
const end = child(element, "sdtEndPr");
|
|
248
|
+
const after = end ? source.slice(end.start, end.end) : "";
|
|
249
|
+
const whatItSays = (c: ControlJSON | undefined) => {
|
|
250
|
+
const { ext: _ext, deleted: _deleted, placeholder, ...rest } = c ?? ({} as ControlJSON);
|
|
251
|
+
const { text: _text, ...shown } = placeholder ?? {};
|
|
252
|
+
return { ...rest, placeholder: { ...shown, showing: shown.showing === true } };
|
|
253
|
+
};
|
|
254
|
+
if (reread && same(whatItSays(control), whatItSays(reread)))
|
|
255
|
+
return source.slice(element.openEnd, element.closeStart);
|
|
256
|
+
if (!pr || !reread || pr.openEnd === pr.end)
|
|
257
|
+
return newProperties(control, this.#freshId(), ns) + after;
|
|
258
|
+
return patched(source, pr, control, reread) + after;
|
|
259
|
+
}
|
|
260
|
+
}
|