starlight-annotations 0.7.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,11 @@
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
+
3
9
  ## 0.7.0
4
10
 
5
11
  ### Minor Changes
package/index.d.ts CHANGED
@@ -65,6 +65,9 @@ export type AnnotationStrings = {
65
65
  moveHint: string;
66
66
  moveHere: string;
67
67
  textChanged: string;
68
+ fresh: string;
69
+ freshCount: string;
70
+ mentions: string;
68
71
  };
69
72
 
70
73
  export interface StarlightAnnotationsOptions {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "starlight-annotations",
3
- "version": "0.7.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",
@@ -10,6 +10,8 @@ import config from 'virtual:starlight-annotations/config';
10
10
  import { createBackend } from './backend.js';
11
11
  import { anchor, buildIndex as indexText, skipSelector } from './anchoring.js';
12
12
  import { strings } from './i18n.js';
13
+ import { isNew, knownPeople, markSeen, rememberPeople, seenTimes } from './memory.js';
14
+ import { attachMentions } from './mentions.js';
13
15
  import { h, loadMarkdown, quoteText, renderMarkdown } from './shared.js';
14
16
 
15
17
  const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
@@ -177,6 +179,15 @@ async function start(root) {
177
179
  error: '',
178
180
  };
179
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);
180
191
 
181
192
  const ui = h('div', { class: 'annot-ui' });
182
193
  const selectButton = h(
@@ -191,7 +202,8 @@ async function start(root) {
191
202
  T.annotate,
192
203
  );
193
204
  const count = h('span', { class: 'annot-count' });
194
- 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);
195
207
  const body = h('div', { class: 'annot-body' });
196
208
  // The page with every note on the site, when the plugin adds it.
197
209
  // In the reader's locale, like the rest of the page.
@@ -268,6 +280,7 @@ async function start(root) {
268
280
  return null;
269
281
  }
270
282
  state.annotations = data.annotations;
283
+ remember();
271
284
  reanchor();
272
285
  paint();
273
286
  render();
@@ -296,12 +309,29 @@ async function start(root) {
296
309
  const edited = item.edited
297
310
  ? h('span', { class: 'annot-edited', title: new Date(item.edited).toLocaleString(document.documentElement.lang || undefined) }, ` · ${T.edited}`)
298
311
  : null;
299
- return h('div', { class: 'annot-meta' }, h('span', { class: 'annot-author', title: item.author.login }, item.author.name), ' · ', when, edited);
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
+ );
300
321
  }
301
322
 
302
323
  function editor(placeholder, onSave, onCancel, initial = '') {
303
324
  const area = h('textarea', { rows: 4, placeholder, maxlength: 5000, 'aria-label': placeholder });
304
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
+ );
305
335
  const preview = h('div', { class: 'annot-preview annot-md', hidden: true });
306
336
  const save = h('button', { type: 'button', class: 'annot-primary' }, T.save);
307
337
  const tools = h(
@@ -360,12 +390,16 @@ async function start(root) {
360
390
  tool[2](area);
361
391
  }
362
392
  });
363
- queueMicrotask(() => area.focus());
393
+ queueMicrotask(() => {
394
+ area.focus();
395
+ area.setSelectionRange(area.value.length, area.value.length);
396
+ });
364
397
  return h(
365
398
  'div',
366
399
  { class: 'annot-editor' },
367
400
  h('div', { class: 'annot-editor-bar' }, h('div', { class: 'annot-tabs', role: 'tablist' }, writeTab, previewTab), tools),
368
401
  area,
402
+ mentions,
369
403
  preview,
370
404
  h(
371
405
  'div',
@@ -489,11 +523,11 @@ async function start(root) {
489
523
  ),
490
524
  ...(thread.resolved ? [h('span', { class: 'annot-badge' }, T.resolved)] : []),
491
525
  ...moveBox(),
492
- h('div', { class: 'annot-message', 'data-msg': thread.id }, meta(thread), text(thread)),
526
+ h('div', { class: `annot-message${fresh(thread) ? ' annot-fresh' : ''}`, 'data-msg': thread.id }, meta(thread), text(thread)),
493
527
  ...repliesOf(thread.id).map((reply) =>
494
528
  h(
495
529
  'div',
496
- { class: 'annot-reply annot-message', 'data-msg': reply.id },
530
+ { class: `annot-reply annot-message${fresh(reply) ? ' annot-fresh' : ''}`, 'data-msg': reply.id },
497
531
  reply.inReplyTo ? reference(reply.inReplyTo, T.inReplyTo) : null,
498
532
  meta(reply),
499
533
  text(reply),
@@ -526,6 +560,11 @@ async function start(root) {
526
560
  function render() {
527
561
  const all = threads();
528
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));
529
568
  const parts = [];
530
569
  if (state.user) parts.push(userLine());
531
570
  else parts.push(loginLink());
@@ -66,6 +66,9 @@ const en = {
66
66
  moveHint: 'Select the passage this note is about now, then press “Attach here”.',
67
67
  moveHere: 'Attach here',
68
68
  textChanged: 'Text changed',
69
+ fresh: 'New',
70
+ freshCount: '{n} new',
71
+ mentions: 'People',
69
72
  };
70
73
 
71
74
  const it = {
@@ -133,6 +136,9 @@ const it = {
133
136
  moveHint: 'Seleziona il passaggio a cui si riferisce ora la nota, poi premi “Collega qui”.',
134
137
  moveHere: 'Collega qui',
135
138
  textChanged: 'Testo cambiato',
139
+ fresh: 'Nuova',
140
+ freshCount: '{n} nuove',
141
+ mentions: 'Persone',
136
142
  };
137
143
 
138
144
  const de = {
@@ -200,6 +206,9 @@ const de = {
200
206
  moveHint: 'Markiere die Stelle, um die es in dieser Notiz jetzt geht, und klicke auf „Hier verknüpfen“.',
201
207
  moveHere: 'Hier verknüpfen',
202
208
  textChanged: 'Text geändert',
209
+ fresh: 'Neu',
210
+ freshCount: '{n} neu',
211
+ mentions: 'Personen',
203
212
  };
204
213
 
205
214
  const fr = {
@@ -267,6 +276,9 @@ const fr = {
267
276
  moveHint: 'Sélectionnez le passage dont parle maintenant la note, puis cliquez sur « Rattacher ici ».',
268
277
  moveHere: 'Rattacher ici',
269
278
  textChanged: 'Texte modifié',
279
+ fresh: 'Nouveau',
280
+ freshCount: '{n} nouveaux',
281
+ mentions: 'Personnes',
270
282
  };
271
283
 
272
284
  const es = {
@@ -334,6 +346,9 @@ const es = {
334
346
  moveHint: 'Selecciona el pasaje al que se refiere ahora la nota y pulsa «Vincular aquí».',
335
347
  moveHere: 'Vincular aquí',
336
348
  textChanged: 'Texto cambiado',
349
+ fresh: 'Nueva',
350
+ freshCount: '{n} nuevas',
351
+ mentions: 'Personas',
337
352
  };
338
353
 
339
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
+ }
@@ -4,6 +4,7 @@ import config from 'virtual:starlight-annotations/config';
4
4
  import { anchor, buildIndex, skipSelector } from './anchoring.js';
5
5
  import { createBackend } from './backend.js';
6
6
  import { strings } from './i18n.js';
7
+ import { isNew, rememberPeople, seenTimes } from './memory.js';
7
8
  import { h, quoteText, renderMarkdown } from './shared.js';
8
9
 
9
10
  const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
@@ -36,6 +37,11 @@ async function start(container) {
36
37
  replies: annotations.filter((item) => item.replyTo === thread.id),
37
38
  })),
38
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));
39
45
  if (threads.length === 0) {
40
46
  container.replaceChildren(h('p', {}, T.overviewEmpty));
41
47
  return;
@@ -44,7 +50,7 @@ async function start(container) {
44
50
  // Filters live in the address, so a filtered view can be shared.
45
51
  const params = new URLSearchParams(location.search);
46
52
  const state = {
47
- status: ['open', 'changed', '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',
48
54
  author: params.get('author') ?? '',
49
55
  text: params.get('q') ?? '',
50
56
  };
@@ -52,11 +58,12 @@ async function start(container) {
52
58
  const changed = new Set(); // ids of open threads whose text is gone
53
59
  const counts = {
54
60
  open: threads.filter((entry) => !entry.thread.resolved).length,
61
+ new: threads.filter((entry) => entry.fresh).length,
55
62
  changed: 0, // known once the pages are checked
56
63
  resolved: threads.filter((entry) => entry.thread.resolved).length,
57
64
  all: threads.length,
58
65
  };
59
- const labels = { open: T.statusOpen, changed: T.textChanged, resolved: T.statusResolved, all: T.statusAll };
66
+ const labels = { open: T.statusOpen, new: T.fresh, changed: T.textChanged, resolved: T.statusResolved, all: T.statusAll };
60
67
  const option = (value) => `${labels[value]} (${counts[value]})`;
61
68
  const authors = new Map();
62
69
  for (const { thread, replies } of threads)
@@ -65,7 +72,7 @@ async function start(container) {
65
72
  const status = h(
66
73
  'select',
67
74
  { onchange: (event) => update({ status: event.target.value }) },
68
- ['open', 'changed', 'resolved', 'all'].map((value) => h('option', { value, selected: state.status === value }, option(value))),
75
+ ['open', 'new', 'changed', 'resolved', 'all'].map((value) => h('option', { value, selected: state.status === value }, option(value))),
69
76
  );
70
77
  const author = h(
71
78
  'select',
@@ -105,7 +112,8 @@ async function start(container) {
105
112
  render();
106
113
  }
107
114
 
108
- function matches({ thread, replies }) {
115
+ function matches({ thread, replies, fresh }) {
116
+ if (state.status === 'new' && !fresh) return false;
109
117
  if (state.status === 'open' && thread.resolved) return false;
110
118
  if (state.status === 'resolved' && !thread.resolved) return false;
111
119
  if (state.status === 'changed' && (thread.resolved || !changed.has(thread.id))) return false;
@@ -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,7 @@ 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,
133
142
  !thread.resolved && changed.has(thread.id) ? h('span', { class: 'annot-badge annot-changed' }, T.textChanged) : null,
134
143
  ),
135
144
  renderMarkdown(h('div', { class: 'annot-text annot-md' }), thread.body),
@@ -161,6 +161,46 @@
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
+ }
164
204
  .annot-badge.annot-changed {
165
205
  margin-left: 0.4rem;
166
206
  background: var(--sl-color-orange-low);