starlight-annotations 0.7.0 → 0.9.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.9.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 61b2bef: Notes can have a kind (question, problem, proposal or decision), shown as a label and filtered on the overview page. **+ Note on this page** writes a note about the whole page rather than a passage. In the file, a thread has an optional `kind`, and a page note has a `target` without a `selector`. Slack and Teams titles name the kind ("Ada added a question on …").
8
+
9
+ ## 0.8.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 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.
14
+
3
15
  ## 0.7.0
4
16
 
5
17
  ### Minor Changes
package/index.d.ts CHANGED
@@ -65,6 +65,18 @@ export type AnnotationStrings = {
65
65
  moveHint: string;
66
66
  moveHere: string;
67
67
  textChanged: string;
68
+ fresh: string;
69
+ freshCount: string;
70
+ mentions: string;
71
+ kind: string;
72
+ noKind: string;
73
+ allKinds: string;
74
+ kindQuestion: string;
75
+ kindIssue: string;
76
+ kindProposal: string;
77
+ kindDecision: string;
78
+ wholePage: string;
79
+ pageNote: string;
68
80
  };
69
81
 
70
82
  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.9.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,7 +10,9 @@ 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 { h, loadMarkdown, quoteText, renderMarkdown } from './shared.js';
13
+ import { isNew, knownPeople, markSeen, rememberPeople, seenTimes } from './memory.js';
14
+ import { attachMentions } from './mentions.js';
15
+ import { h, kindLabel, KINDS, loadMarkdown, quoteText, renderMarkdown } from './shared.js';
14
16
 
15
17
  const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
16
18
  const SKIP = skipSelector(config.exclude);
@@ -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.
@@ -241,6 +253,7 @@ async function start(root) {
241
253
  state.index = buildIndex(root);
242
254
  state.anchors.clear();
243
255
  for (const thread of threads()) {
256
+ if (!thread.target?.selector) continue;
244
257
  const found = anchor(state.index, thread.target.selector);
245
258
  if (found) state.anchors.set(thread.id, { start: found[0], end: found[1], range: rangeFor(state.index, ...found) });
246
259
  }
@@ -268,6 +281,7 @@ async function start(root) {
268
281
  return null;
269
282
  }
270
283
  state.annotations = data.annotations;
284
+ remember();
271
285
  reanchor();
272
286
  paint();
273
287
  render();
@@ -296,12 +310,40 @@ async function start(root) {
296
310
  const edited = item.edited
297
311
  ? h('span', { class: 'annot-edited', title: new Date(item.edited).toLocaleString(document.documentElement.lang || undefined) }, ` · ${T.edited}`)
298
312
  : null;
299
- return h('div', { class: 'annot-meta' }, h('span', { class: 'annot-author', title: item.author.login }, item.author.name), ' · ', when, edited);
313
+ return h(
314
+ 'div',
315
+ { class: 'annot-meta' },
316
+ h('span', { class: 'annot-author', title: item.author.login }, item.author.name),
317
+ ' · ',
318
+ when,
319
+ edited,
320
+ fresh(item) ? h('span', { class: 'annot-fresh-label' }, T.fresh) : null,
321
+ );
300
322
  }
301
323
 
302
- function editor(placeholder, onSave, onCancel, initial = '') {
324
+ // `kind` is given for the first note of a thread (null when it has none):
325
+ // the editor then lets the writer pick one. onSave gets (text, kind).
326
+ function editor(placeholder, onSave, onCancel, { initial = '', kind } = {}) {
303
327
  const area = h('textarea', { rows: 4, placeholder, maxlength: 5000, 'aria-label': placeholder });
304
328
  area.value = initial;
329
+ const kindSelect =
330
+ kind === undefined
331
+ ? null
332
+ : h(
333
+ 'select',
334
+ { class: 'annot-kind-select', 'aria-label': T.kind },
335
+ h('option', { value: '' }, T.noKind),
336
+ KINDS.map((value) => h('option', { value, selected: kind === value }, kindLabel(value, T))),
337
+ );
338
+ const mentions = attachMentions(
339
+ area,
340
+ () =>
341
+ Object.entries(knownPeople(config.storageKey))
342
+ .filter(([login]) => login !== state.user?.login)
343
+ .sort((a, b) => a[1].localeCompare(b[1])),
344
+ insert,
345
+ T.mentions,
346
+ );
305
347
  const preview = h('div', { class: 'annot-preview annot-md', hidden: true });
306
348
  const save = h('button', { type: 'button', class: 'annot-primary' }, T.save);
307
349
  const tools = h(
@@ -346,7 +388,7 @@ async function start(root) {
346
388
  save.addEventListener('click', async () => {
347
389
  if (!area.value.trim()) return area.focus();
348
390
  busy(true);
349
- const ok = await onSave(area.value);
391
+ const ok = await onSave(area.value, kindSelect ? kindSelect.value || null : undefined);
350
392
  if (!ok) busy(false);
351
393
  });
352
394
  area.addEventListener('keydown', (event) => {
@@ -360,24 +402,31 @@ async function start(root) {
360
402
  tool[2](area);
361
403
  }
362
404
  });
363
- queueMicrotask(() => area.focus());
405
+ queueMicrotask(() => {
406
+ area.focus();
407
+ area.setSelectionRange(area.value.length, area.value.length);
408
+ });
364
409
  return h(
365
410
  'div',
366
411
  { class: 'annot-editor' },
367
412
  h('div', { class: 'annot-editor-bar' }, h('div', { class: 'annot-tabs', role: 'tablist' }, writeTab, previewTab), tools),
368
413
  area,
414
+ mentions,
369
415
  preview,
370
416
  h(
371
417
  'div',
372
418
  { class: 'annot-actions' },
373
419
  save,
420
+ kindSelect,
374
421
  h('button', { type: 'button', onclick: onCancel }, T.cancel),
375
422
  h('a', { class: 'annot-hint', href: 'https://www.markdownguide.org/basic-syntax/', target: '_blank', rel: 'noopener noreferrer' }, T.markdown),
376
423
  ),
377
424
  );
378
425
  }
379
426
 
427
+ // The quoted passage, or "Whole page" for a note about the page.
380
428
  function quote(selector) {
429
+ if (!selector) return h('div', { class: 'annot-quote annot-whole-page' }, T.wholePage);
381
430
  return h('blockquote', { class: 'annot-quote' }, quoteText(selector));
382
431
  }
383
432
 
@@ -403,6 +452,7 @@ async function start(root) {
403
452
  }
404
453
 
405
454
  function threadCard(thread, anchored) {
455
+ const whole = !thread.target?.selector;
406
456
  const card = h('article', {
407
457
  class: `annot-thread${thread.resolved ? ' resolved' : ''}${state.active === thread.id ? ' active' : ''}`,
408
458
  'data-id': thread.id,
@@ -451,24 +501,25 @@ async function start(root) {
451
501
  if (state.editing !== item.id || !own(item)) return renderMarkdown(h('div', { class: 'annot-text annot-md' }), item.body);
452
502
  return editor(
453
503
  item.replyTo ? T.replyPlaceholder : T.placeholder,
454
- async (value) => {
455
- if (value.trim() === item.body) {
504
+ async (value, kind) => {
505
+ const sameKind = kind === undefined || kind === (item.kind ?? null);
506
+ if (value.trim() === item.body && sameKind) {
456
507
  stopEditing();
457
508
  return true;
458
509
  }
459
- const saved = await send({ action: 'edit', id: item.id, body: value });
510
+ const saved = await send({ action: 'edit', id: item.id, body: value, ...(kind === undefined ? {} : { kind }) });
460
511
  if (!saved) return false;
461
512
  stopEditing();
462
513
  return true;
463
514
  },
464
515
  stopEditing,
465
- item.body,
516
+ { initial: item.body, kind: item.replyTo ? undefined : (item.kind ?? null) },
466
517
  );
467
518
  }
468
519
 
469
520
  // A thread whose text is gone: attach it to the passage it is about now.
470
521
  function moveBox() {
471
- if (anchored || !state.user) return [];
522
+ if (anchored || whole || !state.user) return [];
472
523
  if (state.moving !== thread.id)
473
524
  return [h('div', { class: 'annot-actions' }, h('button', { type: 'button', onclick: () => startMoving(thread.id) }, T.move))];
474
525
  return [
@@ -485,15 +536,16 @@ async function start(root) {
485
536
  h(
486
537
  'button',
487
538
  { type: 'button', class: 'annot-quote-button', disabled: !anchored, onclick: () => focusThread(thread.id, true) },
488
- quote(thread.target.selector),
539
+ quote(thread.target?.selector),
489
540
  ),
541
+ ...(thread.kind ? [h('span', { class: `annot-kind annot-kind-${thread.kind}` }, kindLabel(thread.kind, T))] : []),
490
542
  ...(thread.resolved ? [h('span', { class: 'annot-badge' }, T.resolved)] : []),
491
543
  ...moveBox(),
492
- h('div', { class: 'annot-message', 'data-msg': thread.id }, meta(thread), text(thread)),
544
+ h('div', { class: `annot-message${fresh(thread) ? ' annot-fresh' : ''}`, 'data-msg': thread.id }, meta(thread), text(thread)),
493
545
  ...repliesOf(thread.id).map((reply) =>
494
546
  h(
495
547
  'div',
496
- { class: 'annot-reply annot-message', 'data-msg': reply.id },
548
+ { class: `annot-reply annot-message${fresh(reply) ? ' annot-fresh' : ''}`, 'data-msg': reply.id },
497
549
  reply.inReplyTo ? reference(reply.inReplyTo, T.inReplyTo) : null,
498
550
  meta(reply),
499
551
  text(reply),
@@ -526,9 +578,17 @@ async function start(root) {
526
578
  function render() {
527
579
  const all = threads();
528
580
  count.textContent = String(all.filter((thread) => !thread.resolved).length);
581
+ // New messages in open threads.
582
+ const open = new Set(all.filter((thread) => !thread.resolved).map((thread) => thread.id));
583
+ const news = state.annotations.filter((item) => open.has(item.replyTo ?? item.id) && fresh(item)).length;
584
+ freshCount.hidden = news === 0;
585
+ freshCount.textContent = T.freshCount.replace('{n}', String(news));
529
586
  const parts = [];
530
- if (state.user) parts.push(userLine());
531
- else parts.push(loginLink());
587
+ if (state.user) {
588
+ parts.push(userLine());
589
+ if (!state.pending && !state.moving)
590
+ parts.push(h('button', { type: 'button', class: 'annot-page-note', onclick: () => composePageNote() }, `+ ${T.pageNote}`));
591
+ } else parts.push(loginLink());
532
592
  if (state.error) parts.push(h('p', { class: 'annot-error', role: 'alert' }, state.error));
533
593
  if (state.pending) {
534
594
  parts.push(
@@ -536,12 +596,12 @@ async function start(root) {
536
596
  'section',
537
597
  { class: 'annot-new' },
538
598
  h('strong', {}, T.newNote),
539
- quote(state.pending),
599
+ quote(state.pending.type === 'Page' ? null : state.pending),
540
600
  state.user
541
601
  ? editor(
542
602
  T.placeholder,
543
- async (text) => {
544
- const created = await send({ action: 'create', target: state.pending, body: text });
603
+ async (text, kind) => {
604
+ const created = await send({ action: 'create', target: state.pending, body: text, ...(kind ? { kind } : {}) });
545
605
  if (!created) return false;
546
606
  state.pending = null;
547
607
  focusThread(created.id, false);
@@ -551,6 +611,7 @@ async function start(root) {
551
611
  state.pending = null;
552
612
  render();
553
613
  },
614
+ { kind: null },
554
615
  )
555
616
  : loginLink(),
556
617
  ),
@@ -559,9 +620,12 @@ async function start(root) {
559
620
  const anchored = all
560
621
  .filter((thread) => visible(thread) && state.anchors.has(thread.id))
561
622
  .sort((a, b) => state.anchors.get(a.id).start - state.anchors.get(b.id).start);
562
- const orphans = all.filter((thread) => visible(thread) && !state.anchors.has(thread.id));
623
+ // Notes about the whole page come first; they have no passage to lose.
624
+ const whole = all.filter((thread) => visible(thread) && !thread.target?.selector);
625
+ const orphans = all.filter((thread) => visible(thread) && thread.target?.selector && !state.anchors.has(thread.id));
563
626
  if (all.length === 0 && !state.pending)
564
627
  parts.push(h('p', { class: 'annot-empty' }, T.empty, overviewUrl ? [' ', h('a', { href: overviewUrl }, T.seeAll)] : null));
628
+ parts.push(...whole.map((thread) => threadCard(thread, false)));
565
629
  parts.push(...anchored.map((thread) => threadCard(thread, true)));
566
630
  if (orphans.length) parts.push(h('h3', { class: 'annot-orphans' }, T.orphans), ...orphans.map((thread) => threadCard(thread, false)));
567
631
  body.replaceChildren(...parts.filter(Boolean));
@@ -629,6 +693,13 @@ async function start(root) {
629
693
  selectButton.style.left = `${Math.min(window.scrollX + rect.right - selectButton.offsetWidth, window.scrollX + document.documentElement.clientWidth - selectButton.offsetWidth - 8)}px`;
630
694
  }
631
695
 
696
+ function composePageNote() {
697
+ loadMarkdown();
698
+ state.pending = { type: 'Page' };
699
+ render();
700
+ setOpen(true);
701
+ }
702
+
632
703
  async function compose() {
633
704
  if (!selected) return;
634
705
  if (state.moving) {
@@ -66,6 +66,18 @@ 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',
72
+ kind: 'Type',
73
+ noKind: 'No type',
74
+ allKinds: 'All types',
75
+ kindQuestion: 'Question',
76
+ kindIssue: 'Problem',
77
+ kindProposal: 'Proposal',
78
+ kindDecision: 'Decision',
79
+ wholePage: 'Whole page',
80
+ pageNote: 'Note on this page',
69
81
  };
70
82
 
71
83
  const it = {
@@ -133,6 +145,18 @@ const it = {
133
145
  moveHint: 'Seleziona il passaggio a cui si riferisce ora la nota, poi premi “Collega qui”.',
134
146
  moveHere: 'Collega qui',
135
147
  textChanged: 'Testo cambiato',
148
+ fresh: 'Nuova',
149
+ freshCount: '{n} nuove',
150
+ mentions: 'Persone',
151
+ kind: 'Tipo',
152
+ noKind: 'Nessun tipo',
153
+ allKinds: 'Tutti i tipi',
154
+ kindQuestion: 'Domanda',
155
+ kindIssue: 'Problema',
156
+ kindProposal: 'Proposta',
157
+ kindDecision: 'Decisione',
158
+ wholePage: 'Tutta la pagina',
159
+ pageNote: 'Nota sulla pagina',
136
160
  };
137
161
 
138
162
  const de = {
@@ -200,6 +224,18 @@ const de = {
200
224
  moveHint: 'Markiere die Stelle, um die es in dieser Notiz jetzt geht, und klicke auf „Hier verknüpfen“.',
201
225
  moveHere: 'Hier verknüpfen',
202
226
  textChanged: 'Text geändert',
227
+ fresh: 'Neu',
228
+ freshCount: '{n} neu',
229
+ mentions: 'Personen',
230
+ kind: 'Art',
231
+ noKind: 'Ohne Art',
232
+ allKinds: 'Alle Arten',
233
+ kindQuestion: 'Frage',
234
+ kindIssue: 'Problem',
235
+ kindProposal: 'Vorschlag',
236
+ kindDecision: 'Entscheidung',
237
+ wholePage: 'Ganze Seite',
238
+ pageNote: 'Notiz zur Seite',
203
239
  };
204
240
 
205
241
  const fr = {
@@ -267,6 +303,18 @@ const fr = {
267
303
  moveHint: 'Sélectionnez le passage dont parle maintenant la note, puis cliquez sur « Rattacher ici ».',
268
304
  moveHere: 'Rattacher ici',
269
305
  textChanged: 'Texte modifié',
306
+ fresh: 'Nouveau',
307
+ freshCount: '{n} nouveaux',
308
+ mentions: 'Personnes',
309
+ kind: 'Type',
310
+ noKind: 'Sans type',
311
+ allKinds: 'Tous les types',
312
+ kindQuestion: 'Question',
313
+ kindIssue: 'Problème',
314
+ kindProposal: 'Proposition',
315
+ kindDecision: 'Décision',
316
+ wholePage: 'Toute la page',
317
+ pageNote: 'Note sur la page',
270
318
  };
271
319
 
272
320
  const es = {
@@ -334,6 +382,18 @@ const es = {
334
382
  moveHint: 'Selecciona el pasaje al que se refiere ahora la nota y pulsa «Vincular aquí».',
335
383
  moveHere: 'Vincular aquí',
336
384
  textChanged: 'Texto cambiado',
385
+ fresh: 'Nueva',
386
+ freshCount: '{n} nuevas',
387
+ mentions: 'Personas',
388
+ kind: 'Tipo',
389
+ noKind: 'Sin tipo',
390
+ allKinds: 'Todos los tipos',
391
+ kindQuestion: 'Pregunta',
392
+ kindIssue: 'Problema',
393
+ kindProposal: 'Propuesta',
394
+ kindDecision: 'Decisión',
395
+ wholePage: 'Toda la página',
396
+ pageNote: 'Nota sobre la página',
337
397
  };
338
398
 
339
399
  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,7 +4,8 @@ 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 { h, quoteText, renderMarkdown } from './shared.js';
7
+ import { isNew, rememberPeople, seenTimes } from './memory.js';
8
+ import { h, kindLabel, KINDS, quoteText, renderMarkdown } from './shared.js';
8
9
 
9
10
  const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
10
11
  const T = strings(document.documentElement.lang, config.translations);
@@ -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,19 +50,21 @@ 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') ?? '',
56
+ kind: KINDS.includes(params.get('kind')) || params.get('kind') === 'none' ? params.get('kind') : '',
50
57
  };
51
58
 
52
59
  const changed = new Set(); // ids of open threads whose text is gone
53
60
  const counts = {
54
61
  open: threads.filter((entry) => !entry.thread.resolved).length,
62
+ new: threads.filter((entry) => entry.fresh).length,
55
63
  changed: 0, // known once the pages are checked
56
64
  resolved: threads.filter((entry) => entry.thread.resolved).length,
57
65
  all: threads.length,
58
66
  };
59
- const labels = { open: T.statusOpen, changed: T.textChanged, resolved: T.statusResolved, all: T.statusAll };
67
+ const labels = { open: T.statusOpen, new: T.fresh, changed: T.textChanged, resolved: T.statusResolved, all: T.statusAll };
60
68
  const option = (value) => `${labels[value]} (${counts[value]})`;
61
69
  const authors = new Map();
62
70
  for (const { thread, replies } of threads)
@@ -65,7 +73,7 @@ async function start(container) {
65
73
  const status = h(
66
74
  'select',
67
75
  { onchange: (event) => update({ status: event.target.value }) },
68
- ['open', 'changed', 'resolved', 'all'].map((value) => h('option', { value, selected: state.status === value }, option(value))),
76
+ ['open', 'new', 'changed', 'resolved', 'all'].map((value) => h('option', { value, selected: state.status === value }, option(value))),
69
77
  );
70
78
  const author = h(
71
79
  'select',
@@ -75,6 +83,18 @@ async function start(container) {
75
83
  .sort((a, b) => a[1].localeCompare(b[1]))
76
84
  .map(([login, name]) => h('option', { value: login, selected: state.author === login }, name)),
77
85
  );
86
+ const kind = h(
87
+ 'select',
88
+ { onchange: (event) => update({ kind: event.target.value }) },
89
+ h('option', { value: '' }, T.allKinds),
90
+ [...KINDS, 'none'].map((value) =>
91
+ h(
92
+ 'option',
93
+ { value, selected: state.kind === value },
94
+ `${value === 'none' ? T.noKind : kindLabel(value, T)} (${threads.filter((entry) => (entry.thread.kind ?? 'none') === value).length})`,
95
+ ),
96
+ ),
97
+ );
78
98
  const search = h('input', {
79
99
  type: 'search',
80
100
  value: state.text,
@@ -89,6 +109,7 @@ async function start(container) {
89
109
  { class: 'annot-overview-filters not-content' },
90
110
  h('label', {}, T.showing, status),
91
111
  h('label', {}, T.author, author),
112
+ h('label', {}, T.kind, kind),
92
113
  search,
93
114
  ),
94
115
  list,
@@ -99,30 +120,37 @@ async function start(container) {
99
120
  const query = new URLSearchParams();
100
121
  if (state.status !== 'open') query.set('status', state.status);
101
122
  if (state.author) query.set('author', state.author);
123
+ if (state.kind) query.set('kind', state.kind);
102
124
  if (state.text) query.set('q', state.text);
103
125
  const qs = String(query);
104
126
  history.replaceState(null, '', `${location.pathname}${qs ? `?${qs}` : ''}`);
105
127
  render();
106
128
  }
107
129
 
108
- function matches({ thread, replies }) {
130
+ function matches({ thread, replies, fresh }) {
131
+ if (state.status === 'new' && !fresh) return false;
109
132
  if (state.status === 'open' && thread.resolved) return false;
110
133
  if (state.status === 'resolved' && !thread.resolved) return false;
111
134
  if (state.status === 'changed' && (thread.resolved || !changed.has(thread.id))) return false;
112
135
  const messages = [thread, ...replies];
136
+ if (state.kind && (thread.kind ?? 'none') !== state.kind) return false;
113
137
  if (state.author && !messages.some((item) => item.author.login === state.author)) return false;
114
138
  const text = state.text.trim().toLowerCase();
115
139
  if (!text) return true;
116
- return [quoteText(thread.target.selector), ...messages.map((item) => item.body)].some((value) => value.toLowerCase().includes(text));
140
+ const quoted = thread.target?.selector ? quoteText(thread.target.selector) : '';
141
+ return [quoted, ...messages.map((item) => item.body)].some((value) => value.toLowerCase().includes(text));
117
142
  }
118
143
 
119
- function card({ page, thread, replies }) {
144
+ function card({ page, thread, replies, fresh }) {
120
145
  const when = new Date(thread.created).toLocaleString(document.documentElement.lang || undefined, { dateStyle: 'medium', timeStyle: 'short' });
121
146
  const last = replies.at(-1);
122
147
  return h(
123
148
  'article',
124
149
  { class: `annot-thread annot-overview-card${thread.resolved ? ' resolved' : ''}` },
125
- h('blockquote', { class: 'annot-quote' }, quoteText(thread.target.selector)),
150
+ thread.target?.selector
151
+ ? h('blockquote', { class: 'annot-quote' }, quoteText(thread.target.selector))
152
+ : h('div', { class: 'annot-quote annot-whole-page' }, T.wholePage),
153
+ thread.kind ? h('span', { class: `annot-kind annot-kind-${thread.kind}` }, kindLabel(thread.kind, T)) : null,
126
154
  h(
127
155
  'div',
128
156
  { class: 'annot-meta' },
@@ -130,6 +158,7 @@ async function start(container) {
130
158
  ' · ',
131
159
  when,
132
160
  thread.resolved ? h('span', { class: 'annot-badge' }, T.resolved) : null,
161
+ fresh ? h('span', { class: 'annot-badge annot-fresh-label' }, T.fresh) : null,
133
162
  !thread.resolved && changed.has(thread.id) ? h('span', { class: 'annot-badge annot-changed' }, T.textChanged) : null,
134
163
  ),
135
164
  renderMarkdown(h('div', { class: 'annot-text annot-md' }), thread.body),
@@ -180,7 +209,7 @@ async function start(container) {
180
209
  if (!root) return; // Not a page we can read: say nothing.
181
210
  const index = buildIndex(root, skip);
182
211
  for (const entry of threads)
183
- if (entry.page === page && !entry.thread.resolved && !anchor(index, entry.thread.target.selector)) changed.add(entry.thread.id);
212
+ if (entry.page === page && !entry.thread.resolved && entry.thread.target?.selector && !anchor(index, entry.thread.target.selector)) changed.add(entry.thread.id);
184
213
  });
185
214
  counts.changed = changed.size;
186
215
  status.querySelector('option[value="changed"]').textContent = option('changed');
@@ -71,3 +71,10 @@ export function quoteText(selector) {
71
71
  const exact = squash(selector.exact);
72
72
  return exact.length > 220 ? `${exact.slice(0, 130).trimEnd()} … ${exact.slice(-70).trimStart()}` : exact;
73
73
  }
74
+
75
+ export { KINDS } from '../core.js';
76
+
77
+ // "question" -> T.kindQuestion
78
+ export function kindLabel(kind, T) {
79
+ return T[`kind${kind[0].toUpperCase()}${kind.slice(1)}`] ?? kind;
80
+ }
@@ -161,6 +161,79 @@
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-kind {
205
+ align-self: flex-start;
206
+ padding: 0 0.4rem;
207
+ border-radius: 0.25rem;
208
+ font-size: var(--sl-text-xs);
209
+ font-weight: 600;
210
+ }
211
+ .annot-kind-question {
212
+ background: var(--sl-color-blue-low);
213
+ color: var(--sl-color-blue-high);
214
+ }
215
+ .annot-kind-issue {
216
+ background: var(--sl-color-red-low);
217
+ color: var(--sl-color-red-high);
218
+ }
219
+ .annot-kind-proposal {
220
+ background: var(--sl-color-green-low);
221
+ color: var(--sl-color-green-high);
222
+ }
223
+ .annot-kind-decision {
224
+ background: var(--sl-color-purple-low);
225
+ color: var(--sl-color-purple-high);
226
+ }
227
+ .annot-whole-page {
228
+ border-left-style: dashed;
229
+ font-style: normal;
230
+ }
231
+ .annot-page-note {
232
+ align-self: flex-start;
233
+ }
234
+ .annot-kind-select {
235
+ margin-left: auto;
236
+ }
164
237
  .annot-badge.annot-changed {
165
238
  margin-left: 0.4rem;
166
239
  background: var(--sl-color-orange-low);
package/src/core.js CHANGED
@@ -15,6 +15,9 @@ const MAX_EXACT = 2000;
15
15
  const MAX_EDGE = 200;
16
16
  const MAX_CONTEXT = 64;
17
17
 
18
+ // What a thread is, when its writer says: shown as a label, used as a filter.
19
+ export const KINDS = ['question', 'issue', 'proposal', 'decision'];
20
+
18
21
  export class AnnotationError extends Error {
19
22
  constructor(status, message) {
20
23
  super(message);
@@ -102,11 +105,24 @@ function selector(target) {
102
105
  };
103
106
  }
104
107
 
108
+ // A thread is about a passage (a selector), or about the whole page:
109
+ // `target: { type: 'Page' }` in the change, stored as a target without a
110
+ // selector.
111
+ function targetOf(target) {
112
+ return target?.type === 'Page' ? {} : { selector: selector(target) };
113
+ }
114
+
115
+ function kindOf(value) {
116
+ if (value === undefined || value === null || value === '') return undefined;
117
+ if (!KINDS.includes(value)) throw new AnnotationError(400, 'Unknown kind.');
118
+ return value;
119
+ }
120
+
105
121
  // A change is one of:
106
- // { action: 'create', target: { exact, prefix, suffix }, body }
122
+ // { action: 'create', target: { exact, prefix, suffix } | { type: 'Page' }, body, kind? }
107
123
  // { action: 'reply', replyTo, body }
108
124
  // { action: 'resolve', id, resolved }
109
- // { action: 'edit', id, body } the author changes their message
125
+ // { action: 'edit', id, body, kind? } the author changes their message
110
126
  // { action: 'anchor', id, target } a thread moves to another passage
111
127
  // { action: 'delete', id }
112
128
  // It returns the annotation it touched, and a commit message.
@@ -127,10 +143,12 @@ export function applyChange(doc, change, user, now = new Date()) {
127
143
  id: crypto.randomUUID(),
128
144
  created,
129
145
  author: writer,
130
- target: { selector: selector(change.target) },
146
+ target: targetOf(change.target),
131
147
  body: text(change.body, MAX_BODY, 'note'),
132
148
  resolved: false,
133
149
  };
150
+ const kind = kindOf(change.kind);
151
+ if (kind) annotation.kind = kind;
134
152
  doc.annotations.push(annotation);
135
153
  return { annotation, message: `docs(annotations): note on ${doc.page}` };
136
154
  }
@@ -161,6 +179,12 @@ export function applyChange(doc, change, user, now = new Date()) {
161
179
  const annotation = find(change.id);
162
180
  if (annotation.author?.login !== user.login) throw new AnnotationError(403, 'Only the author can edit a note.');
163
181
  annotation.body = text(change.body, MAX_BODY, annotation.replyTo ? 'reply' : 'note');
182
+ // A thread's kind changes with it; leaving `kind` out keeps it.
183
+ if (!annotation.replyTo && 'kind' in change) {
184
+ const kind = kindOf(change.kind);
185
+ if (kind) annotation.kind = kind;
186
+ else delete annotation.kind;
187
+ }
164
188
  annotation.edited = created;
165
189
  return { annotation, message: `docs(annotations): edit note on ${doc.page}` };
166
190
  }
@@ -169,7 +193,7 @@ export function applyChange(doc, change, user, now = new Date()) {
169
193
  // attaches the thread to the passage it is now about.
170
194
  const annotation = find(change.id);
171
195
  if (annotation.replyTo) throw new AnnotationError(400, 'Only a thread can be moved.');
172
- annotation.target = { selector: selector(change.target) };
196
+ annotation.target = targetOf(change.target);
173
197
  annotation.movedBy = author;
174
198
  annotation.movedAt = created;
175
199
  return { annotation, message: `docs(annotations): move note on ${doc.page}` };
@@ -57,8 +57,10 @@ export function quoteOf(thread) {
57
57
  */
58
58
  export function describeChange(event) {
59
59
  const who = event.user.name;
60
+ // "Ada added a question on …" when the note has a kind.
61
+ const what = { question: 'a question', issue: 'a problem', proposal: 'a proposal', decision: 'a decision' }[event.annotation?.kind] ?? 'a note';
60
62
  const title = {
61
- create: `${who} added a note on ${event.page}`,
63
+ create: `${who} added ${what} on ${event.page}`,
62
64
  reply: `${who} replied on ${event.page}`,
63
65
  resolve: `${who} resolved a note on ${event.page}`,
64
66
  reopen: `${who} reopened a note on ${event.page}`,