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
@@ -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,9 @@ export class DocxViewer {
253
454
  this.observer.observe(row);
254
455
  });
255
456
  this.root.scrollTop = scrollRatio * this.root.scrollHeight;
457
+ this.commentsCtl.rowsBuilt();
458
+ // The AI's marks and effects sit at page positions: follow the new rows (zoom, column width).
459
+ this.activityLayer?.rowsBuilt();
256
460
  }
257
461
  onIntersect(entries) {
258
462
  for (const entry of entries) {
@@ -273,9 +477,6 @@ export class DocxViewer {
273
477
  const missing = this.missingImages(page);
274
478
  pageEl.innerHTML = pageToSvg(page, { fontFamily: this.fontFamily, imageUrl: (t, ext) => this.imageUrl(t, ext) });
275
479
  pageEl.appendChild(this.overlay(page));
276
- const gutter = row.children[1];
277
- if (gutter)
278
- this.renderComments(page, gutter);
279
480
  this.emit('pagemount', { index: i, element: pageEl, page });
280
481
  if (missing.length) {
281
482
  void this.loadImages(missing).then(() => {
@@ -289,7 +490,7 @@ export class DocxViewer {
289
490
  missingImages(page) {
290
491
  const out = [];
291
492
  for (const item of page.items)
292
- if (item.type === 'image' && item.target && !item.external && !this.imageUrls.has(item.target))
493
+ if (item.type === 'image' && !item.frameOnly && item.target && !item.external && !this.imageUrls.has(item.target))
293
494
  out.push(item.target);
294
495
  return out;
295
496
  }
@@ -307,13 +508,12 @@ export class DocxViewer {
307
508
  await Promise.all(targets.map(async (target) => {
308
509
  if (this.imageUrls.has(target))
309
510
  return;
310
- const mime = IMAGE_MIME[extension(target)];
311
- if (!mime || !doc.pkg.has(target)) {
511
+ if (!doc.pkg.has(target)) {
312
512
  this.imageUrls.set(target, null);
313
513
  return;
314
514
  }
315
- const bytes = await doc.media(target);
316
- this.imageUrls.set(target, URL.createObjectURL(new Blob([bytes], { type: mime })));
515
+ const shown = await browserImage(await doc.media(target), extension(target), this.fonts);
516
+ this.imageUrls.set(target, shown ? URL.createObjectURL(new Blob([shown.bytes], { type: shown.mime })) : null);
317
517
  }));
318
518
  }
319
519
  overlay(page) {
@@ -344,10 +544,10 @@ export class DocxViewer {
344
544
  layer.appendChild(el);
345
545
  }
346
546
  for (const c of page.comments) {
347
- if (c.w <= 0 || !this.comments.has(c.id))
547
+ if (c.w <= 0 || !this.commentMap.has(c.id))
348
548
  continue;
349
549
  const el = document.createElement('div');
350
- el.className = 'docxkeun-comment-hl' + (this.activeComment === c.id ? ' active' : '');
550
+ el.className = 'docxkeun-comment-hl' + (this.activeComments.has(c.id) ? ' active' : '');
351
551
  el.dataset.comment = c.id;
352
552
  place(el, c);
353
553
  layer.appendChild(el);
@@ -390,72 +590,12 @@ export class DocxViewer {
390
590
  if (url)
391
591
  window.open(url, '_blank', 'noopener,noreferrer');
392
592
  else if (target.anchor) {
393
- const bookmark = this.navigation.bookmarks.find((b) => b.name === target.anchor);
593
+ const bookmark = this.collectedTargets().bookmarks.find((b) => b.name === target.anchor);
394
594
  // Remember where the link was, so back() returns to it.
395
595
  if (bookmark)
396
596
  this.goTo(bookmark, { history: true });
397
597
  }
398
598
  }
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
599
  scrollToPage(index, y = 0) {
460
600
  const row = this.rows[index];
461
601
  if (!row)
@@ -464,15 +604,23 @@ export class DocxViewer {
464
604
  }
465
605
  /** Scroll to a bookmark. Returns false when the bookmark does not exist. */
466
606
  scrollToAnchor(name) {
467
- const bookmark = this.navigation.bookmarks.find((b) => b.name === name);
607
+ const bookmark = this.collectedTargets().bookmarks.find((b) => b.name === name);
468
608
  if (!bookmark)
469
609
  return false;
470
610
  this.goTo(bookmark, { flash: false });
471
611
  return true;
472
612
  }
473
613
  // ---- navigation -----------------------------------------------------------------------------
474
- /** Headings, bookmarks and hyperlinks of the current layout, each in document order. */
614
+ /**
615
+ * The navigation panel: `show()`, `hide()`, `collapsed`, `tab`. It also lists the headings,
616
+ * bookmarks and hyperlinks of the current layout (`headings`, `bookmarks`, `links`), each in
617
+ * document order.
618
+ */
475
619
  get navigation() {
620
+ return this.navigationCtl;
621
+ }
622
+ /** The navigation targets of the current layout, collected once per layout. @internal */
623
+ collectedTargets() {
476
624
  if (!this.navTargets)
477
625
  this.navTargets = this.layoutResult ? collectNavTargets(this.layoutResult) : { headings: [], bookmarks: [], links: [] };
478
626
  return this.navTargets;
@@ -503,7 +651,7 @@ export class DocxViewer {
503
651
  this.scrollToPage(target.page, Math.max(0, target.y - 24));
504
652
  const nav = 'kind' in target ? target : undefined;
505
653
  if (nav) {
506
- const list = this.navigation[`${nav.kind}s`];
654
+ const list = this.collectedTargets()[`${nav.kind}s`];
507
655
  this.navCursor = { kind: nav.kind, index: list.indexOf(nav), scrollTop: this.root.scrollTop };
508
656
  if (options.flash ?? true)
509
657
  this.flash(nav);
@@ -519,7 +667,7 @@ export class DocxViewer {
519
667
  return this.step(kind, -1, options.includeHidden ?? false);
520
668
  }
521
669
  step(kind, dir, includeHidden) {
522
- const all = this.navigation[`${kind}s`];
670
+ const all = this.collectedTargets()[`${kind}s`];
523
671
  const list = includeHidden ? all : all.filter((t) => !t.hidden);
524
672
  let target;
525
673
  const cursor = this.navCursor;
@@ -587,6 +735,7 @@ export class DocxViewer {
587
735
  if (!anchor)
588
736
  return false;
589
737
  this.scrollToPage(anchor.page, anchor.rect.y);
738
+ this.commentsCtl.open(id);
590
739
  return true;
591
740
  }
592
741
  /** The current text selection as document positions. */
@@ -600,11 +749,74 @@ export class DocxViewer {
600
749
  return selectionPositions(sel, pages);
601
750
  }
602
751
  onSelectionChange = () => {
752
+ this.selectionMoved();
603
753
  if (!this.listeners.get('selectionchange')?.size)
604
754
  return;
605
755
  this.emit('selectionchange', this.getSelection());
606
756
  };
757
+ selectionTimer;
758
+ lastSelectionKey = '';
759
+ /** @internal The caret or the selection moved: tell `selectioninfo` listeners (batched, when it changed). */
760
+ selectionMoved() {
761
+ if (!this.listeners.get('selectioninfo')?.size || this.selectionTimer)
762
+ return;
763
+ // A timer rather than an animation frame: pages in background tabs still report selections.
764
+ this.selectionTimer = setTimeout(() => {
765
+ this.selectionTimer = undefined;
766
+ const selection = this.selectionInfo();
767
+ const key = selection ? `${selection.story}|${selection.part ?? ''}|${selection.start.paragraph}:${selection.start.offset}|${selection.end.paragraph}:${selection.end.offset}|${selection.text.length}` : '';
768
+ if (key === this.lastSelectionKey)
769
+ return;
770
+ this.lastSelectionKey = key;
771
+ this.emit('selectioninfo', { selection });
772
+ }, 16);
773
+ }
774
+ /**
775
+ * What the user has selected, or where the caret is: paragraph numbers (as docxkeun-mcp's
776
+ * read_document numbers them), offsets, pages and text. The editing caret when typing is on,
777
+ * otherwise the browser's text selection on the pages. `describeSelection` turns it into a prompt.
778
+ */
779
+ selectionInfo() {
780
+ const doc = this.doc;
781
+ if (!doc)
782
+ return undefined;
783
+ const typed = this.editingLayer?.isEnabled ? this.editingLayer.selectionInfo() : undefined;
784
+ if (typed)
785
+ return typed;
786
+ const sel = this.getSelection();
787
+ if (!sel)
788
+ return undefined;
789
+ const layout = this.layoutResult;
790
+ // The paragraphs of each story, looked up by the text nodes the selection points at.
791
+ const stories = [{ story: 'body', paras: paragraphsOf(doc.body().blocks) }];
792
+ for (const sp of doc.storyParts()) {
793
+ if (sp.kind === 'header' || sp.kind === 'footer')
794
+ stories.push({ story: sp.kind, part: sp.part, paras: paragraphsOf(doc.headerFooter(sp.part).blocks) });
795
+ }
796
+ const locate = (pos) => {
797
+ for (const s of stories) {
798
+ for (let i = 0; i < s.paras.length; i++) {
799
+ for (const seg of paragraphText(s.paras[i], { objects: true }).segments) {
800
+ if (seg.node !== pos.inline.node)
801
+ continue;
802
+ return { s, caret: { para: i, char: seg.start + (seg.node.name === 'w:t' ? pos.offset : pos.offset > 0 ? 1 : 0) } };
803
+ }
804
+ }
805
+ }
806
+ return undefined;
807
+ };
808
+ const a = locate(sel.start);
809
+ const b = locate(sel.end);
810
+ if (!a || !b || a.s !== b.s)
811
+ return undefined;
812
+ return selectionInfoFor(doc, a.s.paras, a.caret, b.caret, { story: a.s.story, ...(a.s.part ? { part: a.s.part } : {}), ...(layout ? { layout } : {}) });
813
+ }
607
814
  destroy() {
815
+ this.activityLayer?.destroy();
816
+ this.contextMenuCtl.destroy();
817
+ this.toolbarCtl.destroy();
818
+ this.navigationCtl.destroy();
819
+ this.commentsCtl.destroy();
608
820
  this.editingLayer?.destroy();
609
821
  this.observer?.disconnect();
610
822
  this.unsubscribe?.();
@@ -612,6 +824,6 @@ export class DocxViewer {
612
824
  for (const url of this.imageUrls.values())
613
825
  if (url)
614
826
  URL.revokeObjectURL(url);
615
- this.root.remove();
827
+ this.frameParts ? this.frameParts.frame.remove() : this.root.remove();
616
828
  }
617
829
  }
@@ -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',