starlight-annotations 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +73 -2
- package/index.d.ts +74 -0
- package/index.js +111 -0
- package/package.json +71 -4
- package/server-node.d.ts +10 -0
- package/server.d.ts +77 -0
- package/src/client/annotations.js +731 -0
- package/src/client/backend.js +67 -0
- package/src/client/i18n.js +237 -0
- package/src/client/styles.css +387 -0
- package/src/core.js +161 -0
- package/src/server/github.js +284 -0
- package/src/server/index.js +89 -0
- package/src/server/node.js +86 -0
|
@@ -0,0 +1,731 @@
|
|
|
1
|
+
// starlight-annotations client. Select text in a page, write a note, and the
|
|
2
|
+
// note goes to the configured backend. Highlights use the CSS Custom Highlight
|
|
3
|
+
// API, so the page DOM is never rewritten: Mermaid, Expressive Code and other
|
|
4
|
+
// plugins keep working on the same nodes.
|
|
5
|
+
//
|
|
6
|
+
// Notes are written in Markdown (GitHub flavour) and stored as typed.
|
|
7
|
+
// micromark escapes raw HTML and drops javascript: links by default, so a
|
|
8
|
+
// note cannot inject markup into the page.
|
|
9
|
+
import config from 'virtual:starlight-annotations/config';
|
|
10
|
+
import { createBackend } from './backend.js';
|
|
11
|
+
import { strings } from './i18n.js';
|
|
12
|
+
|
|
13
|
+
const BASE = import.meta.env.BASE_URL.replace(/\/$/, '');
|
|
14
|
+
// Text the reader does not see as content: diagrams (rendered late), heading
|
|
15
|
+
// anchor links ("Section titled …"), buttons, and the selectors you add.
|
|
16
|
+
const SKIP = ['pre.mermaid', 'svg', 'script', 'style', 'button', '.sl-anchor-link', '.annot-ui', ...config.exclude].join(', ');
|
|
17
|
+
const CONTEXT = 32;
|
|
18
|
+
const T = strings(document.documentElement.lang, config.translations);
|
|
19
|
+
const backend = createBackend(config, BASE, T);
|
|
20
|
+
|
|
21
|
+
const mac = /Mac|iPhone|iPad/.test(navigator.platform);
|
|
22
|
+
const mod = mac ? '⌘' : 'Ctrl+';
|
|
23
|
+
|
|
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
|
+
// Edits go through execCommand when it works, so Cmd+Z still undoes them.
|
|
68
|
+
function insert(area, text) {
|
|
69
|
+
area.focus();
|
|
70
|
+
if (!document.execCommand?.('insertText', false, text)) {
|
|
71
|
+
area.setRangeText(text, area.selectionStart, area.selectionEnd, 'end');
|
|
72
|
+
area.dispatchEvent(new Event('input', { bubbles: true }));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function wrap(area, before, after, fallback) {
|
|
77
|
+
const { selectionStart: start, selectionEnd: end, value } = area;
|
|
78
|
+
// Pressing the button again on wrapped text removes the marks.
|
|
79
|
+
if (value.slice(start - before.length, start) === before && value.slice(end, end + after.length) === after) {
|
|
80
|
+
const inner = value.slice(start, end);
|
|
81
|
+
area.setSelectionRange(start - before.length, end + after.length);
|
|
82
|
+
insert(area, inner);
|
|
83
|
+
area.setSelectionRange(start - before.length, start - before.length + inner.length);
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
const inner = value.slice(start, end) || fallback;
|
|
87
|
+
insert(area, before + inner + after);
|
|
88
|
+
area.setSelectionRange(start + before.length, start + before.length + inner.length);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function prefixLines(area, prefixFor) {
|
|
92
|
+
const { selectionStart, selectionEnd, value } = area;
|
|
93
|
+
const start = value.lastIndexOf('\n', selectionStart - 1) + 1;
|
|
94
|
+
let end = value.indexOf('\n', selectionEnd);
|
|
95
|
+
if (end === -1) end = value.length;
|
|
96
|
+
const lines = value.slice(start, end).split('\n');
|
|
97
|
+
const marked = lines.every((line, i) => line.startsWith(prefixFor(i)));
|
|
98
|
+
const out = lines.map((line, i) => (marked ? line.slice(prefixFor(i).length) : prefixFor(i) + line)).join('\n');
|
|
99
|
+
area.setSelectionRange(start, end);
|
|
100
|
+
insert(area, out);
|
|
101
|
+
area.setSelectionRange(start, start + out.length);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function link(area) {
|
|
105
|
+
const { selectionStart: start, selectionEnd: end, value } = area;
|
|
106
|
+
const selected = value.slice(start, end);
|
|
107
|
+
if (/^https?:\/\/\S+$/.test(selected)) {
|
|
108
|
+
insert(area, `[${T.link.toLowerCase()}](${selected})`);
|
|
109
|
+
area.setSelectionRange(start + 1, start + 1 + T.link.length);
|
|
110
|
+
} else {
|
|
111
|
+
const label = selected || T.link.toLowerCase();
|
|
112
|
+
insert(area, `[${label}](https://)`);
|
|
113
|
+
area.setSelectionRange(start + label.length + 3, start + label.length + 11);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function code(area) {
|
|
118
|
+
const selected = area.value.slice(area.selectionStart, area.selectionEnd);
|
|
119
|
+
if (selected.includes('\n')) wrap(area, '```\n', '\n```', '');
|
|
120
|
+
else wrap(area, '`', '`', T.code.toLowerCase());
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
const svg = (paths) =>
|
|
124
|
+
`<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">${paths}</svg>`;
|
|
125
|
+
|
|
126
|
+
// [label, icon, action, shortcut key]
|
|
127
|
+
const TOOLS = [
|
|
128
|
+
[T.bold, '<b>B</b>', (area) => wrap(area, '**', '**', T.bold.toLowerCase()), 'b'],
|
|
129
|
+
[T.italic, '<i>I</i>', (area) => wrap(area, '_', '_', T.italic.toLowerCase()), 'i'],
|
|
130
|
+
[T.strike, '<s>S</s>', (area) => wrap(area, '~~', '~~', T.strike.toLowerCase())],
|
|
131
|
+
null,
|
|
132
|
+
[T.code, svg('<path d="m16 18 6-6-6-6"/><path d="m8 6-6 6 6 6"/>'), code, 'e'],
|
|
133
|
+
[T.link, svg('<path d="M10 13a5 5 0 0 0 7.5.5l3-3a5 5 0 0 0-7-7l-1.7 1.7"/><path d="M14 11a5 5 0 0 0-7.5-.5l-3 3a5 5 0 0 0 7 7l1.7-1.7"/>'), link, 'k'],
|
|
134
|
+
[T.quote, svg('<path d="M3 21c3 0 7-1 7-8V5H3v7h4c0 3-1 5-4 6"/><path d="M14 21c3 0 7-1 7-8V5h-7v7h4c0 3-1 5-4 6"/>'), (area) => prefixLines(area, () => '> ')],
|
|
135
|
+
null,
|
|
136
|
+
[T.bullets, svg('<path d="M9 6h12M9 12h12M9 18h12"/><circle cx="4" cy="6" r="1"/><circle cx="4" cy="12" r="1"/><circle cx="4" cy="18" r="1"/>'), (area) => prefixLines(area, () => '- ')],
|
|
137
|
+
[T.numbers, svg('<path d="M10 6h11M10 12h11M10 18h11"/><path d="M4 6h1v4M4 10h2M6 18H4c0-1 2-2 2-3s-1-1.5-2-1"/>'), (area) => prefixLines(area, (i) => `${i + 1}. `)],
|
|
138
|
+
[T.tasks, svg('<rect x="3" y="5" width="6" height="6" rx="1"/><path d="m3 17 2 2 4-4"/><path d="M13 6h8M13 12h8M13 18h8"/>'), (area) => prefixLines(area, () => '- [ ] ')],
|
|
139
|
+
[T.codeBlock, svg('<rect x="3" y="3" width="18" height="18" rx="2"/><path d="m10 9-3 3 3 3M14 15l3-3-3-3"/>'), (area) => wrap(area, '```\n', '\n```', '')],
|
|
140
|
+
];
|
|
141
|
+
|
|
142
|
+
const root = document.querySelector(config.content);
|
|
143
|
+
if (root instanceof HTMLElement) start(root);
|
|
144
|
+
|
|
145
|
+
function pageKey() {
|
|
146
|
+
let path = decodeURIComponent(location.pathname);
|
|
147
|
+
if (BASE && path.startsWith(BASE)) path = path.slice(BASE.length);
|
|
148
|
+
path = path.replace(/\/index\.html$|\.html$/, '').replace(/^\/+|\/+$/g, '');
|
|
149
|
+
return path || 'index';
|
|
150
|
+
}
|
|
151
|
+
|
|
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
|
+
// ---- Text index: the page text as one string, mapped back to DOM nodes ----
|
|
165
|
+
|
|
166
|
+
function buildIndex(root) {
|
|
167
|
+
const nodes = [];
|
|
168
|
+
const byNode = new Map();
|
|
169
|
+
let text = '';
|
|
170
|
+
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT, {
|
|
171
|
+
acceptNode: (node) =>
|
|
172
|
+
node.parentElement && !node.parentElement.closest(SKIP) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT,
|
|
173
|
+
});
|
|
174
|
+
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
|
|
175
|
+
const entry = { node, start: text.length };
|
|
176
|
+
nodes.push(entry);
|
|
177
|
+
byNode.set(node, entry);
|
|
178
|
+
text += node.data;
|
|
179
|
+
}
|
|
180
|
+
return { text, nodes, byNode };
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function offsetOf(index, container, offset) {
|
|
184
|
+
const entry = container.nodeType === Node.TEXT_NODE && index.byNode.get(container);
|
|
185
|
+
if (entry) return entry.start + offset;
|
|
186
|
+
const point = document.createRange();
|
|
187
|
+
point.setStart(container, offset);
|
|
188
|
+
for (const item of index.nodes) if (point.comparePoint(item.node, 0) >= 0) return item.start;
|
|
189
|
+
return index.text.length;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function pointAt(index, offset, isEnd) {
|
|
193
|
+
let found = index.nodes[0];
|
|
194
|
+
for (const item of index.nodes) {
|
|
195
|
+
if (isEnd ? item.start < offset : item.start <= offset) found = item;
|
|
196
|
+
else break;
|
|
197
|
+
}
|
|
198
|
+
return [found.node, Math.min(offset - found.start, found.node.data.length)];
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function rangeFor(index, start, end) {
|
|
202
|
+
const range = document.createRange();
|
|
203
|
+
range.setStart(...pointAt(index, start, false));
|
|
204
|
+
range.setEnd(...pointAt(index, end, true));
|
|
205
|
+
return range;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function shared(a, b, fromEnd) {
|
|
209
|
+
let n = 0;
|
|
210
|
+
const max = Math.min(a.length, b.length);
|
|
211
|
+
while (n < max && (fromEnd ? a[a.length - 1 - n] === b[b.length - 1 - n] : a[n] === b[n])) n++;
|
|
212
|
+
return n;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Finds a quote in the page, at or after `from`. Among several matches, the
|
|
216
|
+
// one whose surrounding text agrees best with the stored context wins; on a
|
|
217
|
+
// tie, the first one.
|
|
218
|
+
function anchorQuote(index, { exact, prefix = '', suffix = '' }, from = 0) {
|
|
219
|
+
const text = index.text;
|
|
220
|
+
const matches = [];
|
|
221
|
+
for (let at = text.indexOf(exact, from); at !== -1; at = text.indexOf(exact, at + 1)) matches.push([at, at + exact.length]);
|
|
222
|
+
if (matches.length === 0) {
|
|
223
|
+
// Whitespace may differ after an edit or a rebuild.
|
|
224
|
+
const pattern = exact.trim().replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/\s+/g, '\\s+');
|
|
225
|
+
if (!pattern) return null;
|
|
226
|
+
for (const match of text.matchAll(new RegExp(pattern, 'g'))) {
|
|
227
|
+
if (match.index >= from) matches.push([match.index, match.index + match[0].length]);
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
let best = null;
|
|
231
|
+
let bestScore = -1;
|
|
232
|
+
for (const [start, end] of matches) {
|
|
233
|
+
const score =
|
|
234
|
+
shared(text.slice(Math.max(0, start - prefix.length), start), prefix, true) +
|
|
235
|
+
shared(text.slice(end, end + suffix.length), suffix, false);
|
|
236
|
+
if (score > bestScore) [best, bestScore] = [[start, end], score];
|
|
237
|
+
}
|
|
238
|
+
return best;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// A long passage is stored as its start and its end: find the start, then
|
|
242
|
+
// the end after it.
|
|
243
|
+
function anchor(index, selector) {
|
|
244
|
+
if (selector.type !== 'RangeSelector') return anchorQuote(index, selector);
|
|
245
|
+
const start = anchorQuote(index, selector.startSelector);
|
|
246
|
+
if (!start) return null;
|
|
247
|
+
const end = anchorQuote(index, selector.endSelector, start[1]);
|
|
248
|
+
return end ? [start[0], end[1]] : null;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Selections longer than LONG keep only their first and last EDGE characters.
|
|
252
|
+
const LONG = config.longQuote;
|
|
253
|
+
const EDGE = 80;
|
|
254
|
+
|
|
255
|
+
function selectorFor(text, start, end) {
|
|
256
|
+
const exact = text.slice(start, end);
|
|
257
|
+
const prefix = text.slice(Math.max(0, start - CONTEXT), start);
|
|
258
|
+
const suffix = text.slice(end, end + CONTEXT);
|
|
259
|
+
if (exact.length <= LONG) return { type: 'TextQuoteSelector', exact, prefix, suffix };
|
|
260
|
+
return {
|
|
261
|
+
type: 'RangeSelector',
|
|
262
|
+
startSelector: { type: 'TextQuoteSelector', exact: exact.slice(0, EDGE), prefix },
|
|
263
|
+
endSelector: { type: 'TextQuoteSelector', exact: exact.slice(-EDGE), suffix },
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
|
|
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
|
+
// ---- The feature ----
|
|
281
|
+
|
|
282
|
+
async function start(root) {
|
|
283
|
+
const page = pageKey();
|
|
284
|
+
const initial = await backend.load(page);
|
|
285
|
+
if (!initial) return; // No backend here: stay invisible.
|
|
286
|
+
|
|
287
|
+
const state = {
|
|
288
|
+
annotations: initial.annotations,
|
|
289
|
+
user: initial.user,
|
|
290
|
+
mode: initial.mode,
|
|
291
|
+
index: null,
|
|
292
|
+
anchors: new Map(), // id -> { start, end, range }
|
|
293
|
+
pending: null, // the selector of the selection being annotated
|
|
294
|
+
showResolved: false,
|
|
295
|
+
active: null,
|
|
296
|
+
error: '',
|
|
297
|
+
};
|
|
298
|
+
const supportsHighlights = 'highlights' in CSS && typeof Highlight === 'function';
|
|
299
|
+
|
|
300
|
+
const ui = h('div', { class: 'annot-ui' });
|
|
301
|
+
const selectButton = h(
|
|
302
|
+
'button',
|
|
303
|
+
{
|
|
304
|
+
type: 'button',
|
|
305
|
+
class: 'annot-select-button',
|
|
306
|
+
hidden: true,
|
|
307
|
+
onmousedown: (event) => event.preventDefault(),
|
|
308
|
+
onclick: () => compose(),
|
|
309
|
+
},
|
|
310
|
+
T.annotate,
|
|
311
|
+
);
|
|
312
|
+
const count = h('span', { class: 'annot-count' });
|
|
313
|
+
const toggle = h('button', { type: 'button', class: 'annot-toggle', onclick: () => setOpen(!drawer.classList.contains('open')) }, T.notes, count);
|
|
314
|
+
const body = h('div', { class: 'annot-body' });
|
|
315
|
+
const drawer = h(
|
|
316
|
+
'aside',
|
|
317
|
+
{ class: 'annot-drawer', 'aria-label': T.notes },
|
|
318
|
+
h(
|
|
319
|
+
'header',
|
|
320
|
+
{},
|
|
321
|
+
h('strong', {}, T.notes),
|
|
322
|
+
h(
|
|
323
|
+
'label',
|
|
324
|
+
{ 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
|
+
}),
|
|
333
|
+
T.showResolved,
|
|
334
|
+
),
|
|
335
|
+
h('button', { type: 'button', class: 'annot-close', 'aria-label': T.close, onclick: () => setOpen(false) }, '×'),
|
|
336
|
+
),
|
|
337
|
+
body,
|
|
338
|
+
);
|
|
339
|
+
ui.append(selectButton, toggle, drawer);
|
|
340
|
+
document.body.append(ui);
|
|
341
|
+
|
|
342
|
+
function setOpen(open) {
|
|
343
|
+
drawer.classList.toggle('open', open);
|
|
344
|
+
toggle.setAttribute('aria-expanded', String(open));
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const threads = () => state.annotations.filter((item) => !item.replyTo);
|
|
348
|
+
const repliesOf = (id) => state.annotations.filter((item) => item.replyTo === id);
|
|
349
|
+
const visible = (thread) => state.showResolved || !thread.resolved;
|
|
350
|
+
|
|
351
|
+
function reanchor() {
|
|
352
|
+
state.index = buildIndex(root);
|
|
353
|
+
state.anchors.clear();
|
|
354
|
+
for (const thread of threads()) {
|
|
355
|
+
const found = anchor(state.index, thread.target.selector);
|
|
356
|
+
if (found) state.anchors.set(thread.id, { start: found[0], end: found[1], range: rangeFor(state.index, ...found) });
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function paint() {
|
|
361
|
+
if (!supportsHighlights) return;
|
|
362
|
+
// Resolved notes are highlighted only while "Show resolved" is on,
|
|
363
|
+
// and then like the others. The active note follows the same rule.
|
|
364
|
+
const shown = threads().filter((thread) => visible(thread) && state.anchors.has(thread.id));
|
|
365
|
+
CSS.highlights.set('annot', new Highlight(...shown.map((thread) => state.anchors.get(thread.id).range)));
|
|
366
|
+
const active = shown.find((thread) => thread.id === state.active);
|
|
367
|
+
if (active) CSS.highlights.set('annot-active', new Highlight(state.anchors.get(active.id).range));
|
|
368
|
+
else CSS.highlights.delete('annot-active');
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
async function send(change) {
|
|
372
|
+
state.error = '';
|
|
373
|
+
const data = await backend.send(page, change);
|
|
374
|
+
if (!data.ok) {
|
|
375
|
+
state.error = data.error;
|
|
376
|
+
if (data.status === 401) state.user = null;
|
|
377
|
+
render();
|
|
378
|
+
return null;
|
|
379
|
+
}
|
|
380
|
+
state.annotations = data.annotations;
|
|
381
|
+
reanchor();
|
|
382
|
+
paint();
|
|
383
|
+
render();
|
|
384
|
+
return data.annotation;
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function loginLink() {
|
|
388
|
+
return backend.loginUrl && initial.canSignIn !== false ? h('a', { class: 'annot-login', href: backend.loginUrl() }, T.login) : null;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
function userLine() {
|
|
392
|
+
if (state.mode === 'browser') return h('div', { class: 'annot-user' }, T.browserOnly);
|
|
393
|
+
return h(
|
|
394
|
+
'div',
|
|
395
|
+
{ class: 'annot-user' },
|
|
396
|
+
state.user.name,
|
|
397
|
+
state.mode === 'local' || !backend.logoutUrl ? ` (${T.local})` : h('a', { href: backend.logoutUrl() }, T.logout),
|
|
398
|
+
);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function meta(item) {
|
|
402
|
+
const when = new Date(item.created).toLocaleString(document.documentElement.lang || undefined, {
|
|
403
|
+
dateStyle: 'medium',
|
|
404
|
+
timeStyle: 'short',
|
|
405
|
+
});
|
|
406
|
+
return h('div', { class: 'annot-meta' }, h('span', { class: 'annot-author', title: item.author.login }, item.author.name), ' · ', when);
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
function editor(placeholder, onSave, onCancel) {
|
|
410
|
+
const area = h('textarea', { rows: 4, placeholder, maxlength: 5000, 'aria-label': placeholder });
|
|
411
|
+
const preview = h('div', { class: 'annot-preview annot-md', hidden: true });
|
|
412
|
+
const save = h('button', { type: 'button', class: 'annot-primary' }, T.save);
|
|
413
|
+
const tools = h(
|
|
414
|
+
'div',
|
|
415
|
+
{ class: 'annot-tools', role: 'toolbar', 'aria-label': T.formatting },
|
|
416
|
+
TOOLS.map((tool) => {
|
|
417
|
+
if (!tool) return h('span', { class: 'annot-tools-gap' });
|
|
418
|
+
const [label, icon, run, key] = tool;
|
|
419
|
+
const title = key ? `${label} (${mod}${key.toUpperCase()})` : label;
|
|
420
|
+
const button = h('button', {
|
|
421
|
+
type: 'button',
|
|
422
|
+
title,
|
|
423
|
+
'aria-label': title,
|
|
424
|
+
// Keep the textarea selection when the button is pressed.
|
|
425
|
+
onmousedown: (event) => event.preventDefault(),
|
|
426
|
+
onclick: () => run(area),
|
|
427
|
+
});
|
|
428
|
+
button.innerHTML = icon;
|
|
429
|
+
return button;
|
|
430
|
+
}),
|
|
431
|
+
);
|
|
432
|
+
const tab = (label, showPreview) =>
|
|
433
|
+
h('button', { type: 'button', class: 'annot-tab', role: 'tab', onclick: () => setPreview(showPreview) }, label);
|
|
434
|
+
const writeTab = tab(T.write, false);
|
|
435
|
+
const previewTab = tab(T.preview, true);
|
|
436
|
+
function setPreview(on) {
|
|
437
|
+
writeTab.setAttribute('aria-selected', String(!on));
|
|
438
|
+
previewTab.setAttribute('aria-selected', String(on));
|
|
439
|
+
area.hidden = on;
|
|
440
|
+
preview.hidden = !on;
|
|
441
|
+
tools.hidden = on;
|
|
442
|
+
if (on) {
|
|
443
|
+
if (area.value.trim()) renderMarkdown(preview, area.value);
|
|
444
|
+
else preview.replaceChildren(h('p', { class: 'annot-empty' }, T.nothing));
|
|
445
|
+
} else area.focus();
|
|
446
|
+
}
|
|
447
|
+
setPreview(false);
|
|
448
|
+
const busy = (on) => {
|
|
449
|
+
save.disabled = on;
|
|
450
|
+
area.disabled = on;
|
|
451
|
+
};
|
|
452
|
+
save.addEventListener('click', async () => {
|
|
453
|
+
if (!area.value.trim()) return area.focus();
|
|
454
|
+
busy(true);
|
|
455
|
+
const ok = await onSave(area.value);
|
|
456
|
+
if (!ok) busy(false);
|
|
457
|
+
});
|
|
458
|
+
area.addEventListener('keydown', (event) => {
|
|
459
|
+
const command = mac ? event.metaKey : event.ctrlKey;
|
|
460
|
+
if (event.key === 'Enter' && command) return save.click();
|
|
461
|
+
if (event.key === 'Escape') return onCancel();
|
|
462
|
+
if (!command || event.altKey || event.shiftKey) return;
|
|
463
|
+
const tool = TOOLS.find((item) => item && item[3] === event.key.toLowerCase());
|
|
464
|
+
if (tool) {
|
|
465
|
+
event.preventDefault();
|
|
466
|
+
tool[2](area);
|
|
467
|
+
}
|
|
468
|
+
});
|
|
469
|
+
queueMicrotask(() => area.focus());
|
|
470
|
+
return h(
|
|
471
|
+
'div',
|
|
472
|
+
{ class: 'annot-editor' },
|
|
473
|
+
h('div', { class: 'annot-editor-bar' }, h('div', { class: 'annot-tabs', role: 'tablist' }, writeTab, previewTab), tools),
|
|
474
|
+
area,
|
|
475
|
+
preview,
|
|
476
|
+
h(
|
|
477
|
+
'div',
|
|
478
|
+
{ class: 'annot-actions' },
|
|
479
|
+
save,
|
|
480
|
+
h('button', { type: 'button', onclick: onCancel }, T.cancel),
|
|
481
|
+
h('a', { class: 'annot-hint', href: 'https://www.markdownguide.org/basic-syntax/', target: '_blank', rel: 'noopener noreferrer' }, T.markdown),
|
|
482
|
+
),
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
function quote(selector) {
|
|
487
|
+
return h('blockquote', { class: 'annot-quote' }, quoteText(selector));
|
|
488
|
+
}
|
|
489
|
+
|
|
490
|
+
// A short plain-text preview of a Markdown message.
|
|
491
|
+
function snippet(body) {
|
|
492
|
+
const plain = body
|
|
493
|
+
.replace(/```[\s\S]*?```/g, ' ')
|
|
494
|
+
.replace(/!?\[([^\]]*)\]\([^)]*\)/g, '$1')
|
|
495
|
+
.replace(/[*_~`>#|]/g, '')
|
|
496
|
+
.replace(/\s+/g, ' ')
|
|
497
|
+
.trim();
|
|
498
|
+
return plain.length > 80 ? `${plain.slice(0, 80).trimEnd()}…` : plain;
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// Scrolls the panel to a message and lights it up for a moment.
|
|
502
|
+
function flash(id) {
|
|
503
|
+
const target = body.querySelector(`[data-msg="${id}"]`);
|
|
504
|
+
if (!target) return;
|
|
505
|
+
target.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
|
|
506
|
+
target.classList.remove('annot-flash');
|
|
507
|
+
void target.offsetWidth; // restart the animation
|
|
508
|
+
target.classList.add('annot-flash');
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function threadCard(thread, anchored) {
|
|
512
|
+
const card = h('article', {
|
|
513
|
+
class: `annot-thread${thread.resolved ? ' resolved' : ''}${state.active === thread.id ? ' active' : ''}`,
|
|
514
|
+
'data-id': thread.id,
|
|
515
|
+
});
|
|
516
|
+
const replyBox = h('div');
|
|
517
|
+
const byId = new Map(state.annotations.map((item) => [item.id, item]));
|
|
518
|
+
|
|
519
|
+
// One editor at a time at the bottom of the thread. Answering a reply
|
|
520
|
+
// (not the first note) records it in `inReplyTo`.
|
|
521
|
+
function openReply(answered) {
|
|
522
|
+
const header = answered ? reference(answered.id, T.replyingTo) : null;
|
|
523
|
+
replyBox.replaceChildren(
|
|
524
|
+
...(header ? [header] : []),
|
|
525
|
+
editor(
|
|
526
|
+
T.replyPlaceholder,
|
|
527
|
+
(text) => send({ action: 'reply', replyTo: thread.id, inReplyTo: answered?.id, body: text }),
|
|
528
|
+
() => replyBox.replaceChildren(),
|
|
529
|
+
),
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// "↪ in reply to Mario: «first words…»", a link to that message.
|
|
534
|
+
function reference(id, label) {
|
|
535
|
+
const target = byId.get(id);
|
|
536
|
+
if (!target) return h('div', { class: 'annot-ref deleted' }, `↪ ${T.deletedMessage}`);
|
|
537
|
+
return h(
|
|
538
|
+
'button',
|
|
539
|
+
{ type: 'button', class: 'annot-ref', onclick: () => flash(id) },
|
|
540
|
+
`↪ ${label} `,
|
|
541
|
+
h('strong', {}, target.author.name),
|
|
542
|
+
`: «${snippet(target.body)}»`,
|
|
543
|
+
);
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
const ownDelete = (item, question) =>
|
|
547
|
+
state.user && item.author.login === state.user.login
|
|
548
|
+
? h('button', { type: 'button', class: 'annot-danger', onclick: () => confirm(question) && send({ action: 'delete', id: item.id }) }, T.delete)
|
|
549
|
+
: null;
|
|
550
|
+
|
|
551
|
+
card.append(
|
|
552
|
+
h(
|
|
553
|
+
'button',
|
|
554
|
+
{ type: 'button', class: 'annot-quote-button', disabled: !anchored, onclick: () => focusThread(thread.id, true) },
|
|
555
|
+
quote(thread.target.selector),
|
|
556
|
+
),
|
|
557
|
+
...(thread.resolved ? [h('span', { class: 'annot-badge' }, T.resolved)] : []),
|
|
558
|
+
h('div', { class: 'annot-message', 'data-msg': thread.id }, meta(thread), renderMarkdown(h('div', { class: 'annot-text annot-md' }), thread.body)),
|
|
559
|
+
...repliesOf(thread.id).map((reply) =>
|
|
560
|
+
h(
|
|
561
|
+
'div',
|
|
562
|
+
{ class: 'annot-reply annot-message', 'data-msg': reply.id },
|
|
563
|
+
reply.inReplyTo ? reference(reply.inReplyTo, T.inReplyTo) : null,
|
|
564
|
+
meta(reply),
|
|
565
|
+
renderMarkdown(h('div', { class: 'annot-text annot-md' }), reply.body),
|
|
566
|
+
state.user
|
|
567
|
+
? h(
|
|
568
|
+
'div',
|
|
569
|
+
{ class: 'annot-actions annot-reply-actions' },
|
|
570
|
+
h('button', { type: 'button', onclick: () => openReply(reply) }, T.reply),
|
|
571
|
+
ownDelete(reply, T.confirmDeleteReply),
|
|
572
|
+
)
|
|
573
|
+
: null,
|
|
574
|
+
),
|
|
575
|
+
),
|
|
576
|
+
replyBox,
|
|
577
|
+
);
|
|
578
|
+
if (state.user) {
|
|
579
|
+
card.append(
|
|
580
|
+
h(
|
|
581
|
+
'div',
|
|
582
|
+
{ class: 'annot-actions' },
|
|
583
|
+
h('button', { type: 'button', onclick: () => openReply(null) }, T.reply),
|
|
584
|
+
h('button', { type: 'button', onclick: () => send({ action: 'resolve', id: thread.id, resolved: !thread.resolved }) }, thread.resolved ? T.reopen : T.resolve),
|
|
585
|
+
ownDelete(thread, T.confirmDelete),
|
|
586
|
+
),
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
return card;
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
function render() {
|
|
593
|
+
const all = threads();
|
|
594
|
+
count.textContent = String(all.filter((thread) => !thread.resolved).length);
|
|
595
|
+
const parts = [];
|
|
596
|
+
if (state.user) parts.push(userLine());
|
|
597
|
+
else parts.push(loginLink());
|
|
598
|
+
if (state.error) parts.push(h('p', { class: 'annot-error', role: 'alert' }, state.error));
|
|
599
|
+
if (state.pending) {
|
|
600
|
+
parts.push(
|
|
601
|
+
h(
|
|
602
|
+
'section',
|
|
603
|
+
{ class: 'annot-new' },
|
|
604
|
+
h('strong', {}, T.newNote),
|
|
605
|
+
quote(state.pending),
|
|
606
|
+
state.user
|
|
607
|
+
? editor(
|
|
608
|
+
T.placeholder,
|
|
609
|
+
async (text) => {
|
|
610
|
+
const created = await send({ action: 'create', target: state.pending, body: text });
|
|
611
|
+
if (!created) return false;
|
|
612
|
+
state.pending = null;
|
|
613
|
+
focusThread(created.id, false);
|
|
614
|
+
return true;
|
|
615
|
+
},
|
|
616
|
+
() => {
|
|
617
|
+
state.pending = null;
|
|
618
|
+
render();
|
|
619
|
+
},
|
|
620
|
+
)
|
|
621
|
+
: loginLink(),
|
|
622
|
+
),
|
|
623
|
+
);
|
|
624
|
+
}
|
|
625
|
+
const anchored = all
|
|
626
|
+
.filter((thread) => visible(thread) && state.anchors.has(thread.id))
|
|
627
|
+
.sort((a, b) => state.anchors.get(a.id).start - state.anchors.get(b.id).start);
|
|
628
|
+
const orphans = all.filter((thread) => visible(thread) && !state.anchors.has(thread.id));
|
|
629
|
+
if (all.length === 0 && !state.pending) parts.push(h('p', { class: 'annot-empty' }, T.empty));
|
|
630
|
+
parts.push(...anchored.map((thread) => threadCard(thread, true)));
|
|
631
|
+
if (orphans.length) parts.push(h('h3', { class: 'annot-orphans' }, T.orphans), ...orphans.map((thread) => threadCard(thread, false)));
|
|
632
|
+
body.replaceChildren(...parts.filter(Boolean));
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
function focusThread(id, scroll) {
|
|
636
|
+
state.active = id;
|
|
637
|
+
paint();
|
|
638
|
+
render();
|
|
639
|
+
setOpen(true);
|
|
640
|
+
body.querySelector(`[data-id="${id}"]`)?.scrollIntoView({ block: 'nearest' });
|
|
641
|
+
const at = state.anchors.get(id);
|
|
642
|
+
if (scroll && at) {
|
|
643
|
+
const rect = at.range.getBoundingClientRect();
|
|
644
|
+
window.scrollTo({ top: window.scrollY + rect.top - window.innerHeight / 3, behavior: 'smooth' });
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
// ---- Selection ----
|
|
649
|
+
|
|
650
|
+
function currentSelection() {
|
|
651
|
+
const selection = window.getSelection();
|
|
652
|
+
if (!selection || selection.isCollapsed || selection.rangeCount === 0) return null;
|
|
653
|
+
const range = selection.getRangeAt(0);
|
|
654
|
+
if (!root.contains(range.commonAncestorContainer)) return null;
|
|
655
|
+
state.index = buildIndex(root);
|
|
656
|
+
const text = state.index.text;
|
|
657
|
+
let start = offsetOf(state.index, range.startContainer, range.startOffset);
|
|
658
|
+
let end = offsetOf(state.index, range.endContainer, range.endOffset);
|
|
659
|
+
// Leading and trailing blanks only make the quote harder to find later.
|
|
660
|
+
while (start < end && /\s/.test(text[start])) start++;
|
|
661
|
+
while (end > start && /\s/.test(text[end - 1])) end--;
|
|
662
|
+
if (start === end) return null;
|
|
663
|
+
return { range, selector: selectorFor(text, start, end) };
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
let selected = null;
|
|
667
|
+
function onSelection() {
|
|
668
|
+
selected = currentSelection();
|
|
669
|
+
if (!selected) {
|
|
670
|
+
selectButton.hidden = true;
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
const rect = selected.range.getBoundingClientRect();
|
|
674
|
+
selectButton.hidden = false;
|
|
675
|
+
selectButton.style.top = `${window.scrollY + rect.bottom + 6}px`;
|
|
676
|
+
selectButton.style.left = `${Math.min(window.scrollX + rect.right - selectButton.offsetWidth, window.scrollX + document.documentElement.clientWidth - selectButton.offsetWidth - 8)}px`;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
function compose() {
|
|
680
|
+
if (!selected) return;
|
|
681
|
+
loadMarkdown();
|
|
682
|
+
state.pending = selected.selector;
|
|
683
|
+
selectButton.hidden = true;
|
|
684
|
+
window.getSelection()?.removeAllRanges();
|
|
685
|
+
render();
|
|
686
|
+
setOpen(true);
|
|
687
|
+
drawer.querySelector('.annot-new textarea')?.focus();
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
document.addEventListener('mouseup', () => setTimeout(onSelection));
|
|
691
|
+
document.addEventListener('keyup', (event) => {
|
|
692
|
+
if (event.shiftKey || event.key === 'Shift') onSelection();
|
|
693
|
+
});
|
|
694
|
+
document.addEventListener('selectionchange', () => {
|
|
695
|
+
if (window.getSelection()?.isCollapsed) selectButton.hidden = true;
|
|
696
|
+
});
|
|
697
|
+
|
|
698
|
+
// A click on highlighted text opens its thread.
|
|
699
|
+
root.addEventListener('click', (event) => {
|
|
700
|
+
if (!window.getSelection()?.isCollapsed) return;
|
|
701
|
+
let node;
|
|
702
|
+
let offset;
|
|
703
|
+
if (document.caretPositionFromPoint) {
|
|
704
|
+
const pos = document.caretPositionFromPoint(event.clientX, event.clientY);
|
|
705
|
+
[node, offset] = pos ? [pos.offsetNode, pos.offset] : [];
|
|
706
|
+
} else if (document.caretRangeFromPoint) {
|
|
707
|
+
const range = document.caretRangeFromPoint(event.clientX, event.clientY);
|
|
708
|
+
[node, offset] = range ? [range.startContainer, range.startOffset] : [];
|
|
709
|
+
}
|
|
710
|
+
if (!node) return;
|
|
711
|
+
for (const thread of threads()) {
|
|
712
|
+
const at = state.anchors.get(thread.id);
|
|
713
|
+
if (!at || !visible(thread)) continue;
|
|
714
|
+
// isPointInRange is inclusive at both ends; skip a click just past the end.
|
|
715
|
+
if (at.range.isPointInRange(node, offset) && at.range.comparePoint(node, offset) === 0 && !(node === at.range.endContainer && offset === at.range.endOffset)) {
|
|
716
|
+
focusThread(thread.id, false);
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
});
|
|
721
|
+
|
|
722
|
+
reanchor();
|
|
723
|
+
paint();
|
|
724
|
+
render();
|
|
725
|
+
// Fonts and late layout do not move text nodes, but a late script might.
|
|
726
|
+
window.addEventListener('load', () => {
|
|
727
|
+
reanchor();
|
|
728
|
+
paint();
|
|
729
|
+
render();
|
|
730
|
+
});
|
|
731
|
+
}
|