starlight-annotations 0.4.0 → 0.5.1

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,23 @@
1
1
  # starlight-annotations
2
2
 
3
+ ## 0.5.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 4ff776c: Adds the overview page for every locale of a multilingual site (`/it/annotations/` next to `/annotations/`), in that locale's language, and makes the notes panel link to the one in the reader's language. A sidebar link to `/annotations/` no longer leads to a missing page on localized pages, since Starlight adds the locale to it.
8
+
9
+ ## 0.5.0
10
+
11
+ ### Minor Changes
12
+
13
+ - 6ee673f: Adds a page listing every note on the site, at `/annotations/` (change it with the `overview` option, or set `overview: false` to leave it out). Notes are grouped by page and can be filtered by status, author and text; the filters are kept in the address. Each note links to its page with `#annotation-<id>`, which opens the panel on that note and scrolls to its passage, also for resolved notes. The notes panel links to the overview.
14
+
15
+ Storages gain an optional `list()`, implemented for GitHub, GitLab, Gitea/Forgejo, the disk and the browser, and the handler answers `GET {prefix}/api/all`.
16
+
17
+ ### Patch Changes
18
+
19
+ - b1bf95b: Makes the overview page easier to find: the notes panel links to it from its header, next to the title, and from the message shown on a page without notes, instead of at the end of the list.
20
+
3
21
  ## 0.4.0
4
22
 
5
23
  ### Minor Changes
package/README.md CHANGED
@@ -12,6 +12,7 @@ Let readers highlight text and leave notes on your [Starlight](https://starlight
12
12
  ## Features
13
13
 
14
14
  - 💬 **Select, note, discuss.** Markdown notes with a formatting toolbar, replies, "in reply to" references, resolve and reopen.
15
+ - 🗒️ **All notes on one page.** An overview of every note on the site, filtered by status, author or text, each one a click away from its passage.
15
16
  - 📌 **Anchored to the text.** W3C Web Annotation selectors: notes find their place again after edits, and long passages are stored by their start and end.
16
17
  - 🗂️ **Your repo, your data.** One file per page on a branch of its own; every note is a commit by its author. Works with **GitHub**, **GitLab** (gitlab.com or self-managed) and **Gitea / Forgejo** (including Codeberg).
17
18
  - 🌍 **Runs anywhere.** The API is one Web-standard handler for Cloudflare Workers, Netlify, Vercel, Deno or Node. Or keep personal notes in the browser, with no server.
package/index.d.ts CHANGED
@@ -42,6 +42,23 @@ export type AnnotationStrings = {
42
42
  numbers: string;
43
43
  tasks: string;
44
44
  codeBlock: string;
45
+ allNotes: string;
46
+ overviewDescription: string;
47
+ statusOpen: string;
48
+ statusResolved: string;
49
+ statusAll: string;
50
+ everyone: string;
51
+ filter: string;
52
+ openOnPage: string;
53
+ oneReply: string;
54
+ replies: string;
55
+ noMatches: string;
56
+ overviewEmpty: string;
57
+ overviewUnavailable: string;
58
+ loading: string;
59
+ showing: string;
60
+ author: string;
61
+ seeAll: string;
45
62
  };
46
63
 
47
64
  export interface StarlightAnnotationsOptions {
@@ -62,6 +79,11 @@ export interface StarlightAnnotationsOptions {
62
79
  longQuote?: number;
63
80
  /** Override UI strings per language, e.g. `{ it: { annotate: 'Commenta' } }`. */
64
81
  translations?: Record<string, Partial<AnnotationStrings>>;
82
+ /**
83
+ * Path of the page listing every note on the site, relative to the site base.
84
+ * Default `"annotations"` (so `/annotations/`). `false` leaves it out.
85
+ */
86
+ overview?: string | false;
65
87
  /** localStorage key prefix for the `"browser"` backend. Default `"starlight-annotations"`. */
66
88
  storageKey?: string;
67
89
  /**
package/index.js CHANGED
@@ -18,7 +18,16 @@ export default function starlightAnnotations(options = {}) {
18
18
  // Starlight links customCss on every page, in dev and in the build.
19
19
  // (CSS imported by an injected script is bundled but not linked.)
20
20
  updateConfig({ customCss: [...(starlightConfig.customCss ?? []), 'starlight-annotations/styles.css'] });
21
- addIntegration(annotationsIntegration(config));
21
+ // The overview page exists once per locale (/annotations/, /it/annotations/…),
22
+ // because Starlight prefixes sidebar links with the reader's locale.
23
+ const locales = starlightConfig.locales ?? {};
24
+ const lang = locales[starlightConfig.defaultLocale ?? 'root']?.lang ?? locales.root?.lang ?? starlightConfig.defaultLocale ?? 'en';
25
+ const prefixed = Object.fromEntries(
26
+ Object.entries(locales)
27
+ .filter(([key]) => key !== 'root')
28
+ .map(([key, locale]) => [key, locale?.lang ?? key]),
29
+ );
30
+ addIntegration(annotationsIntegration({ ...config, lang, locales: prefixed }));
22
31
  },
23
32
  },
24
33
  };
@@ -34,9 +43,14 @@ function resolveOptions(options) {
34
43
  if (!Number.isInteger(longQuote) || longQuote < 100) {
35
44
  throw new Error('starlight-annotations: "longQuote" must be an integer of at least 100.');
36
45
  }
46
+ const overview = options.overview ?? 'annotations';
47
+ if (overview !== false && (typeof overview !== 'string' || !/^[a-z0-9][a-z0-9/_-]*$/i.test(overview.replace(/^\/+|\/+$/g, '')))) {
48
+ throw new Error('starlight-annotations: "overview" must be a path such as "annotations", or false.');
49
+ }
37
50
  return {
38
51
  backend,
39
52
  apiBase,
53
+ overview: overview === false ? false : overview.replace(/^\/+|\/+$/g, ''),
40
54
  content: options.content ?? '.sl-markdown-content',
41
55
  exclude: options.exclude ?? [],
42
56
  longQuote,
@@ -55,7 +69,7 @@ function annotationsIntegration(config) {
55
69
  return {
56
70
  name: 'starlight-annotations',
57
71
  hooks: {
58
- 'astro:config:setup'({ config: astroConfig, injectScript, updateConfig }) {
72
+ 'astro:config:setup'({ config: astroConfig, injectRoute, injectScript, updateConfig }) {
59
73
  base = astroConfig.base.replace(/\/$/, '');
60
74
  root = fileURLToPath(astroConfig.root);
61
75
  updateConfig({
@@ -70,6 +84,13 @@ function annotationsIntegration(config) {
70
84
  },
71
85
  });
72
86
  injectScript('page', `import 'starlight-annotations/client';`);
87
+ if (config.overview) {
88
+ injectRoute({
89
+ pattern: `/[...locale]/${config.overview}`,
90
+ entrypoint: fileURLToPath(new URL('./src/overview.astro', import.meta.url)),
91
+ prerender: true,
92
+ });
93
+ }
73
94
  },
74
95
 
75
96
  // `astro dev` serves the same API from disk, so the feature works
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "starlight-annotations",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
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
@@ -13,6 +13,8 @@ export interface AnnotationDocument {
13
13
  export interface Storage {
14
14
  mode?: string;
15
15
  load(page: string): Promise<AnnotationDocument>;
16
+ /** Every page that has a notes file, for the overview page. Optional. */
17
+ list?(): Promise<{ page: string; annotations: AnnotationDocument['annotations'] }[]>;
16
18
  update(
17
19
  page: string,
18
20
  mutate: (doc: AnnotationDocument) => { annotation: Record<string, unknown>; message: string },
@@ -9,6 +9,7 @@
9
9
  import config from 'virtual:starlight-annotations/config';
10
10
  import { createBackend } from './backend.js';
11
11
  import { strings } from './i18n.js';
12
+ import { h, loadMarkdown, quoteText, renderMarkdown } from './shared.js';
12
13
 
13
14
  const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
14
15
  // Text the reader does not see as content: diagrams (rendered late), heading
@@ -21,49 +22,6 @@ const backend = createBackend(config, BASE, T);
21
22
  const mac = /Mac|iPhone|iPad/.test(navigator.platform);
22
23
  const mod = mac ? '⌘' : 'Ctrl+';
23
24
 
24
- // ---- Markdown ----
25
-
26
- // The Markdown parser is most of the client's weight, so it loads on demand:
27
- // when the page has notes, or when the reader starts to write one. Until it
28
- // arrives a note shows as plain text, then it is filled in.
29
- let markdown = null;
30
- let markdownLoading = null;
31
- const waitingForMarkdown = new Map(); // element -> source
32
-
33
- function loadMarkdown() {
34
- markdownLoading ??= Promise.all([import('micromark'), import('micromark-extension-gfm')]).then(([{ micromark }, { gfm, gfmHtml }]) => {
35
- markdown = (source) => micromark(source, { extensions: [gfm()], htmlExtensions: [gfmHtml()] });
36
- for (const [target, source] of waitingForMarkdown) if (target.isConnected) renderMarkdown(target, source);
37
- waitingForMarkdown.clear();
38
- }).catch(() => {
39
- // Offline or blocked: notes stay as plain text, and the next note retries.
40
- markdownLoading = null;
41
- });
42
- return markdownLoading;
43
- }
44
-
45
- function renderMarkdown(target, source) {
46
- if (!markdown) {
47
- target.textContent = source;
48
- target.classList.add('annot-md-pending');
49
- waitingForMarkdown.set(target, source);
50
- loadMarkdown();
51
- return target;
52
- }
53
- target.classList.remove('annot-md-pending');
54
- target.innerHTML = markdown(source);
55
- for (const link of target.querySelectorAll('a[href]')) {
56
- // micromark empties unsafe URLs (javascript: and the like): show plain text.
57
- if (!link.getAttribute('href')) {
58
- link.replaceWith(...link.childNodes);
59
- continue;
60
- }
61
- link.target = '_blank';
62
- link.rel = 'noopener noreferrer nofollow';
63
- }
64
- return target;
65
- }
66
-
67
25
  // Edits go through execCommand when it works, so Cmd+Z still undoes them.
68
26
  function insert(area, text) {
69
27
  area.focus();
@@ -140,7 +98,8 @@ const TOOLS = [
140
98
  ];
141
99
 
142
100
  const root = document.querySelector(config.content);
143
- if (root instanceof HTMLElement) start(root);
101
+ // The overview page lists notes; it is not annotated itself.
102
+ if (root instanceof HTMLElement && !document.querySelector('.annot-overview')) start(root);
144
103
 
145
104
  function pageKey() {
146
105
  let path = decodeURIComponent(location.pathname);
@@ -149,18 +108,6 @@ function pageKey() {
149
108
  return path || 'index';
150
109
  }
151
110
 
152
- function h(tag, attrs = {}, ...children) {
153
- const el = document.createElement(tag);
154
- for (const [key, value] of Object.entries(attrs)) {
155
- if (value === undefined || value === false) continue;
156
- if (key.startsWith('on')) el.addEventListener(key.slice(2), value);
157
- else if (key === 'class') el.className = value;
158
- else el.setAttribute(key, value === true ? '' : value);
159
- }
160
- for (const child of children.flat()) if (child != null && child !== false) el.append(child);
161
- return el;
162
- }
163
-
164
111
  // ---- Text index: the page text as one string, mapped back to DOM nodes ----
165
112
 
166
113
  function buildIndex(root) {
@@ -264,19 +211,6 @@ function selectorFor(text, start, end) {
264
211
  };
265
212
  }
266
213
 
267
- // What the panel shows: a long quote is cut in the middle.
268
- function quoteText(selector) {
269
- const squash = (value) => value.replace(/\s+/g, ' ').trim();
270
- if (selector.type === 'RangeSelector') {
271
- // The stored edges are cut by length: drop the half words at the cut.
272
- const head = squash(selector.startSelector.exact).replace(/\s+\S*$/, '');
273
- const tail = squash(selector.endSelector.exact).replace(/^\S*\s+/, '');
274
- return `${head} … ${tail}`;
275
- }
276
- const exact = squash(selector.exact);
277
- return exact.length > 220 ? `${exact.slice(0, 130).trimEnd()} … ${exact.slice(-70).trimStart()}` : exact;
278
- }
279
-
280
214
  // ---- The feature ----
281
215
 
282
216
  async function start(root) {
@@ -312,6 +246,20 @@ async function start(root) {
312
246
  const count = h('span', { class: 'annot-count' });
313
247
  const toggle = h('button', { type: 'button', class: 'annot-toggle', onclick: () => setOpen(!drawer.classList.contains('open')) }, T.notes, count);
314
248
  const body = h('div', { class: 'annot-body' });
249
+ // The page with every note on the site, when the plugin adds it.
250
+ // In the reader's locale, like the rest of the page.
251
+ const locale = page.split('/')[0];
252
+ const overviewUrl = config.overview
253
+ ? `${BASE}/${config.locales && locale in config.locales ? `${locale}/` : ''}${config.overview}/`
254
+ : null;
255
+ const resolvedBox = h('input', {
256
+ type: 'checkbox',
257
+ onchange: (event) => {
258
+ state.showResolved = event.target.checked;
259
+ paint();
260
+ render();
261
+ },
262
+ });
315
263
  const drawer = h(
316
264
  'aside',
317
265
  { class: 'annot-drawer', 'aria-label': T.notes },
@@ -319,17 +267,11 @@ async function start(root) {
319
267
  'header',
320
268
  {},
321
269
  h('strong', {}, T.notes),
270
+ overviewUrl ? h('a', { class: 'annot-all', href: overviewUrl }, T.allNotes) : null,
322
271
  h(
323
272
  'label',
324
273
  { class: 'annot-resolved-toggle' },
325
- h('input', {
326
- type: 'checkbox',
327
- onchange: (event) => {
328
- state.showResolved = event.target.checked;
329
- paint();
330
- render();
331
- },
332
- }),
274
+ resolvedBox,
333
275
  T.showResolved,
334
276
  ),
335
277
  h('button', { type: 'button', class: 'annot-close', 'aria-label': T.close, onclick: () => setOpen(false) }, '×'),
@@ -627,7 +569,8 @@ async function start(root) {
627
569
  .filter((thread) => visible(thread) && state.anchors.has(thread.id))
628
570
  .sort((a, b) => state.anchors.get(a.id).start - state.anchors.get(b.id).start);
629
571
  const orphans = all.filter((thread) => visible(thread) && !state.anchors.has(thread.id));
630
- if (all.length === 0 && !state.pending) parts.push(h('p', { class: 'annot-empty' }, T.empty));
572
+ if (all.length === 0 && !state.pending)
573
+ parts.push(h('p', { class: 'annot-empty' }, T.empty, overviewUrl ? [' ', h('a', { href: overviewUrl }, T.seeAll)] : null));
631
574
  parts.push(...anchored.map((thread) => threadCard(thread, true)));
632
575
  if (orphans.length) parts.push(h('h3', { class: 'annot-orphans' }, T.orphans), ...orphans.map((thread) => threadCard(thread, false)));
633
576
  body.replaceChildren(...parts.filter(Boolean));
@@ -720,9 +663,26 @@ async function start(root) {
720
663
  }
721
664
  });
722
665
 
666
+ // "#annotation-<id>", from the overview page or a shared link: open that
667
+ // note, showing resolved notes if it is one, and scroll to its text.
668
+ function openFromHash() {
669
+ const id = decodeURIComponent(location.hash.match(/^#annotation-(.+)$/)?.[1] ?? '');
670
+ const item = id && state.annotations.find((annotation) => annotation.id === id);
671
+ if (!item) return;
672
+ const thread = (item.replyTo && state.annotations.find((annotation) => annotation.id === item.replyTo)) || item;
673
+ if (thread.resolved && !state.showResolved) {
674
+ state.showResolved = true;
675
+ resolvedBox.checked = true;
676
+ }
677
+ focusThread(thread.id, true);
678
+ if (item !== thread) flash(item.id);
679
+ }
680
+ window.addEventListener('hashchange', openFromHash);
681
+
723
682
  reanchor();
724
683
  paint();
725
684
  render();
685
+ openFromHash();
726
686
  // Fonts and late layout do not move text nodes, but a late script might.
727
687
  window.addEventListener('load', () => {
728
688
  reanchor();
@@ -35,6 +35,15 @@ function apiBackend(config, base) {
35
35
  return { ok: false, status: response.status, signedOut: Boolean(data.signedOut), error: data.error || `Error ${response.status}` };
36
36
  return { ok: true, ...data };
37
37
  },
38
+ // Every page with notes, or null when the API cannot list them.
39
+ async list() {
40
+ try {
41
+ const response = await fetch(`${api}/api/all`, { credentials: 'same-origin' });
42
+ return response.ok ? (await response.json()).pages : null;
43
+ } catch {
44
+ return null;
45
+ }
46
+ },
38
47
  loginUrl: () => `${api}/login?return=${here()}`,
39
48
  logoutUrl: () => `${api}/logout?return=${here()}`,
40
49
  };
@@ -54,6 +63,22 @@ function browserBackend(config, T) {
54
63
  async load(page) {
55
64
  return { annotations: read(page).annotations, user, mode: 'browser' };
56
65
  },
66
+ async list() {
67
+ const prefix = `${config.storageKey}:`;
68
+ const pages = [];
69
+ try {
70
+ for (let i = 0; i < localStorage.length; i++) {
71
+ const name = localStorage.key(i);
72
+ if (!name?.startsWith(prefix)) continue;
73
+ const page = name.slice(prefix.length);
74
+ const { annotations } = read(page);
75
+ if (annotations.length) pages.push({ page, annotations });
76
+ }
77
+ } catch {
78
+ return null;
79
+ }
80
+ return pages.sort((a, b) => a.page.localeCompare(b.page));
81
+ },
57
82
  async send(page, change) {
58
83
  try {
59
84
  const doc = read(page);
@@ -43,6 +43,23 @@ const en = {
43
43
  numbers: 'Numbered list',
44
44
  tasks: 'Task list',
45
45
  codeBlock: 'Code block',
46
+ allNotes: 'All notes',
47
+ overviewDescription: 'Every note left on these docs, page by page.',
48
+ statusOpen: 'Open',
49
+ statusResolved: 'Resolved',
50
+ statusAll: 'All',
51
+ everyone: 'Everyone',
52
+ filter: 'Filter notes…',
53
+ openOnPage: 'Open on the page',
54
+ oneReply: '1 reply',
55
+ replies: '{n} replies',
56
+ noMatches: 'No notes match these filters.',
57
+ overviewEmpty: 'No notes yet.',
58
+ overviewUnavailable: 'Notes are not available on this site.',
59
+ loading: 'Loading notes…',
60
+ showing: 'Status',
61
+ author: 'Author',
62
+ seeAll: 'See the notes on other pages.',
46
63
  };
47
64
 
48
65
  const it = {
@@ -87,6 +104,23 @@ const it = {
87
104
  numbers: 'Elenco numerato',
88
105
  tasks: 'Lista di attività',
89
106
  codeBlock: 'Blocco di codice',
107
+ allNotes: 'Tutte le note',
108
+ overviewDescription: 'Tutte le note lasciate su questa documentazione, pagina per pagina.',
109
+ statusOpen: 'Aperte',
110
+ statusResolved: 'Risolte',
111
+ statusAll: 'Tutte',
112
+ everyone: 'Tutti',
113
+ filter: 'Filtra le note…',
114
+ openOnPage: 'Apri nella pagina',
115
+ oneReply: '1 risposta',
116
+ replies: '{n} risposte',
117
+ noMatches: 'Nessuna nota corrisponde ai filtri.',
118
+ overviewEmpty: 'Ancora nessuna nota.',
119
+ overviewUnavailable: 'Le note non sono disponibili su questo sito.',
120
+ loading: 'Caricamento delle note…',
121
+ showing: 'Stato',
122
+ author: 'Autore',
123
+ seeAll: 'Guarda le note delle altre pagine.',
90
124
  };
91
125
 
92
126
  const de = {
@@ -131,6 +165,23 @@ const de = {
131
165
  numbers: 'Nummerierte Liste',
132
166
  tasks: 'Aufgabenliste',
133
167
  codeBlock: 'Codeblock',
168
+ allNotes: 'Alle Notizen',
169
+ overviewDescription: 'Alle Notizen zu dieser Dokumentation, Seite für Seite.',
170
+ statusOpen: 'Offen',
171
+ statusResolved: 'Erledigt',
172
+ statusAll: 'Alle',
173
+ everyone: 'Alle Personen',
174
+ filter: 'Notizen filtern…',
175
+ openOnPage: 'Auf der Seite öffnen',
176
+ oneReply: '1 Antwort',
177
+ replies: '{n} Antworten',
178
+ noMatches: 'Keine Notizen passen zu diesen Filtern.',
179
+ overviewEmpty: 'Noch keine Notizen.',
180
+ overviewUnavailable: 'Notizen sind auf dieser Website nicht verfügbar.',
181
+ loading: 'Notizen werden geladen…',
182
+ showing: 'Status',
183
+ author: 'Autor',
184
+ seeAll: 'Notizen auf anderen Seiten ansehen.',
134
185
  };
135
186
 
136
187
  const fr = {
@@ -175,6 +226,23 @@ const fr = {
175
226
  numbers: 'Liste numérotée',
176
227
  tasks: 'Liste de tâches',
177
228
  codeBlock: 'Bloc de code',
229
+ allNotes: 'Toutes les notes',
230
+ overviewDescription: 'Toutes les notes laissées sur cette documentation, page par page.',
231
+ statusOpen: 'Ouvertes',
232
+ statusResolved: 'Résolues',
233
+ statusAll: 'Toutes',
234
+ everyone: 'Tout le monde',
235
+ filter: 'Filtrer les notes…',
236
+ openOnPage: 'Ouvrir dans la page',
237
+ oneReply: '1 réponse',
238
+ replies: '{n} réponses',
239
+ noMatches: 'Aucune note ne correspond à ces filtres.',
240
+ overviewEmpty: 'Aucune note pour le moment.',
241
+ overviewUnavailable: 'Les notes ne sont pas disponibles sur ce site.',
242
+ loading: 'Chargement des notes…',
243
+ showing: 'Statut',
244
+ author: 'Auteur',
245
+ seeAll: 'Voir les notes des autres pages.',
178
246
  };
179
247
 
180
248
  const es = {
@@ -219,6 +287,23 @@ const es = {
219
287
  numbers: 'Lista numerada',
220
288
  tasks: 'Lista de tareas',
221
289
  codeBlock: 'Bloque de código',
290
+ allNotes: 'Todas las notas',
291
+ overviewDescription: 'Todas las notas dejadas en esta documentación, página por página.',
292
+ statusOpen: 'Abiertas',
293
+ statusResolved: 'Resueltas',
294
+ statusAll: 'Todas',
295
+ everyone: 'Todos',
296
+ filter: 'Filtrar notas…',
297
+ openOnPage: 'Abrir en la página',
298
+ oneReply: '1 respuesta',
299
+ replies: '{n} respuestas',
300
+ noMatches: 'Ninguna nota coincide con estos filtros.',
301
+ overviewEmpty: 'Aún no hay notas.',
302
+ overviewUnavailable: 'Las notas no están disponibles en este sitio.',
303
+ loading: 'Cargando notas…',
304
+ showing: 'Estado',
305
+ author: 'Autor',
306
+ seeAll: 'Ver las notas de otras páginas.',
222
307
  };
223
308
 
224
309
  export const builtIn = { en, it, de, fr, es };
@@ -0,0 +1,172 @@
1
+ // The overview page: every note on the site, grouped by page, with filters.
2
+ // Read-only: a note opens on its page, where it can be answered or resolved.
3
+ import config from 'virtual:starlight-annotations/config';
4
+ import { createBackend } from './backend.js';
5
+ import { strings } from './i18n.js';
6
+ import { h, quoteText, renderMarkdown } from './shared.js';
7
+
8
+ const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
9
+ const T = strings(document.documentElement.lang, config.translations);
10
+ const container = document.querySelector('.annot-overview');
11
+ if (container instanceof HTMLElement) start(container);
12
+
13
+ // "guides/demo" -> "/base/guides/demo/", "index" -> "/base/", "it/index" -> "/base/it/".
14
+ function pageUrl(page) {
15
+ const path = page === 'index' ? '' : page.replace(/\/index$/, '');
16
+ return `${BASE}/${path ? `${path}/` : ''}`;
17
+ }
18
+
19
+ async function start(container) {
20
+ const titles = JSON.parse(container.dataset.titles || '{}');
21
+ const pages = await createBackend(config, BASE, T).list();
22
+ if (!pages) {
23
+ container.replaceChildren(h('p', {}, T.overviewUnavailable));
24
+ return;
25
+ }
26
+
27
+ // One entry per thread, with what the filters and the cards need.
28
+ const threads = pages.flatMap(({ page, annotations }) =>
29
+ annotations
30
+ .filter((item) => !item.replyTo)
31
+ .map((thread) => ({
32
+ page,
33
+ title: titles[page] ?? titles[page.replace(/\/index$/, '')] ?? page,
34
+ thread,
35
+ replies: annotations.filter((item) => item.replyTo === thread.id),
36
+ })),
37
+ );
38
+ if (threads.length === 0) {
39
+ container.replaceChildren(h('p', {}, T.overviewEmpty));
40
+ return;
41
+ }
42
+
43
+ // Filters live in the address, so a filtered view can be shared.
44
+ const params = new URLSearchParams(location.search);
45
+ const state = {
46
+ status: ['open', 'resolved', 'all'].includes(params.get('status')) ? params.get('status') : 'open',
47
+ author: params.get('author') ?? '',
48
+ text: params.get('q') ?? '',
49
+ };
50
+
51
+ const counts = {
52
+ open: threads.filter((entry) => !entry.thread.resolved).length,
53
+ resolved: threads.filter((entry) => entry.thread.resolved).length,
54
+ all: threads.length,
55
+ };
56
+ const authors = new Map();
57
+ for (const { thread, replies } of threads)
58
+ for (const item of [thread, ...replies]) authors.set(item.author.login, item.author.name || item.author.login);
59
+
60
+ const status = h(
61
+ 'select',
62
+ { 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
+ ),
70
+ );
71
+ const author = h(
72
+ 'select',
73
+ { onchange: (event) => update({ author: event.target.value }) },
74
+ h('option', { value: '' }, T.everyone),
75
+ [...authors]
76
+ .sort((a, b) => a[1].localeCompare(b[1]))
77
+ .map(([login, name]) => h('option', { value: login, selected: state.author === login }, name)),
78
+ );
79
+ const search = h('input', {
80
+ type: 'search',
81
+ value: state.text,
82
+ placeholder: T.filter,
83
+ 'aria-label': T.filter,
84
+ oninput: (event) => update({ text: event.target.value }),
85
+ });
86
+ const list = h('div', { class: 'annot-overview-list' });
87
+ container.replaceChildren(
88
+ h(
89
+ 'div',
90
+ { class: 'annot-overview-filters not-content' },
91
+ h('label', {}, T.showing, status),
92
+ h('label', {}, T.author, author),
93
+ search,
94
+ ),
95
+ list,
96
+ );
97
+
98
+ function update(change) {
99
+ Object.assign(state, change);
100
+ const query = new URLSearchParams();
101
+ if (state.status !== 'open') query.set('status', state.status);
102
+ if (state.author) query.set('author', state.author);
103
+ if (state.text) query.set('q', state.text);
104
+ const qs = String(query);
105
+ history.replaceState(null, '', `${location.pathname}${qs ? `?${qs}` : ''}`);
106
+ render();
107
+ }
108
+
109
+ function matches({ thread, replies }) {
110
+ if (state.status === 'open' && thread.resolved) return false;
111
+ if (state.status === 'resolved' && !thread.resolved) return false;
112
+ const messages = [thread, ...replies];
113
+ if (state.author && !messages.some((item) => item.author.login === state.author)) return false;
114
+ const text = state.text.trim().toLowerCase();
115
+ if (!text) return true;
116
+ return [quoteText(thread.target.selector), ...messages.map((item) => item.body)].some((value) => value.toLowerCase().includes(text));
117
+ }
118
+
119
+ function card({ page, thread, replies }) {
120
+ const when = new Date(thread.created).toLocaleString(document.documentElement.lang || undefined, { dateStyle: 'medium', timeStyle: 'short' });
121
+ const last = replies.at(-1);
122
+ return h(
123
+ 'article',
124
+ { class: `annot-thread annot-overview-card${thread.resolved ? ' resolved' : ''}` },
125
+ h('blockquote', { class: 'annot-quote' }, quoteText(thread.target.selector)),
126
+ h(
127
+ 'div',
128
+ { class: 'annot-meta' },
129
+ h('span', { class: 'annot-author', title: thread.author.login }, thread.author.name),
130
+ ' · ',
131
+ when,
132
+ thread.resolved ? h('span', { class: 'annot-badge' }, T.resolved) : null,
133
+ ),
134
+ renderMarkdown(h('div', { class: 'annot-text annot-md' }), thread.body),
135
+ h(
136
+ 'div',
137
+ { class: 'annot-overview-footer' },
138
+ replies.length
139
+ ? h('span', {}, replies.length === 1 ? T.oneReply : T.replies.replace('{n}', String(replies.length)), last ? ` · ${last.author.name}` : '')
140
+ : h('span'),
141
+ h('a', { href: `${pageUrl(page)}#annotation-${encodeURIComponent(thread.id)}` }, `${T.openOnPage} →`),
142
+ ),
143
+ );
144
+ }
145
+
146
+ function render() {
147
+ const shown = threads.filter(matches);
148
+ if (shown.length === 0) {
149
+ list.replaceChildren(h('p', { class: 'annot-empty' }, T.noMatches));
150
+ return;
151
+ }
152
+ const byPage = new Map();
153
+ for (const entry of shown) byPage.set(entry.page, [...(byPage.get(entry.page) ?? []), entry]);
154
+ const groups = [...byPage].sort((a, b) => a[1][0].title.localeCompare(b[1][0].title));
155
+ list.replaceChildren(
156
+ ...groups.map(([page, entries]) =>
157
+ h(
158
+ 'section',
159
+ { class: 'annot-overview-page' },
160
+ h('h2', {}, h('a', { href: pageUrl(page) }, entries[0].title), h('span', { class: 'annot-count' }, String(entries.length))),
161
+ h(
162
+ 'div',
163
+ { class: 'not-content annot-overview-cards' },
164
+ entries.sort((a, b) => b.thread.created.localeCompare(a.thread.created)).map(card),
165
+ ),
166
+ ),
167
+ ),
168
+ );
169
+ }
170
+
171
+ render();
172
+ }
@@ -0,0 +1,73 @@
1
+ // Pieces shared by the notes panel and the overview page.
2
+ //
3
+ // Notes are written in Markdown (GitHub flavour) and stored as typed.
4
+ // micromark escapes raw HTML and drops javascript: links by default, so a
5
+ // note cannot inject markup into the page.
6
+
7
+ // ---- Markdown ----
8
+
9
+ // The Markdown parser is most of the client's weight, so it loads on demand:
10
+ // when the page has notes, or when the reader starts to write one. Until it
11
+ // arrives a note shows as plain text, then it is filled in.
12
+ let markdown = null;
13
+ let markdownLoading = null;
14
+ const waitingForMarkdown = new Map(); // element -> source
15
+
16
+ export function loadMarkdown() {
17
+ markdownLoading ??= Promise.all([import('micromark'), import('micromark-extension-gfm')]).then(([{ micromark }, { gfm, gfmHtml }]) => {
18
+ markdown = (source) => micromark(source, { extensions: [gfm()], htmlExtensions: [gfmHtml()] });
19
+ for (const [target, source] of waitingForMarkdown) if (target.isConnected) renderMarkdown(target, source);
20
+ waitingForMarkdown.clear();
21
+ }).catch(() => {
22
+ // Offline or blocked: notes stay as plain text, and the next note retries.
23
+ markdownLoading = null;
24
+ });
25
+ return markdownLoading;
26
+ }
27
+
28
+ export function renderMarkdown(target, source) {
29
+ if (!markdown) {
30
+ target.textContent = source;
31
+ target.classList.add('annot-md-pending');
32
+ waitingForMarkdown.set(target, source);
33
+ loadMarkdown();
34
+ return target;
35
+ }
36
+ target.classList.remove('annot-md-pending');
37
+ target.innerHTML = markdown(source);
38
+ for (const link of target.querySelectorAll('a[href]')) {
39
+ // micromark empties unsafe URLs (javascript: and the like): show plain text.
40
+ if (!link.getAttribute('href')) {
41
+ link.replaceWith(...link.childNodes);
42
+ continue;
43
+ }
44
+ link.target = '_blank';
45
+ link.rel = 'noopener noreferrer nofollow';
46
+ }
47
+ return target;
48
+ }
49
+
50
+ export function h(tag, attrs = {}, ...children) {
51
+ const el = document.createElement(tag);
52
+ for (const [key, value] of Object.entries(attrs)) {
53
+ if (value === undefined || value === false) continue;
54
+ if (key.startsWith('on')) el.addEventListener(key.slice(2), value);
55
+ else if (key === 'class') el.className = value;
56
+ else el.setAttribute(key, value === true ? '' : value);
57
+ }
58
+ for (const child of children.flat()) if (child != null && child !== false) el.append(child);
59
+ return el;
60
+ }
61
+
62
+ // What the panel shows: a long quote is cut in the middle.
63
+ export function quoteText(selector) {
64
+ const squash = (value) => value.replace(/\s+/g, ' ').trim();
65
+ if (selector.type === 'RangeSelector') {
66
+ // The stored edges are cut by length: drop the half words at the cut.
67
+ const head = squash(selector.startSelector.exact).replace(/\s+\S*$/, '');
68
+ const tail = squash(selector.endSelector.exact).replace(/^\S*\s+/, '');
69
+ return `${head} … ${tail}`;
70
+ }
71
+ const exact = squash(selector.exact);
72
+ return exact.length > 220 ? `${exact.slice(0, 130).trimEnd()} … ${exact.slice(-70).trimStart()}` : exact;
73
+ }
@@ -385,3 +385,61 @@ button.annot-ref:hover {
385
385
  display: none;
386
386
  }
387
387
  }
388
+
389
+ /* Link from the panel header to the overview page. */
390
+ .annot-all {
391
+ font-size: var(--sl-text-xs);
392
+ white-space: nowrap;
393
+ }
394
+
395
+ /* The overview page. */
396
+ .annot-overview-filters {
397
+ display: flex;
398
+ flex-wrap: wrap;
399
+ gap: 0.75rem 1.25rem;
400
+ align-items: center;
401
+ margin-bottom: 1.5rem;
402
+ font-size: var(--sl-text-sm);
403
+ }
404
+ .annot-overview-filters label {
405
+ display: flex;
406
+ gap: 0.4rem;
407
+ align-items: center;
408
+ color: var(--sl-color-gray-2);
409
+ }
410
+ .annot-overview-filters :is(select, input) {
411
+ padding: 0.3rem 0.5rem;
412
+ border: 1px solid var(--sl-color-gray-5);
413
+ border-radius: 0.4rem;
414
+ background: var(--sl-color-bg);
415
+ color: var(--sl-color-white);
416
+ font: inherit;
417
+ }
418
+ .annot-overview-filters input {
419
+ flex: 1 1 12rem;
420
+ }
421
+ .annot-overview-page h2 {
422
+ display: flex;
423
+ gap: 0.6rem;
424
+ align-items: center;
425
+ }
426
+ .annot-overview-page h2 .annot-count {
427
+ font-size: var(--sl-text-xs);
428
+ }
429
+ .annot-overview-cards {
430
+ display: grid;
431
+ gap: 0.75rem;
432
+ margin-top: 0.75rem;
433
+ }
434
+ .annot-overview-card {
435
+ font-size: var(--sl-text-sm);
436
+ }
437
+ .annot-overview-footer {
438
+ display: flex;
439
+ flex-wrap: wrap;
440
+ gap: 0.5rem;
441
+ justify-content: space-between;
442
+ margin-top: 0.6rem;
443
+ color: var(--sl-color-gray-3);
444
+ font-size: var(--sl-text-xs);
445
+ }
package/src/core.js CHANGED
@@ -36,6 +36,18 @@ export function filePath(page, dir = 'annotations') {
36
36
  return folder ? `${folder}/${checkPage(page)}.json` : `${checkPage(page)}.json`;
37
37
  }
38
38
 
39
+ // The page of a stored file, or null for anything else in the folder.
40
+ export function pageFromPath(file, dir = 'annotations') {
41
+ const folder = String(dir).replace(/^\/+|\/+$/g, '');
42
+ const prefix = folder ? `${folder}/` : '';
43
+ if (!file.startsWith(prefix) || !file.endsWith('.json')) return null;
44
+ try {
45
+ return checkPage(file.slice(prefix.length, -'.json'.length));
46
+ } catch {
47
+ return null;
48
+ }
49
+ }
50
+
39
51
  export function emptyDocument(page) {
40
52
  return { version: FORMAT_VERSION, page, annotations: [] };
41
53
  }
@@ -0,0 +1,29 @@
1
+ ---
2
+ // The overview page, added by the plugin at `/<overview>/` and once per
3
+ // locale (`/it/<overview>/`), so links from a localized sidebar or panel
4
+ // land in the reader's language. Every locale lists every note of the site.
5
+ // The list itself is drawn in the browser (client/overview.js), from the
6
+ // same API as the notes panel; here only the page titles are known.
7
+ import StarlightPage from '@astrojs/starlight/components/StarlightPage.astro';
8
+ import { getCollection } from 'astro:content';
9
+ import config from 'virtual:starlight-annotations/config';
10
+ import { strings } from './client/i18n.js';
11
+
12
+ export function getStaticPaths() {
13
+ return [{ params: { locale: undefined } }, ...Object.keys(config.locales ?? {}).map((locale) => ({ params: { locale } }))];
14
+ }
15
+
16
+ const { locale } = Astro.params;
17
+ const T = strings(locale ? config.locales[locale] : config.lang, config.translations);
18
+ const docs = await getCollection('docs');
19
+ const titles = Object.fromEntries(docs.map((entry) => [entry.id, entry.data.title]));
20
+ ---
21
+
22
+ <StarlightPage frontmatter={{ title: T.allNotes, description: T.overviewDescription, tableOfContents: false, pagefind: false, editUrl: false }}>
23
+ <div class="annot-overview" data-titles={JSON.stringify(titles)}>
24
+ <p>{T.loading}</p>
25
+ </div>
26
+ <script>
27
+ import './client/overview.js';
28
+ </script>
29
+ </StarlightPage>
@@ -12,6 +12,7 @@ import { AnnotationError, parseDocument, serializeDocument } from '../core.js';
12
12
  * write: (page: string, text: string, version: string | undefined, message: string, user: object) =>
13
13
  * Promise<'ok' | 'conflict' | 'missing-branch'>,
14
14
  * createBranch: () => Promise<void>,
15
+ * pages?: () => Promise<string[]>,
15
16
  * }} host
16
17
  */
17
18
  export function gitStorage(host) {
@@ -25,6 +26,14 @@ export function gitStorage(host) {
25
26
  async load(page) {
26
27
  return (await read(page)).doc;
27
28
  },
29
+ // Every page with a notes file, for the overview. One request to list the
30
+ // files, then one per page, a few at a time.
31
+ ...(host.pages && {
32
+ async list() {
33
+ const pages = await host.pages();
34
+ return mapLimit(pages, 6, async (page) => ({ page, annotations: (await read(page)).doc.annotations }));
35
+ },
36
+ }),
28
37
  async update(page, mutate, user) {
29
38
  let branchCreated = false;
30
39
  for (let attempt = 0; attempt < 4; attempt++) {
@@ -49,3 +58,16 @@ export function gitStorage(host) {
49
58
  },
50
59
  };
51
60
  }
61
+
62
+ async function mapLimit(items, limit, run) {
63
+ const results = new Array(items.length);
64
+ let next = 0;
65
+ const worker = async () => {
66
+ while (next < items.length) {
67
+ const i = next++;
68
+ results[i] = await run(items[i]);
69
+ }
70
+ };
71
+ await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
72
+ return results;
73
+ }
@@ -8,7 +8,7 @@
8
8
  // Sign-in: an OAuth2 application on the server. Only people with write
9
9
  // access to the repository may annotate, unless `writers` says otherwise.
10
10
 
11
- import { filePath } from '../core.js';
11
+ import { filePath, pageFromPath } from '../core.js';
12
12
  import { gitStorage } from './git-storage.js';
13
13
  import { oauthAuth } from './oauth.js';
14
14
  import { decodeText, encodeText, required, restClient } from './util.js';
@@ -60,6 +60,20 @@ export function giteaStorage({ host, repo, token, branch = 'annotations', dir =
60
60
  throw new Error(`Gitea ${sha ? 'PUT' : 'POST'} ${response.status}: ${detail}`);
61
61
  },
62
62
 
63
+ async pages() {
64
+ const pages = [];
65
+ // The tree comes in pages; `truncated` says there is more.
66
+ for (let page = 1; page <= 50; page++) {
67
+ const tree = await api.get(`/repos/${repo}/git/trees/${encodeURIComponent(branch)}?recursive=true&per_page=1000&page=${page}`, {
68
+ allow404: true,
69
+ });
70
+ if (!tree) break; // No notes branch yet.
71
+ for (const entry of tree.tree ?? []) if (entry.type === 'blob') pages.push(pageFromPath(entry.path, dir));
72
+ if (!tree.truncated) break;
73
+ }
74
+ return pages.filter(Boolean);
75
+ },
76
+
63
77
  async createBranch() {
64
78
  const info = await api.get(`/repos/${repo}`);
65
79
  const response = await api.raw(`/repos/${repo}/branches`, {
@@ -13,7 +13,7 @@
13
13
  // Server credentials: a token, or `app` ({ appId, privateKey }) for a GitHub
14
14
  // App installed on `repo` (see github-app.js).
15
15
 
16
- import { filePath } from '../core.js';
16
+ import { filePath, pageFromPath } from '../core.js';
17
17
  import { githubAppToken } from './github-app.js';
18
18
  import { gitStorage } from './git-storage.js';
19
19
  import { oauthAuth } from './oauth.js';
@@ -84,6 +84,13 @@ export function githubStorage({ repo, token, app, branch = 'annotations', dir =
84
84
  throw new Error(`GitHub PUT ${response.status}: ${detail}`);
85
85
  },
86
86
 
87
+ async pages() {
88
+ const tree = await api.get(`/repos/${repo}/git/trees/${encodeURIComponent(branch)}?recursive=1`, { allow404: true });
89
+ if (!tree) return []; // No notes branch yet.
90
+ if (tree.truncated) console.warn('starlight-annotations: the notes branch is too large to list in one request; some pages are missing.');
91
+ return tree.tree.filter((entry) => entry.type === 'blob').map((entry) => pageFromPath(entry.path, dir)).filter(Boolean);
92
+ },
93
+
87
94
  async createBranch() {
88
95
  const info = await api.get(`/repos/${repo}`);
89
96
  const head = await api.get(`/repos/${repo}/git/ref/heads/${encodeURIComponent(info.default_branch)}`);
@@ -9,7 +9,7 @@
9
9
  // project members with the Developer role or higher may annotate, unless
10
10
  // `writers` says otherwise.
11
11
 
12
- import { filePath } from '../core.js';
12
+ import { filePath, pageFromPath } from '../core.js';
13
13
  import { gitStorage } from './git-storage.js';
14
14
  import { oauthAuth } from './oauth.js';
15
15
  import { decodeText, encodeText, required, restClient } from './util.js';
@@ -69,6 +69,20 @@ export function gitlabStorage({ host, project, token, branch = 'annotations', di
69
69
  throw new Error(`GitLab ${lastCommitId ? 'PUT' : 'POST'} ${response.status}: ${detail}`);
70
70
  },
71
71
 
72
+ async pages() {
73
+ const folder = String(dir).replace(/^\/+|\/+$/g, '');
74
+ const pages = [];
75
+ for (let page = 1; page <= 50; page++) {
76
+ const query = new URLSearchParams({ ref: branch, recursive: 'true', per_page: '100', page: String(page) });
77
+ if (folder) query.set('path', folder);
78
+ const entries = await api.get(`/projects/${id}/repository/tree?${query}`, { allow404: true });
79
+ if (!entries) break; // No notes branch, or no folder yet.
80
+ for (const entry of entries) if (entry.type === 'blob') pages.push(pageFromPath(entry.path, dir));
81
+ if (entries.length < 100) break;
82
+ }
83
+ return pages.filter(Boolean);
84
+ },
85
+
72
86
  async createBranch() {
73
87
  const info = await api.get(`/projects/${id}`);
74
88
  const response = await api.raw(
@@ -8,6 +8,7 @@
8
8
  //
9
9
  // Routes, under `prefix` (default "/_annotations"):
10
10
  // GET /api?page=<page> notes of a page, and who is signed in
11
+ // GET /api/all notes of every page, for the overview
11
12
  // POST /api { page, change } applies one change
12
13
  // GET /login /callback /logout handled by the auth, when it has them
13
14
 
@@ -58,6 +59,13 @@ export function createAnnotationsHandler({ storage, auth, prefix = ROUTE_PREFIX
58
59
  );
59
60
  }
60
61
 
62
+ if (route === '/api/all' && request.method === 'GET') {
63
+ if (!storage.list) return json({ error: 'This storage cannot list pages.' }, 501);
64
+ const pages = (await storage.list()).filter((entry) => entry.annotations.length > 0);
65
+ pages.sort((a, b) => a.page.localeCompare(b.page));
66
+ return json({ pages, mode: auth?.mode ?? storage.mode ?? 'api' });
67
+ }
68
+
61
69
  if (route === '/api' && request.method === 'POST') {
62
70
  const origin = request.headers.get('Origin');
63
71
  if (origin && origin !== url.origin) return json({ error: 'Cross-site request refused.' }, 403);
@@ -95,6 +103,7 @@ export function staticAuth(user) {
95
103
  * @typedef {{
96
104
  * mode?: string,
97
105
  * load(page: string): Promise<AnnotationDocument>,
106
+ * list?(): Promise<{ page: string, annotations: object[] }[]>,
98
107
  * update(page: string, mutate: (doc: AnnotationDocument) => { annotation: object, message: string }, user: User):
99
108
  * Promise<{ annotation: object, annotations: object[] }>,
100
109
  * }} Storage
@@ -2,9 +2,9 @@
2
2
  // IncomingMessage/ServerResponse to the Web-standard handler (used by the dev
3
3
  // server, and usable with Express, Fastify or plain node:http).
4
4
 
5
- import { mkdir, readFile, rename, writeFile } from 'node:fs/promises';
5
+ import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises';
6
6
  import path from 'node:path';
7
- import { filePath, parseDocument, serializeDocument } from '../core.js';
7
+ import { filePath, pageFromPath, parseDocument, serializeDocument } from '../core.js';
8
8
 
9
9
  /**
10
10
  * Notes as JSON files in a folder. Good for development, or for a Node
@@ -29,6 +29,17 @@ export function fsStorage({ dir }) {
29
29
  return {
30
30
  mode: 'local',
31
31
  load,
32
+ async list() {
33
+ let files;
34
+ try {
35
+ files = await readdir(dir, { recursive: true });
36
+ } catch (error) {
37
+ if (error.code === 'ENOENT') return [];
38
+ throw error;
39
+ }
40
+ const pages = files.map((file) => pageFromPath(file.split(path.sep).join('/'), '')).filter(Boolean);
41
+ return Promise.all(pages.map(async (page) => ({ page, annotations: (await load(page)).annotations })));
42
+ },
32
43
  update(page, mutate) {
33
44
  const run = async () => {
34
45
  const doc = await load(page);