-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathsectionPropertiesSerializer.ts
More file actions
419 lines (372 loc) · 12.8 KB
/
Copy pathsectionPropertiesSerializer.ts
File metadata and controls
419 lines (372 loc) · 12.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
import type {
EndnoteProperties,
FooterReference,
FootnoteProperties,
HeaderReference,
SectionPropertyChange,
SectionProperties,
} from "../../types/document";
import { normalizeRevisionId } from "@stll/docx-core/model";
import { getUnserializedSectionPropertyChildNames } from "../sectionParser";
import { serializeBorder } from "./borderSerializer";
import { escapeXml, intAttr } from "./xmlUtils";
const serializeHeaderReference = (ref: HeaderReference): string =>
`<w:headerReference w:type="${ref.type}" r:id="${ref.rId}"/>`;
const serializeFooterReference = (ref: FooterReference): string =>
`<w:footerReference w:type="${ref.type}" r:id="${ref.rId}"/>`;
function serializeFootnoteProperties(props: FootnoteProperties | undefined): string {
if (!props) {
return "";
}
const parts: string[] = [];
if (props.position) {
parts.push(`<w:pos w:val="${props.position}"/>`);
}
if (props.numFmt) {
parts.push(`<w:numFmt w:val="${props.numFmt}"/>`);
}
if (props.numStart !== undefined) {
parts.push(`<w:numStart w:val="${intAttr(props.numStart)}"/>`);
}
if (props.numRestart) {
parts.push(`<w:numRestart w:val="${props.numRestart}"/>`);
}
return parts.length > 0 ? `<w:footnotePr>${parts.join("")}</w:footnotePr>` : "";
}
function serializeFootnoteColumns(props: SectionProperties): string {
return props.footnoteColumns !== undefined
? `<w15:footnoteColumns w:val="${intAttr(props.footnoteColumns)}"/>`
: "";
}
function serializeEndnoteProperties(props: EndnoteProperties | undefined): string {
if (!props) {
return "";
}
const parts: string[] = [];
if (props.position) {
parts.push(`<w:pos w:val="${props.position}"/>`);
}
if (props.numFmt) {
parts.push(`<w:numFmt w:val="${props.numFmt}"/>`);
}
if (props.numStart !== undefined) {
parts.push(`<w:numStart w:val="${intAttr(props.numStart)}"/>`);
}
if (props.numRestart) {
parts.push(`<w:numRestart w:val="${props.numRestart}"/>`);
}
return parts.length > 0 ? `<w:endnotePr>${parts.join("")}</w:endnotePr>` : "";
}
function serializePageSize(props: SectionProperties): string {
const attrs: string[] = [];
if (props.pageWidth !== undefined) {
attrs.push(`w:w="${intAttr(props.pageWidth)}"`);
}
if (props.pageHeight !== undefined) {
attrs.push(`w:h="${intAttr(props.pageHeight)}"`);
}
if (props.orientation === "landscape") {
attrs.push('w:orient="landscape"');
}
return attrs.length > 0 ? `<w:pgSz ${attrs.join(" ")}/>` : "";
}
function serializePageMargins(props: SectionProperties): string {
const attrs: string[] = [];
if (props.marginTop !== undefined) {
attrs.push(`w:top="${intAttr(props.marginTop)}"`);
}
if (props.marginRight !== undefined) {
attrs.push(`w:right="${intAttr(props.marginRight)}"`);
}
if (props.marginBottom !== undefined) {
attrs.push(`w:bottom="${intAttr(props.marginBottom)}"`);
}
if (props.marginLeft !== undefined) {
attrs.push(`w:left="${intAttr(props.marginLeft)}"`);
}
if (props.headerDistance !== undefined) {
attrs.push(`w:header="${intAttr(props.headerDistance)}"`);
}
if (props.footerDistance !== undefined) {
attrs.push(`w:footer="${intAttr(props.footerDistance)}"`);
}
if (props.gutter !== undefined) {
attrs.push(`w:gutter="${intAttr(props.gutter)}"`);
}
return attrs.length > 0 ? `<w:pgMar ${attrs.join(" ")}/>` : "";
}
function serializePaperSource(props: SectionProperties): string {
const attrs: string[] = [];
if (props.paperSrcFirst !== undefined) {
attrs.push(`w:first="${intAttr(props.paperSrcFirst)}"`);
}
if (props.paperSrcOther !== undefined) {
attrs.push(`w:other="${intAttr(props.paperSrcOther)}"`);
}
return attrs.length > 0 ? `<w:paperSrc ${attrs.join(" ")}/>` : "";
}
function serializeColumns(props: SectionProperties): string {
// A single-column section still carries its gutter as `<w:cols w:space=".."/>`,
// so bail only when there is genuinely nothing to emit (no count, no explicit
// columns, and no space) — otherwise the column spacing is dropped on save.
if (!props.columnCount && !props.columns?.length && props.columnSpace === undefined) {
return "";
}
const attrs: string[] = [];
if (props.columnCount !== undefined && props.columnCount > 1) {
attrs.push(`w:num="${intAttr(props.columnCount)}"`);
}
if (props.columnSpace !== undefined) {
attrs.push(`w:space="${intAttr(props.columnSpace)}"`);
}
if (props.equalWidth !== undefined) {
attrs.push(`w:equalWidth="${props.equalWidth ? "1" : "0"}"`);
}
if (props.separator) {
attrs.push('w:sep="1"');
}
const colElements = (props.columns ?? [])
.map((col) => {
const colAttrs: string[] = [];
if (col.width !== undefined) {
colAttrs.push(`w:w="${intAttr(col.width)}"`);
}
if (col.space !== undefined) {
colAttrs.push(`w:space="${intAttr(col.space)}"`);
}
return `<w:col ${colAttrs.join(" ")}/>`;
})
.join("");
if (attrs.length === 0 && !colElements) {
return "";
}
const attrsStr = attrs.length > 0 ? ` ${attrs.join(" ")}` : "";
return `<w:cols${attrsStr}>${colElements}</w:cols>`;
}
function serializeLineNumbers(props: SectionProperties): string {
if (!props.lineNumbers) {
return "";
}
const attrs: string[] = [];
const ln = props.lineNumbers;
if (ln.countBy !== undefined) {
attrs.push(`w:countBy="${intAttr(ln.countBy)}"`);
}
if (ln.start !== undefined) {
attrs.push(`w:start="${intAttr(ln.start)}"`);
}
if (ln.distance !== undefined) {
attrs.push(`w:distance="${intAttr(ln.distance)}"`);
}
if (ln.restart) {
attrs.push(`w:restart="${ln.restart}"`);
}
return attrs.length > 0 ? `<w:lnNumType ${attrs.join(" ")}/>` : "";
}
function serializePageNumbering(props: SectionProperties): string {
if (!props.pageNumbering) {
return "";
}
const attrs: string[] = [];
const pageNumbering = props.pageNumbering;
if (pageNumbering.format) {
attrs.push(`w:fmt="${pageNumbering.format}"`);
}
if (pageNumbering.start !== undefined) {
attrs.push(`w:start="${intAttr(pageNumbering.start)}"`);
}
if (pageNumbering.chapterStyle !== undefined) {
attrs.push(`w:chapStyle="${intAttr(pageNumbering.chapterStyle)}"`);
}
if (pageNumbering.chapterSeparator) {
attrs.push(`w:chapSep="${pageNumbering.chapterSeparator}"`);
}
return attrs.length > 0 ? `<w:pgNumType ${attrs.join(" ")}/>` : "";
}
function serializePageBorders(props: SectionProperties): string {
if (!props.pageBorders) {
return "";
}
const attrs: string[] = [];
const borderElements: string[] = [];
const pb = props.pageBorders;
if (pb.display) {
attrs.push(`w:display="${pb.display}"`);
}
if (pb.offsetFrom) {
attrs.push(`w:offsetFrom="${pb.offsetFrom}"`);
}
if (pb.zOrder) {
attrs.push(`w:zOrder="${pb.zOrder}"`);
}
for (const [key, elementName] of [
["top", "top"],
["left", "left"],
["bottom", "bottom"],
["right", "right"],
] as const) {
const xml = serializeBorder(pb[key], elementName);
if (xml) {
borderElements.push(xml);
}
}
// Drop the element entirely when nothing meaningful would be emitted —
// an attribute-less, child-less `<w:pgBorders>` carries no information.
// Attributes alone (display/offsetFrom/zOrder) on a parsed pgBorders
// are still meaningful for round-trip fidelity, so keep the element in
// that case even when every side is `none`/`nil`.
if (borderElements.length === 0 && attrs.length === 0) {
return "";
}
const attrsStr = attrs.length > 0 ? ` ${attrs.join(" ")}` : "";
if (borderElements.length === 0) {
return `<w:pgBorders${attrsStr}/>`;
}
return `<w:pgBorders${attrsStr}>${borderElements.join("")}</w:pgBorders>`;
}
function serializeBackground(props: SectionProperties): string {
if (!props.background) {
return "";
}
const attrs: string[] = [];
const { background } = props;
if (background.color?.auto) {
attrs.push('w:color="auto"');
} else if (background.color?.rgb) {
attrs.push(`w:color="${background.color.rgb}"`);
}
if (background.themeColor ?? background.color?.themeColor) {
attrs.push(`w:themeColor="${background.themeColor ?? background.color?.themeColor}"`);
}
if (background.themeTint ?? background.color?.themeTint) {
attrs.push(`w:themeTint="${background.themeTint ?? background.color?.themeTint}"`);
}
if (background.themeShade ?? background.color?.themeShade) {
attrs.push(`w:themeShade="${background.themeShade ?? background.color?.themeShade}"`);
}
return attrs.length > 0 ? `<w:background ${attrs.join(" ")}/>` : "";
}
function serializeDocGrid(props: SectionProperties): string {
if (!props.docGrid) {
return "";
}
const attrs: string[] = [];
const dg = props.docGrid;
if (dg.type) {
attrs.push(`w:type="${dg.type}"`);
}
if (dg.linePitch !== undefined) {
attrs.push(`w:linePitch="${intAttr(dg.linePitch)}"`);
}
if (dg.charSpace !== undefined) {
attrs.push(`w:charSpace="${intAttr(dg.charSpace)}"`);
}
return attrs.length > 0 ? `<w:docGrid ${attrs.join(" ")}/>` : "";
}
function serializeOnOffElement(value: boolean | undefined, name: string): string {
if (value === undefined) {
return "";
}
return value ? `<w:${name}/>` : `<w:${name} w:val="0"/>`;
}
function serializeSectionPropertyChange(change: SectionPropertyChange): string {
const normalizedId = normalizeRevisionId(change.info.id);
const authorCandidate = typeof change.info.author === "string" ? change.info.author.trim() : "";
const normalizedAuthor = authorCandidate.length > 0 ? authorCandidate : "Unknown";
const normalizedDate = typeof change.info.date === "string" ? change.info.date.trim() : undefined;
const normalizedRsid = typeof change.info.rsid === "string" ? change.info.rsid.trim() : undefined;
const attrs = [`w:id="${normalizedId}"`, `w:author="${escapeXml(normalizedAuthor)}"`];
if (normalizedDate) {
attrs.push(`w:date="${escapeXml(normalizedDate)}"`);
}
if (normalizedRsid) {
attrs.push(`w:rsid="${escapeXml(normalizedRsid)}"`);
}
const previousSectPrXml = serializeSectionProperties(change.previousProperties) || "<w:sectPr/>";
return `<w:sectPrChange ${attrs.join(" ")}>${previousSectPrXml}</w:sectPrChange>`;
}
export function serializeSectionProperties(props: SectionProperties | undefined): string {
if (!props) {
return "";
}
const parts: string[] = [];
for (const ref of props.headerReferences ?? []) {
parts.push(serializeHeaderReference(ref));
}
for (const ref of props.footerReferences ?? []) {
parts.push(serializeFooterReference(ref));
}
const footnotePrXml = serializeFootnoteProperties(props.footnotePr);
if (footnotePrXml) {
parts.push(footnotePrXml);
}
const footnoteColumnsXml = serializeFootnoteColumns(props);
if (footnoteColumnsXml) {
parts.push(footnoteColumnsXml);
}
const endnotePrXml = serializeEndnoteProperties(props.endnotePr);
if (endnotePrXml) {
parts.push(endnotePrXml);
}
if (props.sectionStart) {
parts.push(`<w:type w:val="${props.sectionStart}"/>`);
}
for (const xml of [
serializePageSize(props),
serializePageMargins(props),
serializePaperSource(props),
serializePageBorders(props),
serializeBackground(props),
serializeLineNumbers(props),
serializePageNumbering(props),
serializeColumns(props),
serializeDocGrid(props),
]) {
if (xml) {
parts.push(xml);
}
}
if (props.verticalAlign) {
parts.push(`<w:vAlign w:val="${props.verticalAlign}"/>`);
}
if (props.textDirection) {
parts.push(`<w:textDirection w:val="${props.textDirection}"/>`);
}
if (props.titlePg) {
parts.push("<w:titlePg/>");
}
if (props.bidi) {
parts.push("<w:bidi/>");
}
for (const xml of [
serializeOnOffElement(props.formProtection, "formProt"),
serializeOnOffElement(props.noEndnote, "noEndnote"),
serializeOnOffElement(props.rtlGutter, "rtlGutter"),
]) {
if (xml) {
parts.push(xml);
}
}
if (props.printerSettingsRelationshipId) {
parts.push(`<w:printerSettings r:id="${props.printerSettingsRelationshipId}"/>`);
}
for (const change of props.propertyChanges ?? []) {
parts.push(serializeSectionPropertyChange(change));
}
const unserializedChildNames = getUnserializedSectionPropertyChildNames(props);
if (unserializedChildNames && unserializedChildNames.length > 0) {
return "";
}
if (parts.length > 0) {
return `<w:sectPr>${parts.join("")}</w:sectPr>`;
}
if (Object.keys(props).length > 0) {
return "";
}
// Empty `<w:sectPr/>` is meaningful in OOXML: as a paragraph-level child it
// marks a mid-body section break that inherits all settings from the following
// section. Only use that fallback for truly empty section properties; if the
// parser saw unparsed children, keep returning "" so the package fidelity
// guard fails closed instead of silently dropping those settings.
return "<w:sectPr/>";
}