@folijs/docx 0.4.0 → 0.5.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.
Files changed (71) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/README.md +57 -5
  3. package/dist/export/content.d.ts +2 -0
  4. package/dist/export/content.d.ts.map +1 -1
  5. package/dist/export/content.js +41 -3
  6. package/dist/export/content.js.map +1 -1
  7. package/dist/export/index.d.ts +6 -1
  8. package/dist/export/index.d.ts.map +1 -1
  9. package/dist/export/index.js +67 -14
  10. package/dist/export/index.js.map +1 -1
  11. package/dist/export/parts.d.ts.map +1 -1
  12. package/dist/export/parts.js +13 -0
  13. package/dist/export/parts.js.map +1 -1
  14. package/dist/export/pictures.d.ts +51 -0
  15. package/dist/export/pictures.d.ts.map +1 -0
  16. package/dist/export/pictures.js +346 -0
  17. package/dist/export/pictures.js.map +1 -0
  18. package/dist/export/properties.d.ts +11 -1
  19. package/dist/export/properties.d.ts.map +1 -1
  20. package/dist/export/properties.js +1 -1
  21. package/dist/export/properties.js.map +1 -1
  22. package/dist/export/tables.d.ts +27 -0
  23. package/dist/export/tables.d.ts.map +1 -0
  24. package/dist/export/tables.js +344 -0
  25. package/dist/export/tables.js.map +1 -0
  26. package/dist/images.d.ts +21 -0
  27. package/dist/images.d.ts.map +1 -0
  28. package/dist/images.js +53 -0
  29. package/dist/images.js.map +1 -0
  30. package/dist/import/content.d.ts +5 -1
  31. package/dist/import/content.d.ts.map +1 -1
  32. package/dist/import/content.js +161 -7
  33. package/dist/import/content.js.map +1 -1
  34. package/dist/import/index.d.ts +1 -1
  35. package/dist/import/index.d.ts.map +1 -1
  36. package/dist/import/index.js +5 -3
  37. package/dist/import/index.js.map +1 -1
  38. package/dist/import/parts.d.ts.map +1 -1
  39. package/dist/import/parts.js +7 -0
  40. package/dist/import/parts.js.map +1 -1
  41. package/dist/import/pictures.d.ts +34 -0
  42. package/dist/import/pictures.d.ts.map +1 -0
  43. package/dist/import/pictures.js +147 -0
  44. package/dist/import/pictures.js.map +1 -0
  45. package/dist/import/report.d.ts +6 -0
  46. package/dist/import/report.d.ts.map +1 -1
  47. package/dist/import/report.js +5 -0
  48. package/dist/import/report.js.map +1 -1
  49. package/dist/import/tables.d.ts +31 -0
  50. package/dist/import/tables.d.ts.map +1 -0
  51. package/dist/import/tables.js +236 -0
  52. package/dist/import/tables.js.map +1 -0
  53. package/dist/index.d.ts +1 -0
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js +1 -0
  56. package/dist/index.js.map +1 -1
  57. package/package.json +2 -2
  58. package/src/export/content.ts +49 -5
  59. package/src/export/index.ts +106 -18
  60. package/src/export/parts.ts +15 -0
  61. package/src/export/pictures.ts +405 -0
  62. package/src/export/properties.ts +1 -1
  63. package/src/export/tables.ts +386 -0
  64. package/src/images.ts +60 -0
  65. package/src/import/content.ts +154 -9
  66. package/src/import/index.ts +6 -4
  67. package/src/import/parts.ts +13 -0
  68. package/src/import/pictures.ts +176 -0
  69. package/src/import/report.ts +11 -0
  70. package/src/import/tables.ts +267 -0
  71. package/src/index.ts +1 -0
@@ -4,7 +4,15 @@
4
4
  */
5
5
 
6
6
  import type { MarkJSON, NodeJSON } from "@folijs/core";
7
+ import { DocxError } from "../package.js";
7
8
  import { paragraphPropertiesXml, runPropertiesXml, same } from "./properties.js";
9
+ import {
10
+ cellPropertiesXml,
11
+ exceptionsXml,
12
+ gridXml,
13
+ rowPropertiesXml,
14
+ tablePropertiesXml,
15
+ } from "./tables.js";
8
16
  import { bagXml, el, escapeText, fragment, type Namespaces } from "./xmlout.js";
9
17
 
10
18
  export interface WriteContext {
@@ -14,6 +22,8 @@ export interface WriteContext {
14
22
  * still has it with that target, otherwise a new one.
15
23
  */
16
24
  readonly hyperlink: (href: string, id: string | undefined) => string;
25
+ /** A picture's `w:drawing` (its image related to the part, its media part allocated). */
26
+ readonly picture: (attrs: Record<string, unknown>) => string;
17
27
  }
18
28
 
19
29
  type Json = Record<string, unknown>;
@@ -30,14 +40,40 @@ export function blocksXml(blocks: readonly NodeJSON[], context: WriteContext): s
30
40
  for (const block of blocks) {
31
41
  if (block.type === "paragraph") out += paragraphXml(block, context);
32
42
  else if (block.type === "opaqueBlock") out += verbatim(block.attrs?.xml, context);
43
+ else if (block.type === "table") out += tableXml(block, context);
44
+ else notYet(block);
33
45
  }
34
46
  return out;
35
47
  }
36
48
 
49
+ /** A table: its properties, its grid, then each row's exceptions, properties and cells. */
50
+ function tableXml(table: NodeJSON, context: WriteContext): string {
51
+ const ns = context.namespaces;
52
+ const attrs = (table.attrs ?? {}) as Json;
53
+ let out = `<w:tbl>${tablePropertiesXml(attrs, ns)}${gridXml(attrs, ns)}`;
54
+ for (const row of table.content ?? []) {
55
+ const r = (row.attrs ?? {}) as Json;
56
+ out += `<w:tr${bagXml(r.attributes, ns)}>${exceptionsXml(r.exceptions, ns)}${rowPropertiesXml(r, ns)}`;
57
+ for (const cell of row.content ?? []) {
58
+ const c = (cell.attrs ?? {}) as Json;
59
+ out += `<w:tc>${cellPropertiesXml(c, ns)}${blocksXml(cell.content ?? [], context)}</w:tc>`;
60
+ }
61
+ out += "</w:tr>";
62
+ }
63
+ return `${out}</w:tbl>`;
64
+ }
65
+
66
+ /** Content export does not write yet (pictures: 10.8): refused, never dropped. */
67
+ function notYet(node: NodeJSON): never {
68
+ throw new DocxError(`A ${node.type} cannot be exported to .docx yet`);
69
+ }
70
+
37
71
  export function paragraphXml(p: NodeJSON, context: WriteContext): string {
38
72
  const attrs = (p.attrs ?? {}) as Json;
39
73
  const own = bagXml(attrs.attributes, context.namespaces);
40
- return `<w:p${own}>${paragraphPropertiesXml(attrs, context.namespaces)}${inlinesXml(p.content ?? [], context)}</w:p>`;
74
+ const inner = `${paragraphPropertiesXml(attrs, context.namespaces)}${inlinesXml(p.content ?? [], context)}`;
75
+ // An empty paragraph as Word writes it.
76
+ return inner ? `<w:p${own}>${inner}</w:p>` : `<w:p${own}/>`;
41
77
  }
42
78
 
43
79
  const markOf = (node: NodeJSON, type: string) => node.marks?.find((m) => m.type === type);
@@ -132,9 +168,15 @@ function hyperlinkXml(link: MarkJSON, inner: string, context: WriteContext): str
132
168
  /** Inline nodes that are a run's content (the rest stands between runs). */
133
169
  function inRun(node: NodeJSON): boolean {
134
170
  if (node.type === "opaqueInline") return node.attrs?.run === true;
135
- return ["text", "tab", "hardBreak", "pageBreak", "columnBreak", "commentReference"].includes(
136
- node.type,
137
- );
171
+ return [
172
+ "text",
173
+ "tab",
174
+ "hardBreak",
175
+ "pageBreak",
176
+ "columnBreak",
177
+ "commentReference",
178
+ "picture",
179
+ ].includes(node.type);
138
180
  }
139
181
 
140
182
  const STRUCTURE = new Set(["link", "insertion", "deletion"]);
@@ -179,7 +221,7 @@ function markerXml(node: NodeJSON, context: WriteContext): string {
179
221
  case "opaqueInline":
180
222
  return verbatim(a.xml, context);
181
223
  default:
182
- return "";
224
+ return notYet(node);
183
225
  }
184
226
  }
185
227
 
@@ -223,6 +265,8 @@ function runContentXml(node: NodeJSON, deleted: boolean, context: WriteContext):
223
265
  return `${el("w:commentReference", { "w:id": String(a.id) }).slice(0, -2)}${bagXml(a.attributes, context.namespaces, ["w:id"])}/>`;
224
266
  case "opaqueInline":
225
267
  return verbatim(a.xml, context);
268
+ case "picture":
269
+ return context.picture(a);
226
270
  default:
227
271
  return "";
228
272
  }
@@ -5,7 +5,7 @@
5
5
  * byte for byte. Without a package, a new one is made.
6
6
  */
7
7
 
8
- import { type FoliDocument, parseDocument } from "@folijs/core";
8
+ import { type FoliDocument, parseDocument, type ResourceJSON } from "@folijs/core";
9
9
  import { child, REL } from "../import/ooxml.js";
10
10
  import { DocxError, type DocxPackage, type NewPart } from "../package.js";
11
11
  import { newSettingsXml, withTrackRevisions } from "../settings.js";
@@ -18,6 +18,7 @@ import {
18
18
  type OriginalPart,
19
19
  stylesXml,
20
20
  } from "./parts.js";
21
+ import { drawingXml, Media, pictureBytes } from "./pictures.js";
21
22
  import { sectionXml } from "./properties.js";
22
23
  import {
23
24
  DEFAULT_NAMESPACES,
@@ -45,17 +46,51 @@ class Relationships {
45
46
  readonly added: { id: string; type: string; target: string; external: boolean }[] = [];
46
47
  readonly #ids: Set<string>;
47
48
  readonly #byTarget = new Map<string, string>();
48
- readonly #existing: ReadonlyMap<string, { type: string; target: string; external: boolean }>;
49
+ readonly #existing: ReadonlyMap<
50
+ string,
51
+ { type: string; target: string; external: boolean; partName?: string }
52
+ >;
53
+ /** The part each internal relationship points to (resolved, as the package resolves it). */
54
+ readonly #parts = new Map<string, string>();
49
55
 
50
56
  constructor(
51
- existing: readonly { id: string; type: string; target: string; external: boolean }[],
57
+ existing: readonly {
58
+ id: string;
59
+ type: string;
60
+ target: string;
61
+ external: boolean;
62
+ partName?: string;
63
+ }[],
52
64
  ) {
53
65
  this.#existing = new Map(existing.map((r) => [r.id, r]));
66
+ for (const r of existing) if (!r.external && r.partName) this.#parts.set(r.id, r.partName);
54
67
  this.#ids = new Set(existing.map((r) => r.id));
55
68
  for (const r of existing)
56
69
  if (r.type === REL.hyperlink && r.external) this.#byTarget.set(r.target, r.id);
57
70
  }
58
71
 
72
+ /** The part relationship `id` points to (one it had, or one added), if internal. */
73
+ target(id: string): string | undefined {
74
+ return this.#parts.get(id);
75
+ }
76
+
77
+ /**
78
+ * The relationship to image part `part` (absolute; `target` as this part refers to it):
79
+ * `current` when it is one, else a known or new one. Compared by part, not by the target's
80
+ * text (`/word/media/x.png`, `./media/x.png` and `media/x.png` are one part).
81
+ */
82
+ image(part: string, target: string, current: string | undefined): string {
83
+ const isImage = (id: string) => {
84
+ const r = this.#existing.get(id) ?? this.added.find((a) => a.id === id);
85
+ return r?.type === REL_IMAGE && this.#parts.get(id)?.toLowerCase() === part.toLowerCase();
86
+ };
87
+ if (current !== undefined && isImage(current)) return current;
88
+ for (const id of this.#parts.keys()) if (isImage(id)) return id;
89
+ const id = this.add(REL_IMAGE, target, false);
90
+ this.#parts.set(id, part);
91
+ return id;
92
+ }
93
+
59
94
  hyperlink(href: string, id: string | undefined): string {
60
95
  const own = id === undefined ? undefined : this.#existing.get(id);
61
96
  if (own && own.type === REL.hyperlink && own.target === href) return id as string;
@@ -91,8 +126,28 @@ class Relationships {
91
126
  }
92
127
  }
93
128
 
94
- function contextFor(namespaces: Namespaces, relationships: Relationships): WriteContext {
95
- return { namespaces, hyperlink: (href, id) => relationships.hyperlink(href, id) };
129
+ const REL_IMAGE = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image";
130
+
131
+ function contextFor(
132
+ namespaces: Namespaces,
133
+ relationships: Relationships,
134
+ media: Media,
135
+ source: string,
136
+ ): WriteContext {
137
+ return {
138
+ namespaces,
139
+ hyperlink: (href, id) => relationships.hyperlink(href, id),
140
+ picture: (attrs) =>
141
+ drawingXml(
142
+ attrs,
143
+ {
144
+ image: (part, current) => relationships.image(part, relative(source, part), current),
145
+ target: (id) => relationships.target(id),
146
+ },
147
+ namespaces,
148
+ media,
149
+ ),
150
+ };
96
151
  }
97
152
 
98
153
  /** `/word/_rels/document.xml.rels` for `/word/document.xml`. */
@@ -113,6 +168,14 @@ export interface ExportOptions {
113
168
  * original package has it (off in a new one).
114
169
  */
115
170
  trackRevisions?: boolean;
171
+ /**
172
+ * The bytes of a picture's image the package does not hold and its resource gives no `data:`
173
+ * URL for (an app's upload, by its URL). Undefined: the export fails, never drops it.
174
+ */
175
+ resource?: (
176
+ key: string,
177
+ resource: ResourceJSON,
178
+ ) => Promise<Uint8Array | undefined> | Uint8Array | undefined;
116
179
  }
117
180
 
118
181
  /**
@@ -125,7 +188,26 @@ export async function exportDocx(
125
188
  options: ExportOptions = {},
126
189
  ): Promise<Uint8Array> {
127
190
  const doc = withThreadIds(parseDocument(document), original);
128
- return original ? intoPackage(doc, original, options) : newPackage(doc, options);
191
+ // Before the app is asked for any picture's bytes.
192
+ const reference = original ? undefined : packageReference(doc);
193
+ if (reference) {
194
+ throw new DocxError(
195
+ `The document refers to a part of its original package (${reference}): export it with that package`,
196
+ );
197
+ }
198
+ // The parts written from the model: their drawings are the document's own.
199
+ const rewritten = original
200
+ ? [
201
+ original.mainDocument,
202
+ ...original
203
+ .relationships(original.mainDocument)
204
+ .filter((r) => r.type === REL.comments && r.partName)
205
+ .map((r) => r.partName as string),
206
+ ]
207
+ : [];
208
+ const bytes = await pictureBytes(doc, original, options.resource);
209
+ const media = new Media(doc, original, bytes, rewritten);
210
+ return original ? intoPackage(doc, original, options, media) : newPackage(doc, options, media);
129
211
  }
130
212
 
131
213
  const PARA_ID = "w14:paraId";
@@ -192,6 +274,7 @@ async function intoPackage(
192
274
  doc: FoliDocument,
193
275
  pkg: DocxPackage,
194
276
  options: ExportOptions,
277
+ media: Media,
195
278
  ): Promise<Uint8Array> {
196
279
  const mainName = pkg.mainDocument;
197
280
  const main = pkg.xml(mainName);
@@ -199,7 +282,7 @@ async function intoPackage(
199
282
  if (!body) throw new DocxError(`${mainName}: no w:body`);
200
283
  const namespaces = namespacesOf(main.root, main.source);
201
284
  const rels = new Relationships(pkg.relationships(mainName));
202
- const context = contextFor(namespaces, rels);
285
+ const context = contextFor(namespaces, rels, media, mainName);
203
286
 
204
287
  const content = blocksXml(doc.content.content ?? [], context) + bodySection(doc, namespaces);
205
288
  const documentXml =
@@ -277,7 +360,8 @@ async function intoPackage(
277
360
  REL.comments,
278
361
  "/word/comments.xml",
279
362
  CT.comments,
280
- (o, ns) => commentsXml(doc, o, contextFor(ns, commentRels)),
363
+ (o, ns) =>
364
+ commentsXml(doc, o, contextFor(ns, commentRels, media, commentsName ?? "/word/comments.xml")),
281
365
  doc.comments.length > 0,
282
366
  );
283
367
  if (comments && commentRels.added.length) writeRelationships(comments, commentRels);
@@ -304,6 +388,7 @@ async function intoPackage(
304
388
  }
305
389
 
306
390
  if (rels.added.length) writeRelationships(mainName, rels);
391
+ add.push(...media.added);
307
392
  return pkg.write(replace, add);
308
393
 
309
394
  function writeRelationships(source: string, relationships: Relationships): void {
@@ -352,15 +437,13 @@ function changedThreads(doc: FoliDocument, pkg: DocxPackage): boolean {
352
437
  }
353
438
 
354
439
  /** A new package: content types, relationships, the document and the parts it needs. */
355
- async function newPackage(doc: FoliDocument, options: ExportOptions): Promise<Uint8Array> {
356
- const reference = packageReference(doc);
357
- if (reference) {
358
- throw new DocxError(
359
- `The document refers to a part of its original package (${reference}): export it with that package`,
360
- );
361
- }
440
+ async function newPackage(
441
+ doc: FoliDocument,
442
+ options: ExportOptions,
443
+ media: Media,
444
+ ): Promise<Uint8Array> {
362
445
  const rels = new Relationships([]);
363
- const context = contextFor(DEFAULT_NAMESPACES, rels);
446
+ const context = contextFor(DEFAULT_NAMESPACES, rels, media, "/word/document.xml");
364
447
  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
448
  const parts: { name: string; text: string; contentType: string }[] = [
366
449
  { name: "/word/document.xml", text: main, contentType: CT.main },
@@ -384,7 +467,11 @@ async function newPackage(doc: FoliDocument, options: ExportOptions): Promise<Ui
384
467
  "/word/comments.xml",
385
468
  REL.comments,
386
469
  CT.comments,
387
- commentsXml(doc, undefined, contextFor(DEFAULT_NAMESPACES, commentRels)),
470
+ commentsXml(
471
+ doc,
472
+ undefined,
473
+ contextFor(DEFAULT_NAMESPACES, commentRels, media, "/word/comments.xml"),
474
+ ),
388
475
  );
389
476
  if (commentRels.added.length)
390
477
  parts.push({
@@ -408,7 +495,7 @@ async function newPackage(doc: FoliDocument, options: ExportOptions): Promise<Ui
408
495
  text: rels.xml(undefined),
409
496
  contentType: CT.rels,
410
497
  });
411
- const overrides = parts
498
+ const overrides = [...parts, ...media.added]
412
499
  .filter((p) => p.contentType !== CT.rels)
413
500
  .map((p) => `<Override PartName="${p.name}" ContentType="${p.contentType}"/>`)
414
501
  .join("");
@@ -425,6 +512,7 @@ async function newPackage(doc: FoliDocument, options: ExportOptions): Promise<Ui
425
512
  ];
426
513
  const entries = [];
427
514
  for (const [name, text] of files) entries.push(await deflateEntry(name, encoder.encode(text)));
515
+ for (const part of media.added) entries.push(await deflateEntry(part.name.slice(1), part.data));
428
516
  return writeZip(entries);
429
517
  }
430
518
 
@@ -24,9 +24,11 @@ import {
24
24
  usableStyle,
25
25
  } from "../import/parts.js";
26
26
  import { Recorder } from "../import/report.js";
27
+ import { DocxError } from "../package.js";
27
28
  import type { XmlElement, XmlNode } from "../xml.js";
28
29
  import { blocksXml, type WriteContext } from "./content.js";
29
30
  import { paragraphPropertiesXml, runPropertiesXml, same } from "./properties.js";
31
+ import { stylePartsXml } from "./tables.js";
30
32
  import {
31
33
  attributesOf,
32
34
  el,
@@ -187,6 +189,18 @@ function styleXml(style: StyleJSON, ns: Namespaces): string {
187
189
  if (reread && same(normalizeStyle(style), normalizeStyle(reread))) return style.ext as string;
188
190
  }
189
191
  const reread = o ? styleOf(o.element, reading(o.source)) : undefined;
192
+ // A table style read from the file has its parts written as read (`w:tblPr`… kept): a change
193
+ // would be lost. A new one (Word's Table Grid, added by a command) is written from the model,
194
+ // without conditional formats.
195
+ for (const key of o
196
+ ? (["table", "row", "cell", "conditions"] as const)
197
+ : (["conditions"] as const)) {
198
+ if (!same(style[key], reread?.[key])) {
199
+ throw new DocxError(
200
+ `Style ${style.id}: a changed table style (${key}) cannot be exported yet`,
201
+ );
202
+ }
203
+ }
190
204
  const generated = new Map<string, string>([
191
205
  ["name", val("name", style.name)],
192
206
  ["basedOn", val("basedOn", style.basedOn)],
@@ -208,6 +222,7 @@ function styleXml(style: StyleJSON, ns: Namespaces): string {
208
222
  "rPr",
209
223
  runPropertiesXml(style.run ?? [], childSource(o, "rPr"), ns, "w:rPr", false, undefined, true),
210
224
  ],
225
+ ...(o ? [] : Object.entries(stylePartsXml(style, ns))),
211
226
  ]);
212
227
  const children = merged(STYLE_ORDER, new Set(generated.keys()), generated, o);
213
228
  const open =