docxkeun 0.3.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;
@@ -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 ---------------------------------------------------------------------------------------
@@ -174,7 +200,7 @@ function still(prefix) {
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}`,
176
202
  // The other working styles, held still.
177
- `${prefix}.docxkeun-ai-words{animation:none;background-image:linear-gradient(90deg,var(--dk-ai-1),var(--dk-ai-2))}`,
203
+ `${prefix}.docxkeun-ai-in,${prefix}.docxkeun-ai-flash{animation:none}`,
178
204
  `${prefix}.docxkeun-ai-underline{animation:none;background-image:linear-gradient(90deg,var(--dk-ai-1),var(--dk-ai-2));background-size:100% 100%}`,
179
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)}`,
180
206
  `${prefix}.docxkeun-ai-spot,${prefix}.docxkeun-ai-pulse,${prefix}.docxkeun-ai-intro{animation:none}`,
@@ -185,7 +211,11 @@ const CSS = `
185
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}
186
212
  .docxkeun-ai-layer{position:absolute;left:0;top:0;width:0;height:0;pointer-events:none}
187
213
  .docxkeun-ai-layer>*{position:absolute;pointer-events:none}
188
- .docxkeun-ai-words{border-radius:2px;background-image:linear-gradient(100deg,#000 30%,var(--dk-ai-1) 44%,var(--dk-ai-2) 56%,#000 70%);background-size:300% 100%;mix-blend-mode:lighten;animation:docxkeun-ai-shimmer 1.8s linear infinite}
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)}}
189
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}
190
220
  @keyframes docxkeun-ai-wave{from{background-position:-40% 0}to{background-position:140% 0}}
191
221
  .docxkeun-ai-edge{border-radius:6px;animation:docxkeun-ai-aura 2.2s ease-in-out infinite}
@@ -196,8 +226,6 @@ const CSS = `
196
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}
197
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)}}
198
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}
199
- .docxkeun-ai-mark-halo{border-radius:6px;background:linear-gradient(90deg,color-mix(in srgb,var(--dk-ai-1) 24%,transparent),color-mix(in srgb,var(--dk-ai-2) 24%,transparent));filter:blur(4px);mix-blend-mode:multiply}
200
- .docxkeun-ai-mark-words{border-radius:2px;background:linear-gradient(90deg,var(--dk-ai-1),var(--dk-ai-2));mix-blend-mode:lighten}
201
229
  .docxkeun-ai-mark-underline{border-radius:1px;background:linear-gradient(90deg,var(--dk-ai-1),var(--dk-ai-2))}
202
230
  .docxkeun-ai-intro{animation:docxkeun-ai-in .9s ease-out var(--t,0ms) both}
203
231
  .docxkeun-ai-mark-underline.docxkeun-ai-intro{transform-origin:left;animation-name:docxkeun-ai-draw}
@@ -303,10 +331,119 @@ function spread(i, axis) {
303
331
  }
304
332
  const reducedMotion = () => typeof matchMedia !== 'undefined' && matchMedia('(prefers-reduced-motion: reduce)').matches;
305
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
+ }
306
443
  /** The styles, with a label and a line to show in a picker, in the order to show them. */
307
444
  export const ACTIVITY_STYLES = [
308
445
  { style: 'highlight', label: 'Highlight band', description: 'A tinted band sweeps over the lines; the changed paragraph keeps a soft tint.' },
309
- { style: 'words', label: 'Word shimmer', description: 'The letters themselves shimmer; the changed words keep a glow.' },
446
+ { style: 'words', label: 'Word shimmer', description: 'The letters themselves shimmer; the changed words stay coloured.' },
310
447
  { style: 'underline', label: 'Underline wave', description: 'A streak runs under each line; the changed words stay underlined.' },
311
448
  { style: 'edge', label: 'Edge glow', description: 'A soft glow breathes around the paragraph.' },
312
449
  { style: 'spotlight', label: 'Spotlight', description: 'The rest of the page dims while the paragraph is changed.' },
@@ -330,6 +467,11 @@ export class AiActivity {
330
467
  shimmers = [];
331
468
  marks = [];
332
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;
333
475
  hideTimer;
334
476
  cleanup = [];
335
477
  on;
@@ -357,6 +499,9 @@ export class AiActivity {
357
499
  this.label = document.createElement('span');
358
500
  this.caret.appendChild(this.label);
359
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');
360
505
  if (options.color !== undefined)
361
506
  this.color = options.color;
362
507
  if (options.style !== undefined)
@@ -441,6 +586,8 @@ export class AiActivity {
441
586
  this.shimmers = [];
442
587
  this.markEls = [];
443
588
  this.marks = [];
589
+ for (const paint of [this.workPaint, this.markPaint, this.flashPaint])
590
+ paint.clear();
444
591
  this.caret.style.opacity = '0';
445
592
  this.drawMap();
446
593
  }
@@ -451,6 +598,9 @@ export class AiActivity {
451
598
  set animate(on) {
452
599
  this.motion = on;
453
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);
454
604
  }
455
605
  /** Change bars and the change map after a change. */
456
606
  get marksShown() {
@@ -536,6 +686,67 @@ export class AiActivity {
536
686
  }
537
687
  return merged;
538
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
+ }
539
750
  place(el, r, pad = 0) {
540
751
  const p = this.at(r.page.index, r.x - pad, r.y - pad);
541
752
  if (!p)
@@ -584,26 +795,29 @@ export class AiActivity {
584
795
  if (!this.on)
585
796
  return;
586
797
  this.working = undefined;
587
- for (const el of this.shimmers)
588
- el.remove();
589
- this.shimmers = [];
798
+ this.clearWorking();
590
799
  this.caret.classList.remove('working');
591
800
  this.label.textContent = this.name;
592
801
  clearTimeout(this.hideTimer);
593
802
  this.hideTimer = setTimeout(() => (this.caret.style.opacity = '0'), 2500);
594
803
  }
595
- drawWorking(scroll) {
804
+ clearWorking() {
596
805
  for (const el of this.shimmers)
597
806
  el.remove();
598
807
  this.shimmers = [];
808
+ this.workPaint.clear();
809
+ }
810
+ drawWorking(scroll) {
811
+ this.clearWorking();
599
812
  const w = this.working;
600
813
  if (!w)
601
814
  return;
602
815
  const all = this.paragraphs();
816
+ const paras = w.paras.map((n) => all[n - 1]).filter((p) => !!p);
603
817
  // The lines of each paragraph being worked on.
604
- const groups = w.paras.map((n) => all[n - 1]).filter((p) => !!p).map((p) => this.lineRects(p.el));
818
+ const groups = paras.map((p) => this.lineRects(p.el));
605
819
  const first = groups.flat()[0];
606
- this.drawStyle(groups, first);
820
+ this.drawStyle(groups, first, paras);
607
821
  this.label.textContent = this.workingText(w);
608
822
  if (first) {
609
823
  this.moveCaret(first.page, first.x, first.y, first.h, true);
@@ -614,7 +828,7 @@ export class AiActivity {
614
828
  this.parkCaret();
615
829
  }
616
830
  /** The working effect of the current style over each paragraph's lines. */
617
- drawStyle(groups, first) {
831
+ drawStyle(groups, first, paras) {
618
832
  const keep = (el) => {
619
833
  if (el)
620
834
  this.shimmers.push(el);
@@ -633,9 +847,8 @@ export class AiActivity {
633
847
  ripple(keep(this.add('docxkeun-ai-shimmer', r, 1.5)));
634
848
  break;
635
849
  case 'words':
636
- // A band blended with "lighten": white stays white, only the letters take its colours.
637
- for (const r of lines)
638
- ripple(keep(this.add('docxkeun-ai-words', r, 0.5)));
850
+ // The letters themselves take the colours; the paper, shading and pictures stay as they are.
851
+ this.workPaint.paint(this.shimmerPaint(paras));
639
852
  break;
640
853
  case 'underline':
641
854
  for (const r of lines)
@@ -729,7 +942,7 @@ export class AiActivity {
729
942
  /** The body's paragraphs now (text and formatting): pass to `reveal()` after the document changed. */
730
943
  snapshot() {
731
944
  const paras = this.paragraphs();
732
- 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)) };
733
946
  }
734
947
  /**
735
948
  * Show what changed since `before` (from `snapshot()`), once the viewer has laid out the new
@@ -744,7 +957,7 @@ export class AiActivity {
744
957
  // Same text, other formatting (bold, a style, alignment, a list): the whole paragraph glows.
745
958
  if (old.formats.length) {
746
959
  for (const [o, n] of diff.same) {
747
- if (old.formats[o] !== undefined && old.formats[o] !== formatSignature(paras[n]))
960
+ if (old.formats[o] !== undefined && old.formats[o] !== formatSignature(paras[n], this.viewer.document))
748
961
  diff.changes.push({ para: n, kind: 'changed', ranges: [], cuts: [], formatting: true, before: old.texts[o], from: o });
749
962
  }
750
963
  diff.changes.sort((x, y) => x.para - y.para);
@@ -752,14 +965,15 @@ export class AiActivity {
752
965
  if (!this.on)
753
966
  return diff;
754
967
  this.working = undefined;
755
- for (const el of this.shimmers)
756
- el.remove();
757
- this.shimmers = [];
968
+ this.clearWorking();
758
969
  // The marks of earlier changes stay (following their paragraphs); this change's join them.
759
970
  this.marks = this.mergeMarks(diff, after);
760
971
  this.drawMarks(new Set(diff.changes.map((c) => c.para)));
761
- // A style with its own mark lets the mark fade in; the others get the passing glow.
762
- const glow = !(OWN_MARK.has(this.aiStyle) && this.keepMarks);
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);
763
977
  // Ink in the new text, line after line, as if written (about 2.5 s at most).
764
978
  const pieces = [];
765
979
  for (const c of diff.changes) {
@@ -883,6 +1097,7 @@ export class AiActivity {
883
1097
  el.remove();
884
1098
  this.markEls = [];
885
1099
  const paras = this.paragraphs();
1100
+ const painted = [];
886
1101
  let n = 0;
887
1102
  let animate = false;
888
1103
  // Marks of the style's own kind fade (or draw) in one after another.
@@ -908,21 +1123,27 @@ export class AiActivity {
908
1123
  intro(this.add('docxkeun-ai-mark-tint', r, 1.5));
909
1124
  continue;
910
1125
  }
911
- if (style === 'words' || style === 'underline') {
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') {
912
1140
  // The changed words; the whole paragraph when only its formatting changed.
913
1141
  const rects = m.ranges.length ? m.ranges.flatMap(([from, to]) => this.charRects(para, from, to)) : m.formatting ? lines : [];
914
- if (rects.length) {
915
- for (const r of rects) {
916
- if (style === 'words') {
917
- intro(this.add('docxkeun-ai-mark-halo', r, 2));
918
- intro(this.add('docxkeun-ai-mark-words', r, 0.5));
919
- }
920
- else
921
- intro(this.add('docxkeun-ai-mark-underline', { ...r, y: r.y + r.h - 0.2, h: 1.4 }));
922
- }
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)
923
1145
  continue;
924
- }
925
- // Only deletions in this paragraph: nothing to colour, so the margin bar marks it.
1146
+ // Only deletions in this paragraph: nothing to underline, so the margin bar marks it.
926
1147
  }
927
1148
  // One bar per page the paragraph is on, in the left margin.
928
1149
  const byPage = new Map();
@@ -951,8 +1172,27 @@ export class AiActivity {
951
1172
  firstBar = false;
952
1173
  }
953
1174
  }
1175
+ this.markPaint.paint(painted);
954
1176
  this.drawMap();
955
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
+ }
956
1196
  /** Ticks on the right edge for every change, scaled to the scroll height; click to jump. */
957
1197
  drawMap() {
958
1198
  const root = this.viewer.root;
@@ -989,6 +1229,7 @@ export class AiActivity {
989
1229
  if (el !== this.caret && !this.markEls.includes(el) && !this.shimmers.includes(el))
990
1230
  el.remove();
991
1231
  }
1232
+ this.flashPaint.clear();
992
1233
  this.drawMarks();
993
1234
  if (this.working)
994
1235
  this.drawWorking(false);
@@ -997,6 +1238,9 @@ export class AiActivity {
997
1238
  for (const fn of this.cleanup)
998
1239
  fn();
999
1240
  clearTimeout(this.hideTimer);
1241
+ clearTimeout(this.flashTimer);
1242
+ for (const paint of [this.workPaint, this.markPaint, this.flashPaint])
1243
+ paint.remove();
1000
1244
  this.layer.remove();
1001
1245
  this.map.remove();
1002
1246
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "docxkeun",
3
- "version": "0.3.0",
3
+ "version": "0.4.0",
4
4
  "description": "Read, render, edit and convert .docx files in the browser with zero runtime dependencies: a DOCX viewer and editor (toolbar, comments, tracked changes, undo), a DOCX-to-PDF converter, and live effects for AI edits.",
5
5
  "author": "Kevin Jeremia (https://github.com/kevinkjs)",
6
6
  "license": "MIT",