starlight-annotations 0.6.0 → 0.8.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,17 @@
1
1
  # starlight-annotations
2
2
 
3
+ ## 0.8.0
4
+
5
+ ### Minor Changes
6
+
7
+ - ef37ba4: Notes, replies and edits from others since you last opened a page are marked **New**, the **Notes** button counts them, and the overview page has a **New** filter. Typing `@` in a note suggests the people who write notes on the site. Both are remembered in the browser only.
8
+
9
+ ## 0.7.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 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.
14
+
3
15
  ## 0.6.0
4
16
 
5
17
  ### Minor Changes
package/index.d.ts CHANGED
@@ -59,6 +59,15 @@ 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;
68
+ fresh: string;
69
+ freshCount: string;
70
+ mentions: string;
62
71
  };
63
72
 
64
73
  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.8.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,14 @@
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';
13
+ import { isNew, knownPeople, markSeen, rememberPeople, seenTimes } from './memory.js';
14
+ import { attachMentions } from './mentions.js';
12
15
  import { h, loadMarkdown, quoteText, renderMarkdown } from './shared.js';
13
16
 
14
17
  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(', ');
18
+ const SKIP = skipSelector(config.exclude);
18
19
  const CONTEXT = 32;
19
20
  const T = strings(document.documentElement.lang, config.translations);
20
21
  const backend = createBackend(config, BASE, T);
@@ -108,24 +109,10 @@ function pageKey() {
108
109
  return path || 'index';
109
110
  }
110
111
 
111
- // ---- Text index: the page text as one string, mapped back to DOM nodes ----
112
+ // ---- Text index: offsets in the page text, mapped back to DOM nodes ----
113
+
114
+ const buildIndex = (root) => indexText(root, SKIP);
112
115
 
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
116
 
130
117
  function offsetOf(index, container, offset) {
131
118
  const entry = container.nodeType === Node.TEXT_NODE && index.byNode.get(container);
@@ -152,48 +139,8 @@ function rangeFor(index, start, end) {
152
139
  return range;
153
140
  }
154
141
 
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
142
 
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
143
 
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
144
 
198
145
  // Selections longer than LONG keep only their first and last EDGE characters.
199
146
  const LONG = config.longQuote;
@@ -227,9 +174,20 @@ async function start(root) {
227
174
  pending: null, // the selector of the selection being annotated
228
175
  showResolved: false,
229
176
  active: null,
177
+ editing: null, // the id of the message being edited
178
+ moving: null, // the id of the thread being attached to new text
230
179
  error: '',
231
180
  };
232
181
  const supportsHighlights = 'highlights' in CSS && typeof Highlight === 'function';
182
+ // Messages from others since the reader last looked at this page's notes
183
+ // are "new" for as long as the page stays open.
184
+ const since = seenTimes(config.storageKey)[page] ?? null;
185
+ const remember = () => {
186
+ markSeen(config.storageKey, page, state.annotations);
187
+ rememberPeople(config.storageKey, state.annotations);
188
+ };
189
+ remember();
190
+ const fresh = (item) => isNew(item, since, state.user?.login);
233
191
 
234
192
  const ui = h('div', { class: 'annot-ui' });
235
193
  const selectButton = h(
@@ -244,7 +202,8 @@ async function start(root) {
244
202
  T.annotate,
245
203
  );
246
204
  const count = h('span', { class: 'annot-count' });
247
- const toggle = h('button', { type: 'button', class: 'annot-toggle', onclick: () => setOpen(!drawer.classList.contains('open')) }, T.notes, count);
205
+ const freshCount = h('span', { class: 'annot-fresh-count', hidden: true });
206
+ const toggle = h('button', { type: 'button', class: 'annot-toggle', onclick: () => setOpen(!drawer.classList.contains('open')) }, T.notes, count, freshCount);
248
207
  const body = h('div', { class: 'annot-body' });
249
208
  // The page with every note on the site, when the plugin adds it.
250
209
  // In the reader's locale, like the rest of the page.
@@ -321,6 +280,7 @@ async function start(root) {
321
280
  return null;
322
281
  }
323
282
  state.annotations = data.annotations;
283
+ remember();
324
284
  reanchor();
325
285
  paint();
326
286
  render();
@@ -346,11 +306,32 @@ async function start(root) {
346
306
  dateStyle: 'medium',
347
307
  timeStyle: 'short',
348
308
  });
349
- return h('div', { class: 'annot-meta' }, h('span', { class: 'annot-author', title: item.author.login }, item.author.name), ' · ', when);
309
+ const edited = item.edited
310
+ ? h('span', { class: 'annot-edited', title: new Date(item.edited).toLocaleString(document.documentElement.lang || undefined) }, ` · ${T.edited}`)
311
+ : null;
312
+ return h(
313
+ 'div',
314
+ { class: 'annot-meta' },
315
+ h('span', { class: 'annot-author', title: item.author.login }, item.author.name),
316
+ ' · ',
317
+ when,
318
+ edited,
319
+ fresh(item) ? h('span', { class: 'annot-fresh-label' }, T.fresh) : null,
320
+ );
350
321
  }
351
322
 
352
- function editor(placeholder, onSave, onCancel) {
323
+ function editor(placeholder, onSave, onCancel, initial = '') {
353
324
  const area = h('textarea', { rows: 4, placeholder, maxlength: 5000, 'aria-label': placeholder });
325
+ area.value = initial;
326
+ const mentions = attachMentions(
327
+ area,
328
+ () =>
329
+ Object.entries(knownPeople(config.storageKey))
330
+ .filter(([login]) => login !== state.user?.login)
331
+ .sort((a, b) => a[1].localeCompare(b[1])),
332
+ insert,
333
+ T.mentions,
334
+ );
354
335
  const preview = h('div', { class: 'annot-preview annot-md', hidden: true });
355
336
  const save = h('button', { type: 'button', class: 'annot-primary' }, T.save);
356
337
  const tools = h(
@@ -409,12 +390,16 @@ async function start(root) {
409
390
  tool[2](area);
410
391
  }
411
392
  });
412
- queueMicrotask(() => area.focus());
393
+ queueMicrotask(() => {
394
+ area.focus();
395
+ area.setSelectionRange(area.value.length, area.value.length);
396
+ });
413
397
  return h(
414
398
  'div',
415
399
  { class: 'annot-editor' },
416
400
  h('div', { class: 'annot-editor-bar' }, h('div', { class: 'annot-tabs', role: 'tablist' }, writeTab, previewTab), tools),
417
401
  area,
402
+ mentions,
418
403
  preview,
419
404
  h(
420
405
  'div',
@@ -486,10 +471,49 @@ async function start(root) {
486
471
  );
487
472
  }
488
473
 
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;
474
+ const own = (item) => state.user && item.author.login === state.user.login;
475
+ const ownActions = (item, question) =>
476
+ own(item)
477
+ ? [
478
+ h('button', { type: 'button', onclick: () => startEditing(item.id) }, T.edit),
479
+ h('button', { type: 'button', class: 'annot-danger', onclick: () => confirm(question) && send({ action: 'delete', id: item.id }) }, T.delete),
480
+ ]
481
+ : [];
482
+
483
+ // The message, or an editor on it while its author edits it.
484
+ function text(item) {
485
+ if (state.editing !== item.id || !own(item)) return renderMarkdown(h('div', { class: 'annot-text annot-md' }), item.body);
486
+ return editor(
487
+ item.replyTo ? T.replyPlaceholder : T.placeholder,
488
+ async (value) => {
489
+ if (value.trim() === item.body) {
490
+ stopEditing();
491
+ return true;
492
+ }
493
+ const saved = await send({ action: 'edit', id: item.id, body: value });
494
+ if (!saved) return false;
495
+ stopEditing();
496
+ return true;
497
+ },
498
+ stopEditing,
499
+ item.body,
500
+ );
501
+ }
502
+
503
+ // A thread whose text is gone: attach it to the passage it is about now.
504
+ function moveBox() {
505
+ if (anchored || !state.user) return [];
506
+ if (state.moving !== thread.id)
507
+ return [h('div', { class: 'annot-actions' }, h('button', { type: 'button', onclick: () => startMoving(thread.id) }, T.move))];
508
+ return [
509
+ h(
510
+ 'div',
511
+ { class: 'annot-move', role: 'status' },
512
+ h('p', {}, T.moveHint),
513
+ h('button', { type: 'button', onclick: () => startMoving(null) }, T.cancel),
514
+ ),
515
+ ];
516
+ }
493
517
 
494
518
  card.append(
495
519
  h(
@@ -498,34 +522,35 @@ async function start(root) {
498
522
  quote(thread.target.selector),
499
523
  ),
500
524
  ...(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)),
525
+ ...moveBox(),
526
+ h('div', { class: `annot-message${fresh(thread) ? ' annot-fresh' : ''}`, 'data-msg': thread.id }, meta(thread), text(thread)),
502
527
  ...repliesOf(thread.id).map((reply) =>
503
528
  h(
504
529
  'div',
505
- { class: 'annot-reply annot-message', 'data-msg': reply.id },
530
+ { class: `annot-reply annot-message${fresh(reply) ? ' annot-fresh' : ''}`, 'data-msg': reply.id },
506
531
  reply.inReplyTo ? reference(reply.inReplyTo, T.inReplyTo) : null,
507
532
  meta(reply),
508
- renderMarkdown(h('div', { class: 'annot-text annot-md' }), reply.body),
509
- state.user
533
+ text(reply),
534
+ state.user && state.editing !== reply.id
510
535
  ? h(
511
536
  'div',
512
537
  { class: 'annot-actions annot-reply-actions' },
513
538
  h('button', { type: 'button', onclick: () => openReply(reply) }, T.reply),
514
- ownDelete(reply, T.confirmDeleteReply),
539
+ ...ownActions(reply, T.confirmDeleteReply),
515
540
  )
516
541
  : null,
517
542
  ),
518
543
  ),
519
544
  replyBox,
520
545
  );
521
- if (state.user) {
546
+ if (state.user && state.editing !== thread.id) {
522
547
  card.append(
523
548
  h(
524
549
  'div',
525
550
  { class: 'annot-actions' },
526
551
  h('button', { type: 'button', onclick: () => openReply(null) }, T.reply),
527
552
  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),
553
+ ...ownActions(thread, T.confirmDelete),
529
554
  ),
530
555
  );
531
556
  }
@@ -535,6 +560,11 @@ async function start(root) {
535
560
  function render() {
536
561
  const all = threads();
537
562
  count.textContent = String(all.filter((thread) => !thread.resolved).length);
563
+ // New messages in open threads.
564
+ const open = new Set(all.filter((thread) => !thread.resolved).map((thread) => thread.id));
565
+ const news = state.annotations.filter((item) => open.has(item.replyTo ?? item.id) && fresh(item)).length;
566
+ freshCount.hidden = news === 0;
567
+ freshCount.textContent = T.freshCount.replace('{n}', String(news));
538
568
  const parts = [];
539
569
  if (state.user) parts.push(userLine());
540
570
  else parts.push(loginLink());
@@ -576,6 +606,23 @@ async function start(root) {
576
606
  body.replaceChildren(...parts.filter(Boolean));
577
607
  }
578
608
 
609
+ function startEditing(id) {
610
+ loadMarkdown();
611
+ state.editing = id;
612
+ render();
613
+ }
614
+
615
+ function stopEditing() {
616
+ state.editing = null;
617
+ render();
618
+ }
619
+
620
+ function startMoving(id) {
621
+ state.moving = id;
622
+ if (id) state.pending = null;
623
+ render();
624
+ }
625
+
579
626
  function focusThread(id, scroll) {
580
627
  state.active = id;
581
628
  paint();
@@ -615,13 +662,24 @@ async function start(root) {
615
662
  return;
616
663
  }
617
664
  const rect = selected.range.getBoundingClientRect();
665
+ selectButton.textContent = state.moving ? T.moveHere : T.annotate;
618
666
  selectButton.hidden = false;
619
667
  selectButton.style.top = `${window.scrollY + rect.bottom + 6}px`;
620
668
  selectButton.style.left = `${Math.min(window.scrollX + rect.right - selectButton.offsetWidth, window.scrollX + document.documentElement.clientWidth - selectButton.offsetWidth - 8)}px`;
621
669
  }
622
670
 
623
- function compose() {
671
+ async function compose() {
624
672
  if (!selected) return;
673
+ if (state.moving) {
674
+ const id = state.moving;
675
+ selectButton.hidden = true;
676
+ window.getSelection()?.removeAllRanges();
677
+ const moved = await send({ action: 'anchor', id, target: selected.selector });
678
+ if (!moved) return;
679
+ state.moving = null;
680
+ focusThread(id, false);
681
+ return;
682
+ }
625
683
  loadMarkdown();
626
684
  state.pending = selected.selector;
627
685
  selectButton.hidden = true;
@@ -60,6 +60,15 @@ 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',
69
+ fresh: 'New',
70
+ freshCount: '{n} new',
71
+ mentions: 'People',
63
72
  };
64
73
 
65
74
  const it = {
@@ -121,6 +130,15 @@ const it = {
121
130
  showing: 'Stato',
122
131
  author: 'Autore',
123
132
  seeAll: 'Guarda le note delle altre pagine.',
133
+ edit: 'Modifica',
134
+ edited: 'modificata',
135
+ move: 'Collega ad altro testo',
136
+ moveHint: 'Seleziona il passaggio a cui si riferisce ora la nota, poi premi “Collega qui”.',
137
+ moveHere: 'Collega qui',
138
+ textChanged: 'Testo cambiato',
139
+ fresh: 'Nuova',
140
+ freshCount: '{n} nuove',
141
+ mentions: 'Persone',
124
142
  };
125
143
 
126
144
  const de = {
@@ -182,6 +200,15 @@ const de = {
182
200
  showing: 'Status',
183
201
  author: 'Autor',
184
202
  seeAll: 'Notizen auf anderen Seiten ansehen.',
203
+ edit: 'Bearbeiten',
204
+ edited: 'bearbeitet',
205
+ move: 'Mit anderem Text verknüpfen',
206
+ moveHint: 'Markiere die Stelle, um die es in dieser Notiz jetzt geht, und klicke auf „Hier verknüpfen“.',
207
+ moveHere: 'Hier verknüpfen',
208
+ textChanged: 'Text geändert',
209
+ fresh: 'Neu',
210
+ freshCount: '{n} neu',
211
+ mentions: 'Personen',
185
212
  };
186
213
 
187
214
  const fr = {
@@ -243,6 +270,15 @@ const fr = {
243
270
  showing: 'Statut',
244
271
  author: 'Auteur',
245
272
  seeAll: 'Voir les notes des autres pages.',
273
+ edit: 'Modifier',
274
+ edited: 'modifiée',
275
+ move: 'Rattacher à un autre texte',
276
+ moveHint: 'Sélectionnez le passage dont parle maintenant la note, puis cliquez sur « Rattacher ici ».',
277
+ moveHere: 'Rattacher ici',
278
+ textChanged: 'Texte modifié',
279
+ fresh: 'Nouveau',
280
+ freshCount: '{n} nouveaux',
281
+ mentions: 'Personnes',
246
282
  };
247
283
 
248
284
  const es = {
@@ -304,6 +340,15 @@ const es = {
304
340
  showing: 'Estado',
305
341
  author: 'Autor',
306
342
  seeAll: 'Ver las notas de otras páginas.',
343
+ edit: 'Editar',
344
+ edited: 'editada',
345
+ move: 'Vincular a otro texto',
346
+ moveHint: 'Selecciona el pasaje al que se refiere ahora la nota y pulsa «Vincular aquí».',
347
+ moveHere: 'Vincular aquí',
348
+ textChanged: 'Texto cambiado',
349
+ fresh: 'Nueva',
350
+ freshCount: '{n} nuevas',
351
+ mentions: 'Personas',
307
352
  };
308
353
 
309
354
  export const builtIn = { en, it, de, fr, es };
@@ -0,0 +1,68 @@
1
+ // What this browser remembers for the reader, in localStorage: when they last
2
+ // looked at each page's notes, and the people they have seen write notes.
3
+ // Nothing here reaches the server. Without storage (private mode, blocked
4
+ // site data) every function still works, it just remembers nothing.
5
+ //
6
+ // The keys use "~", not ":", so the browser backend, which stores notes under
7
+ // "<storageKey>:<page>", never mistakes them for a page.
8
+
9
+ function read(key) {
10
+ try {
11
+ return JSON.parse(localStorage.getItem(key) || '{}') ?? {};
12
+ } catch {
13
+ return {};
14
+ }
15
+ }
16
+
17
+ function write(key, value) {
18
+ try {
19
+ localStorage.setItem(key, JSON.stringify(value));
20
+ } catch {
21
+ // Full or blocked: forget quietly.
22
+ }
23
+ }
24
+
25
+ // The time of the latest message the reader saw on each page:
26
+ // { "guides/demo": "2026-11-24T10:00:00Z" }. It is a note's own time, not the
27
+ // reader's clock, so a wrong clock cannot hide notes.
28
+ export function seenTimes(storageKey) {
29
+ return read(`${storageKey}~seen`);
30
+ }
31
+
32
+ export function markSeen(storageKey, page, annotations) {
33
+ const latest = annotations.reduce((max, item) => (stamp(item) > max ? stamp(item) : max), '');
34
+ if (!latest) return;
35
+ const seen = seenTimes(storageKey);
36
+ if ((seen[page] ?? '') >= latest) return;
37
+ seen[page] = latest;
38
+ write(`${storageKey}~seen`, seen);
39
+ }
40
+
41
+ // When a message last changed: its edit, else its creation.
42
+ export function stamp(item) {
43
+ return item.edited && item.edited > item.created ? item.edited : item.created;
44
+ }
45
+
46
+ // Whether a message is new to this reader: written or edited by someone else
47
+ // after the last time they looked at the page. A page never opened has
48
+ // everything new.
49
+ export function isNew(item, since, login) {
50
+ if (login && item.author?.login === login) return false;
51
+ return !since || stamp(item) > since;
52
+ }
53
+
54
+ // Everyone seen writing notes, for @mention suggestions: { login: name }.
55
+ export function knownPeople(storageKey) {
56
+ return read(`${storageKey}~people`);
57
+ }
58
+
59
+ export function rememberPeople(storageKey, annotations) {
60
+ const people = knownPeople(storageKey);
61
+ let changed = false;
62
+ for (const { author } of annotations) {
63
+ if (!author?.login || people[author.login] === (author.name || author.login)) continue;
64
+ people[author.login] = author.name || author.login;
65
+ changed = true;
66
+ }
67
+ if (changed) write(`${storageKey}~people`, people);
68
+ }
@@ -0,0 +1,100 @@
1
+ // "@" in a note suggests the people who already write notes on these docs.
2
+ // Picking one writes "@login ", which the server reads as a mention
3
+ // (`event.mentions` for onChange).
4
+ import { h } from './shared.js';
5
+
6
+ const MAX = 6;
7
+
8
+ /**
9
+ * Adds suggestions to a textarea. Returns the list element to place under it.
10
+ * Its keydown listener must run before the editor's own, so Enter and Escape
11
+ * pick or close a suggestion instead of saving or cancelling.
12
+ * @param {HTMLTextAreaElement} area
13
+ * @param {() => [string, string][]} people [login, name] pairs, the writer left out
14
+ * @param {(area: HTMLTextAreaElement, text: string) => void} insert
15
+ * @param {string} label
16
+ */
17
+ export function attachMentions(area, people, insert, label) {
18
+ const list = h('ul', { class: 'annot-mentions', role: 'listbox', 'aria-label': label, hidden: true });
19
+ area.setAttribute('aria-autocomplete', 'list');
20
+ let matches = [];
21
+ let active = 0;
22
+ let from = -1; // where the "@" is
23
+
24
+ function query() {
25
+ const before = area.value.slice(0, area.selectionStart);
26
+ const match = area.selectionStart === area.selectionEnd && before.match(/(?:^|[\s(])@([a-z\d-]{0,39})$/i);
27
+ if (!match) return null;
28
+ from = before.length - match[1].length - 1;
29
+ return match[1].toLowerCase();
30
+ }
31
+
32
+ function update() {
33
+ const typed = query();
34
+ matches =
35
+ typed === null
36
+ ? []
37
+ : people()
38
+ .filter(([login, name]) => login.toLowerCase().startsWith(typed) || name.toLowerCase().split(/\s+/).some((word) => word.startsWith(typed)))
39
+ .slice(0, MAX);
40
+ active = Math.min(active, Math.max(0, matches.length - 1));
41
+ render();
42
+ }
43
+
44
+ function render() {
45
+ list.hidden = matches.length === 0;
46
+ area.setAttribute('aria-expanded', String(!list.hidden));
47
+ list.replaceChildren(
48
+ ...matches.map(([login, name], i) =>
49
+ h(
50
+ 'li',
51
+ {
52
+ role: 'option',
53
+ 'aria-selected': String(i === active),
54
+ // Keep the focus in the textarea.
55
+ onmousedown: (event) => event.preventDefault(),
56
+ onclick: () => pick(i),
57
+ },
58
+ h('strong', {}, name),
59
+ name !== login ? h('span', {}, ` @${login}`) : null,
60
+ ),
61
+ ),
62
+ );
63
+ }
64
+
65
+ function pick(i) {
66
+ const [login] = matches[i];
67
+ area.setSelectionRange(from, area.selectionStart);
68
+ insert(area, `@${login} `);
69
+ close();
70
+ }
71
+
72
+ function close() {
73
+ matches = [];
74
+ render();
75
+ }
76
+
77
+ area.addEventListener('input', update);
78
+ area.addEventListener('click', update);
79
+ area.addEventListener('blur', close);
80
+ area.addEventListener('keyup', (event) => {
81
+ if (['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) update();
82
+ });
83
+ area.addEventListener('keydown', (event) => {
84
+ if (list.hidden) return;
85
+ const keys = {
86
+ ArrowDown: () => (active = (active + 1) % matches.length),
87
+ ArrowUp: () => (active = (active - 1 + matches.length) % matches.length),
88
+ Enter: () => pick(active),
89
+ Tab: () => pick(active),
90
+ Escape: close,
91
+ };
92
+ const run = keys[event.key];
93
+ if (!run || (event.key === 'Enter' && (event.metaKey || event.ctrlKey))) return;
94
+ event.preventDefault();
95
+ event.stopImmediatePropagation();
96
+ run();
97
+ if (!list.hidden) render();
98
+ });
99
+ return list;
100
+ }
@@ -1,8 +1,10 @@
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';
7
+ import { isNew, rememberPeople, seenTimes } from './memory.js';
6
8
  import { h, quoteText, renderMarkdown } from './shared.js';
7
9
 
8
10
  const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
@@ -35,6 +37,11 @@ async function start(container) {
35
37
  replies: annotations.filter((item) => item.replyTo === thread.id),
36
38
  })),
37
39
  );
40
+ // People for @mention suggestions, and what is new since each page was
41
+ // last opened in this browser.
42
+ rememberPeople(config.storageKey, pages.flatMap((entry) => entry.annotations));
43
+ const seen = seenTimes(config.storageKey);
44
+ for (const entry of threads) entry.fresh = [entry.thread, ...entry.replies].some((item) => isNew(item, seen[entry.page] ?? null));
38
45
  if (threads.length === 0) {
39
46
  container.replaceChildren(h('p', {}, T.overviewEmpty));
40
47
  return;
@@ -43,16 +50,21 @@ async function start(container) {
43
50
  // Filters live in the address, so a filtered view can be shared.
44
51
  const params = new URLSearchParams(location.search);
45
52
  const state = {
46
- status: ['open', 'resolved', 'all'].includes(params.get('status')) ? params.get('status') : 'open',
53
+ status: ['open', 'new', 'changed', 'resolved', 'all'].includes(params.get('status')) ? params.get('status') : 'open',
47
54
  author: params.get('author') ?? '',
48
55
  text: params.get('q') ?? '',
49
56
  };
50
57
 
58
+ const changed = new Set(); // ids of open threads whose text is gone
51
59
  const counts = {
52
60
  open: threads.filter((entry) => !entry.thread.resolved).length,
61
+ new: threads.filter((entry) => entry.fresh).length,
62
+ changed: 0, // known once the pages are checked
53
63
  resolved: threads.filter((entry) => entry.thread.resolved).length,
54
64
  all: threads.length,
55
65
  };
66
+ const labels = { open: T.statusOpen, new: T.fresh, changed: T.textChanged, resolved: T.statusResolved, all: T.statusAll };
67
+ const option = (value) => `${labels[value]} (${counts[value]})`;
56
68
  const authors = new Map();
57
69
  for (const { thread, replies } of threads)
58
70
  for (const item of [thread, ...replies]) authors.set(item.author.login, item.author.name || item.author.login);
@@ -60,13 +72,7 @@ async function start(container) {
60
72
  const status = h(
61
73
  'select',
62
74
  { 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
- ),
75
+ ['open', 'new', 'changed', 'resolved', 'all'].map((value) => h('option', { value, selected: state.status === value }, option(value))),
70
76
  );
71
77
  const author = h(
72
78
  'select',
@@ -106,9 +112,11 @@ async function start(container) {
106
112
  render();
107
113
  }
108
114
 
109
- function matches({ thread, replies }) {
115
+ function matches({ thread, replies, fresh }) {
116
+ if (state.status === 'new' && !fresh) return false;
110
117
  if (state.status === 'open' && thread.resolved) return false;
111
118
  if (state.status === 'resolved' && !thread.resolved) return false;
119
+ if (state.status === 'changed' && (thread.resolved || !changed.has(thread.id))) return false;
112
120
  const messages = [thread, ...replies];
113
121
  if (state.author && !messages.some((item) => item.author.login === state.author)) return false;
114
122
  const text = state.text.trim().toLowerCase();
@@ -116,7 +124,7 @@ async function start(container) {
116
124
  return [quoteText(thread.target.selector), ...messages.map((item) => item.body)].some((value) => value.toLowerCase().includes(text));
117
125
  }
118
126
 
119
- function card({ page, thread, replies }) {
127
+ function card({ page, thread, replies, fresh }) {
120
128
  const when = new Date(thread.created).toLocaleString(document.documentElement.lang || undefined, { dateStyle: 'medium', timeStyle: 'short' });
121
129
  const last = replies.at(-1);
122
130
  return h(
@@ -130,6 +138,8 @@ async function start(container) {
130
138
  ' · ',
131
139
  when,
132
140
  thread.resolved ? h('span', { class: 'annot-badge' }, T.resolved) : null,
141
+ fresh ? h('span', { class: 'annot-badge annot-fresh-label' }, T.fresh) : null,
142
+ !thread.resolved && changed.has(thread.id) ? h('span', { class: 'annot-badge annot-changed' }, T.textChanged) : null,
133
143
  ),
134
144
  renderMarkdown(h('div', { class: 'annot-text annot-md' }), thread.body),
135
145
  h(
@@ -169,4 +179,37 @@ async function start(container) {
169
179
  }
170
180
 
171
181
  render();
182
+
183
+ // Open notes whose quoted text is no longer on their page: fetch each page
184
+ // and look for the quotes, as the page itself does.
185
+ const skip = skipSelector(config.exclude);
186
+ const open = [...new Set(threads.filter((entry) => !entry.thread.resolved).map((entry) => entry.page))];
187
+ await mapLimit(open, 4, async (page) => {
188
+ const root = await fetchContent(pageUrl(page));
189
+ if (!root) return; // Not a page we can read: say nothing.
190
+ const index = buildIndex(root, skip);
191
+ for (const entry of threads)
192
+ if (entry.page === page && !entry.thread.resolved && !anchor(index, entry.thread.target.selector)) changed.add(entry.thread.id);
193
+ });
194
+ counts.changed = changed.size;
195
+ status.querySelector('option[value="changed"]').textContent = option('changed');
196
+ render();
197
+ }
198
+
199
+ async function fetchContent(url) {
200
+ try {
201
+ const response = await fetch(url, { credentials: 'same-origin' });
202
+ if (!response.ok) return null;
203
+ const doc = new DOMParser().parseFromString(await response.text(), 'text/html');
204
+ return doc.querySelector(config.content);
205
+ } catch {
206
+ return null;
207
+ }
208
+ }
209
+
210
+ async function mapLimit(items, limit, run) {
211
+ const queue = [...items];
212
+ await Promise.all(Array.from({ length: Math.min(limit, queue.length) }, async () => {
213
+ while (queue.length) await run(queue.shift());
214
+ }));
172
215
  }
@@ -161,6 +161,64 @@
161
161
  background: var(--sl-color-gray-5);
162
162
  font-size: var(--sl-text-xs);
163
163
  }
164
+ .annot-fresh-count {
165
+ padding: 0 0.4em;
166
+ border-radius: 999px;
167
+ background: var(--sl-color-blue-low);
168
+ color: var(--sl-color-blue-high);
169
+ font-size: var(--sl-text-xs);
170
+ }
171
+ .annot-message.annot-fresh {
172
+ border-left: 3px solid var(--sl-color-blue);
173
+ padding-left: 0.5rem;
174
+ }
175
+ .annot-fresh-label {
176
+ margin-left: 0.4rem;
177
+ padding: 0 0.35rem;
178
+ border-radius: 0.25rem;
179
+ background: var(--sl-color-blue-low);
180
+ color: var(--sl-color-blue-high);
181
+ font-size: var(--sl-text-xs);
182
+ }
183
+ .annot-mentions {
184
+ margin: 0;
185
+ padding: 0.25rem;
186
+ list-style: none;
187
+ border: 1px solid var(--sl-color-hairline);
188
+ border-radius: 0.4rem;
189
+ background: var(--sl-color-bg);
190
+ font-size: var(--sl-text-sm);
191
+ }
192
+ .annot-mentions li {
193
+ margin: 0;
194
+ padding: 0.2rem 0.4rem;
195
+ border-radius: 0.25rem;
196
+ cursor: pointer;
197
+ }
198
+ .annot-mentions li[aria-selected='true'] {
199
+ background: var(--sl-color-accent-low);
200
+ }
201
+ .annot-mentions li span {
202
+ color: var(--sl-color-gray-3);
203
+ }
204
+ .annot-badge.annot-changed {
205
+ margin-left: 0.4rem;
206
+ background: var(--sl-color-orange-low);
207
+ color: var(--sl-color-orange-high);
208
+ }
209
+ .annot-move {
210
+ display: flex;
211
+ flex-direction: column;
212
+ align-items: flex-start;
213
+ gap: 0.4rem;
214
+ padding: 0.5rem 0.6rem;
215
+ border: 1px dashed var(--sl-color-accent);
216
+ border-radius: 0.4rem;
217
+ font-size: var(--sl-text-sm);
218
+ }
219
+ .annot-move p {
220
+ margin: 0;
221
+ }
164
222
  .annot-meta {
165
223
  color: var(--sl-color-gray-3);
166
224
  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.');