docxkeun 0.1.3 → 0.3.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 (199) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +166 -16
  3. package/dist/api/editor.d.ts +231 -7
  4. package/dist/api/editor.js +1125 -26
  5. package/dist/api/headers.d.ts +51 -0
  6. package/dist/api/headers.js +133 -0
  7. package/dist/api/index.d.ts +6 -1
  8. package/dist/api/index.js +4 -1
  9. package/dist/api/lists.d.ts +37 -0
  10. package/dist/api/lists.js +132 -0
  11. package/dist/api/parts.js +1 -0
  12. package/dist/api/positions.js +1 -0
  13. package/dist/api/revisions.d.ts +61 -0
  14. package/dist/api/revisions.js +401 -0
  15. package/dist/api/selection.d.ts +57 -0
  16. package/dist/api/selection.js +91 -0
  17. package/dist/api/tables.d.ts +60 -0
  18. package/dist/api/tables.js +138 -0
  19. package/dist/charts/color.d.ts +45 -0
  20. package/dist/charts/color.js +322 -0
  21. package/dist/charts/format.d.ts +12 -0
  22. package/dist/charts/format.js +459 -0
  23. package/dist/charts/index.d.ts +11 -0
  24. package/dist/charts/index.js +8 -0
  25. package/dist/charts/model.d.ts +225 -0
  26. package/dist/charts/model.js +758 -0
  27. package/dist/charts/outline.d.ts +17 -0
  28. package/dist/charts/outline.js +214 -0
  29. package/dist/charts/render.d.ts +20 -0
  30. package/dist/charts/render.js +1772 -0
  31. package/dist/drawing/arrows.d.ts +37 -0
  32. package/dist/drawing/arrows.js +99 -0
  33. package/dist/drawing/formula.d.ts +40 -0
  34. package/dist/drawing/formula.js +159 -0
  35. package/dist/drawing/geometry.d.ts +61 -0
  36. package/dist/drawing/geometry.js +286 -0
  37. package/dist/drawing/index.d.ts +12 -0
  38. package/dist/drawing/index.js +8 -0
  39. package/dist/drawing/presets.d.ts +72 -0
  40. package/dist/drawing/presets.js +2874 -0
  41. package/dist/fonts/shaping/apply.d.ts +94 -0
  42. package/dist/fonts/shaping/apply.js +349 -0
  43. package/dist/fonts/shaping/arabic.d.ts +28 -0
  44. package/dist/fonts/shaping/arabic.js +235 -0
  45. package/dist/fonts/shaping/buffer.d.ts +53 -0
  46. package/dist/fonts/shaping/buffer.js +95 -0
  47. package/dist/fonts/shaping/gdef.d.ts +30 -0
  48. package/dist/fonts/shaping/gdef.js +66 -0
  49. package/dist/fonts/shaping/gpos.d.ts +86 -0
  50. package/dist/fonts/shaping/gpos.js +428 -0
  51. package/dist/fonts/shaping/gsub.d.ts +65 -0
  52. package/dist/fonts/shaping/gsub.js +313 -0
  53. package/dist/fonts/shaping/index.d.ts +32 -0
  54. package/dist/fonts/shaping/index.js +402 -0
  55. package/dist/fonts/shaping/indic.d.ts +6 -0
  56. package/dist/fonts/shaping/indic.js +805 -0
  57. package/dist/fonts/shaping/layout-common.d.ts +124 -0
  58. package/dist/fonts/shaping/layout-common.js +349 -0
  59. package/dist/fonts/shaping/plan.d.ts +87 -0
  60. package/dist/fonts/shaping/plan.js +152 -0
  61. package/dist/fonts/shaping/scripts.d.ts +26 -0
  62. package/dist/fonts/shaping/scripts.js +160 -0
  63. package/dist/fonts/shaping/shaper.d.ts +23 -0
  64. package/dist/fonts/shaping/shaper.js +5 -0
  65. package/dist/fonts/shaping/unicode.d.ts +34 -0
  66. package/dist/fonts/shaping/unicode.js +138 -0
  67. package/dist/images/bmp.d.ts +9 -0
  68. package/dist/images/bmp.js +234 -0
  69. package/dist/images/gif.d.ts +9 -0
  70. package/dist/images/gif.js +215 -0
  71. package/dist/images/index.d.ts +18 -0
  72. package/dist/images/index.js +63 -0
  73. package/dist/images/png-encode.d.ts +4 -0
  74. package/dist/images/png-encode.js +73 -0
  75. package/dist/images/size.d.ts +10 -0
  76. package/dist/images/size.js +83 -0
  77. package/dist/images/tiff.d.ts +14 -0
  78. package/dist/images/tiff.js +407 -0
  79. package/dist/index.d.ts +7 -2
  80. package/dist/index.js +5 -0
  81. package/dist/layout/bidi.d.ts +18 -0
  82. package/dist/layout/bidi.js +71 -0
  83. package/dist/layout/blocks.d.ts +20 -3
  84. package/dist/layout/blocks.js +88 -58
  85. package/dist/layout/cache.d.ts +31 -0
  86. package/dist/layout/cache.js +38 -0
  87. package/dist/layout/drawing.d.ts +30 -0
  88. package/dist/layout/drawing.js +120 -0
  89. package/dist/layout/engine.d.ts +3 -0
  90. package/dist/layout/engine.js +218 -11
  91. package/dist/layout/index.d.ts +1 -0
  92. package/dist/layout/index.js +1 -0
  93. package/dist/layout/lines.d.ts +63 -5
  94. package/dist/layout/lines.js +245 -20
  95. package/dist/layout/paint.d.ts +25 -3
  96. package/dist/layout/paint.js +26 -10
  97. package/dist/layout/shapes.d.ts +7 -0
  98. package/dist/layout/shapes.js +338 -0
  99. package/dist/layout/style.d.ts +4 -0
  100. package/dist/layout/style.js +2 -0
  101. package/dist/layout/types.d.ts +89 -2
  102. package/dist/math/boxes.d.ts +88 -0
  103. package/dist/math/boxes.js +166 -0
  104. package/dist/math/index.d.ts +29 -0
  105. package/dist/math/index.js +44 -0
  106. package/dist/math/layout.d.ts +13 -0
  107. package/dist/math/layout.js +771 -0
  108. package/dist/math/linear.d.ts +3 -0
  109. package/dist/math/linear.js +152 -0
  110. package/dist/math/omml.d.ts +15 -0
  111. package/dist/math/omml.js +57 -0
  112. package/dist/math/paths.d.ts +61 -0
  113. package/dist/math/paths.js +450 -0
  114. package/dist/math/symbols.d.ts +49 -0
  115. package/dist/math/symbols.js +269 -0
  116. package/dist/math/text.d.ts +53 -0
  117. package/dist/math/text.js +316 -0
  118. package/dist/metafile/canvas.d.ts +80 -0
  119. package/dist/metafile/canvas.js +515 -0
  120. package/dist/metafile/dib.d.ts +27 -0
  121. package/dist/metafile/dib.js +300 -0
  122. package/dist/metafile/emf.d.ts +31 -0
  123. package/dist/metafile/emf.js +591 -0
  124. package/dist/metafile/geometry.d.ts +49 -0
  125. package/dist/metafile/geometry.js +85 -0
  126. package/dist/metafile/index.d.ts +27 -0
  127. package/dist/metafile/index.js +34 -0
  128. package/dist/metafile/reader.d.ts +28 -0
  129. package/dist/metafile/reader.js +59 -0
  130. package/dist/metafile/state.d.ts +118 -0
  131. package/dist/metafile/state.js +172 -0
  132. package/dist/metafile/text.d.ts +17 -0
  133. package/dist/metafile/text.js +130 -0
  134. package/dist/metafile/wmf.d.ts +33 -0
  135. package/dist/metafile/wmf.js +395 -0
  136. package/dist/model/content.d.ts +92 -7
  137. package/dist/model/content.js +251 -17
  138. package/dist/model/document.d.ts +34 -1
  139. package/dist/model/document.js +80 -1
  140. package/dist/model/fields.d.ts +4 -0
  141. package/dist/model/fields.js +10 -0
  142. package/dist/model/numbering.d.ts +2 -0
  143. package/dist/model/numbering.js +22 -0
  144. package/dist/model/props.d.ts +2 -0
  145. package/dist/model/props.js +3 -0
  146. package/dist/opc/index.d.ts +1 -1
  147. package/dist/opc/package.d.ts +34 -0
  148. package/dist/opc/package.js +58 -4
  149. package/dist/pdf/export.js +97 -6
  150. package/dist/pdf/images.d.ts +7 -0
  151. package/dist/pdf/images.js +39 -2
  152. package/dist/render/activity.d.ts +179 -0
  153. package/dist/render/activity.js +1003 -0
  154. package/dist/render/clipboard.d.ts +29 -0
  155. package/dist/render/clipboard.js +401 -0
  156. package/dist/render/comments.d.ts +166 -0
  157. package/dist/render/comments.js +779 -0
  158. package/dist/render/context-menu.d.ts +124 -0
  159. package/dist/render/context-menu.js +525 -0
  160. package/dist/render/editing.d.ts +146 -5
  161. package/dist/render/editing.js +678 -53
  162. package/dist/render/index.d.ts +12 -0
  163. package/dist/render/index.js +11 -0
  164. package/dist/render/navigation-panel.d.ts +76 -0
  165. package/dist/render/navigation-panel.js +431 -0
  166. package/dist/render/selection.js +5 -0
  167. package/dist/render/svg.d.ts +4 -6
  168. package/dist/render/svg.js +69 -7
  169. package/dist/render/toolbar.d.ts +83 -0
  170. package/dist/render/toolbar.js +505 -0
  171. package/dist/render/ui/comment-layout.d.ts +39 -0
  172. package/dist/render/ui/comment-layout.js +79 -0
  173. package/dist/render/ui/icons.d.ts +6 -0
  174. package/dist/render/ui/icons.js +38 -0
  175. package/dist/render/ui/menu.d.ts +38 -0
  176. package/dist/render/ui/menu.js +274 -0
  177. package/dist/render/ui/nav-model.d.ts +11 -0
  178. package/dist/render/ui/nav-model.js +34 -0
  179. package/dist/render/ui/overflow.d.ts +5 -0
  180. package/dist/render/ui/overflow.js +18 -0
  181. package/dist/render/ui/popover.d.ts +18 -0
  182. package/dist/render/ui/popover.js +109 -0
  183. package/dist/render/ui/theme.d.ts +2 -0
  184. package/dist/render/ui/theme.js +29 -0
  185. package/dist/render/undo.d.ts +76 -0
  186. package/dist/render/undo.js +144 -0
  187. package/dist/render/viewer.d.ts +100 -7
  188. package/dist/render/viewer.js +304 -92
  189. package/dist/security/policy.d.ts +3 -0
  190. package/dist/security/policy.js +6 -2
  191. package/dist/security/protection.d.ts +1 -0
  192. package/dist/security/protection.js +1 -1
  193. package/dist/text/bidi-data.d.ts +53 -0
  194. package/dist/text/bidi-data.js +318 -0
  195. package/dist/text/bidi.d.ts +37 -0
  196. package/dist/text/bidi.js +508 -0
  197. package/dist/xml/ns.d.ts +5 -0
  198. package/dist/xml/ns.js +7 -0
  199. package/package.json +9 -2
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Open Packaging Conventions: parts, content types and relationships on top of the zip layer.
3
+ * Parts that nobody touched are written back from their original compressed bytes.
4
+ */
5
+ import { type ZipRawData } from '../zip/zip.js';
1
6
  import { type XmlDocument } from '../xml/index.js';
2
7
  import { type RelKind, REL } from './constants.js';
3
8
  export interface Relationship {
@@ -6,6 +11,24 @@ export interface Relationship {
6
11
  target: string;
7
12
  external: boolean;
8
13
  }
14
+ interface Part {
15
+ name: string;
16
+ raw?: ZipRawData;
17
+ bytes?: Uint8Array;
18
+ xml?: XmlDocument;
19
+ dirty: boolean;
20
+ /** Changes whenever the part may have changed; lets checkpoints reuse unchanged snapshots. */
21
+ rev: number;
22
+ }
23
+ /** An opaque snapshot of every part, content type and relationship list (see `OpcPackage.checkpoint`). */
24
+ export interface PackageCheckpoint {
25
+ readonly parts: Array<[string, Part]>;
26
+ readonly order: string[];
27
+ readonly defaults: Array<[string, string]>;
28
+ readonly overrides: Array<[string, string]>;
29
+ readonly contentTypesDirty: boolean;
30
+ readonly rels: Array<[string, Relationship[]]>;
31
+ }
9
32
  export declare class OpcError extends Error {
10
33
  name: string;
11
34
  }
@@ -15,6 +38,9 @@ export declare class OpcPackage {
15
38
  private readonly defaults;
16
39
  private readonly overrides;
17
40
  private contentTypesDirty;
41
+ private revSeq;
42
+ /** Last frozen copy per part, with the revision it was taken at. Never handed to live state. */
43
+ private readonly snapshots;
18
44
  private readonly relsCache;
19
45
  private readonly readers;
20
46
  private contentTypesRaw;
@@ -22,6 +48,14 @@ export declare class OpcPackage {
22
48
  static open(bytes: Uint8Array): Promise<OpcPackage>;
23
49
  /** An empty package with the standard defaults. */
24
50
  static create(): OpcPackage;
51
+ /**
52
+ * Snapshot the whole package so `restore` can bring it back. Parsed XML is deep-cloned; bytes are shared
53
+ * because they are replaced, never mutated in place.
54
+ */
55
+ checkpoint(): PackageCheckpoint;
56
+ private frozenCopy;
57
+ /** Put the package back as it was at `checkpoint()`. The same checkpoint can be restored again. */
58
+ restore(cp: PackageCheckpoint): void;
25
59
  partNames(): string[];
26
60
  has(name: string): boolean;
27
61
  contentType(name: string): string | undefined;
@@ -4,7 +4,7 @@
4
4
  */
5
5
  import { readZip, writeZip } from '../zip/zip.js';
6
6
  import { decodeXmlBytes, utf8Encode } from '../util/text.js';
7
- import { el, elements, parseXml, serializeXml } from '../xml/index.js';
7
+ import { cloneElement, el, elements, parseXml, serializeXml } from '../xml/index.js';
8
8
  import { CONTENT_TYPE, IMAGE_CONTENT_TYPES, isRelType, REL } from './constants.js';
9
9
  import { extension, normalizePartName, partKey, relsPartFor, relativeTarget, resolveTarget } from './paths.js';
10
10
  export class OpcError extends Error {
@@ -17,6 +17,9 @@ export class OpcPackage {
17
17
  defaults = new Map();
18
18
  overrides = new Map();
19
19
  contentTypesDirty = false;
20
+ revSeq = 0;
21
+ /** Last frozen copy per part, with the revision it was taken at. Never handed to live state. */
22
+ snapshots = new Map();
20
23
  relsCache = new Map();
21
24
  readers = new Map();
22
25
  contentTypesRaw;
@@ -33,7 +36,7 @@ export class OpcPackage {
33
36
  continue;
34
37
  }
35
38
  const name = normalizePartName(entry.name);
36
- pkg.parts.set(partKey(name), { name, raw: entry.raw, dirty: false });
39
+ pkg.parts.set(partKey(name), { name, raw: entry.raw, dirty: false, rev: 0 });
37
40
  pkg.order.push(partKey(name));
38
41
  // Keep a reader so bytes are inflated lazily.
39
42
  pkg.readers.set(partKey(name), entry.read);
@@ -61,6 +64,46 @@ export class OpcPackage {
61
64
  pkg.contentTypesDirty = true;
62
65
  return pkg;
63
66
  }
67
+ /**
68
+ * Snapshot the whole package so `restore` can bring it back. Parsed XML is deep-cloned; bytes are shared
69
+ * because they are replaced, never mutated in place.
70
+ */
71
+ checkpoint() {
72
+ return {
73
+ parts: [...this.parts].map(([key, part]) => [key, this.frozenCopy(key, part)]),
74
+ order: [...this.order],
75
+ defaults: [...this.defaults],
76
+ overrides: [...this.overrides],
77
+ contentTypesDirty: this.contentTypesDirty,
78
+ rels: [...this.relsCache].map(([key, list]) => [key, list.map((r) => ({ ...r }))]),
79
+ };
80
+ }
81
+ frozenCopy(key, part) {
82
+ const cached = this.snapshots.get(key);
83
+ if (cached && cached.rev === part.rev)
84
+ return cached.part;
85
+ const copy = copyPart(part);
86
+ this.snapshots.set(key, { rev: part.rev, part: copy });
87
+ return copy;
88
+ }
89
+ /** Put the package back as it was at `checkpoint()`. The same checkpoint can be restored again. */
90
+ restore(cp) {
91
+ this.parts.clear();
92
+ for (const [key, part] of cp.parts)
93
+ this.parts.set(key, { ...copyPart(part), rev: ++this.revSeq });
94
+ this.snapshots.clear();
95
+ this.order.splice(0, this.order.length, ...cp.order);
96
+ this.defaults.clear();
97
+ for (const [k, v] of cp.defaults)
98
+ this.defaults.set(k, v);
99
+ this.overrides.clear();
100
+ for (const [k, v] of cp.overrides)
101
+ this.overrides.set(k, v);
102
+ this.contentTypesDirty = cp.contentTypesDirty;
103
+ this.relsCache.clear();
104
+ for (const [key, list] of cp.rels)
105
+ this.relsCache.set(key, list.map((r) => ({ ...r })));
106
+ }
64
107
  partNames() {
65
108
  return this.order.map((k) => this.parts.get(k).name);
66
109
  }
@@ -104,7 +147,9 @@ export class OpcPackage {
104
147
  return this.getXml(name);
105
148
  }
106
149
  markDirty(name) {
107
- this.requirePart(name).dirty = true;
150
+ const part = this.requirePart(name);
151
+ part.dirty = true;
152
+ part.rev = ++this.revSeq;
108
153
  }
109
154
  isDirty(name) {
110
155
  return this.parts.get(partKey(name))?.dirty ?? false;
@@ -114,17 +159,20 @@ export class OpcPackage {
114
159
  part.xml = doc;
115
160
  part.bytes = undefined;
116
161
  part.dirty = true;
162
+ part.rev = ++this.revSeq;
117
163
  }
118
164
  setBytes(name, bytes, contentType) {
119
165
  const part = this.ensurePart(name, contentType);
120
166
  part.bytes = bytes;
121
167
  part.xml = undefined;
122
168
  part.dirty = true;
169
+ part.rev = ++this.revSeq;
123
170
  }
124
171
  removePart(name) {
125
172
  const key = partKey(name);
126
173
  if (!this.parts.delete(key))
127
174
  return;
175
+ this.snapshots.delete(key);
128
176
  this.order.splice(this.order.indexOf(key), 1);
129
177
  if (this.overrides.delete(key))
130
178
  this.contentTypesDirty = true;
@@ -138,7 +186,7 @@ export class OpcPackage {
138
186
  const key = partKey(clean);
139
187
  let part = this.parts.get(key);
140
188
  if (!part) {
141
- part = { name: clean, dirty: true };
189
+ part = { name: clean, dirty: true, rev: 0 };
142
190
  this.parts.set(key, part);
143
191
  this.order.push(key);
144
192
  }
@@ -280,3 +328,9 @@ export class OpcPackage {
280
328
  }
281
329
  }
282
330
  export { REL };
331
+ function copyPart(part) {
332
+ const copy = { ...part };
333
+ if (part.xml)
334
+ copy.xml = { ...part.xml, root: cloneElement(part.xml.root) };
335
+ return copy;
336
+ }
@@ -6,7 +6,7 @@
6
6
  import { readComments } from '../comments/read.js';
7
7
  import { randomBytes } from '../crypto/index.js';
8
8
  import { layoutDocument } from '../layout/engine.js';
9
- import { addImage } from './images.js';
9
+ import { addImage, addRasterImage } from './images.js';
10
10
  import { PdfFont } from './fonts.js';
11
11
  import { name, num, pdfDate, str } from './objects.js';
12
12
  import { PdfWriter } from './writer.js';
@@ -29,6 +29,34 @@ class PageContent {
29
29
  ops = [];
30
30
  fonts = new Map();
31
31
  images = new Map();
32
+ /** Graphics states for transparency: resource name → [fill alpha, stroke alpha]. */
33
+ alphas = new Map();
34
+ alpha(fill, stroke) {
35
+ const key = `GA${Math.round(fill * 1000)}_${Math.round(stroke * 1000)}`;
36
+ this.alphas.set(key, [fill, stroke]);
37
+ return key;
38
+ }
39
+ }
40
+ /** The image-space matrix for an image item: its box, rotated (clockwise on the page) and flipped about its centre. */
41
+ function imageMatrix(item, H) {
42
+ const cx = item.x + item.w / 2;
43
+ const cy = H - item.y - item.h / 2;
44
+ // PDF y points up, so a clockwise page rotation is a negative angle here.
45
+ const a = (-(item.rotation ?? 0) * Math.PI) / 180;
46
+ const sx = item.flipH ? -item.w : item.w;
47
+ const sy = item.flipV ? -item.h : item.h;
48
+ const cos = Math.cos(a);
49
+ const sin = Math.sin(a);
50
+ // translate(cx, cy) · rotate(a) · scale(sx, sy) · translate(-0.5, -0.5)
51
+ const m = [cos * sx, sin * sx, -sin * sy, cos * sy];
52
+ const e = cx - 0.5 * m[0] - 0.5 * m[2];
53
+ const f = cy - 0.5 * m[1] - 0.5 * m[3];
54
+ return [...m, e, f].map(num).join(' ');
55
+ }
56
+ function pathOps(commands, H) {
57
+ return commands
58
+ .map((c) => (c.op === 'Z' ? 'h' : c.op === 'M' ? `${num(c.x)} ${num(H - c.y)} m` : c.op === 'L' ? `${num(c.x)} ${num(H - c.y)} l` : `${num(c.x1)} ${num(H - c.y1)} ${num(c.x2)} ${num(H - c.y2)} ${num(c.x)} ${num(H - c.y)} c`))
59
+ .join(' ');
32
60
  }
33
61
  export async function exportPdf(doc, options) {
34
62
  const layout = options.layout ?? layoutDocument(doc, { fonts: options.fonts });
@@ -64,6 +92,16 @@ export async function exportPdf(doc, options) {
64
92
  }
65
93
  return images.get(target) ?? null;
66
94
  };
95
+ const rasters = new Map();
96
+ const rasterFor = async (image) => {
97
+ let entry = rasters.get(image);
98
+ if (!entry) {
99
+ const { ref } = await addRasterImage(writer, image);
100
+ entry = { ref, resource: `Im${images.size + rasters.size + 1}r` };
101
+ rasters.set(image, entry);
102
+ }
103
+ return entry;
104
+ };
67
105
  const pageAnnots = layout.pages.map(() => []);
68
106
  if (options.comments ?? true)
69
107
  addComments(writer, readComments(doc), layout, pageAnnots);
@@ -71,7 +109,7 @@ export async function exportPdf(doc, options) {
71
109
  const content = new PageContent();
72
110
  const H = page.height;
73
111
  for (const item of page.items)
74
- await drawItem(item, content, H, fontFor, imageFor);
112
+ await drawItem(item, content, H, fontFor, imageFor, rasterFor);
75
113
  const stream = await writer.stream({}, new TextEncoder().encode(content.ops.join('\n')));
76
114
  const fontRes = {};
77
115
  for (const [res, ref] of content.fonts)
@@ -79,6 +117,9 @@ export async function exportPdf(doc, options) {
79
117
  const xobjects = {};
80
118
  for (const [res, ref] of content.images)
81
119
  xobjects[res] = ref;
120
+ const extGStates = {};
121
+ for (const [res, [fill, stroke]] of content.alphas)
122
+ extGStates[res] = { Type: name('ExtGState'), ca: fill, CA: stroke };
82
123
  // Link annotations.
83
124
  for (const link of page.links) {
84
125
  const rect = [link.x, H - link.y - link.h, link.x + link.w, H - link.y];
@@ -100,7 +141,12 @@ export async function exportPdf(doc, options) {
100
141
  Type: name('Page'),
101
142
  Parent: pagesRef,
102
143
  MediaBox: [0, 0, page.width, page.height],
103
- Resources: { Font: fontRes, XObject: Object.keys(xobjects).length ? xobjects : undefined, ProcSet: [name('PDF'), name('Text'), name('ImageB'), name('ImageC')] },
144
+ Resources: {
145
+ Font: fontRes,
146
+ XObject: Object.keys(xobjects).length ? xobjects : undefined,
147
+ ExtGState: Object.keys(extGStates).length ? extGStates : undefined,
148
+ ProcSet: [name('PDF'), name('Text'), name('ImageB'), name('ImageC')],
149
+ },
104
150
  Contents: stream,
105
151
  Annots: pageAnnots[page.index].length ? pageAnnots[page.index] : undefined,
106
152
  });
@@ -139,7 +185,7 @@ export async function exportPdf(doc, options) {
139
185
  });
140
186
  return writer.build(catalogRef, info, randomBytes(16), options.encryption);
141
187
  }
142
- async function drawItem(item, content, H, fontFor, imageFor) {
188
+ async function drawItem(item, content, H, fontFor, imageFor, rasterFor) {
143
189
  const ops = content.ops;
144
190
  switch (item.type) {
145
191
  case 'rect':
@@ -165,14 +211,40 @@ async function drawItem(item, content, H, fontFor, imageFor) {
165
211
  seg(item.x1, item.y1, item.x2, item.y2, item.width);
166
212
  break;
167
213
  }
214
+ case 'path': {
215
+ if (!item.commands.length || (!item.fill && !item.stroke))
216
+ break;
217
+ const parts = ['q'];
218
+ const fa = item.fill ? (item.fillOpacity ?? 1) : 1;
219
+ const sa = item.stroke ? (item.strokeOpacity ?? 1) : 1;
220
+ if (fa < 1 || sa < 1)
221
+ parts.push(`/${content.alpha(fa, sa)} gs`);
222
+ if (item.fill)
223
+ parts.push(`${rgb(item.fill)} rg`);
224
+ if (item.stroke) {
225
+ parts.push(`${rgb(item.stroke)} RG ${num(item.strokeWidth ?? 0.75)} w`);
226
+ parts.push(item.dash?.length ? `[${item.dash.map(num).join(' ')}] 0 d` : '[] 0 d');
227
+ if (item.lineCap)
228
+ parts.push(`${{ butt: 0, round: 1, square: 2 }[item.lineCap]} J`);
229
+ if (item.lineJoin)
230
+ parts.push(`${{ miter: 0, round: 1, bevel: 2 }[item.lineJoin]} j`);
231
+ }
232
+ parts.push(pathOps(item.commands, H));
233
+ parts.push(item.fill && item.stroke ? (item.evenOdd ? 'B*' : 'B') : item.fill ? (item.evenOdd ? 'f*' : 'f') : 'S');
234
+ parts.push('Q');
235
+ ops.push(parts.join(' '));
236
+ break;
237
+ }
168
238
  case 'image': {
169
- const img = await imageFor(item.target, item.external);
239
+ if (item.frameOnly)
240
+ break;
241
+ const img = item.raster ? await rasterFor(item.raster) : await imageFor(item.target, item.external);
170
242
  if (!img) {
171
243
  ops.push(`0.945 0.953 0.957 rg ${num(item.x)} ${num(H - item.y - item.h)} ${num(item.w)} ${num(item.h)} re f`);
172
244
  break;
173
245
  }
174
246
  content.images.set(img.resource, img.ref);
175
- ops.push(`q ${num(item.w)} 0 0 ${num(item.h)} ${num(item.x)} ${num(H - item.y - item.h)} cm /${img.resource} Do Q`);
247
+ ops.push(`q ${imageMatrix(item, H)} cm /${img.resource} Do Q`);
176
248
  break;
177
249
  }
178
250
  case 'text': {
@@ -181,6 +253,25 @@ async function drawItem(item, content, H, fontFor, imageFor) {
181
253
  const { font, ref } = fontFor(item);
182
254
  content.fonts.set(font.resource, ref);
183
255
  const scale = item.scale || 1;
256
+ if (item.clusterGlyphs) {
257
+ // Shaped text: each glyph at its own position (joining forms, ligatures, attached marks).
258
+ const skew = item.font.syntheticItalic ? 0.21 : 0;
259
+ const bold = item.font.syntheticBold ? ` 2 Tr ${num(item.size * 0.03)} w ${rgb(item.color)} RG` : '';
260
+ const tz = scale !== 1 ? ` ${num(scale * 100)} Tz` : '';
261
+ const parts = [];
262
+ item.clusterGlyphs.forEach((cluster, i) => {
263
+ // Right-to-left clusters are drawn in visual order: their glyphs reversed.
264
+ const glyphs = item.complex?.rtl ? [...cluster].reverse() : cluster;
265
+ let pen = item.xs[i];
266
+ for (const g of glyphs) {
267
+ font.use(g.id, g.text);
268
+ parts.push(`1 0 ${num(skew)} 1 ${num(pen + g.dx)} ${num(H - item.y + g.dy)} Tm <${g.id.toString(16).padStart(4, '0')}> Tj`);
269
+ pen += g.advance * scale;
270
+ }
271
+ });
272
+ ops.push(`BT /${font.resource} ${num(item.size)} Tf${tz}${bold} ${rgb(item.color)} rg ${parts.join(' ')} ET`);
273
+ break;
274
+ }
184
275
  const parts = [];
185
276
  let hex = '';
186
277
  let x = item.xs[0];
@@ -1,3 +1,4 @@
1
+ import type { RasterImage } from '../layout/types.js';
1
2
  import { type PdfRef } from './objects.js';
2
3
  import type { PdfWriter } from './writer.js';
3
4
  export declare class ImageFormatError extends Error {
@@ -11,3 +12,9 @@ export declare function addImage(writer: PdfWriter, bytes: Uint8Array): Promise<
11
12
  width: number;
12
13
  height: number;
13
14
  }>;
15
+ /** Add decoded pixels (RGBA) as an image XObject, with a soft mask when any pixel is not opaque. */
16
+ export declare function addRasterImage(writer: PdfWriter, image: RasterImage): Promise<{
17
+ ref: PdfRef;
18
+ width: number;
19
+ height: number;
20
+ }>;
@@ -1,4 +1,8 @@
1
- /** Image XObjects: JPEG passes through; PNG is re-packed (alpha goes to a soft mask). */
1
+ /**
2
+ * Image XObjects: JPEG passes through; PNG is re-packed (alpha goes to a soft mask); GIF, BMP and
3
+ * TIFF, which PDF has no filter for, are decoded to pixels and embedded like any raster.
4
+ */
5
+ import { decodeRaster, sniffImage } from '../images/index.js';
2
6
  import { ByteReader, concatBytes } from '../util/bytes.js';
3
7
  import { inflate } from '../zip/deflate.js';
4
8
  import { name, PdfStream, str } from './objects.js';
@@ -260,5 +264,38 @@ export async function addImage(writer, bytes) {
260
264
  }, decoded.color);
261
265
  return { ref, width: png.width, height: png.height };
262
266
  }
263
- throw new ImageFormatError('Only JPEG and PNG images can be embedded in PDF');
267
+ const kind = sniffImage(bytes);
268
+ if (kind === 'gif' || kind === 'bmp' || kind === 'tiff') {
269
+ let image;
270
+ try {
271
+ image = await decodeRaster(bytes);
272
+ }
273
+ catch (error) {
274
+ // Callers draw a placeholder for an ImageFormatError, so a damaged or unsupported variant must surface as one.
275
+ throw new ImageFormatError(error instanceof Error ? error.message : String(error), { cause: error });
276
+ }
277
+ return addRasterImage(writer, image);
278
+ }
279
+ throw new ImageFormatError(`${kind ? kind.toUpperCase() : 'Unrecognised'} images cannot be embedded in PDF`);
280
+ }
281
+ /** Add decoded pixels (RGBA) as an image XObject, with a soft mask when any pixel is not opaque. */
282
+ export async function addRasterImage(writer, image) {
283
+ const { width, height, rgba } = image;
284
+ const pixels = width * height;
285
+ const color = new Uint8Array(pixels * 3);
286
+ const alpha = new Uint8Array(pixels);
287
+ let translucent = false;
288
+ for (let i = 0; i < pixels; i++) {
289
+ color[i * 3] = rgba[i * 4];
290
+ color[i * 3 + 1] = rgba[i * 4 + 1];
291
+ color[i * 3 + 2] = rgba[i * 4 + 2];
292
+ alpha[i] = rgba[i * 4 + 3];
293
+ if (alpha[i] !== 255)
294
+ translucent = true;
295
+ }
296
+ const smask = translucent
297
+ ? await writer.stream({ Type: name('XObject'), Subtype: name('Image'), Width: width, Height: height, ColorSpace: name('DeviceGray'), BitsPerComponent: 8 }, alpha)
298
+ : undefined;
299
+ const ref = await writer.stream({ Type: name('XObject'), Subtype: name('Image'), Width: width, Height: height, ColorSpace: name('DeviceRGB'), BitsPerComponent: 8, SMask: smask }, color);
300
+ return { ref, width, height };
264
301
  }
@@ -0,0 +1,179 @@
1
+ import type { DocxViewer } from './viewer.js';
2
+ export interface ParagraphChange {
3
+ /** Index (0-based) of the paragraph in the new text. */
4
+ para: number;
5
+ /** A new paragraph, or one whose text changed. */
6
+ kind: 'inserted' | 'changed';
7
+ /** Ranges of new text in it, [from, to) (the whole paragraph for an inserted one). */
8
+ ranges: Array<[number, number]>;
9
+ /** Offsets where text was removed without new text in its place. */
10
+ cuts: number[];
11
+ /** The paragraph's text before (changed paragraphs). */
12
+ before?: string;
13
+ /** Index (0-based) of the paragraph in the old text (changed paragraphs). */
14
+ from?: number;
15
+ /** Only the formatting changed (bold, style, alignment, list). */
16
+ formatting?: boolean;
17
+ }
18
+ export interface ParagraphDiff {
19
+ changes: ParagraphChange[];
20
+ /** Removed paragraphs: their text, and the index of the new paragraph they were before (or the count, at the end). */
21
+ deleted: Array<{
22
+ at: number;
23
+ text: string;
24
+ }>;
25
+ /** Paragraphs whose text did not change: [old index, new index]. */
26
+ same: Array<[number, number]>;
27
+ }
28
+ /** A document's paragraphs at one moment: text, and formatting (to notice bold, styles, alignment…). */
29
+ export interface ParagraphSnapshot {
30
+ texts: string[];
31
+ formats: string[];
32
+ }
33
+ /** What changed inside one paragraph: ranges of new text and points where text was cut. */
34
+ export declare function diffText(before: string, after: string): {
35
+ ranges: Array<[number, number]>;
36
+ cuts: number[];
37
+ };
38
+ /** Paragraph-level changes between two versions of a document's paragraph texts. */
39
+ export declare function diffParagraphs(before: string[], after: string[]): ParagraphDiff;
40
+ /** How the AI's work shows on the paragraphs it is changing (see `ACTIVITY_STYLES`). */
41
+ export type ActivityStyle = 'highlight' | 'words' | 'underline' | 'edge' | 'spotlight' | 'quiet' | 'sparkles';
42
+ /** The styles, with a label and a line to show in a picker, in the order to show them. */
43
+ export declare const ACTIVITY_STYLES: ReadonlyArray<{
44
+ style: ActivityStyle;
45
+ label: string;
46
+ description: string;
47
+ }>;
48
+ export interface ActivityOptions {
49
+ /** The name on the caret and in the change marks' tooltips (default "Claude"). */
50
+ name?: string;
51
+ /**
52
+ * How the AI's work shows (default `'highlight'`), and so which mark stays after a change:
53
+ * highlight → a still tint on the changed paragraph, words → the changed words glow,
54
+ * underline → the changed words stay underlined, the others → the ✦ margin bar.
55
+ */
56
+ style?: ActivityStyle;
57
+ /**
58
+ * Colour of the caret, shimmer, glow and change marks: one CSS colour, or two for a gradient
59
+ * (default `['#7c5cff', '#d97757']`). The caret's label text turns dark on light colours.
60
+ */
61
+ color?: string | [string, string];
62
+ /** Show anything at all (default true). Off: calls do nothing on screen; `reveal` still returns the diff. */
63
+ enabled?: boolean;
64
+ /** Motion: shimmer sweep, ink, ghosts, scan line, the gliding caret (default true). Off: static highlights. */
65
+ animate?: boolean;
66
+ /** The marks that stay after a change, and the change map on the right edge (default true). */
67
+ marks?: boolean;
68
+ }
69
+ /** The AI's presence on the pages: see the module comment. Get it from `viewer.activity`. */
70
+ export declare class AiActivity {
71
+ private readonly viewer;
72
+ private aiName;
73
+ private aiColor;
74
+ private aiStyle;
75
+ private readonly layer;
76
+ private readonly map;
77
+ private readonly caret;
78
+ private readonly label;
79
+ private working;
80
+ private shimmers;
81
+ private marks;
82
+ private markEls;
83
+ private hideTimer;
84
+ private readonly cleanup;
85
+ private on;
86
+ private motion;
87
+ private keepMarks;
88
+ constructor(viewer: DocxViewer, options?: ActivityOptions);
89
+ /** The name on the caret ("Claude is editing…") and in the change marks' tooltips. */
90
+ get name(): string;
91
+ set name(name: string);
92
+ /**
93
+ * Colour of the caret, shimmer, glow and change marks: one CSS colour, or two for a gradient.
94
+ * `undefined` goes back to the defaults (or to the `--docxkeun-ai-color-1` / `-2` CSS
95
+ * variables when the page sets them). Throws a TypeError for something that isn't a CSS colour.
96
+ */
97
+ get color(): string | [string, string] | undefined;
98
+ set color(value: string | [string, string] | undefined);
99
+ /**
100
+ * How the AI's work shows, and so which mark stays after a change (see `ActivityOptions.style`).
101
+ * Changing it redraws the work in progress and the marks. Throws a TypeError for an unknown style.
102
+ */
103
+ get style(): ActivityStyle;
104
+ set style(style: ActivityStyle);
105
+ /** Show the AI's activity at all. Turning it off clears everything on screen. */
106
+ get enabled(): boolean;
107
+ set enabled(on: boolean);
108
+ /** Motion (sweeps, ink, ghosts, gliding caret); off leaves static highlights. */
109
+ get animate(): boolean;
110
+ set animate(on: boolean);
111
+ /** Change bars and the change map after a change. */
112
+ get marksShown(): boolean;
113
+ set marksShown(on: boolean);
114
+ private paragraphs;
115
+ /** Where a page point is in the scroll container. */
116
+ private at;
117
+ private lineRects;
118
+ /** Rectangles (one per line piece) covering characters [from, to) of a paragraph. */
119
+ private charRects;
120
+ private place;
121
+ /**
122
+ * Add an overlay. `life` (ms): remove it then (animation events are not dispatched reliably for
123
+ * pages in background tabs, so a timer does it); without it, it stays until redrawn.
124
+ */
125
+ private add;
126
+ /**
127
+ * Show the AI working on paragraphs (numbers from 1, as read_document counts them): a shimmer
128
+ * over them and its caret at the first. `mode: 'read'` sweeps a scan line over the view instead
129
+ * when no paragraphs are given. Lasts until `idle()` or `reveal()`.
130
+ */
131
+ work(paragraphs: number[], options?: {
132
+ mode?: 'edit' | 'read';
133
+ label?: string;
134
+ scroll?: boolean;
135
+ }): void;
136
+ /** The AI finished (without a change to show). */
137
+ idle(): void;
138
+ private drawWorking;
139
+ /** The working effect of the current style over each paragraph's lines. */
140
+ private drawStyle;
141
+ private workingText;
142
+ private moveCaret;
143
+ /** The caret near the top of the view (reading the whole document). */
144
+ private parkCaret;
145
+ private scan;
146
+ private ensureVisible;
147
+ /** The body's paragraphs now (text and formatting): pass to `reveal()` after the document changed. */
148
+ snapshot(): ParagraphSnapshot;
149
+ /**
150
+ * Show what changed since `before` (from `snapshot()`), once the viewer has laid out the new
151
+ * version: ink, glow, ghosts and cuts now, change bars and the change map until the next change.
152
+ */
153
+ reveal(before: ParagraphSnapshot | string[], options?: {
154
+ scroll?: boolean;
155
+ }): Promise<ParagraphDiff>;
156
+ /**
157
+ * Remove every mark and the change map. Marks build up over a run of changes (each follows its
158
+ * paragraph as others are added or removed) until this is called, e.g. when a new request starts.
159
+ */
160
+ clearMarks(): void;
161
+ /**
162
+ * The marks after a change: earlier marks follow their paragraphs (and go with deleted ones), a
163
+ * paragraph changed again is marked against its text before the first change, and new ones join.
164
+ */
165
+ private mergeMarks;
166
+ /** What a mark's tooltip says. */
167
+ private markTitle;
168
+ /** Draw the marks; those of the paragraphs in `fresh` (just changed) appear with a short animation. */
169
+ private drawMarks;
170
+ /** Ticks on the right edge for every change, scaled to the scroll height; click to jump. */
171
+ private drawMap;
172
+ /**
173
+ * The viewer rebuilt its page rows (zoom, the comment column's width): redraw at the new positions.
174
+ * @internal
175
+ */
176
+ rowsBuilt(): void;
177
+ private redraw;
178
+ destroy(): void;
179
+ }