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
@@ -0,0 +1,794 @@
1
+ /**
2
+ * Showing an AI assistant at work on the pages:
3
+ * - a shimmer over the paragraphs it is working on, and its own named caret gliding there;
4
+ * - a scan line while it reads;
5
+ * - after a change, new text "inked in" left to right with a spark at the pen tip and a fading
6
+ * glow, removed paragraphs floating away struck through, and red ticks where words were cut;
7
+ * - change bars with a ✦ in the margin (hover: what the text was) and a change map on the
8
+ * scroll bar's edge, until the next change or `clearMarks()`.
9
+ * Everything respects prefers-reduced-motion (static highlights instead of motion).
10
+ */
11
+ import { paragraphsOf, paragraphText } from '../api/editor.js';
12
+ /** Longest common subsequence pairs of two sequences (indices), with a size limit (then: none). */
13
+ function lcs(a, b, eq, limit = 360_000) {
14
+ const n = a.length;
15
+ const m = b.length;
16
+ if (!n || !m || n * m > limit)
17
+ return [];
18
+ const w = m + 1;
19
+ const t = new Uint32Array((n + 1) * w);
20
+ for (let i = n - 1; i >= 0; i--)
21
+ for (let j = m - 1; j >= 0; j--)
22
+ t[i * w + j] = eq(a[i], b[j]) ? t[(i + 1) * w + j + 1] + 1 : Math.max(t[(i + 1) * w + j], t[i * w + j + 1]);
23
+ const out = [];
24
+ for (let i = 0, j = 0; i < n && j < m;) {
25
+ if (eq(a[i], b[j])) {
26
+ out.push([i, j]);
27
+ i++;
28
+ j++;
29
+ }
30
+ else if (t[(i + 1) * w + j] >= t[i * w + j + 1])
31
+ i++;
32
+ else
33
+ j++;
34
+ }
35
+ return out;
36
+ }
37
+ const tokens = (s) => s.match(/\s+|[\p{L}\p{N}_]+|[^\s\p{L}\p{N}_]/gu) ?? [];
38
+ /** What changed inside one paragraph: ranges of new text and points where text was cut. */
39
+ export function diffText(before, after) {
40
+ if (before === after)
41
+ return { ranges: [], cuts: [] };
42
+ const a = tokens(before);
43
+ const b = tokens(after);
44
+ // Common prefix and suffix first, then a token LCS on the middle.
45
+ let p = 0;
46
+ while (p < a.length && p < b.length && a[p] === b[p])
47
+ p++;
48
+ let s = 0;
49
+ while (s < a.length - p && s < b.length - p && a[a.length - 1 - s] === b[b.length - 1 - s])
50
+ s++;
51
+ const am = a.slice(p, a.length - s);
52
+ const bm = b.slice(p, b.length - s);
53
+ const pairs = lcs(am, bm, (x, y) => x === y);
54
+ const keptB = new Set(pairs.map(([, j]) => j + p));
55
+ const keptA = new Set(pairs.map(([i]) => i + p));
56
+ const offsets = [];
57
+ let o = 0;
58
+ for (const t of b) {
59
+ offsets.push(o);
60
+ o += t.length;
61
+ }
62
+ offsets.push(o);
63
+ const ranges = [];
64
+ for (let j = p; j < b.length - s; j++) {
65
+ if (keptB.has(j) || /^\s+$/.test(b[j]))
66
+ continue;
67
+ const from = offsets[j];
68
+ const to = offsets[j + 1];
69
+ const last = ranges[ranges.length - 1];
70
+ // Join ranges separated only by spaces.
71
+ if (last && after.slice(last[1], from).trim() === '')
72
+ last[1] = to;
73
+ else
74
+ ranges.push([from, to]);
75
+ }
76
+ // Removed tokens with nothing new next to them: a cut at the following kept token.
77
+ const cuts = [];
78
+ let bi = p;
79
+ for (let i = p; i < a.length - s; i++) {
80
+ if (keptA.has(i)) {
81
+ const pair = pairs.find(([x]) => x + p === i);
82
+ bi = pair[1] + p + 1;
83
+ continue;
84
+ }
85
+ if (/^\s+$/.test(a[i]))
86
+ continue;
87
+ const at = offsets[Math.min(bi, b.length)];
88
+ if (!ranges.some(([f, t]) => at >= f && at <= t) && !cuts.includes(at))
89
+ cuts.push(at);
90
+ }
91
+ return { ranges, cuts };
92
+ }
93
+ function similarity(a, b) {
94
+ const wa = new Set(a.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []);
95
+ const wb = new Set(b.toLowerCase().match(/[\p{L}\p{N}]+/gu) ?? []);
96
+ if (!wa.size && !wb.size)
97
+ return 1;
98
+ let common = 0;
99
+ for (const w of wa)
100
+ if (wb.has(w))
101
+ common++;
102
+ return common / Math.max(wa.size, wb.size);
103
+ }
104
+ /** Paragraph-level changes between two versions of a document's paragraph texts. */
105
+ export function diffParagraphs(before, after) {
106
+ const changes = [];
107
+ const deleted = [];
108
+ const same = [];
109
+ let p = 0;
110
+ while (p < before.length && p < after.length && before[p] === after[p])
111
+ p++;
112
+ let s = 0;
113
+ while (s < before.length - p && s < after.length - p && before[before.length - 1 - s] === after[after.length - 1 - s])
114
+ s++;
115
+ for (let i = 0; i < p; i++)
116
+ same.push([i, i]);
117
+ for (let k = 1; k <= s; k++)
118
+ same.push([before.length - k, after.length - k]);
119
+ const a = before.slice(p, before.length - s);
120
+ const b = after.slice(p, after.length - s);
121
+ const anchors = [...lcs(a, b, (x, y) => x === y && x.trim() !== ''), [a.length, b.length]];
122
+ let ai = 0;
123
+ let bi = 0;
124
+ for (const [ae, be] of anchors) {
125
+ // A gap between unchanged paragraphs: pair similar ones as changes, the rest are inserts and deletes.
126
+ const oldGap = a.slice(ai, ae);
127
+ const newGap = b.slice(bi, be);
128
+ let k = 0;
129
+ for (let j = 0; j < newGap.length; j++) {
130
+ const para = p + bi + j;
131
+ const text = newGap[j];
132
+ // Find the next old paragraph that is similar enough to count as this one changed.
133
+ let match = -1;
134
+ for (let i = k; i < oldGap.length && match < 0; i++)
135
+ if (similarity(oldGap[i], text) >= 0.34)
136
+ match = i;
137
+ if (match < 0 && oldGap.length === newGap.length && k < oldGap.length)
138
+ match = k;
139
+ if (match >= 0) {
140
+ for (let i = k; i < match; i++)
141
+ deleted.push({ at: para, text: oldGap[i] });
142
+ const d = diffText(oldGap[match], text);
143
+ changes.push({ para, kind: 'changed', ranges: d.ranges, cuts: d.cuts, before: oldGap[match] });
144
+ k = match + 1;
145
+ }
146
+ else {
147
+ changes.push({ para, kind: 'inserted', ranges: text ? [[0, text.length]] : [], cuts: [] });
148
+ }
149
+ }
150
+ for (let i = k; i < oldGap.length; i++)
151
+ deleted.push({ at: p + be, text: oldGap[i] });
152
+ if (ae < a.length)
153
+ same.push([p + ae, p + be]);
154
+ ai = ae + 1;
155
+ bi = be + 1;
156
+ }
157
+ same.sort((x, y) => x[1] - y[1]);
158
+ return { changes, deleted, same };
159
+ }
160
+ /** A paragraph's formatting as a string: style, alignment, list, and each run's properties. */
161
+ function formatSignature(p) {
162
+ const runs = p.inlines.map((i) => (i.kind === 'text' ? JSON.stringify(i.props) : i.kind));
163
+ return `${p.styleId ?? ''}|${p.props.jc ?? ''}|${p.props.bidi ? 'rtl' : ''}|${p.numbering ? `${p.numbering.numId}.${p.numbering.ilvl}` : ''}|${runs.join(';')}`;
164
+ }
165
+ // ---- drawing ---------------------------------------------------------------------------------------
166
+ const STYLE_ID = 'docxkeun-ai-style';
167
+ /** Highlights without motion: for prefers-reduced-motion, and for `animate: false` (scoped by `prefix`). */
168
+ function still(prefix) {
169
+ return [
170
+ `${prefix}.docxkeun-ai-shimmer{animation:none;background-image:none;background-color:color-mix(in srgb,var(--dk-ai-1) 14%,transparent)}`,
171
+ `${prefix}.docxkeun-ai-scan,${prefix}.docxkeun-ai-ink,${prefix}.docxkeun-ai-pen{display:none}`,
172
+ `${prefix}.docxkeun-ai-glow{animation:docxkeun-ai-fade 3s ease-out both}`,
173
+ `${prefix}.docxkeun-ai-caret{transition:none;animation:none}`,
174
+ `${prefix}.docxkeun-ai-ghost,${prefix}.docxkeun-ai-cut{animation:docxkeun-ai-fade 2.4s both}`,
175
+ `${prefix}.docxkeun-ai-bar,${prefix}.docxkeun-ai-spark{animation:none}`,
176
+ ].join('\n');
177
+ }
178
+ const CSS = `
179
+ .docxkeun-viewer{--dk-ai-1:var(--docxkeun-ai-color-1,#7c5cff);--dk-ai-2:var(--docxkeun-ai-color-2,var(--docxkeun-ai-color-1,#d97757));--dk-ai-text:var(--docxkeun-ai-text,#fff);--docxkeun-ai-page:#fff}
180
+ .docxkeun-ai-layer{position:absolute;left:0;top:0;width:0;height:0;pointer-events:none;z-index:5}
181
+ .docxkeun-ai-layer>*{position:absolute;pointer-events:none}
182
+ .docxkeun-ai-shimmer{border-radius:3px;background-color:color-mix(in srgb,var(--dk-ai-1) 7%,transparent);background-image:linear-gradient(100deg,color-mix(in srgb,var(--dk-ai-1) 0%,transparent) 25%,color-mix(in srgb,var(--dk-ai-1) 30%,transparent) 42%,color-mix(in srgb,var(--dk-ai-2) 30%,transparent) 58%,color-mix(in srgb,var(--dk-ai-2) 0%,transparent) 75%);background-size:300% 100%;mix-blend-mode:multiply;animation:docxkeun-ai-shimmer 1.6s ease-in-out infinite}
183
+ @keyframes docxkeun-ai-shimmer{from{background-position:100% 0}to{background-position:0 0}}
184
+ .docxkeun-ai-scan{height:46px;background:linear-gradient(180deg,color-mix(in srgb,var(--dk-ai-1) 0%,transparent),color-mix(in srgb,var(--dk-ai-1) 16%,transparent) 60%,color-mix(in srgb,var(--dk-ai-2) 45%,transparent) 96%,color-mix(in srgb,var(--dk-ai-2) 0%,transparent));mix-blend-mode:multiply;animation:docxkeun-ai-scan 1.3s cubic-bezier(.4,0,.2,1) forwards}
185
+ @keyframes docxkeun-ai-scan{from{transform:translateY(0);opacity:0}12%{opacity:1}85%{opacity:1}to{transform:translateY(var(--travel));opacity:0}}
186
+ .docxkeun-ai-caret{width:2px;border-radius:1px;background:linear-gradient(var(--dk-ai-1),var(--dk-ai-2));transition:left .45s cubic-bezier(.3,.7,.2,1),top .45s cubic-bezier(.3,.7,.2,1),height .2s,opacity .4s;box-shadow:0 0 6px color-mix(in srgb,var(--dk-ai-1) 60%,transparent)}
187
+ .docxkeun-ai-caret.working{animation:docxkeun-ai-blink 1s steps(2,jump-none) infinite}
188
+ @keyframes docxkeun-ai-blink{50%{opacity:.35}}
189
+ .docxkeun-ai-caret span{position:absolute;left:0;bottom:100%;margin-bottom:2px;white-space:nowrap;font:600 11px/1 system-ui,sans-serif;color:var(--dk-ai-text);padding:3px 6px;border-radius:4px 4px 4px 0;background:linear-gradient(90deg,var(--dk-ai-1),var(--dk-ai-2));box-shadow:0 1px 3px rgba(0,0,0,.2)}
190
+ .docxkeun-ai-ink{background:var(--docxkeun-ai-page);animation:docxkeun-ai-wipe var(--d) cubic-bezier(.45,.05,.55,.95) var(--t) both}
191
+ @keyframes docxkeun-ai-wipe{from{clip-path:inset(0 0 0 0)}to{clip-path:inset(0 0 0 100%)}}
192
+ .docxkeun-ai-glow{border-radius:2px;background:linear-gradient(90deg,color-mix(in srgb,var(--dk-ai-1) 26%,transparent),color-mix(in srgb,var(--dk-ai-2) 26%,transparent));mix-blend-mode:multiply;animation:docxkeun-ai-glow calc(var(--d) + 2.6s) ease-out var(--t) both}
193
+ @keyframes docxkeun-ai-glow{0%{clip-path:inset(0 100% 0 0);opacity:1}25%{clip-path:inset(0 0 0 0);opacity:1}to{clip-path:inset(0 0 0 0);opacity:0}}
194
+ .docxkeun-ai-pen{width:9px;height:9px;margin:-4px 0 0 -4px;background:radial-gradient(circle,#fff 0,var(--dk-ai-2) 35%,color-mix(in srgb,var(--dk-ai-1) 0%,transparent) 70%);border-radius:50%;animation:docxkeun-ai-pen var(--d) cubic-bezier(.45,.05,.55,.95) var(--t) both}
195
+ @keyframes docxkeun-ai-pen{from{transform:translateX(0);opacity:1}95%{opacity:1}to{transform:translateX(var(--w));opacity:0}}
196
+ .docxkeun-ai-ghost{font:12px/1.4 system-ui,sans-serif;color:#c5221f;text-decoration:line-through;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;background:rgba(252,232,230,.9);border-left:2px solid #c5221f;padding:1px 6px;border-radius:2px;animation:docxkeun-ai-ghost 2.2s ease-in both}
197
+ @keyframes docxkeun-ai-ghost{0%{opacity:0;transform:translateY(4px)}15%{opacity:1;transform:none}70%{opacity:.9;transform:translateY(-2px)}to{opacity:0;transform:translateY(-14px)}}
198
+ .docxkeun-ai-cut{width:2px;background:#c5221f;border-radius:1px;animation:docxkeun-ai-cut 1.8s ease-out both}
199
+ @keyframes docxkeun-ai-cut{0%{opacity:0;transform:scaleY(.2)}15%{opacity:1;transform:none}to{opacity:0}}
200
+ .docxkeun-ai-bar{width:3px;border-radius:2px;background:linear-gradient(var(--dk-ai-1),var(--dk-ai-2));pointer-events:auto;cursor:help;animation:docxkeun-ai-bar .5s ease-out both}
201
+ @keyframes docxkeun-ai-bar{from{transform:scaleY(0)}}
202
+ .docxkeun-ai-spark{width:12px;height:12px;margin:-6px 0 0 -5px;color:var(--dk-ai-2);font:12px/12px system-ui,sans-serif;text-align:center;animation:docxkeun-ai-spark 1.4s ease-out both}
203
+ @keyframes docxkeun-ai-spark{0%{transform:scale(0) rotate(-90deg);opacity:0}40%{transform:scale(1.5) rotate(0);opacity:1}to{transform:scale(1);opacity:.9}}
204
+ .docxkeun-ai-map{position:sticky;top:0;float:right;width:8px;margin-right:2px;z-index:6;pointer-events:none}
205
+ .docxkeun-ai-map i{position:absolute;right:0;width:8px;height:4px;border-radius:2px;background:linear-gradient(90deg,var(--dk-ai-1),var(--dk-ai-2));pointer-events:auto;cursor:pointer;opacity:.85}
206
+ .docxkeun-ai-map i:hover{opacity:1;height:6px}
207
+ @keyframes docxkeun-ai-fade{0%,40%{opacity:1}to{opacity:0}}
208
+ @media (prefers-reduced-motion:reduce){${still('')}}
209
+ ${still('.docxkeun-ai-still ')}`;
210
+ function ensureStyle() {
211
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID))
212
+ return;
213
+ const style = document.createElement('style');
214
+ style.id = STYLE_ID;
215
+ style.textContent = CSS;
216
+ document.head.appendChild(style);
217
+ }
218
+ /** Whether the browser accepts this as a colour (no check where `CSS.supports` is missing). */
219
+ function isCssColor(value) {
220
+ if (!value.trim())
221
+ return false;
222
+ // `CSS` is this module's style sheet; the browser's CSS namespace is on globalThis.
223
+ const css = globalThis.CSS;
224
+ return typeof css?.supports !== 'function' || css.supports('color', value);
225
+ }
226
+ /** sRGB channels (0-255) of a colour as the browser resolves it, when it can be read. */
227
+ function resolveRgb(color, host) {
228
+ const probe = document.createElement('span');
229
+ probe.style.color = color;
230
+ probe.style.display = 'none';
231
+ host.appendChild(probe);
232
+ const resolved = getComputedStyle(probe).color || probe.style.color || color;
233
+ probe.remove();
234
+ const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(resolved.trim());
235
+ if (hex) {
236
+ const h = hex[1].length === 3 ? [...hex[1]].map((d) => d + d).join('') : hex[1];
237
+ return [0, 2, 4].map((i) => parseInt(h.slice(i, i + 2), 16));
238
+ }
239
+ const rgb = /rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i.exec(resolved);
240
+ return rgb ? [Number(rgb[1]), Number(rgb[2]), Number(rgb[3])] : undefined;
241
+ }
242
+ function luminance([r, g, b]) {
243
+ const lin = (c) => {
244
+ const s = c / 255;
245
+ return s <= 0.03928 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;
246
+ };
247
+ return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b);
248
+ }
249
+ const DARK_TEXT = '#1f1f1f';
250
+ /**
251
+ * The caret label's text colour on `colors`: the default white (`undefined`) while it keeps a
252
+ * 3:1 contrast (WCAG's bar for bold UI text) on every colour, else `DARK_TEXT` when that reads
253
+ * better. White stays when a colour can't be read.
254
+ */
255
+ function labelText(colors, host) {
256
+ const lums = colors.map((c) => resolveRgb(c, host)).map((rgb) => (rgb ? luminance(rgb) : undefined));
257
+ if (lums.some((l) => l === undefined))
258
+ return undefined;
259
+ const darkL = luminance([31, 31, 31]);
260
+ const onWhite = Math.min(...lums.map((l) => 1.05 / (l + 0.05)));
261
+ const onDark = Math.min(...lums.map((l) => (l + 0.05) / (darkL + 0.05)));
262
+ return onWhite < 3 && onDark > onWhite ? DARK_TEXT : undefined;
263
+ }
264
+ const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
265
+ const nextFrame = () => new Promise((ok) => requestAnimationFrame(() => requestAnimationFrame(() => ok())));
266
+ /** The AI's presence on the pages: see the module comment. Get it from `viewer.activity`. */
267
+ export class AiActivity {
268
+ viewer;
269
+ aiName;
270
+ aiColor;
271
+ layer;
272
+ map;
273
+ caret;
274
+ label;
275
+ working;
276
+ shimmers = [];
277
+ marks = [];
278
+ markEls = [];
279
+ hideTimer;
280
+ cleanup = [];
281
+ on;
282
+ motion;
283
+ keepMarks;
284
+ constructor(viewer, options = {}) {
285
+ this.viewer = viewer;
286
+ ensureStyle();
287
+ this.aiName = options.name ?? 'Claude';
288
+ this.on = options.enabled ?? true;
289
+ this.motion = options.animate ?? true;
290
+ this.keepMarks = options.marks ?? true;
291
+ viewer.root.classList.toggle('docxkeun-ai-still', !this.motion);
292
+ const root = viewer.root;
293
+ this.map = document.createElement('div');
294
+ this.map.className = 'docxkeun-ai-map';
295
+ this.map.setAttribute('aria-hidden', 'true');
296
+ root.prepend(this.map);
297
+ this.layer = document.createElement('div');
298
+ this.layer.className = 'docxkeun-ai-layer';
299
+ root.appendChild(this.layer);
300
+ this.caret = document.createElement('div');
301
+ this.caret.className = 'docxkeun-ai-caret';
302
+ this.caret.style.opacity = '0';
303
+ this.label = document.createElement('span');
304
+ this.caret.appendChild(this.label);
305
+ this.layer.appendChild(this.caret);
306
+ if (options.color !== undefined)
307
+ this.color = options.color;
308
+ // Positions depend on the layout and zoom: redraw what lasts.
309
+ this.cleanup.push(viewer.on('layout', () => requestAnimationFrame(() => this.redraw())));
310
+ const onScroll = () => this.drawMap();
311
+ root.addEventListener('scroll', onScroll, { passive: true });
312
+ this.cleanup.push(() => root.removeEventListener('scroll', onScroll));
313
+ }
314
+ // ---- options ----
315
+ /** The name on the caret ("Claude is editing…") and in the change marks' tooltips. */
316
+ get name() {
317
+ return this.aiName;
318
+ }
319
+ set name(name) {
320
+ this.aiName = name;
321
+ this.label.textContent = this.working ? this.workingText(this.working) : name;
322
+ // The change marks' tooltips name the AI too.
323
+ if (this.marks.length)
324
+ this.drawMarks(false);
325
+ }
326
+ /**
327
+ * Colour of the caret, shimmer, glow and change marks: one CSS colour, or two for a gradient.
328
+ * `undefined` goes back to the defaults (or to the `--docxkeun-ai-color-1` / `-2` CSS
329
+ * variables when the page sets them). Throws a TypeError for something that isn't a CSS colour.
330
+ */
331
+ get color() {
332
+ return this.aiColor;
333
+ }
334
+ set color(value) {
335
+ const style = this.viewer.root.style;
336
+ if (value === undefined) {
337
+ this.aiColor = undefined;
338
+ for (const name of ['--docxkeun-ai-color-1', '--docxkeun-ai-color-2', '--docxkeun-ai-text'])
339
+ style.removeProperty(name);
340
+ return;
341
+ }
342
+ const [first, second] = typeof value === 'string' ? [value, value] : value;
343
+ for (const c of [first, second]) {
344
+ if (typeof c !== 'string' || !isCssColor(c))
345
+ throw new TypeError(`"${String(c)}" is not a CSS colour`);
346
+ }
347
+ this.aiColor = typeof value === 'string' ? value : [first, second];
348
+ style.setProperty('--docxkeun-ai-color-1', first);
349
+ style.setProperty('--docxkeun-ai-color-2', second);
350
+ // Keep the caret's label readable: dark text on light colours.
351
+ const text = labelText([first, second], this.viewer.root);
352
+ if (text)
353
+ style.setProperty('--docxkeun-ai-text', text);
354
+ else
355
+ style.removeProperty('--docxkeun-ai-text');
356
+ }
357
+ /** Show the AI's activity at all. Turning it off clears everything on screen. */
358
+ get enabled() {
359
+ return this.on;
360
+ }
361
+ set enabled(on) {
362
+ this.on = on;
363
+ if (on)
364
+ return;
365
+ this.working = undefined;
366
+ for (const el of [...this.layer.children])
367
+ if (el !== this.caret)
368
+ el.remove();
369
+ this.shimmers = [];
370
+ this.markEls = [];
371
+ this.marks = [];
372
+ this.caret.style.opacity = '0';
373
+ this.drawMap();
374
+ }
375
+ /** Motion (sweeps, ink, ghosts, gliding caret); off leaves static highlights. */
376
+ get animate() {
377
+ return this.motion;
378
+ }
379
+ set animate(on) {
380
+ this.motion = on;
381
+ this.viewer.root.classList.toggle('docxkeun-ai-still', !on);
382
+ }
383
+ /** Change bars and the change map after a change. */
384
+ get marksShown() {
385
+ return this.keepMarks;
386
+ }
387
+ set marksShown(on) {
388
+ this.keepMarks = on;
389
+ this.drawMarks(false);
390
+ }
391
+ // ---- geometry ----
392
+ paragraphs() {
393
+ const doc = this.viewer.document;
394
+ return doc ? paragraphsOf(doc.body().blocks) : [];
395
+ }
396
+ /** Where a page point is in the scroll container. */
397
+ at(page, x, y) {
398
+ const el = this.viewer.pageElement(page);
399
+ if (!el)
400
+ return undefined;
401
+ const s = this.viewer.scale;
402
+ return { left: el.offsetLeft + x * s, top: el.offsetTop + y * s };
403
+ }
404
+ lineRects(el) {
405
+ const out = [];
406
+ for (const page of this.viewer.layout?.pages ?? [])
407
+ for (const l of page.lines)
408
+ if (l.paragraph === el)
409
+ out.push({ page, x: l.x, y: l.y, w: l.w, h: l.h });
410
+ return out;
411
+ }
412
+ /** Rectangles (one per line piece) covering characters [from, to) of a paragraph. */
413
+ charRects(para, from, to) {
414
+ const starts = new Map();
415
+ for (const seg of paragraphText(para, { objects: true }).segments)
416
+ starts.set(seg.node, seg.start);
417
+ const out = [];
418
+ for (const page of this.viewer.layout?.pages ?? []) {
419
+ for (const item of page.items) {
420
+ if (item.type !== 'text' || !item.source)
421
+ continue;
422
+ const start = starts.get(item.source.inline.node);
423
+ if (start === undefined)
424
+ continue;
425
+ const t = item;
426
+ const isText = item.source.inline.node.name === 'w:t';
427
+ let run;
428
+ const flush = () => {
429
+ if (run)
430
+ out.push({ page, ...run });
431
+ run = undefined;
432
+ };
433
+ for (let i = 0; i < t.chars.length; i++) {
434
+ const off = start + (isText ? item.source.offsets[i] : 0);
435
+ if (off < from || off >= to) {
436
+ flush();
437
+ continue;
438
+ }
439
+ const top = t.y - t.font.ascent * t.size;
440
+ const h = (t.font.ascent + t.font.descent) * t.size;
441
+ const x = t.xs[i];
442
+ const w = t.widths[i];
443
+ if (run && Math.abs(run.x + run.w - x) < 1.5)
444
+ run.w = x + w - run.x;
445
+ else {
446
+ flush();
447
+ run = { x, y: top, w, h };
448
+ }
449
+ }
450
+ flush();
451
+ }
452
+ }
453
+ // Merge pieces on the same line (items split by formatting).
454
+ out.sort((a, b) => a.page.index - b.page.index || a.y - b.y || a.x - b.x);
455
+ const merged = [];
456
+ for (const r of out) {
457
+ const last = merged[merged.length - 1];
458
+ if (last && last.page === r.page && Math.abs(last.y - r.y) < 2 && r.x - (last.x + last.w) < 4) {
459
+ last.w = Math.max(last.w, r.x + r.w - last.x);
460
+ last.h = Math.max(last.h, r.h);
461
+ }
462
+ else
463
+ merged.push({ ...r });
464
+ }
465
+ return merged;
466
+ }
467
+ place(el, r, pad = 0) {
468
+ const p = this.at(r.page.index, r.x - pad, r.y - pad);
469
+ if (!p)
470
+ return false;
471
+ const s = this.viewer.scale;
472
+ el.style.left = `${p.left}px`;
473
+ el.style.top = `${p.top}px`;
474
+ el.style.width = `${(r.w + pad * 2) * s}px`;
475
+ el.style.height = `${(r.h + pad * 2) * s}px`;
476
+ return true;
477
+ }
478
+ /**
479
+ * Add an overlay. `life` (ms): remove it then (animation events are not dispatched reliably for
480
+ * pages in background tabs, so a timer does it); without it, it stays until redrawn.
481
+ */
482
+ add(className, r, pad = 0, vars = {}, life) {
483
+ const el = document.createElement('div');
484
+ el.className = className;
485
+ if (!this.place(el, r, pad))
486
+ return undefined;
487
+ for (const [k, v] of Object.entries(vars))
488
+ el.style.setProperty(k, v);
489
+ if (life !== undefined)
490
+ setTimeout(() => el.remove(), life + 100);
491
+ this.layer.appendChild(el);
492
+ return el;
493
+ }
494
+ // ---- working ----
495
+ /**
496
+ * Show the AI working on paragraphs (numbers from 1, as read_document counts them): a shimmer
497
+ * over them and its caret at the first. `mode: 'read'` sweeps a scan line over the view instead
498
+ * when no paragraphs are given. Lasts until `idle()` or `reveal()`.
499
+ */
500
+ work(paragraphs, options = {}) {
501
+ if (!this.on)
502
+ return;
503
+ const paras = [...new Set(paragraphs)].filter((n) => n >= 1).sort((a, b) => a - b);
504
+ this.working = { paras, mode: options.mode ?? 'edit', ...(options.label ? { label: options.label } : {}) };
505
+ clearTimeout(this.hideTimer);
506
+ this.drawWorking(options.scroll ?? true);
507
+ if (!paras.length && this.working.mode === 'read')
508
+ this.scan();
509
+ }
510
+ /** The AI finished (without a change to show). */
511
+ idle() {
512
+ if (!this.on)
513
+ return;
514
+ this.working = undefined;
515
+ for (const el of this.shimmers)
516
+ el.remove();
517
+ this.shimmers = [];
518
+ this.caret.classList.remove('working');
519
+ this.label.textContent = this.name;
520
+ clearTimeout(this.hideTimer);
521
+ this.hideTimer = setTimeout(() => (this.caret.style.opacity = '0'), 2500);
522
+ }
523
+ drawWorking(scroll) {
524
+ for (const el of this.shimmers)
525
+ el.remove();
526
+ this.shimmers = [];
527
+ const w = this.working;
528
+ if (!w)
529
+ return;
530
+ const all = this.paragraphs();
531
+ let first;
532
+ let line = 0;
533
+ for (const n of w.paras) {
534
+ const para = all[n - 1];
535
+ if (!para)
536
+ continue;
537
+ for (const r of this.lineRects(para.el)) {
538
+ first ??= r;
539
+ const el = this.add('docxkeun-ai-shimmer', r, 1.5);
540
+ if (el) {
541
+ // Ripple down the paragraph.
542
+ el.style.animationDelay = `${(line++ % 12) * 70}ms`;
543
+ this.shimmers.push(el);
544
+ }
545
+ }
546
+ }
547
+ this.label.textContent = this.workingText(w);
548
+ if (first) {
549
+ this.moveCaret(first.page, first.x, first.y, first.h, true);
550
+ if (scroll)
551
+ this.ensureVisible(first);
552
+ }
553
+ else if (w.mode === 'read')
554
+ this.parkCaret();
555
+ }
556
+ workingText(w) {
557
+ const verb = w.label ?? (w.mode === 'read' ? 'reading' : 'editing');
558
+ return `${this.aiName} is ${verb}…`;
559
+ }
560
+ moveCaret(page, x, y, h, working) {
561
+ const p = this.at(page.index, x, y);
562
+ if (!p)
563
+ return;
564
+ this.caret.style.left = `${p.left - 2}px`;
565
+ this.caret.style.top = `${p.top}px`;
566
+ this.caret.style.height = `${h * this.viewer.scale}px`;
567
+ this.caret.style.opacity = '1';
568
+ this.caret.classList.toggle('working', working);
569
+ }
570
+ /** The caret near the top of the view (reading the whole document). */
571
+ parkCaret() {
572
+ const root = this.viewer.root;
573
+ const page = (this.viewer.layout?.pages ?? []).find((pg) => {
574
+ const el = this.viewer.pageElement(pg.index);
575
+ return el && el.offsetTop + el.offsetHeight > root.scrollTop;
576
+ });
577
+ if (!page)
578
+ return;
579
+ const el = this.viewer.pageElement(page.index);
580
+ const y = Math.max(page.content.y, (root.scrollTop - el.offsetTop) / this.viewer.scale + 24);
581
+ this.moveCaret(page, page.content.x, y, 14, true);
582
+ }
583
+ scan() {
584
+ const root = this.viewer.root;
585
+ const el = document.createElement('div');
586
+ el.className = 'docxkeun-ai-scan';
587
+ const first = this.viewer.pageElement(0);
588
+ el.style.left = `${first ? first.offsetLeft : 0}px`;
589
+ el.style.width = `${first ? first.offsetWidth : root.clientWidth}px`;
590
+ el.style.top = `${root.scrollTop}px`;
591
+ el.style.setProperty('--travel', `${Math.max(0, root.clientHeight - 46)}px`);
592
+ setTimeout(() => el.remove(), 1400);
593
+ this.layer.appendChild(el);
594
+ }
595
+ ensureVisible(r) {
596
+ const p = this.at(r.page.index, r.x, r.y);
597
+ if (!p)
598
+ return;
599
+ const root = this.viewer.root;
600
+ const h = r.h * this.viewer.scale;
601
+ if (p.top < root.scrollTop + 40 || p.top + h > root.scrollTop + root.clientHeight - 40) {
602
+ root.scrollTo({ top: Math.max(0, p.top - root.clientHeight / 3), behavior: reducedMotion() ? 'auto' : 'smooth' });
603
+ }
604
+ }
605
+ // ---- changes ----
606
+ /** The body's paragraphs now (text and formatting): pass to `reveal()` after the document changed. */
607
+ snapshot() {
608
+ const paras = this.paragraphs();
609
+ return { texts: paras.map((p) => paragraphText(p, { objects: true }).text), formats: paras.map(formatSignature) };
610
+ }
611
+ /**
612
+ * Show what changed since `before` (from `snapshot()`), once the viewer has laid out the new
613
+ * version: ink, glow, ghosts and cuts now, change bars and the change map until the next change.
614
+ */
615
+ async reveal(before, options = {}) {
616
+ await nextFrame();
617
+ const paras = this.paragraphs();
618
+ const after = paras.map((p) => paragraphText(p, { objects: true }).text);
619
+ const old = Array.isArray(before) ? { texts: before, formats: [] } : before;
620
+ const diff = diffParagraphs(old.texts, after);
621
+ // Same text, other formatting (bold, a style, alignment, a list): the whole paragraph glows.
622
+ if (old.formats.length) {
623
+ for (const [o, n] of diff.same) {
624
+ if (old.formats[o] !== undefined && old.formats[o] !== formatSignature(paras[n]))
625
+ diff.changes.push({ para: n, kind: 'changed', ranges: [], cuts: [], formatting: true });
626
+ }
627
+ diff.changes.sort((x, y) => x.para - y.para);
628
+ }
629
+ if (!this.on)
630
+ return diff;
631
+ this.working = undefined;
632
+ for (const el of this.shimmers)
633
+ el.remove();
634
+ this.shimmers = [];
635
+ this.marks = diff.changes.map((c) => ({ para: c.para, ...(c.before !== undefined ? { before: c.before } : {}), ...(c.formatting ? { formatting: true } : {}) }));
636
+ this.drawMarks(true);
637
+ // Ink in the new text, line after line, as if written (about 2.5 s at most).
638
+ const pieces = [];
639
+ for (const c of diff.changes) {
640
+ const para = paras[c.para];
641
+ if (!para)
642
+ continue;
643
+ for (const [from, to] of c.ranges)
644
+ for (const r of this.charRects(para, from, to))
645
+ pieces.push({ r, para: c.para });
646
+ if (!c.ranges.length && !c.cuts.length)
647
+ for (const r of this.lineRects(para.el))
648
+ pieces.push({ r, para: c.para });
649
+ }
650
+ const total = pieces.reduce((s, p) => s + p.r.w, 0);
651
+ const speed = Math.max(500, total / 2.4); // points per second
652
+ let t = 0;
653
+ for (const { r } of pieces) {
654
+ const d = Math.min(900, Math.max(140, (r.w / speed) * 1000));
655
+ const vars = { '--d': `${d}ms`, '--t': `${t}ms`, '--w': `${r.w * this.viewer.scale}px` };
656
+ this.add('docxkeun-ai-glow', r, 1, vars, t + d + 2600);
657
+ this.add('docxkeun-ai-ink', r, 0.5, vars, t + d);
658
+ const pen = this.add('docxkeun-ai-pen', { ...r, w: 0, h: 0, y: r.y + r.h / 2 }, 0, vars, t + d);
659
+ if (pen)
660
+ pen.style.width = pen.style.height = '9px';
661
+ t += d * 0.85;
662
+ }
663
+ // Cuts: a red tick where words were removed.
664
+ for (const c of diff.changes) {
665
+ const para = paras[c.para];
666
+ if (!para)
667
+ continue;
668
+ for (const at of c.cuts) {
669
+ const r = this.charRects(para, Math.max(0, at - 1), at)[0] ?? this.charRects(para, at, at + 1)[0];
670
+ if (r)
671
+ this.add('docxkeun-ai-cut', { ...r, x: at > 0 ? r.x + r.w : r.x, w: 0 }, 1, {}, 1800);
672
+ }
673
+ }
674
+ // Removed paragraphs float away where they were.
675
+ for (const d of diff.deleted) {
676
+ const next = paras[d.at];
677
+ const line = next ? this.lineRects(next.el)[0] : undefined;
678
+ const prev = !line && d.at > 0 ? this.lineRects(paras[d.at - 1].el).pop() : undefined;
679
+ const r = line ?? (prev ? { ...prev, y: prev.y + prev.h } : undefined);
680
+ if (!r)
681
+ continue;
682
+ const el = this.add('docxkeun-ai-ghost', { ...r, y: r.y - 9, h: 16, w: Math.min(r.page.content.w, 360) }, 0, {}, 2200);
683
+ if (el) {
684
+ el.textContent = d.text.replace(//g, '').slice(0, 160) || '(empty paragraph)';
685
+ el.style.height = 'auto';
686
+ }
687
+ }
688
+ // The caret ends after the last change, then fades.
689
+ const lastChange = diff.changes[diff.changes.length - 1];
690
+ const end = lastChange ? (lastChange.ranges.length ? this.charRects(paras[lastChange.para], lastChange.ranges[lastChange.ranges.length - 1][0], lastChange.ranges[lastChange.ranges.length - 1][1]).pop() : this.lineRects(paras[lastChange.para].el).pop()) : undefined;
691
+ if (end) {
692
+ setTimeout(() => this.moveCaret(end.page, end.x + end.w, end.y, end.h, false), Math.min(t, 2400));
693
+ if (options.scroll ?? true) {
694
+ const firstChange = diff.changes[0];
695
+ const first = firstChange ? this.lineRects(paras[firstChange.para].el)[0] : undefined;
696
+ if (first)
697
+ this.ensureVisible(first);
698
+ }
699
+ }
700
+ this.caret.classList.remove('working');
701
+ this.label.textContent = this.name;
702
+ clearTimeout(this.hideTimer);
703
+ this.hideTimer = setTimeout(() => (this.caret.style.opacity = '0'), Math.min(t, 2400) + 2500);
704
+ return diff;
705
+ }
706
+ /** Remove the change bars and the change map. */
707
+ clearMarks() {
708
+ this.marks = [];
709
+ this.drawMarks(false);
710
+ }
711
+ drawMarks(animate) {
712
+ for (const el of this.markEls)
713
+ el.remove();
714
+ this.markEls = [];
715
+ const paras = this.paragraphs();
716
+ for (const m of this.keepMarks ? this.marks : []) {
717
+ const para = paras[m.para];
718
+ if (!para)
719
+ continue;
720
+ const lines = this.lineRects(para.el);
721
+ // One bar per page the paragraph is on, in the left margin.
722
+ const byPage = new Map();
723
+ for (const l of lines)
724
+ byPage.set(l.page, [...(byPage.get(l.page) ?? []), l]);
725
+ let firstBar = true;
726
+ for (const [page, ls] of byPage) {
727
+ const top = Math.min(...ls.map((l) => l.y));
728
+ const bottom = Math.max(...ls.map((l) => l.y + l.h));
729
+ const x = Math.max(4, page.content.x - 12);
730
+ const bar = this.add('docxkeun-ai-bar', { page, x, y: top, w: 3, h: bottom - top });
731
+ if (!bar)
732
+ continue;
733
+ if (!animate)
734
+ bar.style.animation = 'none';
735
+ bar.title = m.formatting
736
+ ? `Formatting changed by ${this.name}`
737
+ : m.before !== undefined
738
+ ? `Changed by ${this.name}. Before: ${m.before.replace(//g, '').slice(0, 300) || '(empty)'}`
739
+ : `Added by ${this.name}`;
740
+ this.markEls.push(bar);
741
+ if (firstBar && animate) {
742
+ const spark = this.add('docxkeun-ai-spark', { page, x: x + 1.5, y: top, w: 0, h: 0 });
743
+ if (spark) {
744
+ spark.textContent = '✦';
745
+ spark.style.width = spark.style.height = '12px';
746
+ this.markEls.push(spark);
747
+ }
748
+ }
749
+ firstBar = false;
750
+ }
751
+ }
752
+ this.drawMap();
753
+ }
754
+ /** Ticks on the right edge for every change, scaled to the scroll height; click to jump. */
755
+ drawMap() {
756
+ const root = this.viewer.root;
757
+ this.map.replaceChildren();
758
+ this.map.style.height = `${root.clientHeight}px`;
759
+ this.map.style.marginBottom = `-${root.clientHeight}px`;
760
+ if (!this.marks.length || !this.keepMarks)
761
+ return;
762
+ const paras = this.paragraphs();
763
+ const height = Math.max(root.scrollHeight, 1);
764
+ for (const m of this.marks) {
765
+ const para = paras[m.para];
766
+ const r = para ? this.lineRects(para.el)[0] : undefined;
767
+ const p = r && this.at(r.page.index, r.x, r.y);
768
+ if (!r || !p)
769
+ continue;
770
+ const tick = document.createElement('i');
771
+ tick.style.top = `${(p.top / height) * root.clientHeight}px`;
772
+ tick.title = `Changed by ${this.name}`;
773
+ tick.addEventListener('click', () => root.scrollTo({ top: Math.max(0, p.top - root.clientHeight / 3), behavior: reducedMotion() ? 'auto' : 'smooth' }));
774
+ this.map.appendChild(tick);
775
+ }
776
+ }
777
+ redraw() {
778
+ // Transient animations are tied to the old positions: drop them; redraw what lasts.
779
+ for (const el of [...this.layer.children]) {
780
+ if (el !== this.caret && !this.markEls.includes(el) && !this.shimmers.includes(el))
781
+ el.remove();
782
+ }
783
+ this.drawMarks(false);
784
+ if (this.working)
785
+ this.drawWorking(false);
786
+ }
787
+ destroy() {
788
+ for (const fn of this.cleanup)
789
+ fn();
790
+ clearTimeout(this.hideTimer);
791
+ this.layer.remove();
792
+ this.map.remove();
793
+ }
794
+ }