docxkeun 0.1.3 → 0.2.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 (197) hide show
  1. package/CHANGELOG.md +48 -0
  2. package/README.md +137 -16
  3. package/dist/api/editor.d.ts +172 -5
  4. package/dist/api/editor.js +814 -24
  5. package/dist/api/headers.d.ts +51 -0
  6. package/dist/api/headers.js +133 -0
  7. package/dist/api/index.d.ts +5 -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 +390 -0
  15. package/dist/api/selection.d.ts +57 -0
  16. package/dist/api/selection.js +91 -0
  17. package/dist/charts/color.d.ts +45 -0
  18. package/dist/charts/color.js +322 -0
  19. package/dist/charts/format.d.ts +12 -0
  20. package/dist/charts/format.js +459 -0
  21. package/dist/charts/index.d.ts +11 -0
  22. package/dist/charts/index.js +8 -0
  23. package/dist/charts/model.d.ts +225 -0
  24. package/dist/charts/model.js +758 -0
  25. package/dist/charts/outline.d.ts +17 -0
  26. package/dist/charts/outline.js +214 -0
  27. package/dist/charts/render.d.ts +20 -0
  28. package/dist/charts/render.js +1772 -0
  29. package/dist/drawing/arrows.d.ts +37 -0
  30. package/dist/drawing/arrows.js +99 -0
  31. package/dist/drawing/formula.d.ts +40 -0
  32. package/dist/drawing/formula.js +159 -0
  33. package/dist/drawing/geometry.d.ts +61 -0
  34. package/dist/drawing/geometry.js +286 -0
  35. package/dist/drawing/index.d.ts +12 -0
  36. package/dist/drawing/index.js +8 -0
  37. package/dist/drawing/presets.d.ts +72 -0
  38. package/dist/drawing/presets.js +2874 -0
  39. package/dist/fonts/shaping/apply.d.ts +94 -0
  40. package/dist/fonts/shaping/apply.js +349 -0
  41. package/dist/fonts/shaping/arabic.d.ts +28 -0
  42. package/dist/fonts/shaping/arabic.js +235 -0
  43. package/dist/fonts/shaping/buffer.d.ts +53 -0
  44. package/dist/fonts/shaping/buffer.js +95 -0
  45. package/dist/fonts/shaping/gdef.d.ts +30 -0
  46. package/dist/fonts/shaping/gdef.js +66 -0
  47. package/dist/fonts/shaping/gpos.d.ts +86 -0
  48. package/dist/fonts/shaping/gpos.js +428 -0
  49. package/dist/fonts/shaping/gsub.d.ts +65 -0
  50. package/dist/fonts/shaping/gsub.js +313 -0
  51. package/dist/fonts/shaping/index.d.ts +32 -0
  52. package/dist/fonts/shaping/index.js +402 -0
  53. package/dist/fonts/shaping/indic.d.ts +6 -0
  54. package/dist/fonts/shaping/indic.js +805 -0
  55. package/dist/fonts/shaping/layout-common.d.ts +124 -0
  56. package/dist/fonts/shaping/layout-common.js +349 -0
  57. package/dist/fonts/shaping/plan.d.ts +87 -0
  58. package/dist/fonts/shaping/plan.js +152 -0
  59. package/dist/fonts/shaping/scripts.d.ts +26 -0
  60. package/dist/fonts/shaping/scripts.js +160 -0
  61. package/dist/fonts/shaping/shaper.d.ts +23 -0
  62. package/dist/fonts/shaping/shaper.js +5 -0
  63. package/dist/fonts/shaping/unicode.d.ts +34 -0
  64. package/dist/fonts/shaping/unicode.js +138 -0
  65. package/dist/images/bmp.d.ts +9 -0
  66. package/dist/images/bmp.js +234 -0
  67. package/dist/images/gif.d.ts +9 -0
  68. package/dist/images/gif.js +215 -0
  69. package/dist/images/index.d.ts +18 -0
  70. package/dist/images/index.js +63 -0
  71. package/dist/images/png-encode.d.ts +4 -0
  72. package/dist/images/png-encode.js +73 -0
  73. package/dist/images/size.d.ts +10 -0
  74. package/dist/images/size.js +83 -0
  75. package/dist/images/tiff.d.ts +14 -0
  76. package/dist/images/tiff.js +407 -0
  77. package/dist/index.d.ts +7 -2
  78. package/dist/index.js +5 -0
  79. package/dist/layout/bidi.d.ts +18 -0
  80. package/dist/layout/bidi.js +71 -0
  81. package/dist/layout/blocks.d.ts +20 -3
  82. package/dist/layout/blocks.js +88 -58
  83. package/dist/layout/cache.d.ts +31 -0
  84. package/dist/layout/cache.js +38 -0
  85. package/dist/layout/drawing.d.ts +30 -0
  86. package/dist/layout/drawing.js +120 -0
  87. package/dist/layout/engine.d.ts +3 -0
  88. package/dist/layout/engine.js +218 -11
  89. package/dist/layout/index.d.ts +1 -0
  90. package/dist/layout/index.js +1 -0
  91. package/dist/layout/lines.d.ts +63 -5
  92. package/dist/layout/lines.js +245 -20
  93. package/dist/layout/paint.d.ts +25 -3
  94. package/dist/layout/paint.js +26 -10
  95. package/dist/layout/shapes.d.ts +7 -0
  96. package/dist/layout/shapes.js +338 -0
  97. package/dist/layout/style.d.ts +4 -0
  98. package/dist/layout/style.js +2 -0
  99. package/dist/layout/types.d.ts +89 -2
  100. package/dist/math/boxes.d.ts +88 -0
  101. package/dist/math/boxes.js +166 -0
  102. package/dist/math/index.d.ts +29 -0
  103. package/dist/math/index.js +44 -0
  104. package/dist/math/layout.d.ts +13 -0
  105. package/dist/math/layout.js +771 -0
  106. package/dist/math/linear.d.ts +3 -0
  107. package/dist/math/linear.js +152 -0
  108. package/dist/math/omml.d.ts +15 -0
  109. package/dist/math/omml.js +57 -0
  110. package/dist/math/paths.d.ts +61 -0
  111. package/dist/math/paths.js +450 -0
  112. package/dist/math/symbols.d.ts +49 -0
  113. package/dist/math/symbols.js +269 -0
  114. package/dist/math/text.d.ts +53 -0
  115. package/dist/math/text.js +316 -0
  116. package/dist/metafile/canvas.d.ts +80 -0
  117. package/dist/metafile/canvas.js +515 -0
  118. package/dist/metafile/dib.d.ts +27 -0
  119. package/dist/metafile/dib.js +300 -0
  120. package/dist/metafile/emf.d.ts +31 -0
  121. package/dist/metafile/emf.js +591 -0
  122. package/dist/metafile/geometry.d.ts +49 -0
  123. package/dist/metafile/geometry.js +85 -0
  124. package/dist/metafile/index.d.ts +27 -0
  125. package/dist/metafile/index.js +34 -0
  126. package/dist/metafile/reader.d.ts +28 -0
  127. package/dist/metafile/reader.js +59 -0
  128. package/dist/metafile/state.d.ts +118 -0
  129. package/dist/metafile/state.js +172 -0
  130. package/dist/metafile/text.d.ts +17 -0
  131. package/dist/metafile/text.js +130 -0
  132. package/dist/metafile/wmf.d.ts +33 -0
  133. package/dist/metafile/wmf.js +395 -0
  134. package/dist/model/content.d.ts +92 -7
  135. package/dist/model/content.js +251 -17
  136. package/dist/model/document.d.ts +34 -1
  137. package/dist/model/document.js +80 -1
  138. package/dist/model/fields.d.ts +4 -0
  139. package/dist/model/fields.js +10 -0
  140. package/dist/model/numbering.d.ts +2 -0
  141. package/dist/model/numbering.js +22 -0
  142. package/dist/model/props.d.ts +2 -0
  143. package/dist/model/props.js +3 -0
  144. package/dist/opc/index.d.ts +1 -1
  145. package/dist/opc/package.d.ts +34 -0
  146. package/dist/opc/package.js +58 -4
  147. package/dist/pdf/export.js +97 -6
  148. package/dist/pdf/images.d.ts +7 -0
  149. package/dist/pdf/images.js +39 -2
  150. package/dist/render/activity.d.ts +138 -0
  151. package/dist/render/activity.js +794 -0
  152. package/dist/render/clipboard.d.ts +29 -0
  153. package/dist/render/clipboard.js +401 -0
  154. package/dist/render/comments.d.ts +166 -0
  155. package/dist/render/comments.js +779 -0
  156. package/dist/render/context-menu.d.ts +124 -0
  157. package/dist/render/context-menu.js +525 -0
  158. package/dist/render/editing.d.ts +146 -5
  159. package/dist/render/editing.js +678 -53
  160. package/dist/render/index.d.ts +12 -0
  161. package/dist/render/index.js +11 -0
  162. package/dist/render/navigation-panel.d.ts +76 -0
  163. package/dist/render/navigation-panel.js +431 -0
  164. package/dist/render/selection.js +5 -0
  165. package/dist/render/svg.d.ts +4 -6
  166. package/dist/render/svg.js +69 -7
  167. package/dist/render/toolbar.d.ts +83 -0
  168. package/dist/render/toolbar.js +505 -0
  169. package/dist/render/ui/comment-layout.d.ts +39 -0
  170. package/dist/render/ui/comment-layout.js +79 -0
  171. package/dist/render/ui/icons.d.ts +6 -0
  172. package/dist/render/ui/icons.js +38 -0
  173. package/dist/render/ui/menu.d.ts +38 -0
  174. package/dist/render/ui/menu.js +274 -0
  175. package/dist/render/ui/nav-model.d.ts +11 -0
  176. package/dist/render/ui/nav-model.js +34 -0
  177. package/dist/render/ui/overflow.d.ts +5 -0
  178. package/dist/render/ui/overflow.js +18 -0
  179. package/dist/render/ui/popover.d.ts +18 -0
  180. package/dist/render/ui/popover.js +109 -0
  181. package/dist/render/ui/theme.d.ts +2 -0
  182. package/dist/render/ui/theme.js +29 -0
  183. package/dist/render/undo.d.ts +76 -0
  184. package/dist/render/undo.js +144 -0
  185. package/dist/render/viewer.d.ts +100 -7
  186. package/dist/render/viewer.js +302 -92
  187. package/dist/security/policy.d.ts +3 -0
  188. package/dist/security/policy.js +6 -2
  189. package/dist/security/protection.d.ts +1 -0
  190. package/dist/security/protection.js +1 -1
  191. package/dist/text/bidi-data.d.ts +53 -0
  192. package/dist/text/bidi-data.js +318 -0
  193. package/dist/text/bidi.d.ts +37 -0
  194. package/dist/text/bidi.js +508 -0
  195. package/dist/xml/ns.d.ts +5 -0
  196. package/dist/xml/ns.js +7 -0
  197. package/package.json +9 -2
@@ -5,14 +5,25 @@
5
5
  import { readComments } from '../comments/read.js';
6
6
  import { FontRegistry } from '../fonts/registry.js';
7
7
  import { standaloneFont } from '../fonts/subset.js';
8
+ import { LayoutCache } from '../layout/cache.js';
8
9
  import { layoutDocument } from '../layout/engine.js';
9
10
  import { DocxDocument } from '../model/document.js';
11
+ import { browserShows, decodeRaster, sniffImage } from '../images/index.js';
12
+ import { encodePng } from '../images/png-encode.js';
10
13
  import { extension } from '../opc/paths.js';
11
14
  import { CanvasFontProvider } from './canvas-fonts.js';
12
15
  import { InlineEditing } from './editing.js';
16
+ import { selectionInfoFor } from '../api/selection.js';
17
+ import { paragraphsOf, paragraphText } from '../api/editor.js';
18
+ import { ToolbarController } from './toolbar.js';
19
+ import { NavigationController } from './navigation-panel.js';
20
+ import { ContextMenuController } from './context-menu.js';
21
+ import { CommentsController } from './comments.js';
22
+ import { AiActivity } from './activity.js';
13
23
  import { collectNavTargets, nextTarget } from './navigation.js';
14
24
  import { selectionPositions } from './selection.js';
15
25
  import { pageToSvg } from './svg.js';
26
+ import { ensureUiStyle } from './ui/theme.js';
16
27
  const STYLE_ID = 'docxkeun-viewer-style';
17
28
  const CSS = `
18
29
  .docxkeun-viewer{position:relative;overflow:auto;background:#e8eaed;height:100%;box-sizing:border-box;padding:16px 0}
@@ -26,12 +37,7 @@ const CSS = `
26
37
  .docxkeun-comment-hl.active{background:rgba(251,188,4,.5)}
27
38
  .docxkeun-perm{position:absolute;background:rgba(26,115,232,.12);border-bottom:1px dashed rgba(26,115,232,.7)}
28
39
  .docxkeun-locked{position:absolute;background:repeating-linear-gradient(135deg,rgba(95,99,104,.10) 0 3px,rgba(95,99,104,.03) 3px 7px);box-shadow:inset 0 -1px 0 rgba(95,99,104,.55)}
29
- .docxkeun-gutter{position:relative;width:260px;flex:none}
30
- .docxkeun-card{position:absolute;left:0;right:0;background:#fff;border-radius:8px;padding:8px 10px;font:13px/1.4 system-ui,sans-serif;color:#202124;box-shadow:0 1px 2px rgba(60,64,67,.3);cursor:pointer;box-sizing:border-box}
31
- .docxkeun-card.resolved{opacity:.6}
32
- .docxkeun-card .who{font-weight:600}.docxkeun-card .when{color:#5f6368;font-size:12px;margin-left:6px}
33
- .docxkeun-card .body{white-space:pre-wrap;margin-top:2px;overflow-wrap:anywhere}
34
- .docxkeun-card .reply{border-top:1px solid #e8eaed;margin-top:6px;padding-top:6px}
40
+ .docxkeun-gutter{flex:none;height:1px}
35
41
  .docxkeun-editing .docxkeun-page svg{user-select:none;cursor:text}
36
42
  .docxkeun-editing .docxkeun-link{pointer-events:none}
37
43
  .docxkeun-edit-layer{position:absolute;inset:0;pointer-events:none}
@@ -53,13 +59,31 @@ function ensureStyle() {
53
59
  }
54
60
  const IMAGE_MIME = {
55
61
  png: 'image/png',
56
- jpg: 'image/jpeg',
57
62
  jpeg: 'image/jpeg',
58
63
  gif: 'image/gif',
59
64
  bmp: 'image/bmp',
60
65
  svg: 'image/svg+xml',
61
66
  webp: 'image/webp',
62
67
  };
68
+ /**
69
+ * Media bytes as something an <img> shows: the format is sniffed (extensions lie); TIFF is
70
+ * decoded to PNG, and EMF/WMF are drawn into SVG. Undefined for images that cannot be shown.
71
+ */
72
+ async function browserImage(bytes, ext, _fonts) {
73
+ const kind = sniffImage(bytes);
74
+ if (kind && browserShows(kind))
75
+ return { bytes, mime: IMAGE_MIME[kind] };
76
+ try {
77
+ if (kind === 'tiff')
78
+ return { bytes: encodePng(await decodeRaster(bytes)), mime: 'image/png' };
79
+ }
80
+ catch {
81
+ return undefined;
82
+ }
83
+ // Formats we cannot sniff (WebP): trust the extension.
84
+ const mime = IMAGE_MIME[ext === 'jpg' ? 'jpeg' : ext];
85
+ return mime && !kind ? { bytes, mime } : undefined;
86
+ }
63
87
  /** Allow only links whose scheme is on the allow-list. */
64
88
  export function safeUrl(url, allowed) {
65
89
  if (!url)
@@ -84,13 +108,20 @@ export class DocxViewer {
84
108
  rows = [];
85
109
  mounted = new Set();
86
110
  observer;
87
- comments = new Map();
111
+ commentMap = new Map();
112
+ threadCache;
88
113
  listeners = new Map();
89
114
  unsubscribe;
90
115
  relayoutScheduled = false;
116
+ layoutCache = new LayoutCache();
91
117
  zoomLevel;
92
- activeComment;
118
+ activeComments = new Set();
93
119
  editingLayer;
120
+ toolbarCtl;
121
+ navigationCtl;
122
+ commentsCtl;
123
+ contextMenuCtl;
124
+ containerEl;
94
125
  renderedShape = '';
95
126
  navTargets;
96
127
  navCursor;
@@ -99,6 +130,7 @@ export class DocxViewer {
99
130
  constructor(container, options = {}) {
100
131
  this.options = options;
101
132
  ensureStyle();
133
+ this.containerEl = container;
102
134
  this.zoomLevel = options.zoom ?? 1;
103
135
  this.root = document.createElement('div');
104
136
  this.root.className = 'docxkeun-viewer';
@@ -108,6 +140,171 @@ export class DocxViewer {
108
140
  document.addEventListener('selectionchange', this.onSelectionChange);
109
141
  if (options.editable)
110
142
  this.editingLayer = new InlineEditing(this, options.editable === true ? {} : options.editable);
143
+ const tb = options.toolbar;
144
+ const tbOptions = !tb || tb === true ? {} : 'nodeType' in tb ? { container: tb } : tb;
145
+ this.toolbarCtl = new ToolbarController(this, tbOptions);
146
+ if (tb) {
147
+ if (options.editable)
148
+ this.toolbarCtl.show();
149
+ else
150
+ this.toolbarCtl.deferShow();
151
+ }
152
+ const nav = options.navigation;
153
+ this.navigationCtl = new NavigationController(this, !nav || nav === true ? {} : nav);
154
+ if (nav)
155
+ this.navigationCtl.show();
156
+ this.commentsCtl = new CommentsController(this.commentsHost(), { ...options.comments, visible: options.showComments ?? true });
157
+ const menu = options.contextMenu;
158
+ this.contextMenuCtl = new ContextMenuController(this, !menu || menu === true ? {} : menu);
159
+ if (menu)
160
+ this.contextMenuCtl.enable();
161
+ }
162
+ /** The threads of the document, in order: each root comment with its replies and anchor. */
163
+ commentThreads() {
164
+ if (this.threadCache)
165
+ return this.threadCache;
166
+ const layout = this.layoutResult;
167
+ if (!layout)
168
+ return [];
169
+ const areas = new Map();
170
+ for (const page of layout.pages) {
171
+ for (const a of page.comments)
172
+ if (a.w > 0)
173
+ (areas.get(a.id) ?? areas.set(a.id, []).get(a.id)).push({ page: page.index, rect: a });
174
+ }
175
+ const replies = new Map();
176
+ for (const c of this.commentMap.values())
177
+ if (c.parentId)
178
+ (replies.get(c.parentId) ?? replies.set(c.parentId, []).get(c.parentId)).push(c);
179
+ const threads = [];
180
+ for (const comment of this.commentMap.values()) {
181
+ const anchor = layout.commentAnchors.get(comment.id);
182
+ if (comment.parentId || !anchor)
183
+ continue;
184
+ const others = (areas.get(comment.id) ?? []).filter((a) => a.page === anchor.page && a.rect !== anchor.rect).map((a) => a.rect);
185
+ threads.push({ comment, replies: replies.get(comment.id) ?? [], anchor: { page: anchor.page, y: anchor.rect.y, rects: [anchor.rect, ...others] } });
186
+ }
187
+ threads.sort((a, b) => a.anchor.page - b.anchor.page || a.anchor.y - b.anchor.y);
188
+ return (this.threadCache = threads);
189
+ }
190
+ /** What the comment column needs from this viewer. */
191
+ commentsHost() {
192
+ const guardAllows = (action, detail) => {
193
+ const guard = this.editingLayer?.guard;
194
+ if (!guard)
195
+ return true;
196
+ try {
197
+ guard.assert(action, undefined, detail);
198
+ return true;
199
+ }
200
+ catch {
201
+ return false;
202
+ }
203
+ };
204
+ return {
205
+ root: this.root,
206
+ on: (event, listener) => this.on(event, listener),
207
+ emit: (event, payload) => this.emit(event, payload),
208
+ threads: () => this.commentThreads(),
209
+ anchorOf: (thread) => {
210
+ const page = this.pageElement(thread.anchor.page);
211
+ const rect = thread.anchor.rects[0];
212
+ if (!page || !rect)
213
+ return undefined;
214
+ // The last line of the comment's text on that page (the rects are its highlighted areas there).
215
+ const last = thread.anchor.rects.reduce((m, r) => Math.max(m, r.y + r.h), rect.y + rect.h);
216
+ return { top: page.offsetTop + rect.y * this.scale, pageRight: page.offsetLeft + page.offsetWidth, height: rect.h * this.scale, bottom: page.offsetTop + last * this.scale };
217
+ },
218
+ columnX: () => {
219
+ let right = 0;
220
+ for (const row of this.rows) {
221
+ const page = row.firstElementChild;
222
+ if (page)
223
+ right = Math.max(right, page.offsetLeft + page.offsetWidth);
224
+ }
225
+ return right + 12;
226
+ },
227
+ widestPage: () => ((this.layoutResult?.pages.reduce((m, p) => Math.max(m, p.width), 0) ?? 0) * 96) / 72,
228
+ editable: () => !!this.editingLayer?.isEnabled,
229
+ can: guardAllows,
230
+ author: () => this.editingLayer?.author ?? 'docxkeun',
231
+ transaction: (label, fn) => {
232
+ if (!this.editingLayer)
233
+ return Promise.reject(new Error('Comments can only be changed while the viewer is editable'));
234
+ return this.editingLayer.transaction(label, fn);
235
+ },
236
+ selection: () => {
237
+ const editing = this.editingLayer;
238
+ const sel = editing?.selection;
239
+ const spot = editing?.selectionSpot();
240
+ const page = spot ? this.pageElement(spot.page) : undefined;
241
+ if (!editing || !sel || !spot || !page || (sel.anchor.para === sel.focus.para && sel.anchor.char === sel.focus.char))
242
+ return undefined;
243
+ return { range: editing.rangeOf(sel.anchor, sel.focus), top: page.offsetTop + spot.y * this.scale, pageRight: page.offsetLeft + page.offsetWidth, height: spot.h * this.scale };
244
+ },
245
+ setActive: (ids) => {
246
+ this.activeComments = new Set(ids);
247
+ for (const hl of this.root.querySelectorAll('.docxkeun-comment-hl'))
248
+ hl.classList.toggle('active', this.activeComments.has(hl.dataset.comment ?? ''));
249
+ },
250
+ rebuild: () => this.buildRows(),
251
+ currentDocument: () => this.doc,
252
+ };
253
+ }
254
+ frameParts;
255
+ /**
256
+ * The frame around the viewer, created on first call: `container > .docxkeun-frame >
257
+ * [.docxkeun-toolbar-slot, .docxkeun-body > root]`. Only chrome parts call it; without them
258
+ * the root stays a direct child of the container.
259
+ * @internal
260
+ */
261
+ frame() {
262
+ if (this.frameParts)
263
+ return this.frameParts;
264
+ ensureUiStyle();
265
+ const frame = document.createElement('div');
266
+ frame.className = 'docxkeun-frame';
267
+ const toolbarSlot = document.createElement('div');
268
+ toolbarSlot.className = 'docxkeun-toolbar-slot';
269
+ const body = document.createElement('div');
270
+ body.className = 'docxkeun-body';
271
+ frame.append(toolbarSlot, body);
272
+ this.root.replaceWith(frame);
273
+ body.appendChild(this.root);
274
+ return (this.frameParts = { frame, toolbarSlot, body });
275
+ }
276
+ activityLayer;
277
+ /**
278
+ * An AI assistant's presence on the pages: `work([4, 5])` shimmers the paragraphs it is
279
+ * changing (with its caret), `reveal(before)` animates what changed. Created on first use.
280
+ */
281
+ get activity() {
282
+ const o = this.options.aiActivity;
283
+ return (this.activityLayer ??= new AiActivity(this, o === false ? { enabled: false } : (o ?? {})));
284
+ }
285
+ /** The formatting toolbar: `show()`, `hide()`, `collapsed`. Shown when the `toolbar` option is set. */
286
+ get toolbar() {
287
+ return this.toolbarCtl;
288
+ }
289
+ /** The comment column: `show()`, `hide()`, `mode`, `open(id)`, `compose()`, `width`. */
290
+ get comments() {
291
+ return this.commentsCtl;
292
+ }
293
+ /** The right-click menu: `enable()`, `disable()`, `open(x, y)`, `close()`. Enabled by the `contextMenu` option. */
294
+ get contextMenu() {
295
+ return this.contextMenuCtl;
296
+ }
297
+ /** The element the viewer was created in (where chrome such as the menu is placed). @internal */
298
+ get container() {
299
+ return this.containerEl;
300
+ }
301
+ /** A picture as a blob a browser shows (for copying it). Undefined for external or unreadable images. @internal */
302
+ async imageBlob(image) {
303
+ const doc = this.doc;
304
+ if (!doc || !image.target || image.external)
305
+ return undefined;
306
+ const shown = await browserImage(await doc.media(image.target), extension(image.target), this.fonts).catch(() => undefined);
307
+ return shown ? new Blob([shown.bytes], { type: shown.mime }) : undefined;
111
308
  }
112
309
  /** In-page editing (present when the viewer was created with `editable`). */
113
310
  get editing() {
@@ -118,6 +315,7 @@ export class DocxViewer {
118
315
  if (on && !this.editingLayer)
119
316
  this.editingLayer = new InlineEditing(this, options);
120
317
  this.editingLayer?.setEnabled(on);
318
+ this.toolbarCtl.setEditable(on);
121
319
  }
122
320
  get document() {
123
321
  return this.doc;
@@ -141,6 +339,7 @@ export class DocxViewer {
141
339
  const doc = input instanceof DocxDocument ? input : await DocxDocument.open(input, openOptions);
142
340
  this.unsubscribe?.();
143
341
  this.doc = doc;
342
+ this.layoutCache = new LayoutCache();
144
343
  this.unsubscribe = doc.onChange(() => this.scheduleRelayout());
145
344
  for (const url of this.imageUrls.values())
146
345
  if (url)
@@ -175,9 +374,11 @@ export class DocxViewer {
175
374
  relayout() {
176
375
  if (!this.doc || !this.fonts)
177
376
  return;
178
- this.layoutResult = layoutDocument(this.doc, { fonts: this.fonts });
377
+ this.layoutResult = layoutDocument(this.doc, { fonts: this.fonts, cache: this.layoutCache });
179
378
  this.navTargets = undefined;
180
- this.comments = new Map(readComments(this.doc).map((c) => [c.id, c]));
379
+ this.commentMap = new Map(readComments(this.doc).map((c) => [c.id, c]));
380
+ this.threadCache = undefined;
381
+ this.commentsCtl.sync();
181
382
  // Same pages and sizes (the usual case while typing): redraw the mounted pages in place.
182
383
  const shape = this.shapeKey();
183
384
  if (shape === this.renderedShape && this.rows.length) {
@@ -189,8 +390,7 @@ export class DocxViewer {
189
390
  this.emit('layout', { pages: this.layoutResult.pages });
190
391
  }
191
392
  shapeKey() {
192
- const showComments = (this.options.showComments ?? true) && this.comments.size > 0;
193
- return `${this.scale}|${showComments}|` + (this.layoutResult?.pages.map((p) => `${p.width}x${p.height}`).join(',') ?? '');
393
+ return `${this.scale}|${this.commentsCtl.width}|` + (this.layoutResult?.pages.map((p) => `${p.width}x${p.height}`).join(',') ?? '');
194
394
  }
195
395
  scheduleRelayout() {
196
396
  if (this.relayoutScheduled)
@@ -207,6 +407,7 @@ export class DocxViewer {
207
407
  set zoom(value) {
208
408
  this.zoomLevel = Math.min(5, Math.max(0.25, value));
209
409
  this.buildRows();
410
+ this.commentsCtl.refresh();
210
411
  }
211
412
  /** CSS pixels per point at the current zoom. */
212
413
  get scale() {
@@ -230,7 +431,7 @@ export class DocxViewer {
230
431
  this.rows.length = 0;
231
432
  this.renderedShape = this.shapeKey();
232
433
  this.mounted.clear();
233
- const showComments = (this.options.showComments ?? true) && this.comments.size > 0;
434
+ const gutterWidth = Math.max(0, this.commentsCtl.width - 12);
234
435
  this.observer = new IntersectionObserver((entries) => this.onIntersect(entries), { root: this.root, rootMargin: '600px 0px' });
235
436
  result.pages.forEach((page, i) => {
236
437
  const row = document.createElement('div');
@@ -242,10 +443,10 @@ export class DocxViewer {
242
443
  pageEl.style.height = `${page.height * this.scale}px`;
243
444
  pageEl.setAttribute('aria-label', `Page ${i + 1}`);
244
445
  row.appendChild(pageEl);
245
- if (showComments) {
446
+ if (gutterWidth) {
246
447
  const gutter = document.createElement('div');
247
448
  gutter.className = 'docxkeun-gutter';
248
- gutter.style.height = pageEl.style.height;
449
+ gutter.style.width = `${gutterWidth}px`;
249
450
  row.appendChild(gutter);
250
451
  }
251
452
  this.pagesEl.appendChild(row);
@@ -253,6 +454,7 @@ export class DocxViewer {
253
454
  this.observer.observe(row);
254
455
  });
255
456
  this.root.scrollTop = scrollRatio * this.root.scrollHeight;
457
+ this.commentsCtl.rowsBuilt();
256
458
  }
257
459
  onIntersect(entries) {
258
460
  for (const entry of entries) {
@@ -273,9 +475,6 @@ export class DocxViewer {
273
475
  const missing = this.missingImages(page);
274
476
  pageEl.innerHTML = pageToSvg(page, { fontFamily: this.fontFamily, imageUrl: (t, ext) => this.imageUrl(t, ext) });
275
477
  pageEl.appendChild(this.overlay(page));
276
- const gutter = row.children[1];
277
- if (gutter)
278
- this.renderComments(page, gutter);
279
478
  this.emit('pagemount', { index: i, element: pageEl, page });
280
479
  if (missing.length) {
281
480
  void this.loadImages(missing).then(() => {
@@ -289,7 +488,7 @@ export class DocxViewer {
289
488
  missingImages(page) {
290
489
  const out = [];
291
490
  for (const item of page.items)
292
- if (item.type === 'image' && item.target && !item.external && !this.imageUrls.has(item.target))
491
+ if (item.type === 'image' && !item.frameOnly && item.target && !item.external && !this.imageUrls.has(item.target))
293
492
  out.push(item.target);
294
493
  return out;
295
494
  }
@@ -307,13 +506,12 @@ export class DocxViewer {
307
506
  await Promise.all(targets.map(async (target) => {
308
507
  if (this.imageUrls.has(target))
309
508
  return;
310
- const mime = IMAGE_MIME[extension(target)];
311
- if (!mime || !doc.pkg.has(target)) {
509
+ if (!doc.pkg.has(target)) {
312
510
  this.imageUrls.set(target, null);
313
511
  return;
314
512
  }
315
- const bytes = await doc.media(target);
316
- this.imageUrls.set(target, URL.createObjectURL(new Blob([bytes], { type: mime })));
513
+ const shown = await browserImage(await doc.media(target), extension(target), this.fonts);
514
+ this.imageUrls.set(target, shown ? URL.createObjectURL(new Blob([shown.bytes], { type: shown.mime })) : null);
317
515
  }));
318
516
  }
319
517
  overlay(page) {
@@ -344,10 +542,10 @@ export class DocxViewer {
344
542
  layer.appendChild(el);
345
543
  }
346
544
  for (const c of page.comments) {
347
- if (c.w <= 0 || !this.comments.has(c.id))
545
+ if (c.w <= 0 || !this.commentMap.has(c.id))
348
546
  continue;
349
547
  const el = document.createElement('div');
350
- el.className = 'docxkeun-comment-hl' + (this.activeComment === c.id ? ' active' : '');
548
+ el.className = 'docxkeun-comment-hl' + (this.activeComments.has(c.id) ? ' active' : '');
351
549
  el.dataset.comment = c.id;
352
550
  place(el, c);
353
551
  layer.appendChild(el);
@@ -390,72 +588,12 @@ export class DocxViewer {
390
588
  if (url)
391
589
  window.open(url, '_blank', 'noopener,noreferrer');
392
590
  else if (target.anchor) {
393
- const bookmark = this.navigation.bookmarks.find((b) => b.name === target.anchor);
591
+ const bookmark = this.collectedTargets().bookmarks.find((b) => b.name === target.anchor);
394
592
  // Remember where the link was, so back() returns to it.
395
593
  if (bookmark)
396
594
  this.goTo(bookmark, { history: true });
397
595
  }
398
596
  }
399
- renderComments(page, gutter) {
400
- gutter.replaceChildren();
401
- const s = this.scale;
402
- const roots = [];
403
- const seen = new Set();
404
- for (const area of page.comments) {
405
- const comment = this.comments.get(area.id);
406
- if (!comment || comment.parentId || seen.has(area.id))
407
- continue;
408
- const first = this.layoutResult?.commentAnchors.get(area.id);
409
- if (first && first.page !== page.index)
410
- continue;
411
- seen.add(area.id);
412
- roots.push({ comment, y: area.y });
413
- }
414
- roots.sort((a, b) => a.y - b.y);
415
- let nextFree = 0;
416
- for (const { comment, y } of roots) {
417
- const card = document.createElement('div');
418
- card.className = 'docxkeun-card' + (comment.resolved ? ' resolved' : '');
419
- card.dataset.comment = comment.id;
420
- card.appendChild(this.commentBody(comment));
421
- for (const reply of [...this.comments.values()].filter((c) => c.parentId === comment.id)) {
422
- const r = this.commentBody(reply);
423
- r.className = 'reply';
424
- card.appendChild(r);
425
- }
426
- const top = Math.max(y * s, nextFree);
427
- card.style.top = `${top}px`;
428
- card.addEventListener('click', () => {
429
- this.activeComment = comment.id;
430
- this.emit('commentclick', { comment });
431
- for (const el of this.root.querySelectorAll('.docxkeun-comment-hl'))
432
- el.classList.toggle('active', el.dataset.comment === comment.id);
433
- });
434
- gutter.appendChild(card);
435
- nextFree = top + card.offsetHeight + 8;
436
- }
437
- }
438
- commentBody(c) {
439
- const wrap = document.createElement('div');
440
- const head = document.createElement('div');
441
- const who = document.createElement('span');
442
- who.className = 'who';
443
- who.textContent = c.author || 'Unknown';
444
- head.appendChild(who);
445
- const date = c.dateUtc ?? c.date;
446
- if (date) {
447
- const when = document.createElement('span');
448
- when.className = 'when';
449
- const d = new Date(date);
450
- when.textContent = Number.isNaN(d.getTime()) ? date : d.toLocaleString();
451
- head.appendChild(when);
452
- }
453
- const body = document.createElement('div');
454
- body.className = 'body';
455
- body.textContent = c.text;
456
- wrap.append(head, body);
457
- return wrap;
458
- }
459
597
  scrollToPage(index, y = 0) {
460
598
  const row = this.rows[index];
461
599
  if (!row)
@@ -464,15 +602,23 @@ export class DocxViewer {
464
602
  }
465
603
  /** Scroll to a bookmark. Returns false when the bookmark does not exist. */
466
604
  scrollToAnchor(name) {
467
- const bookmark = this.navigation.bookmarks.find((b) => b.name === name);
605
+ const bookmark = this.collectedTargets().bookmarks.find((b) => b.name === name);
468
606
  if (!bookmark)
469
607
  return false;
470
608
  this.goTo(bookmark, { flash: false });
471
609
  return true;
472
610
  }
473
611
  // ---- navigation -----------------------------------------------------------------------------
474
- /** Headings, bookmarks and hyperlinks of the current layout, each in document order. */
612
+ /**
613
+ * The navigation panel: `show()`, `hide()`, `collapsed`, `tab`. It also lists the headings,
614
+ * bookmarks and hyperlinks of the current layout (`headings`, `bookmarks`, `links`), each in
615
+ * document order.
616
+ */
475
617
  get navigation() {
618
+ return this.navigationCtl;
619
+ }
620
+ /** The navigation targets of the current layout, collected once per layout. @internal */
621
+ collectedTargets() {
476
622
  if (!this.navTargets)
477
623
  this.navTargets = this.layoutResult ? collectNavTargets(this.layoutResult) : { headings: [], bookmarks: [], links: [] };
478
624
  return this.navTargets;
@@ -503,7 +649,7 @@ export class DocxViewer {
503
649
  this.scrollToPage(target.page, Math.max(0, target.y - 24));
504
650
  const nav = 'kind' in target ? target : undefined;
505
651
  if (nav) {
506
- const list = this.navigation[`${nav.kind}s`];
652
+ const list = this.collectedTargets()[`${nav.kind}s`];
507
653
  this.navCursor = { kind: nav.kind, index: list.indexOf(nav), scrollTop: this.root.scrollTop };
508
654
  if (options.flash ?? true)
509
655
  this.flash(nav);
@@ -519,7 +665,7 @@ export class DocxViewer {
519
665
  return this.step(kind, -1, options.includeHidden ?? false);
520
666
  }
521
667
  step(kind, dir, includeHidden) {
522
- const all = this.navigation[`${kind}s`];
668
+ const all = this.collectedTargets()[`${kind}s`];
523
669
  const list = includeHidden ? all : all.filter((t) => !t.hidden);
524
670
  let target;
525
671
  const cursor = this.navCursor;
@@ -587,6 +733,7 @@ export class DocxViewer {
587
733
  if (!anchor)
588
734
  return false;
589
735
  this.scrollToPage(anchor.page, anchor.rect.y);
736
+ this.commentsCtl.open(id);
590
737
  return true;
591
738
  }
592
739
  /** The current text selection as document positions. */
@@ -600,11 +747,74 @@ export class DocxViewer {
600
747
  return selectionPositions(sel, pages);
601
748
  }
602
749
  onSelectionChange = () => {
750
+ this.selectionMoved();
603
751
  if (!this.listeners.get('selectionchange')?.size)
604
752
  return;
605
753
  this.emit('selectionchange', this.getSelection());
606
754
  };
755
+ selectionTimer;
756
+ lastSelectionKey = '';
757
+ /** @internal The caret or the selection moved: tell `selectioninfo` listeners (batched, when it changed). */
758
+ selectionMoved() {
759
+ if (!this.listeners.get('selectioninfo')?.size || this.selectionTimer)
760
+ return;
761
+ // A timer rather than an animation frame: pages in background tabs still report selections.
762
+ this.selectionTimer = setTimeout(() => {
763
+ this.selectionTimer = undefined;
764
+ const selection = this.selectionInfo();
765
+ const key = selection ? `${selection.story}|${selection.part ?? ''}|${selection.start.paragraph}:${selection.start.offset}|${selection.end.paragraph}:${selection.end.offset}|${selection.text.length}` : '';
766
+ if (key === this.lastSelectionKey)
767
+ return;
768
+ this.lastSelectionKey = key;
769
+ this.emit('selectioninfo', { selection });
770
+ }, 16);
771
+ }
772
+ /**
773
+ * What the user has selected, or where the caret is: paragraph numbers (as docxkeun-mcp's
774
+ * read_document numbers them), offsets, pages and text. The editing caret when typing is on,
775
+ * otherwise the browser's text selection on the pages. `describeSelection` turns it into a prompt.
776
+ */
777
+ selectionInfo() {
778
+ const doc = this.doc;
779
+ if (!doc)
780
+ return undefined;
781
+ const typed = this.editingLayer?.isEnabled ? this.editingLayer.selectionInfo() : undefined;
782
+ if (typed)
783
+ return typed;
784
+ const sel = this.getSelection();
785
+ if (!sel)
786
+ return undefined;
787
+ const layout = this.layoutResult;
788
+ // The paragraphs of each story, looked up by the text nodes the selection points at.
789
+ const stories = [{ story: 'body', paras: paragraphsOf(doc.body().blocks) }];
790
+ for (const sp of doc.storyParts()) {
791
+ if (sp.kind === 'header' || sp.kind === 'footer')
792
+ stories.push({ story: sp.kind, part: sp.part, paras: paragraphsOf(doc.headerFooter(sp.part).blocks) });
793
+ }
794
+ const locate = (pos) => {
795
+ for (const s of stories) {
796
+ for (let i = 0; i < s.paras.length; i++) {
797
+ for (const seg of paragraphText(s.paras[i], { objects: true }).segments) {
798
+ if (seg.node !== pos.inline.node)
799
+ continue;
800
+ return { s, caret: { para: i, char: seg.start + (seg.node.name === 'w:t' ? pos.offset : pos.offset > 0 ? 1 : 0) } };
801
+ }
802
+ }
803
+ }
804
+ return undefined;
805
+ };
806
+ const a = locate(sel.start);
807
+ const b = locate(sel.end);
808
+ if (!a || !b || a.s !== b.s)
809
+ return undefined;
810
+ return selectionInfoFor(doc, a.s.paras, a.caret, b.caret, { story: a.s.story, ...(a.s.part ? { part: a.s.part } : {}), ...(layout ? { layout } : {}) });
811
+ }
607
812
  destroy() {
813
+ this.activityLayer?.destroy();
814
+ this.contextMenuCtl.destroy();
815
+ this.toolbarCtl.destroy();
816
+ this.navigationCtl.destroy();
817
+ this.commentsCtl.destroy();
608
818
  this.editingLayer?.destroy();
609
819
  this.observer?.disconnect();
610
820
  this.unsubscribe?.();
@@ -612,6 +822,6 @@ export class DocxViewer {
612
822
  for (const url of this.imageUrls.values())
613
823
  if (url)
614
824
  URL.revokeObjectURL(url);
615
- this.root.remove();
825
+ this.frameParts ? this.frameParts.frame.remove() : this.root.remove();
616
826
  }
617
827
  }
@@ -40,12 +40,15 @@ export declare class AccessPolicy implements EditGuard {
40
40
  /** The reason an action is refused, or undefined when it is allowed. */
41
41
  denial(action: Capability, range?: DocRange, detail?: {
42
42
  commentAuthor?: string;
43
+ tracked?: boolean;
43
44
  }): string | undefined;
44
45
  can(action: Capability, range?: DocRange, detail?: {
45
46
  commentAuthor?: string;
47
+ tracked?: boolean;
46
48
  }): boolean;
47
49
  assert(action: Capability, range?: DocRange, detail?: {
48
50
  commentAuthor?: string;
51
+ tracked?: boolean;
49
52
  }): void;
50
53
  private isCurrentUser;
51
54
  private matchesGroup;
@@ -10,7 +10,7 @@ export class PermissionError extends Error {
10
10
  }
11
11
  }
12
12
  const COMMENT_ACTIONS = ['comment', 'reply', 'resolveComment', 'editComment', 'deleteComment'];
13
- const CONTENT_ACTIONS = ['edit', 'format', 'link', 'bookmark', 'fillForm'];
13
+ const CONTENT_ACTIONS = ['edit', 'format', 'link', 'bookmark', 'fillForm', 'review'];
14
14
  export class AccessPolicy {
15
15
  doc;
16
16
  options;
@@ -63,7 +63,11 @@ export class AccessPolicy {
63
63
  case 'trackedChanges':
64
64
  if (isCommentAction)
65
65
  return undefined;
66
- return 'The document requires tracked changes, which docxkeun does not record yet';
66
+ if (action === 'review')
67
+ return 'Tracked changes cannot be accepted or rejected while the document is protected for tracked changes';
68
+ if (detail.tracked)
69
+ return undefined;
70
+ return 'The document only allows changes that are tracked';
67
71
  case 'forms':
68
72
  if (action === 'fillForm')
69
73
  return undefined;
@@ -25,6 +25,7 @@ export declare function passwordAttributes(password: string, options?: {
25
25
  algorithm?: HashName;
26
26
  spinCount?: number;
27
27
  }): Record<string, string>;
28
+ export declare const SETTINGS_ORDER: string[];
28
29
  export declare function readProtection(doc: DocxDocument): ProtectionInfo;
29
30
  /** Turn protection on (or change it). A password is optional, as in Word. */
30
31
  export declare function setProtection(doc: DocxDocument, mode: ProtectionMode, options?: {
@@ -138,7 +138,7 @@ export function passwordAttributes(password, options = {}) {
138
138
  'w:salt': base64Encode(salt),
139
139
  };
140
140
  }
141
- const SETTINGS_ORDER = [
141
+ export const SETTINGS_ORDER = [
142
142
  'w:writeProtection',
143
143
  'w:view',
144
144
  'w:zoom',