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
@@ -6,16 +6,59 @@
6
6
  * Positions are kept as (paragraph index, character offset) so they survive re-layout and
7
7
  * the run splitting that edits cause.
8
8
  */
9
- import { DocxEditor, paragraphsOf, paragraphText, positionAt } from '../api/editor.js';
10
- import { cloneElement } from '../xml/index.js';
9
+ import { DocxEditor, OBJECT_CHAR, paragraphsOf, paragraphText as plainText, positionAt } from '../api/editor.js';
10
+ import { htmlToParagraphs, paragraphsToHtml } from './clipboard.js';
11
+ import { selectionInfoFor } from '../api/selection.js';
12
+ import { cloneElement, elements, findAll } from '../xml/index.js';
13
+ import { UndoHistory } from './undo.js';
14
+ function sameStory(a, b) {
15
+ if (a.kind !== b.kind)
16
+ return false;
17
+ if (a.kind === 'textbox')
18
+ return a.container === b.container;
19
+ if (a.kind === 'footnote' || a.kind === 'endnote')
20
+ return a.part === b.part && a.noteId === b.noteId;
21
+ if (a.kind === 'header' || a.kind === 'footer')
22
+ return a.part === b.part;
23
+ return true;
24
+ }
25
+ /** Which w:txbxContent of `root` a text-box story is (undefined for other stories or if it is gone). */
26
+ function textboxIndex(root, story) {
27
+ if (story.kind !== 'textbox')
28
+ return undefined;
29
+ const i = findAll(root, 'w:txbxContent').indexOf(story.container);
30
+ return i < 0 ? undefined : i;
31
+ }
32
+ /** The story again after the XML trees were replaced: a text box by its index, else the body. */
33
+ function resolveStory(root, story, index) {
34
+ if (story.kind !== 'textbox')
35
+ return story;
36
+ const container = index === undefined ? undefined : findAll(root, 'w:txbxContent')[index];
37
+ return container ? { kind: 'textbox', container } : { kind: 'body' };
38
+ }
39
+ function storyOfLine(line) {
40
+ switch (line.story) {
41
+ case 'header':
42
+ case 'footer':
43
+ return line.part ? { kind: line.story, part: line.part } : undefined;
44
+ case 'footnote':
45
+ case 'endnote':
46
+ return line.part && line.noteId ? { kind: line.story, part: line.part, noteId: line.noteId } : undefined;
47
+ case 'textbox':
48
+ return line.container ? { kind: 'textbox', container: line.container } : undefined;
49
+ }
50
+ }
51
+ const within = (l, x, y, slack = 2) => x >= l.x - slack && x <= l.x + l.w + slack && y >= l.y - slack && y <= l.y + l.h + slack;
52
+ /** Inline pictures and shapes count as one character (U+FFFC) for the caret. */
53
+ const paragraphText = (p) => plainText(p, { objects: true });
11
54
  const isMac = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/.test(navigator.platform);
12
55
  function compare(a, b) {
13
56
  return a.para - b.para || a.char - b.char;
14
57
  }
15
58
  export class InlineEditing {
16
59
  viewer;
17
- options;
18
60
  enabled = true;
61
+ storyValue = { kind: 'body' };
19
62
  anchor = { para: 0, char: 0 };
20
63
  focusPos = { para: 0, char: 0 };
21
64
  hasCaret = false;
@@ -23,17 +66,21 @@ export class InlineEditing {
23
66
  composing = false;
24
67
  dragging = false;
25
68
  goalX;
26
- undoStack = [];
27
- redoStack = [];
69
+ history = new UndoHistory();
70
+ historyDoc;
28
71
  lastEdit = { kind: '', at: 0 };
72
+ /** Formatting chosen with no selection: applied to the next text typed. */
73
+ pending;
74
+ lastFormat = '';
29
75
  paras = [];
30
76
  nodeIndex = new Map();
31
77
  paraIndex = new Map();
32
78
  layers = new Map();
33
79
  cleanup = [];
80
+ options;
34
81
  constructor(viewer, options = {}) {
35
82
  this.viewer = viewer;
36
- this.options = options;
83
+ this.options = { ...options };
37
84
  const root = viewer.root;
38
85
  this.input = document.createElement('textarea');
39
86
  this.input.className = 'docxkeun-input';
@@ -97,6 +144,70 @@ export class InlineEditing {
97
144
  focus() {
98
145
  this.input.focus({ preventScroll: true });
99
146
  }
147
+ /** The selection (or caret) with paragraph numbers, text and pages, for AI assistants and toolbars. */
148
+ selectionInfo() {
149
+ const doc = this.doc;
150
+ if (!doc || !this.hasCaret || !this.enabled)
151
+ return undefined;
152
+ const s = this.storyValue;
153
+ const part = s.kind === 'header' || s.kind === 'footer' || s.kind === 'footnote' || s.kind === 'endnote' ? s.part : undefined;
154
+ return selectionInfoFor(doc, this.paras, this.anchor, this.focusPos, { story: s.kind, ...(part ? { part } : {}), ...(this.viewer.layout ? { layout: this.viewer.layout } : {}) });
155
+ }
156
+ /** Whether typing is recorded as tracked changes. */
157
+ get trackChanges() {
158
+ return this.doc ? new DocxEditor(this.doc, this.options.guard, { trackChanges: this.options.trackChanges }).trackChanges : false;
159
+ }
160
+ set trackChanges(on) {
161
+ this.options.trackChanges = on;
162
+ this.lastFormat = '';
163
+ this.reportFormat();
164
+ }
165
+ /** The story the caret is in. */
166
+ get story() {
167
+ return this.storyValue;
168
+ }
169
+ /** Move the caret into a header, footer, note or text box (or back to the body). */
170
+ enterStory(story, caret = { para: 0, char: 0 }) {
171
+ this.storyValue = story;
172
+ this.refreshModel();
173
+ this.viewer.root.dataset.editStory = story.kind;
174
+ this.goalX = undefined;
175
+ this.select(caret);
176
+ this.viewer.emit('storychange', { story });
177
+ }
178
+ /** The guard checking this layer's edits, if any. */
179
+ get guard() {
180
+ return this.options.guard;
181
+ }
182
+ /** Who new comments and replies are written by: the `author` option, else the guard's user. */
183
+ get author() {
184
+ const user = this.options.guard?.user;
185
+ return this.options.author ?? user?.name ?? user?.id ?? 'docxkeun';
186
+ }
187
+ /** Put the caret at a point on a page (points), as a click would. No-op while editing is off. */
188
+ placeCaretAt(page, x, y) {
189
+ if (!this.enabled)
190
+ return;
191
+ const caret = this.hitTest(page, x, y);
192
+ if (caret)
193
+ this.select(caret);
194
+ }
195
+ /** Whether a point on a page (points) lies inside the current, non-empty selection. */
196
+ selectionContains(page, x, y) {
197
+ if (!this.enabled || !this.hasCaret || compare(this.anchor, this.focusPos) === 0)
198
+ return false;
199
+ const caret = this.hitTest(page, x, y);
200
+ if (!caret)
201
+ return false;
202
+ const [start, end] = this.ordered();
203
+ return compare(caret, start) >= 0 && compare(caret, end) <= 0;
204
+ }
205
+ /** Where the start of the selection is: its page and the line's top (points on the page). */
206
+ selectionSpot() {
207
+ if (!this.hasCaret)
208
+ return undefined;
209
+ return this.screen(this.ordered()[0]);
210
+ }
100
211
  /** An editor range (for DocxEditor calls such as addComment) between two carets. */
101
212
  rangeOf(a, b) {
102
213
  const [start, end] = compare(a, b) <= 0 ? [a, b] : [b, a];
@@ -114,14 +225,42 @@ export class InlineEditing {
114
225
  get doc() {
115
226
  return this.viewer.document;
116
227
  }
228
+ /** Part holding the current story. */
229
+ get storyPart() {
230
+ const s = this.storyValue;
231
+ return s.kind === 'body' || s.kind === 'textbox' ? this.doc.mainPart : s.part;
232
+ }
117
233
  editor() {
118
- return new DocxEditor(this.doc, this.options.guard);
234
+ return new DocxEditor(this.doc, this.options.guard, { part: this.storyPart, trackChanges: this.options.trackChanges, author: this.options.author });
235
+ }
236
+ storyParagraphs() {
237
+ const doc = this.doc;
238
+ if (!doc)
239
+ return [];
240
+ const s = this.storyValue;
241
+ switch (s.kind) {
242
+ case 'body':
243
+ return paragraphsOf(doc.body().blocks);
244
+ case 'header':
245
+ case 'footer':
246
+ return doc.xmlSync(s.part) ? paragraphsOf(doc.headerFooter(s.part).blocks) : [];
247
+ case 'footnote':
248
+ case 'endnote':
249
+ return paragraphsOf(doc.note(s.kind, s.noteId));
250
+ case 'textbox':
251
+ return paragraphsOf(doc.readBlocks(doc.mainPart, s.container));
252
+ }
119
253
  }
120
254
  refreshModel() {
121
255
  const doc = this.doc;
122
256
  this.nodeIndex.clear();
123
257
  this.paraIndex.clear();
124
- this.paras = doc ? paragraphsOf(doc.body().blocks) : [];
258
+ this.paras = this.storyParagraphs();
259
+ // A story that disappeared (its text box was deleted): back to the body.
260
+ if (!this.paras.length && this.storyValue.kind !== 'body') {
261
+ this.storyValue = { kind: 'body' };
262
+ this.paras = doc ? paragraphsOf(doc.body().blocks) : [];
263
+ }
125
264
  this.paras.forEach((p, i) => {
126
265
  this.paraIndex.set(p.el, i);
127
266
  for (const seg of paragraphText(p).segments)
@@ -165,14 +304,39 @@ export class InlineEditing {
165
304
  pages() {
166
305
  return this.viewer.layout?.pages ?? [];
167
306
  }
307
+ /** Lines of the current story on a page. */
168
308
  bodyLines(page) {
169
- return page.lines.filter((l) => this.paraIndex.has(l.paragraph));
309
+ return (this.storyValue.kind === 'body' ? page.lines : page.storyLines).filter((l) => this.paraIndex.has(l.paragraph));
310
+ }
311
+ linesOf(page) {
312
+ return this.storyValue.kind === 'body' ? page.lines : page.storyLines;
313
+ }
314
+ /** The run child an inline image stands for, when it is in the current story. */
315
+ imageNode(item) {
316
+ const inline = item.inline;
317
+ if (!inline || inline.float)
318
+ return undefined;
319
+ for (const c of inline.run.children)
320
+ if (c.type === 'element' && this.nodeIndex.has(c) && (c === inline.drawing || findAll(c, inline.drawing.name).includes(inline.drawing)))
321
+ return c;
322
+ return undefined;
170
323
  }
171
324
  lineItems(page, line) {
172
- return page.items
173
- .filter((i) => i.type === 'text' && !!i.source && this.nodeIndex.has(i.source.inline.node))
174
- .filter((i) => i.y > line.y - 0.5 && i.y < line.y + line.h + 0.5 && i.xs[0] >= line.x - 1 && i.xs[0] <= line.x + line.w + 1)
175
- .sort((a, b) => a.xs[0] - b.xs[0]);
325
+ const out = [];
326
+ for (const i of page.items) {
327
+ if (i.type === 'text') {
328
+ if (!i.source || !this.nodeIndex.has(i.source.inline.node))
329
+ continue;
330
+ if (i.y > line.y - 0.5 && i.y < line.y + line.h + 0.5 && i.xs[0] >= line.x - 1 && i.xs[0] <= line.x + line.w + 1)
331
+ out.push({ item: i, x: i.xs[0] });
332
+ }
333
+ else if (i.type === 'image' && this.imageNode(i)) {
334
+ const bottom = i.y + i.h;
335
+ if (bottom > line.y - 0.5 && bottom < line.y + line.h + 0.5 && i.x >= line.x - 1 && i.x <= line.x + line.w + 1)
336
+ out.push({ item: i, x: i.x });
337
+ }
338
+ }
339
+ return out.sort((a, b) => a.x - b.x).map((e) => e.item);
176
340
  }
177
341
  clusterLength(inline, offset) {
178
342
  const cp = inline.text.codePointAt(offset) ?? 0;
@@ -198,12 +362,19 @@ export class InlineEditing {
198
362
  return { para, char: sameParaLater ? 0 : this.textOf(para).length };
199
363
  }
200
364
  for (const item of items) {
365
+ if (item.type === 'image') {
366
+ if (x < item.x + item.w / 2)
367
+ return this.fromDoc({ node: this.imageNode(item), offset: 0 });
368
+ continue;
369
+ }
201
370
  for (let i = 0; i < item.chars.length; i++) {
202
371
  if (x < item.xs[i] + item.widths[i] / 2)
203
372
  return this.itemCaret(item, i, true);
204
373
  }
205
374
  }
206
375
  const last = items[items.length - 1];
376
+ if (last.type === 'image')
377
+ return this.fromDoc({ node: this.imageNode(last), offset: 1 });
207
378
  return this.itemCaret(last, last.chars.length - 1, false);
208
379
  }
209
380
  itemCaret(item, i, before) {
@@ -229,12 +400,15 @@ export class InlineEditing {
229
400
  for (const pos of tries) {
230
401
  for (const page of pages) {
231
402
  if (pos.node.name === 'w:p') {
232
- const line = page.lines.find((l) => l.paragraph === pos.node);
403
+ const line = this.linesOf(page).find((l) => l.paragraph === pos.node);
233
404
  if (line)
234
405
  return { page: page.index, x: line.x, y: line.y, h: line.h };
235
406
  continue;
236
407
  }
237
408
  for (const item of page.items) {
409
+ if (item.type === 'image' && pos.node.name !== 'w:t' && item.inline && !item.inline.float && this.imageNode(item) === pos.node) {
410
+ return { page: page.index, x: pos.offset ? item.x + item.w : item.x, y: item.y, h: item.h };
411
+ }
238
412
  if (item.type !== 'text' || item.source?.inline.node !== pos.node)
239
413
  continue;
240
414
  const { offsets, inline } = item.source;
@@ -256,7 +430,7 @@ export class InlineEditing {
256
430
  // An empty paragraph or one with only tabs: fall back to its first line.
257
431
  const el = this.paras[c.para]?.el;
258
432
  for (const page of pages) {
259
- const line = page.lines.find((l) => l.paragraph === el);
433
+ const line = this.linesOf(page).find((l) => l.paragraph === el);
260
434
  if (line)
261
435
  return { page: page.index, x: line.x, y: line.y, h: line.h };
262
436
  }
@@ -264,6 +438,11 @@ export class InlineEditing {
264
438
  }
265
439
  // ---- drawing -------------------------------------------------------------------------------
266
440
  onLayout() {
441
+ if (this.viewer.document !== this.historyDoc) {
442
+ this.historyDoc = this.viewer.document;
443
+ this.history.clear();
444
+ this.lastEdit = { kind: '', at: 0 };
445
+ }
267
446
  this.refreshModel();
268
447
  if (this.hasCaret) {
269
448
  this.anchor = this.clamp(this.anchor);
@@ -281,6 +460,7 @@ export class InlineEditing {
281
460
  redraw(scrollIntoView = false) {
282
461
  for (const index of this.layers.keys())
283
462
  this.drawPage(index);
463
+ this.reportFormat();
284
464
  if (!this.hasCaret || !this.enabled)
285
465
  return;
286
466
  const pos = this.screen(this.focusPos);
@@ -354,6 +534,18 @@ export class InlineEditing {
354
534
  }
355
535
  flush(item.chars.length);
356
536
  }
537
+ // Inline pictures inside the selection.
538
+ for (const item of page.items) {
539
+ if (item.type !== 'image')
540
+ continue;
541
+ const node = this.imageNode(item);
542
+ const e = node && this.nodeIndex.get(node);
543
+ if (!e)
544
+ continue;
545
+ const c = { para: e.para, char: e.start };
546
+ if (compare(c, start) >= 0 && compare(c, end) < 0)
547
+ box('docxkeun-selection', item.x, item.y, item.w, item.h);
548
+ }
357
549
  // Empty paragraphs inside the selection.
358
550
  for (const line of this.bodyLines(page)) {
359
551
  const para = this.paraIndex.get(line.paragraph);
@@ -366,18 +558,49 @@ export class InlineEditing {
366
558
  box('docxkeun-caret', caret.x, caret.y, undefined, caret.h);
367
559
  }
368
560
  // ---- mouse ---------------------------------------------------------------------------------
369
- pointToCaret(e) {
561
+ pagePoint(e) {
370
562
  const target = document.elementFromPoint(e.clientX, e.clientY);
371
563
  const pageEl = (target?.closest('[data-page]') ?? e.target?.closest?.('[data-page]'));
372
564
  if (!pageEl || !this.viewer.root.contains(pageEl))
373
565
  return undefined;
374
- const page = Number(pageEl.dataset.page);
375
566
  const rect = pageEl.getBoundingClientRect();
376
567
  const s = this.viewer.scale;
377
- const x = (e.clientX - rect.left) / s;
378
- const y = (e.clientY - rect.top) / s;
379
- const caret = this.hitTest(page, x, y);
380
- return caret ? { caret, page, x, y } : undefined;
568
+ return { page: Number(pageEl.dataset.page), x: (e.clientX - rect.left) / s, y: (e.clientY - rect.top) / s };
569
+ }
570
+ pointToCaret(e) {
571
+ const at = this.pagePoint(e);
572
+ if (!at)
573
+ return undefined;
574
+ const caret = this.hitTest(at.page, at.x, at.y);
575
+ return caret ? { caret, ...at } : undefined;
576
+ }
577
+ /**
578
+ * Switch stories for a click, as Word does: a click in a note or text box enters it, a
579
+ * double-click enters a header or footer, and a click in the body leaves them.
580
+ */
581
+ storyForClick(at, double) {
582
+ const page = this.pages()[at.page];
583
+ if (!page)
584
+ return undefined;
585
+ const line = page.storyLines.find((l) => within(l, at.x, at.y)) ?? page.storyLines.find((l) => within(l, at.x, at.y, 8));
586
+ const target = line && storyOfLine(line);
587
+ const current = this.storyValue;
588
+ if (target) {
589
+ if (sameStory(target, current))
590
+ return undefined;
591
+ // A single click on a header or footer waits for the second click (as in Word).
592
+ if (target.kind === 'header' || target.kind === 'footer')
593
+ return double ? target : 'ignore';
594
+ return target;
595
+ }
596
+ if (current.kind === 'body')
597
+ return undefined;
598
+ // Leaving a header or footer takes a click in the body area; any click outside a note or text box leaves it.
599
+ const c = page.content;
600
+ const inBody = at.y >= c.y && at.y <= c.y + c.h;
601
+ if (current.kind === 'header' || current.kind === 'footer')
602
+ return inBody ? { kind: 'body' } : 'ignore';
603
+ return { kind: 'body' };
381
604
  }
382
605
  onMouseDown(e) {
383
606
  if (!this.enabled || e.button !== 0)
@@ -397,7 +620,25 @@ export class InlineEditing {
397
620
  }
398
621
  }
399
622
  e.preventDefault();
400
- if (e.shiftKey && this.hasCaret)
623
+ const at = { page: hit.page, x: hit.x, y: hit.y };
624
+ const found = this.storyForClick(at, e.detail >= 2);
625
+ if (found === 'ignore')
626
+ return;
627
+ const next = found;
628
+ if (next) {
629
+ this.storyValue = next;
630
+ this.refreshModel();
631
+ this.viewer.root.dataset.editStory = next.kind;
632
+ this.viewer.emit('storychange', { story: next });
633
+ const caret = this.hitTest(at.page, at.x, at.y);
634
+ if (!caret)
635
+ return;
636
+ hit.caret = caret;
637
+ }
638
+ else if (this.storyValue.kind !== 'body' && e.detail >= 2) {
639
+ // Fall through to word selection in the story.
640
+ }
641
+ if (e.shiftKey && this.hasCaret && !next)
401
642
  this.focusPos = hit.caret;
402
643
  else
403
644
  this.anchor = this.focusPos = hit.caret;
@@ -497,6 +738,18 @@ export class InlineEditing {
497
738
  case 'b':
498
739
  this.toggle('bold');
499
740
  break;
741
+ case 'e':
742
+ this.formatParagraphs({ align: 'center' });
743
+ break;
744
+ case 'l':
745
+ this.formatParagraphs({ align: 'left' });
746
+ break;
747
+ case 'r':
748
+ this.formatParagraphs({ align: 'right' });
749
+ break;
750
+ case 'j':
751
+ this.formatParagraphs({ align: 'justify' });
752
+ break;
500
753
  case 'i':
501
754
  this.toggle('italic');
502
755
  break;
@@ -533,21 +786,145 @@ export class InlineEditing {
533
786
  if (!this.hasCaret || compare(this.anchor, this.focusPos) === 0)
534
787
  return;
535
788
  e.preventDefault();
536
- e.clipboardData?.setData('text/plain', this.selectedText());
789
+ e.clipboardData?.setData('text/plain', this.selectedText().replaceAll(OBJECT_CHAR, ''));
790
+ e.clipboardData?.setData('text/html', this.selectedHtml());
791
+ if (cut)
792
+ this.apply('cut', () => this.deleteSelectionRaw());
793
+ }
794
+ /**
795
+ * Copy (or cut) the selection with the async clipboard: HTML and plain text, or plain text only
796
+ * where rich items are refused. For menus; the keyboard shortcuts use the native events above.
797
+ */
798
+ async copySelection(cut = false) {
799
+ if (!this.enabled || !this.hasCaret || compare(this.anchor, this.focusPos) === 0)
800
+ return;
801
+ const text = this.selectedText().replaceAll(OBJECT_CHAR, '');
802
+ const html = this.selectedHtml();
803
+ const clipboard = typeof navigator === 'undefined' ? undefined : navigator.clipboard;
804
+ if (!clipboard)
805
+ return;
806
+ let done = false;
807
+ if (clipboard.write && typeof ClipboardItem !== 'undefined') {
808
+ try {
809
+ await clipboard.write([new ClipboardItem({ 'text/html': new Blob([html], { type: 'text/html' }), 'text/plain': new Blob([text], { type: 'text/plain' }) })]);
810
+ done = true;
811
+ }
812
+ catch {
813
+ // Fall back to plain text below.
814
+ }
815
+ }
816
+ if (!done) {
817
+ try {
818
+ await clipboard.writeText(text);
819
+ }
820
+ catch {
821
+ return;
822
+ }
823
+ }
537
824
  if (cut)
538
825
  this.apply('cut', () => this.deleteSelectionRaw());
539
826
  }
540
827
  onPaste(e) {
541
828
  e.preventDefault();
829
+ const html = e.clipboardData?.getData('text/html');
830
+ if (html && this.pasteHtml(html))
831
+ return;
542
832
  const text = e.clipboardData?.getData('text/plain');
833
+ if (text)
834
+ this.pasteText(text);
835
+ }
836
+ /** Paste HTML (rich paste: formatting, headings, lists and links). False when it holds no paragraphs. */
837
+ pasteHtml(html) {
838
+ const pasted = htmlToParagraphs(html);
839
+ if (!pasted?.length)
840
+ return false;
841
+ this.pasteParagraphs(pasted);
842
+ return true;
843
+ }
844
+ /** Paste plain text at the caret (replacing the selection). */
845
+ pasteText(text) {
543
846
  if (text)
544
847
  this.typeText(text.replace(/\r\n?/g, '\n'), 'paste');
545
848
  }
849
+ /** The selection as HTML (formatting, headings and lists), for pasting into other programs. */
850
+ selectedHtml() {
851
+ const [start, end] = this.ordered();
852
+ const out = [];
853
+ for (let p = start.para; p <= end.para; p++) {
854
+ const para = this.paras[p];
855
+ out.push({ para, from: p === start.para ? start.char : 0, to: p === end.para ? end.char : paragraphText(para).text.length });
856
+ }
857
+ return paragraphsToHtml(out, (para) => this.listKind(para));
858
+ }
859
+ listKind(para) {
860
+ if (!para.numbering)
861
+ return undefined;
862
+ return para.numbering.level.format === 'bullet' ? 'bullet' : 'number';
863
+ }
864
+ /** Insert formatted paragraphs (from pasted HTML) at the caret. */
865
+ pasteParagraphs(paragraphs) {
866
+ const links = [];
867
+ const lists = [];
868
+ this.apply('paste', () => {
869
+ let caret = this.deleteSelectionRaw();
870
+ const editor = this.editor();
871
+ paragraphs.forEach((para, i) => {
872
+ if (i > 0) {
873
+ const el = editor.splitParagraph(this.toDoc(caret, caret.char === 0 ? 'start' : 'end'));
874
+ this.refreshModel();
875
+ caret = { para: this.paraIndex.get(el) ?? caret.para + 1, char: 0 };
876
+ if (para.style)
877
+ editor.setParagraphStyle(el, para.style);
878
+ }
879
+ else if (para.style && caret.char === 0 && this.textOf(caret.para) === '')
880
+ editor.setParagraphStyle(this.paras[caret.para].el, para.style);
881
+ if (para.list)
882
+ lists.push({ para: caret.para, format: para.list });
883
+ for (const run of para.runs) {
884
+ if (!run.text)
885
+ continue;
886
+ const from = caret.char;
887
+ editor.insertText(this.toDoc(caret, caret.char === 0 ? 'start' : 'end'), run.text);
888
+ this.refreshModel();
889
+ caret = { para: caret.para, char: caret.char + run.text.length };
890
+ // Pasted text keeps its own formatting: the on/off properties are set either way, since
891
+ // text typed after a bold word would otherwise come out bold too.
892
+ const format = { bold: false, italic: false, underline: false, strike: false, ...run.format };
893
+ editor.formatRange(this.rangeOf({ para: caret.para, char: from }, caret), format);
894
+ this.refreshModel();
895
+ if (run.link)
896
+ links.push({ para: caret.para, from, to: caret.char, url: run.link });
897
+ }
898
+ });
899
+ return caret;
900
+ });
901
+ if (!links.length && !lists.length)
902
+ return;
903
+ // Links and lists need new relationships and numbering definitions (asynchronous).
904
+ void (async () => {
905
+ const editor = this.editor();
906
+ try {
907
+ for (const l of links.reverse()) {
908
+ this.refreshModel();
909
+ await editor.addHyperlink(this.rangeOf({ para: l.para, char: l.from }, { para: l.para, char: l.to }), { url: l.url });
910
+ }
911
+ for (const format of ['bullet', 'decimal']) {
912
+ const els = lists.filter((l) => l.format === format).map((l) => this.paras[l.para]?.el).filter((e) => !!e);
913
+ if (els.length)
914
+ await editor.setList(els, { format });
915
+ }
916
+ }
917
+ catch (error) {
918
+ this.viewer.emit('editerror', { error: error instanceof Error ? error : new Error(String(error)) });
919
+ }
920
+ })();
921
+ }
546
922
  // ---- movement ------------------------------------------------------------------------------
547
923
  ordered() {
548
924
  return compare(this.anchor, this.focusPos) <= 0 ? [this.anchor, this.focusPos] : [this.focusPos, this.anchor];
549
925
  }
550
926
  setCaret(c, extend) {
927
+ this.pending = undefined;
551
928
  this.focusPos = this.clamp(c);
552
929
  if (!extend)
553
930
  this.anchor = this.focusPos;
@@ -641,19 +1018,18 @@ export class InlineEditing {
641
1018
  /** Run an edit with undo support; report refused edits instead of throwing. */
642
1019
  apply(kind, fn) {
643
1020
  const doc = this.doc;
644
- if (!doc || !this.enabled || !this.hasCaret)
1021
+ if (!doc || !this.enabled || !this.hasCaret || this.history.busy)
645
1022
  return;
646
1023
  const now = Date.now();
647
1024
  // Consecutive typing within a second is one undo step.
648
1025
  const coalesce = kind === 'type' && this.lastEdit.kind === 'type' && now - this.lastEdit.at < 1000;
649
- const snapshot = { root: cloneElement(doc.documentXml.root), anchor: { ...this.anchor }, focus: { ...this.focusPos } };
1026
+ const snapshot = this.snapshot();
650
1027
  try {
651
1028
  const next = fn();
1029
+ if (this.storyValue.kind === 'textbox')
1030
+ dropStaleFallback(doc.documentXml.root, this.storyValue.container);
652
1031
  if (!coalesce)
653
- this.undoStack.push(snapshot);
654
- if (this.undoStack.length > 200)
655
- this.undoStack.shift();
656
- this.redoStack.length = 0;
1032
+ this.history.push(snapshot);
657
1033
  this.lastEdit = { kind, at: now };
658
1034
  this.refreshModel();
659
1035
  if (next) {
@@ -664,8 +1040,7 @@ export class InlineEditing {
664
1040
  }
665
1041
  catch (error) {
666
1042
  // Edits that failed half-way are rolled back.
667
- doc.documentXml.root = snapshot.root;
668
- doc.touch(doc.mainPart);
1043
+ this.putRoot(snapshot);
669
1044
  this.refreshModel();
670
1045
  this.viewer.emit('editerror', { error: error instanceof Error ? error : new Error(String(error)) });
671
1046
  }
@@ -713,9 +1088,14 @@ export class InlineEditing {
713
1088
  }
714
1089
  if (!line)
715
1090
  return;
1091
+ const from = caret;
716
1092
  editor.insertText(this.toDoc(caret, caret.char === 0 ? 'start' : 'end'), line);
717
1093
  this.refreshModel();
718
1094
  caret = { para: caret.para, char: caret.char + line.length };
1095
+ if (this.pending && kind === 'type') {
1096
+ editor.formatRange(this.rangeOf(from, caret), this.pending);
1097
+ this.refreshModel();
1098
+ }
719
1099
  });
720
1100
  return caret;
721
1101
  });
@@ -782,17 +1162,25 @@ export class InlineEditing {
782
1162
  return this.deleteSelectionRaw();
783
1163
  });
784
1164
  }
1165
+ /** Turn bold, italic, underline or strikethrough on or off for the selection (or the next text typed). */
785
1166
  toggle(prop) {
1167
+ const now = this.caretFormat();
1168
+ if (!now)
1169
+ return;
1170
+ this.format({ [prop]: !now[prop] });
1171
+ }
1172
+ /** Format the selected text; with only a caret, the format applies to the next text typed. */
1173
+ format(format) {
1174
+ if (!this.hasCaret)
1175
+ return;
786
1176
  const [start, end] = this.ordered();
787
- if (compare(start, end) === 0)
1177
+ if (compare(start, end) === 0) {
1178
+ this.pending = { ...this.pending, ...format };
1179
+ this.reportFormat();
788
1180
  return;
789
- const para = this.paras[start.para];
790
- const at = this.toDoc(start, 'start');
791
- const inline = para?.inlines.find((i) => i.kind === 'text' && i.node === at.node);
792
- const current = inline && inline.kind === 'text' ? (prop === 'underline' ? !!inline.props.underline && inline.props.underline !== 'none' : !!inline.props[prop]) : false;
793
- const format = { [prop]: !current };
1181
+ }
794
1182
  this.apply('format', () => {
795
- this.editor().formatRange({ start: at, end: this.toDoc(end, 'end') }, format);
1183
+ this.editor().formatRange(this.rangeOf(start, end), format);
796
1184
  return undefined;
797
1185
  });
798
1186
  // Formatting keeps the selection.
@@ -800,31 +1188,268 @@ export class InlineEditing {
800
1188
  this.focusPos = end;
801
1189
  this.redraw();
802
1190
  }
803
- undo() {
1191
+ /** Paragraphs the selection touches. */
1192
+ selectedParagraphs() {
1193
+ const [start, end] = this.ordered();
1194
+ const out = [];
1195
+ for (let p = start.para; p <= end.para; p++)
1196
+ if (this.paras[p])
1197
+ out.push(this.paras[p].el);
1198
+ return out;
1199
+ }
1200
+ /** Alignment, direction, indents or spacing of the selected paragraphs. */
1201
+ formatParagraphs(format) {
1202
+ return this.act('format', (editor) => {
1203
+ for (const p of this.selectedParagraphs())
1204
+ editor.formatParagraph(p, format);
1205
+ });
1206
+ }
1207
+ /** Apply a paragraph style (e.g. "Heading1") to the selected paragraphs. */
1208
+ setStyle(styleId) {
1209
+ return this.act('style', (editor) => {
1210
+ for (const p of this.selectedParagraphs())
1211
+ editor.setParagraphStyle(p, styleId);
1212
+ });
1213
+ }
1214
+ /** Make the selected paragraphs a bulleted or numbered list, or take them out of one. */
1215
+ setList(format) {
1216
+ return this.act('list', (editor) => editor.setList(this.selectedParagraphs(), { format }));
1217
+ }
1218
+ /** Increase (1) or decrease (-1) the indent: the list level in a list, else the left indent by half an inch. */
1219
+ async indent(dir) {
1220
+ if (!this.hasCaret)
1221
+ return;
1222
+ const first = this.paras[this.ordered()[0].para];
1223
+ if (first?.numbering) {
1224
+ const level = Math.max(0, Math.min(8, first.numbering.ilvl + dir));
1225
+ return this.act('indent', (editor) => editor.setList(this.selectedParagraphs(), { level }));
1226
+ }
1227
+ const left = first?.props.indent?.left ?? 0;
1228
+ return this.formatParagraphs({ indentLeft: Math.max(0, left + dir * 36) });
1229
+ }
1230
+ /** Whether there is something to undo or redo (for toolbars). */
1231
+ get canUndo() {
1232
+ return this.history.canUndo;
1233
+ }
1234
+ get canRedo() {
1235
+ return this.history.canRedo;
1236
+ }
1237
+ /**
1238
+ * Run an edit that may touch any part of the document as one undo step. A failure puts the
1239
+ * document back, reports `editerror` and rethrows. Inside `fn`, change the document through the
1240
+ * `editor` it receives. A nested `transaction()`, `setList()` and the like joins this step only
1241
+ * before `fn`'s first `await`; after it, it waits for this step and gives up after
1242
+ * `UndoHistory.queueTimeout` (10 s by default): a nested `transaction()` rejects with an
1243
+ * `EditError`, while `setList()` and the like report it through `editerror`. Edits requested
1244
+ * elsewhere meanwhile wait their turn, act on the selection they were requested with, and are
1245
+ * undo steps of their own.
1246
+ */
1247
+ async transaction(label, fn) {
1248
+ const doc = this.doc;
1249
+ if (!doc)
1250
+ throw new Error('No document is open');
1251
+ if (this.history.joinable) {
1252
+ // Nested: the outer transaction checkpoints, records, restores and redraws.
1253
+ try {
1254
+ return await fn(this.editor());
1255
+ }
1256
+ catch (error) {
1257
+ this.reportError(error);
1258
+ throw error;
1259
+ }
1260
+ }
1261
+ const story = this.storyValue;
1262
+ const where = { story, anchor: { ...this.anchor }, focus: { ...this.focusPos } };
1263
+ const container = textboxIndex(doc.documentXml.root, story);
1264
+ let started = false;
1265
+ try {
1266
+ const result = await this.history.transaction(doc, label, () => {
1267
+ started = true;
1268
+ // A queued edit acts on the story and selection it was requested with, not on the ones
1269
+ // the transaction ahead of it put back (act() and the menus read them as they run).
1270
+ this.putSelection(doc.documentXml.root, story, container, where);
1271
+ return fn(this.editor());
1272
+ }, { ...where, ...(container !== undefined ? { container } : {}) });
1273
+ this.lastEdit = { kind: '', at: 0 };
1274
+ this.refreshModel();
1275
+ this.anchor = this.clamp(where.anchor);
1276
+ this.focusPos = this.clamp(where.focus);
1277
+ // The selection is put back unchanged: no scrolling to it (a comment card's Resolve on
1278
+ // page 8 must not jump to a caret left on page 1).
1279
+ this.redraw();
1280
+ return result;
1281
+ }
1282
+ catch (error) {
1283
+ // Never started (it gave up waiting for another transaction, or no checkpoint could be
1284
+ // taken): the document is untouched, and the one still running redraws when it ends.
1285
+ if (started) {
1286
+ // The failure restore replaced the XML trees: find the text box again.
1287
+ this.putSelection(doc.documentXml.root, story, container, where);
1288
+ this.redraw();
1289
+ }
1290
+ this.reportError(error);
1291
+ throw error;
1292
+ }
1293
+ }
1294
+ /** Make `story` (a text box found again by its index) and the selection current, with a fresh model. */
1295
+ putSelection(root, story, container, at) {
1296
+ this.storyValue = resolveStory(root, story, container);
1297
+ this.viewer.root.dataset.editStory = this.storyValue.kind;
1298
+ this.refreshModel();
1299
+ this.anchor = this.clamp(at.anchor);
1300
+ this.focusPos = this.clamp(at.focus);
1301
+ }
1302
+ /** Errors already reported through `editerror` (a nested transaction's failure reaching the outer one). */
1303
+ reported = new WeakSet();
1304
+ reportError(error) {
1305
+ if (typeof error === 'object' && error !== null) {
1306
+ if (this.reported.has(error))
1307
+ return;
1308
+ this.reported.add(error);
1309
+ }
1310
+ this.viewer.emit('editerror', { error: error instanceof Error ? error : new Error(String(error)) });
1311
+ }
1312
+ /** A transaction on the selection whose failure has already been reported through `editerror`. */
1313
+ async act(label, fn) {
1314
+ if (!this.doc || !this.hasCaret)
1315
+ return;
1316
+ try {
1317
+ await this.transaction(label, async (editor) => {
1318
+ await fn(editor);
1319
+ if (this.storyValue.kind === 'textbox')
1320
+ dropStaleFallback(this.doc.documentXml.root, this.storyValue.container);
1321
+ });
1322
+ }
1323
+ catch {
1324
+ // editerror was emitted by transaction().
1325
+ }
1326
+ }
1327
+ /** Formatting at the caret (start of the selection), with any format waiting for the next text typed. */
1328
+ caretFormat() {
1329
+ if (!this.hasCaret || !this.paras.length)
1330
+ return undefined;
1331
+ const [start, end] = this.ordered();
1332
+ const para = this.paras[start.para];
1333
+ // The text before the caret decides, as in Word (the first character of a selection).
1334
+ const k = compare(start, end) === 0 ? Math.max(0, start.char - 1) : start.char;
1335
+ const pt = paragraphText(para);
1336
+ const seg = pt.segments.find((sg) => k >= sg.start && k < sg.end) ?? pt.segments[pt.segments.length - 1];
1337
+ const inline = seg && para.inlines.find((i) => (i.kind === 'text' || i.kind === 'tab') && i.node === seg.node);
1338
+ const props = inline && 'props' in inline ? inline.props : para.markProps;
1339
+ const pending = this.pending ?? {};
1340
+ const underline = pending.underline !== undefined ? !!pending.underline : !!props.underline && props.underline !== 'none';
1341
+ const jc = para.props.jc ?? 'left';
1342
+ const rtl = !!para.props.bidi;
1343
+ const align = jc === 'both' || jc === 'distribute' ? 'justify' : jc === 'center' ? 'center' : (jc === 'right') !== rtl ? 'right' : 'left';
1344
+ return {
1345
+ bold: pending.bold ?? !!props.bold,
1346
+ italic: pending.italic ?? !!props.italic,
1347
+ underline,
1348
+ strike: pending.strike ?? !!props.strike,
1349
+ size: pending.size ?? props.size,
1350
+ font: pending.font ?? props.fonts?.ascii,
1351
+ color: pending.color ?? (props.color && props.color !== 'auto' ? props.color : undefined),
1352
+ highlight: pending.highlight ?? props.highlight,
1353
+ align,
1354
+ direction: rtl ? 'rtl' : 'ltr',
1355
+ styleId: para.styleId,
1356
+ list: this.listKind(para),
1357
+ story: this.storyValue.kind,
1358
+ hasSelection: compare(start, end) !== 0,
1359
+ trackChanges: this.trackChanges,
1360
+ canUndo: this.history.canUndo,
1361
+ canRedo: this.history.canRedo,
1362
+ };
1363
+ }
1364
+ reportFormat() {
1365
+ this.viewer.selectionMoved();
1366
+ const format = this.enabled ? this.caretFormat() : undefined;
1367
+ const key = JSON.stringify(format ?? null);
1368
+ if (key === this.lastFormat)
1369
+ return;
1370
+ this.lastFormat = key;
1371
+ this.viewer.emit('caretchange', { format });
1372
+ }
1373
+ /** The current story's part as it is now, with the selection. */
1374
+ snapshot(story = this.storyValue) {
1375
+ const doc = this.doc;
1376
+ const part = story.kind === 'body' || story.kind === 'textbox' ? doc.mainPart : story.part;
1377
+ const root = part === doc.mainPart ? doc.documentXml.root : doc.xmlSync(part).root;
1378
+ const container = story.kind === 'textbox' ? findAll(root, 'w:txbxContent').indexOf(story.container) : undefined;
1379
+ return { kind: 'story', part, story, container, root: cloneElement(root), anchor: { ...this.anchor }, focus: { ...this.focusPos } };
1380
+ }
1381
+ /** Put a snapshot's XML back into its part. */
1382
+ putRoot(snap) {
804
1383
  const doc = this.doc;
805
- const snap = this.undoStack.pop();
806
- if (!doc || !snap)
1384
+ if (snap.part === doc.mainPart)
1385
+ doc.documentXml.root = snap.root;
1386
+ else
1387
+ doc.xmlSync(snap.part).root = snap.root;
1388
+ doc.touch(snap.part);
1389
+ }
1390
+ /** The entry for the state being left, of the same kind as the one being restored. */
1391
+ currentFor(restoring) {
1392
+ const liveRoot = this.doc.documentXml.root;
1393
+ if (restoring.kind === 'story')
1394
+ return this.snapshot(resolveStory(liveRoot, restoring.story, restoring.container));
1395
+ const container = textboxIndex(liveRoot, this.storyValue);
1396
+ return {
1397
+ kind: 'package',
1398
+ checkpoint: this.doc.checkpoint(),
1399
+ story: this.storyValue,
1400
+ ...(container !== undefined ? { container } : {}),
1401
+ anchor: { ...this.anchor },
1402
+ focus: { ...this.focusPos },
1403
+ label: restoring.label,
1404
+ };
1405
+ }
1406
+ undo() {
1407
+ if (!this.doc || this.history.busy)
807
1408
  return;
808
- this.redoStack.push({ root: cloneElement(doc.documentXml.root), anchor: { ...this.anchor }, focus: { ...this.focusPos } });
809
- this.restore(snap);
1409
+ const entry = this.history.undo((e) => this.currentFor(e));
1410
+ if (entry)
1411
+ this.restore(entry);
810
1412
  }
811
1413
  redo() {
812
- const doc = this.doc;
813
- const snap = this.redoStack.pop();
814
- if (!doc || !snap)
1414
+ if (!this.doc || this.history.busy)
815
1415
  return;
816
- this.undoStack.push({ root: cloneElement(doc.documentXml.root), anchor: { ...this.anchor }, focus: { ...this.focusPos } });
817
- this.restore(snap);
1416
+ const entry = this.history.redo((e) => this.currentFor(e));
1417
+ if (entry)
1418
+ this.restore(entry);
818
1419
  }
819
- restore(snap) {
1420
+ restore(entry) {
820
1421
  const doc = this.doc;
821
- doc.documentXml.root = snap.root;
822
- doc.touch(doc.mainPart);
1422
+ let root;
1423
+ if (entry.kind === 'story') {
1424
+ this.putRoot(entry);
1425
+ root = entry.part === doc.mainPart ? doc.documentXml.root : doc.xmlSync(entry.part).root;
1426
+ }
1427
+ else {
1428
+ doc.restore(entry.checkpoint);
1429
+ root = doc.documentXml.root;
1430
+ }
1431
+ // A text box container is replaced along with the document's root: find its copy.
1432
+ const story = resolveStory(root, entry.story, entry.container);
1433
+ this.storyValue = story;
1434
+ this.viewer.root.dataset.editStory = story.kind;
823
1435
  this.refreshModel();
824
1436
  this.lastEdit = { kind: '', at: 0 };
825
- this.anchor = this.clamp(snap.anchor);
826
- this.focusPos = this.clamp(snap.focus);
1437
+ this.anchor = this.clamp(entry.anchor);
1438
+ this.focusPos = this.clamp(entry.focus);
827
1439
  this.hasCaret = true;
828
1440
  this.redraw(true);
829
1441
  }
830
1442
  }
1443
+ /**
1444
+ * Word stores a text box twice: the DrawingML version in mc:Choice and a VML copy in
1445
+ * mc:Fallback. After editing the first, the copy is out of date, so it is removed (Word and
1446
+ * other current readers use the Choice; the Fallback is only for very old ones).
1447
+ */
1448
+ function dropStaleFallback(root, container) {
1449
+ for (const ac of findAll(root, 'mc:AlternateContent')) {
1450
+ const choice = elements(ac).find((n) => n.name === 'mc:Choice');
1451
+ if (!choice || !findAll(choice, 'w:txbxContent').includes(container))
1452
+ continue;
1453
+ ac.children = ac.children.filter((n) => !(n.type === 'element' && n.name === 'mc:Fallback'));
1454
+ }
1455
+ }