starlight-annotations 0.6.0 → 0.7.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # starlight-annotations
2
2
 
3
+ ## 0.7.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 25427bd: Authors can edit their notes and replies, which then show "edited". A note whose text is gone from the page can be attached to another passage with **Attach to other text**. The overview page marks these notes **Text changed** and filters them. The server has two new actions, `edit` and `anchor`, which `onChange` receives too; the Slack and Teams senders skip them unless asked.
8
+
3
9
  ## 0.6.0
4
10
 
5
11
  ### Minor Changes
package/index.d.ts CHANGED
@@ -59,6 +59,12 @@ export type AnnotationStrings = {
59
59
  showing: string;
60
60
  author: string;
61
61
  seeAll: string;
62
+ edit: string;
63
+ edited: string;
64
+ move: string;
65
+ moveHint: string;
66
+ moveHere: string;
67
+ textChanged: string;
62
68
  };
63
69
 
64
70
  export interface StarlightAnnotationsOptions {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "starlight-annotations",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "description": "🖍️ Let readers highlight text and leave notes on Starlight docs. Notes are committed to your Git repository on GitHub, GitLab, Gitea or Forgejo.",
5
5
  "license": "MIT",
6
6
  "author": "Alessandro Rosa",
package/server.d.ts CHANGED
@@ -38,7 +38,7 @@ export interface Auth {
38
38
  openContact?(sealed: string): Promise<string | null>;
39
39
  }
40
40
 
41
- export type AnnotationAction = 'create' | 'reply' | 'resolve' | 'reopen' | 'delete';
41
+ export type AnnotationAction = 'create' | 'reply' | 'resolve' | 'reopen' | 'edit' | 'anchor' | 'delete';
42
42
 
43
43
  /** What `onChange` receives after every saved change. */
44
44
  export interface AnnotationEvent {
@@ -0,0 +1,70 @@
1
+ // Finding a stored quote in a page's text. Shared by the page panel and the
2
+ // overview, which checks pages it fetched for notes whose text has changed.
3
+
4
+ // Text the reader does not see as content: diagrams (rendered late), heading
5
+ // anchor links ("Section titled …"), buttons, and the selectors you add.
6
+ export function skipSelector(exclude = []) {
7
+ return ['pre.mermaid', 'svg', 'script', 'style', 'button', '.sl-anchor-link', '.annot-ui', ...exclude].join(', ');
8
+ }
9
+
10
+ // The text of `root` as one string, with each text node's offset. `skip`
11
+ // names the elements whose text the reader does not see as content.
12
+ export function buildIndex(root, skip) {
13
+ const nodes = [];
14
+ const byNode = new Map();
15
+ let text = '';
16
+ const walker = (root.ownerDocument ?? document).createTreeWalker(root, NodeFilter.SHOW_TEXT, {
17
+ acceptNode: (node) =>
18
+ node.parentElement && !node.parentElement.closest(skip) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT,
19
+ });
20
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
21
+ const entry = { node, start: text.length };
22
+ nodes.push(entry);
23
+ byNode.set(node, entry);
24
+ text += node.data;
25
+ }
26
+ return { text, nodes, byNode };
27
+ }
28
+
29
+ function shared(a, b, fromEnd) {
30
+ let n = 0;
31
+ const max = Math.min(a.length, b.length);
32
+ while (n < max && (fromEnd ? a[a.length - 1 - n] === b[b.length - 1 - n] : a[n] === b[n])) n++;
33
+ return n;
34
+ }
35
+
36
+ // Finds a quote in the page, at or after `from`. Among several matches, the
37
+ // one whose surrounding text agrees best with the stored context wins; on a
38
+ // tie, the first one.
39
+ function anchorQuote(index, { exact, prefix = '', suffix = '' }, from = 0) {
40
+ const text = index.text;
41
+ const matches = [];
42
+ for (let at = text.indexOf(exact, from); at !== -1; at = text.indexOf(exact, at + 1)) matches.push([at, at + exact.length]);
43
+ if (matches.length === 0) {
44
+ // Whitespace may differ after an edit or a rebuild.
45
+ const pattern = exact.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
46
+ if (!pattern) return null;
47
+ for (const match of text.matchAll(new RegExp(pattern, 'g'))) {
48
+ if (match.index >= from) matches.push([match.index, match.index + match[0].length]);
49
+ }
50
+ }
51
+ let best = null;
52
+ let bestScore = -1;
53
+ for (const [start, end] of matches) {
54
+ const score =
55
+ shared(text.slice(Math.max(0, start - prefix.length), start), prefix, true) +
56
+ shared(text.slice(end, end + suffix.length), suffix, false);
57
+ if (score > bestScore) [best, bestScore] = [[start, end], score];
58
+ }
59
+ return best;
60
+ }
61
+
62
+ // A long passage is stored as its start and its end: find the start, then
63
+ // the end after it.
64
+ export function anchor(index, selector) {
65
+ if (selector.type !== 'RangeSelector') return anchorQuote(index, selector);
66
+ const start = anchorQuote(index, selector.startSelector);
67
+ if (!start) return null;
68
+ const end = anchorQuote(index, selector.endSelector, start[1]);
69
+ return end ? [start[0], end[1]] : null;
70
+ }
@@ -8,13 +8,12 @@
8
8
  // note cannot inject markup into the page.
9
9
  import config from 'virtual:starlight-annotations/config';
10
10
  import { createBackend } from './backend.js';
11
+ import { anchor, buildIndex as indexText, skipSelector } from './anchoring.js';
11
12
  import { strings } from './i18n.js';
12
13
  import { h, loadMarkdown, quoteText, renderMarkdown } from './shared.js';
13
14
 
14
15
  const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
15
- // Text the reader does not see as content: diagrams (rendered late), heading
16
- // anchor links ("Section titled …"), buttons, and the selectors you add.
17
- const SKIP = ['pre.mermaid', 'svg', 'script', 'style', 'button', '.sl-anchor-link', '.annot-ui', ...config.exclude].join(', ');
16
+ const SKIP = skipSelector(config.exclude);
18
17
  const CONTEXT = 32;
19
18
  const T = strings(document.documentElement.lang, config.translations);
20
19
  const backend = createBackend(config, BASE, T);
@@ -108,24 +107,10 @@ function pageKey() {
108
107
  return path || 'index';
109
108
  }
110
109
 
111
- // ---- Text index: the page text as one string, mapped back to DOM nodes ----
110
+ // ---- Text index: offsets in the page text, mapped back to DOM nodes ----
111
+
112
+ const buildIndex = (root) => indexText(root, SKIP);
112
113
 
113
- function buildIndex(root) {
114
- const nodes = [];
115
- const byNode = new Map();
116
- let text = '';
117
- const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
118
- acceptNode: (node) =>
119
- node.parentElement && !node.parentElement.closest(SKIP) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT,
120
- });
121
- for (let node = walker.nextNode(); node; node = walker.nextNode()) {
122
- const entry = { node, start: text.length };
123
- nodes.push(entry);
124
- byNode.set(node, entry);
125
- text += node.data;
126
- }
127
- return { text, nodes, byNode };
128
- }
129
114
 
130
115
  function offsetOf(index, container, offset) {
131
116
  const entry = container.nodeType === Node.TEXT_NODE && index.byNode.get(container);
@@ -152,48 +137,8 @@ function rangeFor(index, start, end) {
152
137
  return range;
153
138
  }
154
139
 
155
- function shared(a, b, fromEnd) {
156
- let n = 0;
157
- const max = Math.min(a.length, b.length);
158
- while (n < max && (fromEnd ? a[a.length - 1 - n] === b[b.length - 1 - n] : a[n] === b[n])) n++;
159
- return n;
160
- }
161
140
 
162
- // Finds a quote in the page, at or after `from`. Among several matches, the
163
- // one whose surrounding text agrees best with the stored context wins; on a
164
- // tie, the first one.
165
- function anchorQuote(index, { exact, prefix = '', suffix = '' }, from = 0) {
166
- const text = index.text;
167
- const matches = [];
168
- for (let at = text.indexOf(exact, from); at !== -1; at = text.indexOf(exact, at + 1)) matches.push([at, at + exact.length]);
169
- if (matches.length === 0) {
170
- // Whitespace may differ after an edit or a rebuild.
171
- const pattern = exact.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
172
- if (!pattern) return null;
173
- for (const match of text.matchAll(new RegExp(pattern, 'g'))) {
174
- if (match.index >= from) matches.push([match.index, match.index + match[0].length]);
175
- }
176
- }
177
- let best = null;
178
- let bestScore = -1;
179
- for (const [start, end] of matches) {
180
- const score =
181
- shared(text.slice(Math.max(0, start - prefix.length), start), prefix, true) +
182
- shared(text.slice(end, end + suffix.length), suffix, false);
183
- if (score > bestScore) [best, bestScore] = [[start, end], score];
184
- }
185
- return best;
186
- }
187
141
 
188
- // A long passage is stored as its start and its end: find the start, then
189
- // the end after it.
190
- function anchor(index, selector) {
191
- if (selector.type !== 'RangeSelector') return anchorQuote(index, selector);
192
- const start = anchorQuote(index, selector.startSelector);
193
- if (!start) return null;
194
- const end = anchorQuote(index, selector.endSelector, start[1]);
195
- return end ? [start[0], end[1]] : null;
196
- }
197
142
 
198
143
  // Selections longer than LONG keep only their first and last EDGE characters.
199
144
  const LONG = config.longQuote;
@@ -227,6 +172,8 @@ async function start(root) {
227
172
  pending: null, // the selector of the selection being annotated
228
173
  showResolved: false,
229
174
  active: null,
175
+ editing: null, // the id of the message being edited
176
+ moving: null, // the id of the thread being attached to new text
230
177
  error: '',
231
178
  };
232
179
  const supportsHighlights = 'highlights' in CSS && typeof Highlight === 'function';
@@ -346,11 +293,15 @@ async function start(root) {
346
293
  dateStyle: 'medium',
347
294
  timeStyle: 'short',
348
295
  });
349
- return h('div', { class: 'annot-meta' }, h('span', { class: 'annot-author', title: item.author.login }, item.author.name), ' · ', when);
296
+ const edited = item.edited
297
+ ? h('span', { class: 'annot-edited', title: new Date(item.edited).toLocaleString(document.documentElement.lang || undefined) }, ` · ${T.edited}`)
298
+ : null;
299
+ return h('div', { class: 'annot-meta' }, h('span', { class: 'annot-author', title: item.author.login }, item.author.name), ' · ', when, edited);
350
300
  }
351
301
 
352
- function editor(placeholder, onSave, onCancel) {
302
+ function editor(placeholder, onSave, onCancel, initial = '') {
353
303
  const area = h('textarea', { rows: 4, placeholder, maxlength: 5000, 'aria-label': placeholder });
304
+ area.value = initial;
354
305
  const preview = h('div', { class: 'annot-preview annot-md', hidden: true });
355
306
  const save = h('button', { type: 'button', class: 'annot-primary' }, T.save);
356
307
  const tools = h(
@@ -486,10 +437,49 @@ async function start(root) {
486
437
  );
487
438
  }
488
439
 
489
- const ownDelete = (item, question) =>
490
- state.user && item.author.login === state.user.login
491
- ? h('button', { type: 'button', class: 'annot-danger', onclick: () => confirm(question) && send({ action: 'delete', id: item.id }) }, T.delete)
492
- : null;
440
+ const own = (item) => state.user && item.author.login === state.user.login;
441
+ const ownActions = (item, question) =>
442
+ own(item)
443
+ ? [
444
+ h('button', { type: 'button', onclick: () => startEditing(item.id) }, T.edit),
445
+ h('button', { type: 'button', class: 'annot-danger', onclick: () => confirm(question) && send({ action: 'delete', id: item.id }) }, T.delete),
446
+ ]
447
+ : [];
448
+
449
+ // The message, or an editor on it while its author edits it.
450
+ function text(item) {
451
+ if (state.editing !== item.id || !own(item)) return renderMarkdown(h('div', { class: 'annot-text annot-md' }), item.body);
452
+ return editor(
453
+ item.replyTo ? T.replyPlaceholder : T.placeholder,
454
+ async (value) => {
455
+ if (value.trim() === item.body) {
456
+ stopEditing();
457
+ return true;
458
+ }
459
+ const saved = await send({ action: 'edit', id: item.id, body: value });
460
+ if (!saved) return false;
461
+ stopEditing();
462
+ return true;
463
+ },
464
+ stopEditing,
465
+ item.body,
466
+ );
467
+ }
468
+
469
+ // A thread whose text is gone: attach it to the passage it is about now.
470
+ function moveBox() {
471
+ if (anchored || !state.user) return [];
472
+ if (state.moving !== thread.id)
473
+ return [h('div', { class: 'annot-actions' }, h('button', { type: 'button', onclick: () => startMoving(thread.id) }, T.move))];
474
+ return [
475
+ h(
476
+ 'div',
477
+ { class: 'annot-move', role: 'status' },
478
+ h('p', {}, T.moveHint),
479
+ h('button', { type: 'button', onclick: () => startMoving(null) }, T.cancel),
480
+ ),
481
+ ];
482
+ }
493
483
 
494
484
  card.append(
495
485
  h(
@@ -498,34 +488,35 @@ async function start(root) {
498
488
  quote(thread.target.selector),
499
489
  ),
500
490
  ...(thread.resolved ? [h('span', { class: 'annot-badge' }, T.resolved)] : []),
501
- h('div', { class: 'annot-message', 'data-msg': thread.id }, meta(thread), renderMarkdown(h('div', { class: 'annot-text annot-md' }), thread.body)),
491
+ ...moveBox(),
492
+ h('div', { class: 'annot-message', 'data-msg': thread.id }, meta(thread), text(thread)),
502
493
  ...repliesOf(thread.id).map((reply) =>
503
494
  h(
504
495
  'div',
505
496
  { class: 'annot-reply annot-message', 'data-msg': reply.id },
506
497
  reply.inReplyTo ? reference(reply.inReplyTo, T.inReplyTo) : null,
507
498
  meta(reply),
508
- renderMarkdown(h('div', { class: 'annot-text annot-md' }), reply.body),
509
- state.user
499
+ text(reply),
500
+ state.user && state.editing !== reply.id
510
501
  ? h(
511
502
  'div',
512
503
  { class: 'annot-actions annot-reply-actions' },
513
504
  h('button', { type: 'button', onclick: () => openReply(reply) }, T.reply),
514
- ownDelete(reply, T.confirmDeleteReply),
505
+ ...ownActions(reply, T.confirmDeleteReply),
515
506
  )
516
507
  : null,
517
508
  ),
518
509
  ),
519
510
  replyBox,
520
511
  );
521
- if (state.user) {
512
+ if (state.user && state.editing !== thread.id) {
522
513
  card.append(
523
514
  h(
524
515
  'div',
525
516
  { class: 'annot-actions' },
526
517
  h('button', { type: 'button', onclick: () => openReply(null) }, T.reply),
527
518
  h('button', { type: 'button', onclick: () => send({ action: 'resolve', id: thread.id, resolved: !thread.resolved }) }, thread.resolved ? T.reopen : T.resolve),
528
- ownDelete(thread, T.confirmDelete),
519
+ ...ownActions(thread, T.confirmDelete),
529
520
  ),
530
521
  );
531
522
  }
@@ -576,6 +567,23 @@ async function start(root) {
576
567
  body.replaceChildren(...parts.filter(Boolean));
577
568
  }
578
569
 
570
+ function startEditing(id) {
571
+ loadMarkdown();
572
+ state.editing = id;
573
+ render();
574
+ }
575
+
576
+ function stopEditing() {
577
+ state.editing = null;
578
+ render();
579
+ }
580
+
581
+ function startMoving(id) {
582
+ state.moving = id;
583
+ if (id) state.pending = null;
584
+ render();
585
+ }
586
+
579
587
  function focusThread(id, scroll) {
580
588
  state.active = id;
581
589
  paint();
@@ -615,13 +623,24 @@ async function start(root) {
615
623
  return;
616
624
  }
617
625
  const rect = selected.range.getBoundingClientRect();
626
+ selectButton.textContent = state.moving ? T.moveHere : T.annotate;
618
627
  selectButton.hidden = false;
619
628
  selectButton.style.top = `${window.scrollY + rect.bottom + 6}px`;
620
629
  selectButton.style.left = `${Math.min(window.scrollX + rect.right - selectButton.offsetWidth, window.scrollX + document.documentElement.clientWidth - selectButton.offsetWidth - 8)}px`;
621
630
  }
622
631
 
623
- function compose() {
632
+ async function compose() {
624
633
  if (!selected) return;
634
+ if (state.moving) {
635
+ const id = state.moving;
636
+ selectButton.hidden = true;
637
+ window.getSelection()?.removeAllRanges();
638
+ const moved = await send({ action: 'anchor', id, target: selected.selector });
639
+ if (!moved) return;
640
+ state.moving = null;
641
+ focusThread(id, false);
642
+ return;
643
+ }
625
644
  loadMarkdown();
626
645
  state.pending = selected.selector;
627
646
  selectButton.hidden = true;
@@ -60,6 +60,12 @@ const en = {
60
60
  showing: 'Status',
61
61
  author: 'Author',
62
62
  seeAll: 'See the notes on other pages.',
63
+ edit: 'Edit',
64
+ edited: 'edited',
65
+ move: 'Attach to other text',
66
+ moveHint: 'Select the passage this note is about now, then press “Attach here”.',
67
+ moveHere: 'Attach here',
68
+ textChanged: 'Text changed',
63
69
  };
64
70
 
65
71
  const it = {
@@ -121,6 +127,12 @@ const it = {
121
127
  showing: 'Stato',
122
128
  author: 'Autore',
123
129
  seeAll: 'Guarda le note delle altre pagine.',
130
+ edit: 'Modifica',
131
+ edited: 'modificata',
132
+ move: 'Collega ad altro testo',
133
+ moveHint: 'Seleziona il passaggio a cui si riferisce ora la nota, poi premi “Collega qui”.',
134
+ moveHere: 'Collega qui',
135
+ textChanged: 'Testo cambiato',
124
136
  };
125
137
 
126
138
  const de = {
@@ -182,6 +194,12 @@ const de = {
182
194
  showing: 'Status',
183
195
  author: 'Autor',
184
196
  seeAll: 'Notizen auf anderen Seiten ansehen.',
197
+ edit: 'Bearbeiten',
198
+ edited: 'bearbeitet',
199
+ move: 'Mit anderem Text verknüpfen',
200
+ moveHint: 'Markiere die Stelle, um die es in dieser Notiz jetzt geht, und klicke auf „Hier verknüpfen“.',
201
+ moveHere: 'Hier verknüpfen',
202
+ textChanged: 'Text geändert',
185
203
  };
186
204
 
187
205
  const fr = {
@@ -243,6 +261,12 @@ const fr = {
243
261
  showing: 'Statut',
244
262
  author: 'Auteur',
245
263
  seeAll: 'Voir les notes des autres pages.',
264
+ edit: 'Modifier',
265
+ edited: 'modifiée',
266
+ move: 'Rattacher à un autre texte',
267
+ moveHint: 'Sélectionnez le passage dont parle maintenant la note, puis cliquez sur « Rattacher ici ».',
268
+ moveHere: 'Rattacher ici',
269
+ textChanged: 'Texte modifié',
246
270
  };
247
271
 
248
272
  const es = {
@@ -304,6 +328,12 @@ const es = {
304
328
  showing: 'Estado',
305
329
  author: 'Autor',
306
330
  seeAll: 'Ver las notas de otras páginas.',
331
+ edit: 'Editar',
332
+ edited: 'editada',
333
+ move: 'Vincular a otro texto',
334
+ moveHint: 'Selecciona el pasaje al que se refiere ahora la nota y pulsa «Vincular aquí».',
335
+ moveHere: 'Vincular aquí',
336
+ textChanged: 'Texto cambiado',
307
337
  };
308
338
 
309
339
  export const builtIn = { en, it, de, fr, es };
@@ -1,6 +1,7 @@
1
1
  // The overview page: every note on the site, grouped by page, with filters.
2
2
  // Read-only: a note opens on its page, where it can be answered or resolved.
3
3
  import config from 'virtual:starlight-annotations/config';
4
+ import { anchor, buildIndex, skipSelector } from './anchoring.js';
4
5
  import { createBackend } from './backend.js';
5
6
  import { strings } from './i18n.js';
6
7
  import { h, quoteText, renderMarkdown } from './shared.js';
@@ -43,16 +44,20 @@ async function start(container) {
43
44
  // Filters live in the address, so a filtered view can be shared.
44
45
  const params = new URLSearchParams(location.search);
45
46
  const state = {
46
- status: ['open', 'resolved', 'all'].includes(params.get('status')) ? params.get('status') : 'open',
47
+ status: ['open', 'changed', 'resolved', 'all'].includes(params.get('status')) ? params.get('status') : 'open',
47
48
  author: params.get('author') ?? '',
48
49
  text: params.get('q') ?? '',
49
50
  };
50
51
 
52
+ const changed = new Set(); // ids of open threads whose text is gone
51
53
  const counts = {
52
54
  open: threads.filter((entry) => !entry.thread.resolved).length,
55
+ changed: 0, // known once the pages are checked
53
56
  resolved: threads.filter((entry) => entry.thread.resolved).length,
54
57
  all: threads.length,
55
58
  };
59
+ const labels = { open: T.statusOpen, changed: T.textChanged, resolved: T.statusResolved, all: T.statusAll };
60
+ const option = (value) => `${labels[value]} (${counts[value]})`;
56
61
  const authors = new Map();
57
62
  for (const { thread, replies } of threads)
58
63
  for (const item of [thread, ...replies]) authors.set(item.author.login, item.author.name || item.author.login);
@@ -60,13 +65,7 @@ async function start(container) {
60
65
  const status = h(
61
66
  'select',
62
67
  { onchange: (event) => update({ status: event.target.value }) },
63
- ['open', 'resolved', 'all'].map((value) =>
64
- h(
65
- 'option',
66
- { value, selected: state.status === value },
67
- `${{ open: T.statusOpen, resolved: T.statusResolved, all: T.statusAll }[value]} (${counts[value]})`,
68
- ),
69
- ),
68
+ ['open', 'changed', 'resolved', 'all'].map((value) => h('option', { value, selected: state.status === value }, option(value))),
70
69
  );
71
70
  const author = h(
72
71
  'select',
@@ -109,6 +108,7 @@ async function start(container) {
109
108
  function matches({ thread, replies }) {
110
109
  if (state.status === 'open' && thread.resolved) return false;
111
110
  if (state.status === 'resolved' && !thread.resolved) return false;
111
+ if (state.status === 'changed' && (thread.resolved || !changed.has(thread.id))) return false;
112
112
  const messages = [thread, ...replies];
113
113
  if (state.author && !messages.some((item) => item.author.login === state.author)) return false;
114
114
  const text = state.text.trim().toLowerCase();
@@ -130,6 +130,7 @@ async function start(container) {
130
130
  ' · ',
131
131
  when,
132
132
  thread.resolved ? h('span', { class: 'annot-badge' }, T.resolved) : null,
133
+ !thread.resolved && changed.has(thread.id) ? h('span', { class: 'annot-badge annot-changed' }, T.textChanged) : null,
133
134
  ),
134
135
  renderMarkdown(h('div', { class: 'annot-text annot-md' }), thread.body),
135
136
  h(
@@ -169,4 +170,37 @@ async function start(container) {
169
170
  }
170
171
 
171
172
  render();
173
+
174
+ // Open notes whose quoted text is no longer on their page: fetch each page
175
+ // and look for the quotes, as the page itself does.
176
+ const skip = skipSelector(config.exclude);
177
+ const open = [...new Set(threads.filter((entry) => !entry.thread.resolved).map((entry) => entry.page))];
178
+ await mapLimit(open, 4, async (page) => {
179
+ const root = await fetchContent(pageUrl(page));
180
+ if (!root) return; // Not a page we can read: say nothing.
181
+ const index = buildIndex(root, skip);
182
+ for (const entry of threads)
183
+ if (entry.page === page && !entry.thread.resolved && !anchor(index, entry.thread.target.selector)) changed.add(entry.thread.id);
184
+ });
185
+ counts.changed = changed.size;
186
+ status.querySelector('option[value="changed"]').textContent = option('changed');
187
+ render();
188
+ }
189
+
190
+ async function fetchContent(url) {
191
+ try {
192
+ const response = await fetch(url, { credentials: 'same-origin' });
193
+ if (!response.ok) return null;
194
+ const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
195
+ return doc.querySelector(config.content);
196
+ } catch {
197
+ return null;
198
+ }
199
+ }
200
+
201
+ async function mapLimit(items, limit, run) {
202
+ const queue = [...items];
203
+ await Promise.all(Array.from({ length: Math.min(limit, queue.length) }, async () => {
204
+ while (queue.length) await run(queue.shift());
205
+ }));
172
206
  }
@@ -161,6 +161,24 @@
161
161
  background: var(--sl-color-gray-5);
162
162
  font-size: var(--sl-text-xs);
163
163
  }
164
+ .annot-badge.annot-changed {
165
+ margin-left: 0.4rem;
166
+ background: var(--sl-color-orange-low);
167
+ color: var(--sl-color-orange-high);
168
+ }
169
+ .annot-move {
170
+ display: flex;
171
+ flex-direction: column;
172
+ align-items: flex-start;
173
+ gap: 0.4rem;
174
+ padding: 0.5rem 0.6rem;
175
+ border: 1px dashed var(--sl-color-accent);
176
+ border-radius: 0.4rem;
177
+ font-size: var(--sl-text-sm);
178
+ }
179
+ .annot-move p {
180
+ margin: 0;
181
+ }
164
182
  .annot-meta {
165
183
  color: var(--sl-color-gray-3);
166
184
  font-size: var(--sl-text-xs);
package/src/core.js CHANGED
@@ -106,6 +106,8 @@ function selector(target) {
106
106
  // { action: 'create', target: { exact, prefix, suffix }, body }
107
107
  // { action: 'reply', replyTo, body }
108
108
  // { action: 'resolve', id, resolved }
109
+ // { action: 'edit', id, body } the author changes their message
110
+ // { action: 'anchor', id, target } a thread moves to another passage
109
111
  // { action: 'delete', id }
110
112
  // It returns the annotation it touched, and a commit message.
111
113
  export function applyChange(doc, change, user, now = new Date()) {
@@ -155,6 +157,23 @@ export function applyChange(doc, change, user, now = new Date()) {
155
157
  annotation.resolvedAt = annotation.resolved ? created : undefined;
156
158
  return { annotation, message: `docs(annotations): ${annotation.resolved ? 'resolve' : 'reopen'} note on ${doc.page}` };
157
159
  }
160
+ case 'edit': {
161
+ const annotation = find(change.id);
162
+ if (annotation.author?.login !== user.login) throw new AnnotationError(403, 'Only the author can edit a note.');
163
+ annotation.body = text(change.body, MAX_BODY, annotation.replyTo ? 'reply' : 'note');
164
+ annotation.edited = created;
165
+ return { annotation, message: `docs(annotations): edit note on ${doc.page}` };
166
+ }
167
+ case 'anchor': {
168
+ // When the page changed and the quote is gone, anyone who can write
169
+ // attaches the thread to the passage it is now about.
170
+ const annotation = find(change.id);
171
+ if (annotation.replyTo) throw new AnnotationError(400, 'Only a thread can be moved.');
172
+ annotation.target = { selector: selector(change.target) };
173
+ annotation.movedBy = author;
174
+ annotation.movedAt = created;
175
+ return { annotation, message: `docs(annotations): move note on ${doc.page}` };
176
+ }
158
177
  case 'delete': {
159
178
  const annotation = find(change.id);
160
179
  if (annotation.author?.login !== user.login) throw new AnnotationError(403, 'Only the author can delete a note.');
@@ -7,6 +7,7 @@
7
7
  // these post to a channel. `event.participants` and `event.mentions` (logins)
8
8
  // let you reach people too, with your own login -> address map.
9
9
 
10
+ // What the Slack and Teams senders post by default: not edits and moves.
10
11
  const ACTIONS = ['create', 'reply', 'resolve', 'reopen', 'delete'];
11
12
 
12
13
  // "@ada" and "@ada-l" in a message, not inside an email address or code span.
@@ -61,10 +62,12 @@ export function describeChange(event) {
61
62
  reply: `${who} replied on ${event.page}`,
62
63
  resolve: `${who} resolved a note on ${event.page}`,
63
64
  reopen: `${who} reopened a note on ${event.page}`,
65
+ edit: `${who} edited a note on ${event.page}`,
66
+ anchor: `${who} moved a note on ${event.page}`,
64
67
  delete: `${who} deleted a note on ${event.page}`,
65
68
  }[event.action];
66
69
  const quote = quoteOf(event.thread);
67
- const body = event.action === 'create' || event.action === 'reply' ? cut(event.annotation.body, 600) : '';
70
+ const body = ['create', 'reply', 'edit'].includes(event.action) ? cut(event.annotation.body, 600) : '';
68
71
  const text = [title, quote && `> ${quote}`, body, event.url].filter(Boolean).join('\n\n');
69
72
  return { title, quote, body, text };
70
73
  }
@@ -72,7 +75,7 @@ export function describeChange(event) {
72
75
  /**
73
76
  * Posts each change to a Slack incoming webhook.
74
77
  * @param {string} webhookUrl
75
- * @param {{ actions?: string[] }} [options] Which actions to post. Default: all.
78
+ * @param {{ actions?: string[] }} [options] Which actions to post. Default: all but edit and anchor.
76
79
  */
77
80
  export function slackWebhook(webhookUrl, { actions = ACTIONS } = {}) {
78
81
  if (!webhookUrl) throw new Error('starlight-annotations: slackWebhook needs a webhook URL.');
@@ -93,7 +96,7 @@ export function slackWebhook(webhookUrl, { actions = ACTIONS } = {}) {
93
96
  * Posts each change to a Microsoft Teams channel through a Workflows webhook
94
97
  * ("Post to a channel when a webhook request is received").
95
98
  * @param {string} webhookUrl
96
- * @param {{ actions?: string[] }} [options] Which actions to post. Default: all.
99
+ * @param {{ actions?: string[] }} [options] Which actions to post. Default: all but edit and anchor.
97
100
  */
98
101
  export function teamsWebhook(webhookUrl, { actions = ACTIONS } = {}) {
99
102
  if (!webhookUrl) throw new Error('starlight-annotations: teamsWebhook needs a webhook URL.');