docxkeun 0.2.0 → 0.4.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.
@@ -9,6 +9,7 @@
9
9
  * Everything respects prefers-reduced-motion (static highlights instead of motion).
10
10
  */
11
11
  import { paragraphsOf, paragraphText } from '../api/editor.js';
12
+ import { serializeXml } from '../xml/index.js';
12
13
  /** Longest common subsequence pairs of two sequences (indices), with a size limit (then: none). */
13
14
  function lcs(a, b, eq, limit = 360_000) {
14
15
  const n = a.length;
@@ -140,7 +141,7 @@ export function diffParagraphs(before, after) {
140
141
  for (let i = k; i < match; i++)
141
142
  deleted.push({ at: para, text: oldGap[i] });
142
143
  const d = diffText(oldGap[match], text);
143
- changes.push({ para, kind: 'changed', ranges: d.ranges, cuts: d.cuts, before: oldGap[match] });
144
+ changes.push({ para, kind: 'changed', ranges: d.ranges, cuts: d.cuts, before: oldGap[match], from: p + ai + match });
144
145
  k = match + 1;
145
146
  }
146
147
  else {
@@ -157,9 +158,34 @@ export function diffParagraphs(before, after) {
157
158
  same.sort((x, y) => x[1] - y[1]);
158
159
  return { changes, deleted, same };
159
160
  }
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));
161
+ /** A short checksum of a string (FNV-1a), enough to tell a chart's XML before from after. */
162
+ function checksum(s) {
163
+ let h = 0x811c9dc5;
164
+ for (let i = 0; i < s.length; i++)
165
+ h = Math.imul(h ^ s.charCodeAt(i), 0x01000193);
166
+ return (h >>> 0).toString(36);
167
+ }
168
+ /** An object's size, place, wrap and alt text, a checksum of a chart's XML, and one of the text in a text box or shape. */
169
+ function imageSignature(i, doc) {
170
+ const chartPart = i.content?.type === 'chart' ? i.content.part : undefined;
171
+ const xml = chartPart && doc ? doc.xmlSync(chartPart) : undefined;
172
+ const chart = xml ? checksum(serializeXml(xml)) : '';
173
+ const text = i.content ? boxText(i.content, doc) : '';
174
+ return `image:${i.width},${i.height},${i.float ? JSON.stringify(i.float) : ''},${i.alt ?? ''},${chart},${text ? checksum(text) : ''}`;
175
+ }
176
+ /**
177
+ * The text and formatting of the paragraphs in a text box or shape (a group's, child by child),
178
+ * so a change inside a box marks the paragraph holding it.
179
+ */
180
+ function boxText(content, doc) {
181
+ if (content.type === 'shape') {
182
+ return content.shape.text ? paragraphsOf(content.shape.text.blocks).map((p) => `${paragraphText(p, { objects: true }).text}|${formatSignature(p, doc)}`).join('\n') : '';
183
+ }
184
+ return content.type === 'group' ? content.children.map((c) => boxText(c.content, doc)).join('\u0001') : '';
185
+ }
186
+ /** A paragraph's formatting as a string: style, alignment, list, each run's properties, and its objects. */
187
+ function formatSignature(p, doc) {
188
+ const runs = p.inlines.map((i) => (i.kind === 'text' ? JSON.stringify(i.props) : i.kind === 'image' ? imageSignature(i, doc) : i.kind));
163
189
  return `${p.styleId ?? ''}|${p.props.jc ?? ''}|${p.props.bidi ? 'rtl' : ''}|${p.numbering ? `${p.numbering.numId}.${p.numbering.ilvl}` : ''}|${runs.join(';')}`;
164
190
  }
165
191
  // ---- drawing ---------------------------------------------------------------------------------------
@@ -173,17 +199,43 @@ function still(prefix) {
173
199
  `${prefix}.docxkeun-ai-caret{transition:none;animation:none}`,
174
200
  `${prefix}.docxkeun-ai-ghost,${prefix}.docxkeun-ai-cut{animation:docxkeun-ai-fade 2.4s both}`,
175
201
  `${prefix}.docxkeun-ai-bar,${prefix}.docxkeun-ai-spark{animation:none}`,
202
+ // The other working styles, held still.
203
+ `${prefix}.docxkeun-ai-in,${prefix}.docxkeun-ai-flash{animation:none}`,
204
+ `${prefix}.docxkeun-ai-underline{animation:none;background-image:linear-gradient(90deg,var(--dk-ai-1),var(--dk-ai-2));background-size:100% 100%}`,
205
+ `${prefix}.docxkeun-ai-edge{animation:none;box-shadow:0 0 0 1.5px color-mix(in srgb,var(--dk-ai-1) 70%,transparent),0 0 10px color-mix(in srgb,var(--dk-ai-1) 30%,transparent)}`,
206
+ `${prefix}.docxkeun-ai-spot,${prefix}.docxkeun-ai-pulse,${prefix}.docxkeun-ai-intro{animation:none}`,
207
+ `${prefix}.docxkeun-ai-sparkle{animation:none;opacity:.75}`,
176
208
  ].join('\n');
177
209
  }
178
210
  const CSS = `
179
211
  .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}
212
+ .docxkeun-ai-layer{position:absolute;left:0;top:0;width:0;height:0;pointer-events:none}
181
213
  .docxkeun-ai-layer>*{position:absolute;pointer-events:none}
214
+ .docxkeun-ai-paint{position:absolute;left:0;top:0;width:0;height:0;overflow:hidden;pointer-events:none}
215
+ .docxkeun-ai-in{animation:docxkeun-ai-stop-in .9s ease-out var(--t,0ms) both}
216
+ @keyframes docxkeun-ai-stop-in{from{stop-color:var(--from)}}
217
+ .docxkeun-ai-flash{animation:docxkeun-ai-stop-flash 3.2s ease-in-out var(--t,0ms) both}
218
+ @keyframes docxkeun-ai-stop-flash{from,to{stop-color:var(--from)}20%,65%{stop-color:var(--to)}}
219
+ .docxkeun-ai-underline{border-radius:1px;background-color:color-mix(in srgb,var(--dk-ai-1) 18%,transparent);background-image:linear-gradient(90deg,transparent,var(--dk-ai-1),var(--dk-ai-2),transparent);background-size:35% 100%;background-repeat:no-repeat;animation:docxkeun-ai-wave 1.4s ease-in-out infinite}
220
+ @keyframes docxkeun-ai-wave{from{background-position:-40% 0}to{background-position:140% 0}}
221
+ .docxkeun-ai-edge{border-radius:6px;animation:docxkeun-ai-aura 2.2s ease-in-out infinite}
222
+ @keyframes docxkeun-ai-aura{0%,100%{box-shadow:0 0 0 1.5px color-mix(in srgb,var(--dk-ai-1) 70%,transparent),0 0 12px color-mix(in srgb,var(--dk-ai-1) 35%,transparent)}50%{box-shadow:0 0 0 1.5px color-mix(in srgb,var(--dk-ai-2) 70%,transparent),0 0 16px color-mix(in srgb,var(--dk-ai-2) 40%,transparent)}}
223
+ .docxkeun-ai-spot{border-radius:4px;box-shadow:0 0 0 4000px rgba(255,255,255,.55);animation:docxkeun-ai-in .4s ease-out both}
224
+ .docxkeun-ai-pulse{width:3px;border-radius:2px;background:linear-gradient(var(--dk-ai-1),var(--dk-ai-2));animation:docxkeun-ai-pulse 1.2s ease-in-out infinite}
225
+ @keyframes docxkeun-ai-pulse{0%,100%{opacity:.35;transform:scaleY(.85)}50%{opacity:1;transform:none}}
226
+ .docxkeun-ai-sparkle{width:12px;height:12px;margin:-6px 0 0 -6px;font:11px/12px system-ui,sans-serif;text-align:center;animation:docxkeun-ai-float 2.4s ease-in-out var(--t) infinite both}
227
+ @keyframes docxkeun-ai-float{0%{opacity:0;transform:translateY(4px) scale(.4) rotate(-40deg)}30%{opacity:1;transform:translateY(-2px) scale(1)}to{opacity:0;transform:translateY(-14px) scale(.6) rotate(40deg)}}
228
+ .docxkeun-ai-mark-tint{border-radius:3px;background:linear-gradient(90deg,color-mix(in srgb,var(--dk-ai-1) 14%,transparent),color-mix(in srgb,var(--dk-ai-2) 14%,transparent));mix-blend-mode:multiply}
229
+ .docxkeun-ai-mark-underline{border-radius:1px;background:linear-gradient(90deg,var(--dk-ai-1),var(--dk-ai-2))}
230
+ .docxkeun-ai-intro{animation:docxkeun-ai-in .9s ease-out var(--t,0ms) both}
231
+ .docxkeun-ai-mark-underline.docxkeun-ai-intro{transform-origin:left;animation-name:docxkeun-ai-draw}
232
+ @keyframes docxkeun-ai-in{from{opacity:0}}
233
+ @keyframes docxkeun-ai-draw{from{transform:scaleX(0)}}
182
234
  .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
235
  @keyframes docxkeun-ai-shimmer{from{background-position:100% 0}to{background-position:0 0}}
184
236
  .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
237
  @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)}
238
+ .docxkeun-ai-caret{z-index:2;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
239
  .docxkeun-ai-caret.working{animation:docxkeun-ai-blink 1s steps(2,jump-none) infinite}
188
240
  @keyframes docxkeun-ai-blink{50%{opacity:.35}}
189
241
  .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)}
@@ -261,13 +313,152 @@ function labelText(colors, host) {
261
313
  const onDark = Math.min(...lums.map((l) => (l + 0.05) / (darkL + 0.05)));
262
314
  return onWhite < 3 && onDark > onWhite ? DARK_TEXT : undefined;
263
315
  }
316
+ /** The bounding box of some lines on each page they are on. */
317
+ function boxesByPage(lines) {
318
+ const byPage = new Map();
319
+ for (const l of lines)
320
+ byPage.set(l.page, [...(byPage.get(l.page) ?? []), l]);
321
+ return [...byPage].map(([page, ls]) => {
322
+ const x = Math.min(...ls.map((l) => l.x));
323
+ const y = Math.min(...ls.map((l) => l.y));
324
+ return { page, x, y, w: Math.max(...ls.map((l) => l.x + l.w)) - x, h: Math.max(...ls.map((l) => l.y + l.h)) - y };
325
+ });
326
+ }
327
+ /** A fixed, even-looking spread in [0.1, 0.9) for the i-th item (no randomness: redraws match). */
328
+ function spread(i, axis) {
329
+ const golden = axis === 1 ? 0.6180339887 : 0.7548776662;
330
+ return 0.1 + (((i + 1) * golden) % 1) * 0.8;
331
+ }
264
332
  const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
265
333
  const nextFrame = () => new Promise((ok) => requestAnimationFrame(() => requestAnimationFrame(() => ok())));
334
+ // ---- painting the letters ------------------------------------------------------------------------
335
+ const SVG_NS = 'http://www.w3.org/2000/svg';
336
+ let paintScopes = 0;
337
+ let paintLayers = 0;
338
+ /** A text item's colour as the page draws it (see svg.ts). */
339
+ const inkOf = (t) => (/^[0-9a-f]{6}$/i.test(t.color) ? `#${t.color}` : '#000');
340
+ const offset = (v) => String(Math.round(Math.min(1, Math.max(0, v)) * 10000) / 10000);
341
+ /** A gradient stop; `var(...)` colours go in a style so the custom property resolves. */
342
+ function stop(at, color, extra = {}) {
343
+ const style = [...(color.startsWith('var(') ? [`stop-color:${color}`] : []), ...Object.entries(extra.vars ?? {}).map(([k, v]) => `${k}:${v}`)].join(';');
344
+ return `<stop offset="${offset(at)}"${color.startsWith('var(') ? '' : ` stop-color="${color}"`}${extra.cls ? ` class="${extra.cls}"` : ''}${style ? ` style="${style}"` : ''}/>`;
345
+ }
346
+ /**
347
+ * Colours chosen letters on the pages with SVG gradients: a style sheet points their <text>
348
+ * elements at gradients defined beside it. Only the glyphs change, never the paper, shading,
349
+ * highlights or pictures behind them, and pages drawn later (scrolling) pick the rules up too.
350
+ */
351
+ class GlyphPaint {
352
+ sheet;
353
+ defs;
354
+ scope;
355
+ id;
356
+ constructor(root, name) {
357
+ this.scope = root.getAttribute('data-docxkeun-ai') ?? String(++paintScopes);
358
+ root.setAttribute('data-docxkeun-ai', this.scope);
359
+ this.id = `docxkeun-ai-${this.scope}-${name}-${++paintLayers}`;
360
+ this.sheet = document.createElement('style');
361
+ this.sheet.setAttribute('data-docxkeun-ai-paint', name);
362
+ this.defs = document.createElementNS(SVG_NS, 'svg');
363
+ this.defs.setAttribute('class', 'docxkeun-ai-paint');
364
+ this.defs.setAttribute('aria-hidden', 'true');
365
+ this.defs.setAttribute('data-paint', name);
366
+ root.append(this.sheet, this.defs);
367
+ }
368
+ paint(groups) {
369
+ const rules = [];
370
+ const defs = [];
371
+ groups.forEach((g, k) => {
372
+ if (!g.glyphs.length)
373
+ return;
374
+ const id = `${this.id}-${k}`;
375
+ defs.push(g.gradient(id));
376
+ const sel = (x) => `[data-docxkeun-ai="${this.scope}"] .docxkeun-page[data-page="${x.page.index}"] svg>text[data-i="${x.index}"]`;
377
+ rules.push(`${g.glyphs.map(sel).join(',')}{fill:url(#${id})}`);
378
+ // Synthetic bold strokes the outline in the text colour: it takes the gradient too.
379
+ const stroked = g.glyphs.filter((x) => x.item.font.syntheticBold);
380
+ if (stroked.length)
381
+ rules.push(`${stroked.map(sel).join(',')}{stroke:url(#${id})}`);
382
+ });
383
+ this.defs.innerHTML = defs.join('');
384
+ this.sheet.textContent = rules.join('\n');
385
+ }
386
+ clear() {
387
+ if (this.sheet.textContent)
388
+ this.sheet.textContent = '';
389
+ if (this.defs.firstChild)
390
+ this.defs.replaceChildren();
391
+ }
392
+ remove() {
393
+ this.sheet.remove();
394
+ this.defs.remove();
395
+ }
396
+ }
397
+ /**
398
+ * The working shimmer: the letters keep their own colour (`ink`) and a band of the AI's colours
399
+ * sweeps across the page, slightly slanted so lower lines follow on. `width`: the widest page.
400
+ */
401
+ function sweepGradient(id, ink, width) {
402
+ return (`<linearGradient id="${id}" class="docxkeun-ai-words" gradientUnits="userSpaceOnUse" x1="-400" y1="-60" x2="400" y2="60">` +
403
+ stop(0, ink) +
404
+ stop(0.3, ink) +
405
+ stop(0.44, 'var(--dk-ai-1)') +
406
+ stop(0.56, 'var(--dk-ai-2)') +
407
+ stop(0.7, ink) +
408
+ stop(1, ink) +
409
+ `<animateTransform attributeName="gradientTransform" type="translate" values="-220 0;${Math.round(width + 220)} 0" dur="2s" repeatCount="indefinite"/>` +
410
+ `</linearGradient>`);
411
+ }
412
+ /** The shimmer held still (no motion): the letters take the AI's colours across the page. */
413
+ function stillGradient(id, width) {
414
+ return `<linearGradient id="${id}" class="docxkeun-ai-words" gradientUnits="userSpaceOnUse" x1="0" y1="0" x2="${Math.round(width)}" y2="0">${stop(0, 'var(--dk-ai-1)')}${stop(1, 'var(--dk-ai-2)')}</linearGradient>`;
415
+ }
416
+ /**
417
+ * Changed words in the AI's colours and the rest of the item in its own: hard stops at the
418
+ * edges of each span. `cls` animates the coloured stops from the ink (`docxkeun-ai-in` fades
419
+ * them in, `docxkeun-ai-flash` in and out again), starting after `delay`.
420
+ */
421
+ function spanGradient(id, kind, g, cls, delay = '0ms') {
422
+ const t = g.item;
423
+ const ink = inkOf(t);
424
+ const lefts = t.xs;
425
+ const rights = t.xs.map((x, i) => x + (t.widths[i] ?? 0));
426
+ const left = Math.min(...lefts);
427
+ const right = Math.max(...rights, left + 0.01);
428
+ const at = (x) => (x - left) / (right - left);
429
+ const colour = (c) => (cls ? { cls, vars: { '--from': ink, '--to': c, '--t': delay } } : {});
430
+ const stops = [];
431
+ for (const [from, to] of g.spans) {
432
+ const a = at(lefts[from]);
433
+ const b = at(rights[to - 1]);
434
+ // A span at the item's edge runs on past it (pad), so overhanging glyph ink is coloured too.
435
+ if (from > 0)
436
+ stops.push(stop(a, ink));
437
+ stops.push(stop(a, 'var(--dk-ai-1)', colour('var(--dk-ai-1)')), stop(b, 'var(--dk-ai-2)', colour('var(--dk-ai-2)')));
438
+ if (to < t.chars.length)
439
+ stops.push(stop(b, ink));
440
+ }
441
+ return `<linearGradient id="${id}" class="${kind}" gradientUnits="userSpaceOnUse" x1="${left}" y1="0" x2="${right}" y2="0">${stops.join('')}</linearGradient>`;
442
+ }
443
+ /** The styles, with a label and a line to show in a picker, in the order to show them. */
444
+ export const ACTIVITY_STYLES = [
445
+ { style: 'highlight', label: 'Highlight band', description: 'A tinted band sweeps over the lines; the changed paragraph keeps a soft tint.' },
446
+ { style: 'words', label: 'Word shimmer', description: 'The letters themselves shimmer; the changed words stay coloured.' },
447
+ { style: 'underline', label: 'Underline wave', description: 'A streak runs under each line; the changed words stay underlined.' },
448
+ { style: 'edge', label: 'Edge glow', description: 'A soft glow breathes around the paragraph.' },
449
+ { style: 'spotlight', label: 'Spotlight', description: 'The rest of the page dims while the paragraph is changed.' },
450
+ { style: 'quiet', label: 'Quiet', description: 'Only the named caret and a pulsing bar in the margin.' },
451
+ { style: 'sparkles', label: 'Sparkles', description: 'Small ✦ drift over the paragraph.' },
452
+ ];
453
+ /** Styles whose own mark stays on the changed text; the others leave the ✦ margin bar. */
454
+ const OWN_MARK = new Set(['highlight', 'words', 'underline']);
455
+ const isStyle = (value) => ACTIVITY_STYLES.some((s) => s.style === value);
266
456
  /** The AI's presence on the pages: see the module comment. Get it from `viewer.activity`. */
267
457
  export class AiActivity {
268
458
  viewer;
269
459
  aiName;
270
460
  aiColor;
461
+ aiStyle = 'highlight';
271
462
  layer;
272
463
  map;
273
464
  caret;
@@ -276,6 +467,11 @@ export class AiActivity {
276
467
  shimmers = [];
277
468
  marks = [];
278
469
  markEls = [];
470
+ /** Letters coloured by the marks, the passing flash of a change, and the working shimmer (later wins). */
471
+ markPaint;
472
+ flashPaint;
473
+ workPaint;
474
+ flashTimer;
279
475
  hideTimer;
280
476
  cleanup = [];
281
477
  on;
@@ -303,8 +499,13 @@ export class AiActivity {
303
499
  this.label = document.createElement('span');
304
500
  this.caret.appendChild(this.label);
305
501
  this.layer.appendChild(this.caret);
502
+ this.markPaint = new GlyphPaint(root, 'marks');
503
+ this.flashPaint = new GlyphPaint(root, 'flash');
504
+ this.workPaint = new GlyphPaint(root, 'work');
306
505
  if (options.color !== undefined)
307
506
  this.color = options.color;
507
+ if (options.style !== undefined)
508
+ this.style = options.style;
308
509
  // Positions depend on the layout and zoom: redraw what lasts.
309
510
  this.cleanup.push(viewer.on('layout', () => requestAnimationFrame(() => this.redraw())));
310
511
  const onScroll = () => this.drawMap();
@@ -321,7 +522,7 @@ export class AiActivity {
321
522
  this.label.textContent = this.working ? this.workingText(this.working) : name;
322
523
  // The change marks' tooltips name the AI too.
323
524
  if (this.marks.length)
324
- this.drawMarks(false);
525
+ this.drawMarks();
325
526
  }
326
527
  /**
327
528
  * Colour of the caret, shimmer, glow and change marks: one CSS colour, or two for a gradient.
@@ -354,6 +555,22 @@ export class AiActivity {
354
555
  else
355
556
  style.removeProperty('--docxkeun-ai-text');
356
557
  }
558
+ /**
559
+ * How the AI's work shows, and so which mark stays after a change (see `ActivityOptions.style`).
560
+ * Changing it redraws the work in progress and the marks. Throws a TypeError for an unknown style.
561
+ */
562
+ get style() {
563
+ return this.aiStyle;
564
+ }
565
+ set style(style) {
566
+ if (!isStyle(style))
567
+ throw new TypeError(`Unknown AI effect style "${String(style)}" (use ${ACTIVITY_STYLES.map((s) => s.style).join(', ')})`);
568
+ this.aiStyle = style;
569
+ if (this.working)
570
+ this.drawWorking(false);
571
+ if (this.marks.length)
572
+ this.drawMarks();
573
+ }
357
574
  /** Show the AI's activity at all. Turning it off clears everything on screen. */
358
575
  get enabled() {
359
576
  return this.on;
@@ -369,6 +586,8 @@ export class AiActivity {
369
586
  this.shimmers = [];
370
587
  this.markEls = [];
371
588
  this.marks = [];
589
+ for (const paint of [this.workPaint, this.markPaint, this.flashPaint])
590
+ paint.clear();
372
591
  this.caret.style.opacity = '0';
373
592
  this.drawMap();
374
593
  }
@@ -379,6 +598,9 @@ export class AiActivity {
379
598
  set animate(on) {
380
599
  this.motion = on;
381
600
  this.viewer.root.classList.toggle('docxkeun-ai-still', !on);
601
+ // The word shimmer's sweep is an SVG animation, which the still style sheet cannot stop.
602
+ if (this.working && this.aiStyle === 'words')
603
+ this.drawWorking(false);
382
604
  }
383
605
  /** Change bars and the change map after a change. */
384
606
  get marksShown() {
@@ -386,7 +608,7 @@ export class AiActivity {
386
608
  }
387
609
  set marksShown(on) {
388
610
  this.keepMarks = on;
389
- this.drawMarks(false);
611
+ this.drawMarks();
390
612
  }
391
613
  // ---- geometry ----
392
614
  paragraphs() {
@@ -464,6 +686,67 @@ export class AiActivity {
464
686
  }
465
687
  return merged;
466
688
  }
689
+ /**
690
+ * A paragraph's text items, with the characters in `ranges` (all of them, list labels too, when
691
+ * `ranges` is omitted). Items of other paragraphs on the same lines (table cells) are left out.
692
+ */
693
+ glyphs(para, ranges) {
694
+ const starts = new Map();
695
+ for (const seg of paragraphText(para, { objects: true }).segments)
696
+ starts.set(seg.node, seg.start);
697
+ const out = [];
698
+ for (const page of this.viewer.layout?.pages ?? []) {
699
+ const lines = page.lines.filter((l) => l.paragraph === para.el);
700
+ if (!lines.length)
701
+ continue;
702
+ page.items.forEach((item, index) => {
703
+ if (item.type !== 'text' || !item.chars.length)
704
+ return;
705
+ const t = item;
706
+ if (!t.source) {
707
+ // A list label or a field result: no source, so take it when it sits on one of the lines.
708
+ if (!ranges && lines.some((l) => t.y >= l.y && t.y <= l.y + l.h && t.x >= l.x - 72 && t.x < l.x + l.w))
709
+ out.push({ page, index, item: t, spans: [[0, t.chars.length]] });
710
+ return;
711
+ }
712
+ const start = starts.get(t.source.inline.node);
713
+ if (start === undefined)
714
+ return;
715
+ if (!ranges) {
716
+ out.push({ page, index, item: t, spans: [[0, t.chars.length]] });
717
+ return;
718
+ }
719
+ const isText = t.source.inline.node.name === 'w:t';
720
+ const spans = [];
721
+ for (let i = 0; i < t.chars.length; i++) {
722
+ const off = start + (isText ? t.source.offsets[i] : 0);
723
+ if (!ranges.some(([from, to]) => off >= from && off < to))
724
+ continue;
725
+ const last = spans[spans.length - 1];
726
+ if (last && last[1] === i)
727
+ last[1] = i + 1;
728
+ else
729
+ spans.push([i, i + 1]);
730
+ }
731
+ if (spans.length)
732
+ out.push({ page, index, item: t, spans });
733
+ });
734
+ }
735
+ return out;
736
+ }
737
+ /** The working shimmer on the paragraphs' letters: one gradient per text colour. */
738
+ shimmerPaint(paras) {
739
+ const still = !this.motion || reducedMotion();
740
+ const width = Math.max(612, ...(this.viewer.layout?.pages ?? []).map((p) => p.width));
741
+ const byInk = new Map();
742
+ for (const para of paras) {
743
+ for (const g of this.glyphs(para)) {
744
+ const key = still ? '' : inkOf(g.item);
745
+ byInk.set(key, [...(byInk.get(key) ?? []), g]);
746
+ }
747
+ }
748
+ return [...byInk].map(([ink, glyphs]) => ({ glyphs, gradient: (id) => (still ? stillGradient(id, width) : sweepGradient(id, ink, width)) }));
749
+ }
467
750
  place(el, r, pad = 0) {
468
751
  const p = this.at(r.page.index, r.x - pad, r.y - pad);
469
752
  if (!p)
@@ -512,38 +795,29 @@ export class AiActivity {
512
795
  if (!this.on)
513
796
  return;
514
797
  this.working = undefined;
515
- for (const el of this.shimmers)
516
- el.remove();
517
- this.shimmers = [];
798
+ this.clearWorking();
518
799
  this.caret.classList.remove('working');
519
800
  this.label.textContent = this.name;
520
801
  clearTimeout(this.hideTimer);
521
802
  this.hideTimer = setTimeout(() => (this.caret.style.opacity = '0'), 2500);
522
803
  }
523
- drawWorking(scroll) {
804
+ clearWorking() {
524
805
  for (const el of this.shimmers)
525
806
  el.remove();
526
807
  this.shimmers = [];
808
+ this.workPaint.clear();
809
+ }
810
+ drawWorking(scroll) {
811
+ this.clearWorking();
527
812
  const w = this.working;
528
813
  if (!w)
529
814
  return;
530
815
  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
- }
816
+ const paras = w.paras.map((n) => all[n - 1]).filter((p) => !!p);
817
+ // The lines of each paragraph being worked on.
818
+ const groups = paras.map((p) => this.lineRects(p.el));
819
+ const first = groups.flat()[0];
820
+ this.drawStyle(groups, first, paras);
547
821
  this.label.textContent = this.workingText(w);
548
822
  if (first) {
549
823
  this.moveCaret(first.page, first.x, first.y, first.h, true);
@@ -553,6 +827,68 @@ export class AiActivity {
553
827
  else if (w.mode === 'read')
554
828
  this.parkCaret();
555
829
  }
830
+ /** The working effect of the current style over each paragraph's lines. */
831
+ drawStyle(groups, first, paras) {
832
+ const keep = (el) => {
833
+ if (el)
834
+ this.shimmers.push(el);
835
+ return el;
836
+ };
837
+ // Ripple down the lines.
838
+ let line = 0;
839
+ const ripple = (el) => {
840
+ if (el)
841
+ el.style.animationDelay = `${(line++ % 12) * 70}ms`;
842
+ };
843
+ const lines = groups.flat();
844
+ switch (this.aiStyle) {
845
+ case 'highlight':
846
+ for (const r of lines)
847
+ ripple(keep(this.add('docxkeun-ai-shimmer', r, 1.5)));
848
+ break;
849
+ case 'words':
850
+ // The letters themselves take the colours; the paper, shading and pictures stay as they are.
851
+ this.workPaint.paint(this.shimmerPaint(paras));
852
+ break;
853
+ case 'underline':
854
+ for (const r of lines)
855
+ ripple(keep(this.add('docxkeun-ai-underline', { ...r, y: r.y + r.h - 0.4, h: 1.6 })));
856
+ break;
857
+ case 'edge':
858
+ for (const g of groups)
859
+ for (const box of boxesByPage(g))
860
+ keep(this.add('docxkeun-ai-edge', box, 3));
861
+ break;
862
+ case 'spotlight': {
863
+ // One clear window around the lines on the caret's page; the rest of the view dims.
864
+ const box = first ? boxesByPage(lines).find((b) => b.page === first.page) : undefined;
865
+ if (box)
866
+ keep(this.add('docxkeun-ai-spot', box, 4));
867
+ break;
868
+ }
869
+ case 'quiet':
870
+ for (const g of groups) {
871
+ for (const box of boxesByPage(g))
872
+ keep(this.add('docxkeun-ai-pulse', { page: box.page, x: Math.max(4, box.page.content.x - 12), y: box.y, w: 3, h: box.h }));
873
+ }
874
+ break;
875
+ case 'sparkles': {
876
+ let i = 0;
877
+ for (const r of lines) {
878
+ for (let k = 0, n = Math.min(6, Math.max(1, Math.round(r.w / 70))); k < n && i < 40; k++, i++) {
879
+ const el = keep(this.add('docxkeun-ai-sparkle', { page: r.page, x: r.x + spread(i, 1) * r.w, y: r.y + spread(i, 2) * r.h, w: 0, h: 0 }));
880
+ if (!el)
881
+ continue;
882
+ el.textContent = '✦';
883
+ el.style.width = el.style.height = '12px';
884
+ el.style.color = i % 2 ? 'var(--dk-ai-1)' : 'var(--dk-ai-2)';
885
+ el.style.setProperty('--t', `${(i * 370) % 2400}ms`);
886
+ }
887
+ }
888
+ break;
889
+ }
890
+ }
891
+ }
556
892
  workingText(w) {
557
893
  const verb = w.label ?? (w.mode === 'read' ? 'reading' : 'editing');
558
894
  return `${this.aiName} is ${verb}…`;
@@ -606,7 +942,7 @@ export class AiActivity {
606
942
  /** The body's paragraphs now (text and formatting): pass to `reveal()` after the document changed. */
607
943
  snapshot() {
608
944
  const paras = this.paragraphs();
609
- return { texts: paras.map((p) => paragraphText(p, { objects: true }).text), formats: paras.map(formatSignature) };
945
+ return { texts: paras.map((p) => paragraphText(p, { objects: true }).text), formats: paras.map((p) => formatSignature(p, this.viewer.document)) };
610
946
  }
611
947
  /**
612
948
  * Show what changed since `before` (from `snapshot()`), once the viewer has laid out the new
@@ -621,19 +957,23 @@ export class AiActivity {
621
957
  // Same text, other formatting (bold, a style, alignment, a list): the whole paragraph glows.
622
958
  if (old.formats.length) {
623
959
  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 });
960
+ if (old.formats[o] !== undefined && old.formats[o] !== formatSignature(paras[n], this.viewer.document))
961
+ diff.changes.push({ para: n, kind: 'changed', ranges: [], cuts: [], formatting: true, before: old.texts[o], from: o });
626
962
  }
627
963
  diff.changes.sort((x, y) => x.para - y.para);
628
964
  }
629
965
  if (!this.on)
630
966
  return diff;
631
967
  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);
968
+ this.clearWorking();
969
+ // The marks of earlier changes stay (following their paragraphs); this change's join them.
970
+ this.marks = this.mergeMarks(diff, after);
971
+ this.drawMarks(new Set(diff.changes.map((c) => c.para)));
972
+ // A style with its own mark lets the mark fade in; the others get the passing glow. The word
973
+ // shimmer never tints the paper: without marks, the changed letters light up for a moment.
974
+ const glow = !(OWN_MARK.has(this.aiStyle) && this.keepMarks) && this.aiStyle !== 'words';
975
+ if (this.aiStyle === 'words' && !this.keepMarks)
976
+ this.flash(diff, paras);
637
977
  // Ink in the new text, line after line, as if written (about 2.5 s at most).
638
978
  const pieces = [];
639
979
  for (const c of diff.changes) {
@@ -653,7 +993,8 @@ export class AiActivity {
653
993
  for (const { r } of pieces) {
654
994
  const d = Math.min(900, Math.max(140, (r.w / speed) * 1000));
655
995
  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);
996
+ if (glow)
997
+ this.add('docxkeun-ai-glow', r, 1, vars, t + d + 2600);
657
998
  this.add('docxkeun-ai-ink', r, 0.5, vars, t + d);
658
999
  const pen = this.add('docxkeun-ai-pen', { ...r, w: 0, h: 0, y: r.y + r.h / 2 }, 0, vars, t + d);
659
1000
  if (pen)
@@ -703,21 +1044,107 @@ export class AiActivity {
703
1044
  this.hideTimer = setTimeout(() => (this.caret.style.opacity = '0'), Math.min(t, 2400) + 2500);
704
1045
  return diff;
705
1046
  }
706
- /** Remove the change bars and the change map. */
1047
+ /**
1048
+ * Remove every mark and the change map. Marks build up over a run of changes (each follows its
1049
+ * paragraph as others are added or removed) until this is called, e.g. when a new request starts.
1050
+ */
707
1051
  clearMarks() {
708
1052
  this.marks = [];
709
- this.drawMarks(false);
1053
+ this.drawMarks();
1054
+ }
1055
+ /**
1056
+ * The marks after a change: earlier marks follow their paragraphs (and go with deleted ones), a
1057
+ * paragraph changed again is marked against its text before the first change, and new ones join.
1058
+ */
1059
+ mergeMarks(diff, after) {
1060
+ const earlier = new Map(this.marks.map((m) => [m.para, m]));
1061
+ const out = new Map();
1062
+ for (const [o, n] of diff.same) {
1063
+ const m = earlier.get(o);
1064
+ if (m)
1065
+ out.set(n, { ...m, para: n });
1066
+ }
1067
+ for (const c of diff.changes) {
1068
+ const prev = c.from !== undefined ? earlier.get(c.from) : undefined;
1069
+ if (!prev) {
1070
+ out.set(c.para, { para: c.para, ranges: c.ranges, ...(c.before !== undefined ? { before: c.before } : {}), ...(c.formatting ? { formatting: true } : {}) });
1071
+ continue;
1072
+ }
1073
+ const text = after[c.para] ?? '';
1074
+ const formatting = !!(prev.formatting || c.formatting);
1075
+ // A paragraph the AI added stays added; otherwise compare with the text before the first change.
1076
+ const d = prev.before === undefined ? { ranges: text ? [[0, text.length]] : [], cuts: [] } : diffText(prev.before, text);
1077
+ if (!d.ranges.length && !d.cuts.length && !formatting) {
1078
+ // Changed back to how it was: no mark.
1079
+ out.delete(c.para);
1080
+ continue;
1081
+ }
1082
+ out.set(c.para, { para: c.para, ranges: d.ranges, ...(prev.before !== undefined ? { before: prev.before } : {}), ...(formatting ? { formatting: true } : {}) });
1083
+ }
1084
+ return [...out.values()].sort((a, b) => a.para - b.para);
1085
+ }
1086
+ /** What a mark's tooltip says. */
1087
+ markTitle(m) {
1088
+ if (m.formatting && !m.ranges.length)
1089
+ return `Formatting changed by ${this.name}`;
1090
+ if (m.before !== undefined)
1091
+ return `Changed by ${this.name}. Before: ${m.before.replace(//g, '').slice(0, 300) || '(empty)'}`;
1092
+ return `Added by ${this.name}`;
710
1093
  }
711
- drawMarks(animate) {
1094
+ /** Draw the marks; those of the paragraphs in `fresh` (just changed) appear with a short animation. */
1095
+ drawMarks(fresh = new Set()) {
712
1096
  for (const el of this.markEls)
713
1097
  el.remove();
714
1098
  this.markEls = [];
715
1099
  const paras = this.paragraphs();
1100
+ const painted = [];
1101
+ let n = 0;
1102
+ let animate = false;
1103
+ // Marks of the style's own kind fade (or draw) in one after another.
1104
+ const intro = (el) => {
1105
+ if (!el)
1106
+ return;
1107
+ if (animate) {
1108
+ el.classList.add('docxkeun-ai-intro');
1109
+ el.style.setProperty('--t', `${Math.min(n++ * 90, 1500)}ms`);
1110
+ }
1111
+ this.markEls.push(el);
1112
+ };
716
1113
  for (const m of this.keepMarks ? this.marks : []) {
1114
+ animate = fresh.has(m.para);
717
1115
  const para = paras[m.para];
718
1116
  if (!para)
719
1117
  continue;
720
1118
  const lines = this.lineRects(para.el);
1119
+ const style = this.aiStyle;
1120
+ if (style === 'highlight') {
1121
+ // The changed paragraph keeps a still tint.
1122
+ for (const r of lines)
1123
+ intro(this.add('docxkeun-ai-mark-tint', r, 1.5));
1124
+ continue;
1125
+ }
1126
+ if (style === 'words') {
1127
+ // The changed words' letters keep the colours (the whole paragraph when only its formatting changed).
1128
+ const glyphs = m.ranges.length ? this.glyphs(para, m.ranges) : m.formatting ? this.glyphs(para) : [];
1129
+ // Decide now: the gradients are written after the loop, when `animate` holds the last mark's value.
1130
+ const cls = animate ? 'docxkeun-ai-in' : undefined;
1131
+ for (const g of glyphs) {
1132
+ const delay = `${Math.min(n++ * 90, 1500)}ms`;
1133
+ painted.push({ glyphs: [g], gradient: (id) => spanGradient(id, 'docxkeun-ai-mark-words', g, cls, delay) });
1134
+ }
1135
+ if (glyphs.length)
1136
+ continue;
1137
+ // Only deletions in this paragraph: nothing to colour, so the margin bar marks it.
1138
+ }
1139
+ if (style === 'underline') {
1140
+ // The changed words; the whole paragraph when only its formatting changed.
1141
+ const rects = m.ranges.length ? m.ranges.flatMap(([from, to]) => this.charRects(para, from, to)) : m.formatting ? lines : [];
1142
+ for (const r of rects)
1143
+ intro(this.add('docxkeun-ai-mark-underline', { ...r, y: r.y + r.h - 0.2, h: 1.4 }));
1144
+ if (rects.length)
1145
+ continue;
1146
+ // Only deletions in this paragraph: nothing to underline, so the margin bar marks it.
1147
+ }
721
1148
  // One bar per page the paragraph is on, in the left margin.
722
1149
  const byPage = new Map();
723
1150
  for (const l of lines)
@@ -732,11 +1159,7 @@ export class AiActivity {
732
1159
  continue;
733
1160
  if (!animate)
734
1161
  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}`;
1162
+ bar.title = this.markTitle(m);
740
1163
  this.markEls.push(bar);
741
1164
  if (firstBar && animate) {
742
1165
  const spark = this.add('docxkeun-ai-spark', { page, x: x + 1.5, y: top, w: 0, h: 0 });
@@ -749,8 +1172,27 @@ export class AiActivity {
749
1172
  firstBar = false;
750
1173
  }
751
1174
  }
1175
+ this.markPaint.paint(painted);
752
1176
  this.drawMap();
753
1177
  }
1178
+ /** The changed letters light up in the AI's colours for a moment (the word shimmer without marks). */
1179
+ flash(diff, paras) {
1180
+ const groups = [];
1181
+ let n = 0;
1182
+ for (const c of diff.changes) {
1183
+ const para = paras[c.para];
1184
+ if (!para)
1185
+ continue;
1186
+ const glyphs = c.ranges.length ? this.glyphs(para, c.ranges) : c.cuts.length ? [] : this.glyphs(para);
1187
+ for (const g of glyphs) {
1188
+ const delay = `${Math.min(n++ * 90, 1500)}ms`;
1189
+ groups.push({ glyphs: [g], gradient: (id) => spanGradient(id, 'docxkeun-ai-flash-words', g, 'docxkeun-ai-flash', delay) });
1190
+ }
1191
+ }
1192
+ clearTimeout(this.flashTimer);
1193
+ this.flashPaint.paint(groups);
1194
+ this.flashTimer = setTimeout(() => this.flashPaint.clear(), 3200 + Math.min(n * 90, 1500) + 100);
1195
+ }
754
1196
  /** Ticks on the right edge for every change, scaled to the scroll height; click to jump. */
755
1197
  drawMap() {
756
1198
  const root = this.viewer.root;
@@ -769,18 +1211,26 @@ export class AiActivity {
769
1211
  continue;
770
1212
  const tick = document.createElement('i');
771
1213
  tick.style.top = `${(p.top / height) * root.clientHeight}px`;
772
- tick.title = `Changed by ${this.name}`;
1214
+ tick.title = this.markTitle(m);
773
1215
  tick.addEventListener('click', () => root.scrollTo({ top: Math.max(0, p.top - root.clientHeight / 3), behavior: reducedMotion() ? 'auto' : 'smooth' }));
774
1216
  this.map.appendChild(tick);
775
1217
  }
776
1218
  }
1219
+ /**
1220
+ * The viewer rebuilt its page rows (zoom, the comment column's width): redraw at the new positions.
1221
+ * @internal
1222
+ */
1223
+ rowsBuilt() {
1224
+ requestAnimationFrame(() => this.redraw());
1225
+ }
777
1226
  redraw() {
778
1227
  // Transient animations are tied to the old positions: drop them; redraw what lasts.
779
1228
  for (const el of [...this.layer.children]) {
780
1229
  if (el !== this.caret && !this.markEls.includes(el) && !this.shimmers.includes(el))
781
1230
  el.remove();
782
1231
  }
783
- this.drawMarks(false);
1232
+ this.flashPaint.clear();
1233
+ this.drawMarks();
784
1234
  if (this.working)
785
1235
  this.drawWorking(false);
786
1236
  }
@@ -788,6 +1238,9 @@ export class AiActivity {
788
1238
  for (const fn of this.cleanup)
789
1239
  fn();
790
1240
  clearTimeout(this.hideTimer);
1241
+ clearTimeout(this.flashTimer);
1242
+ for (const paint of [this.workPaint, this.markPaint, this.flashPaint])
1243
+ paint.remove();
791
1244
  this.layer.remove();
792
1245
  this.map.remove();
793
1246
  }