xref: /plugin/annotations/script.js (revision 9fd890c3d28899ac6132f5f0d76a031cc5c27f1a)
1/**
2 * Annotations plugin — front-end script.
3 *
4 * Responsibilities:
5 *
6 *   1. BOOT: read JSINFO.annotations (injected by action.php); if the user
7 *      has disabled annotations, exit early.
8 *
9 *   2. LOAD: fetch the page's annotation list via the AJAX endpoint, then:
10 *        a. Anchor each annotation in the DOM (re-anchoring).
11 *        b. Wrap matched text in highlight <span>s.
12 *        c. Render per-line gutter markers.
13 *        d. Update the page counter bubble.
14 *
15 *   3. SELECTION: detect when the user finishes a text selection inside the
16 *      wiki content area, show an "Annotate" tooltip, capture the anchor on
17 *      click, and open a new-annotation form.
18 *
19 *   4. PANELS: clicking a highlight opens the annotation thread inline, just
20 *      below the paragraph that contains the highlight. One open panel at a
21 *      time. The panel renders the full thread: author, timestamp, body,
22 *      replies; and permission-gated action buttons.
23 *
24 *   5. AJAX: all state-changing operations POST JSON to
25 *      /lib/exe/ajax.php?call=annotations (with the DokuWiki security token).
26 *      Responses update the in-memory state and re-render affected highlights
27 *      / gutter markers / counter without a page reload.
28 *
29 *   6. ORPHANS: annotations that cannot be re-anchored are counted and
30 *      reachable via the orphaned counter link; their panels open in a
31 *      dedicated orphan drawer at the bottom of the content area.
32 *
33 * FF78 ESR compatibility:
34 *   - No #private fields, ??=, ||=, &&=, Array.at, structuredClone,
35 *     Object.hasOwn, native <dialog>.
36 *   - async/await, fetch, classes, ?., ??, Map/Set, IntersectionObserver OK.
37 */
38
39(function () {
40    'use strict';
41
42    // -----------------------------------------------------------------------
43    // Constants
44    // -----------------------------------------------------------------------
45
46    var AJAX_URL   = DOKU_BASE + 'lib/exe/ajax.php?call=annotations';
47    var CONTENT_ID = 'dokuwiki__content';
48    // .page is the article area inside #dokuwiki__content. Gutter markers
49    // are appended here so position:relative doesn't break the sidebar nav.
50    var PAGE_CLS = 'page';
51
52    // Colour tokens (also defined in style.css; kept here so JS can read them)
53    var CLS_HIGHLIGHT_OPEN     = 'ann-highlight-open';
54    var CLS_HIGHLIGHT_RESOLVED = 'ann-highlight-resolved';
55    var CLS_GUTTER_MARKER      = 'ann-gutter-marker';
56    var CLS_PANEL              = 'ann-panel';
57    var CLS_COUNTER            = 'ann-counter';
58    var CLS_TOOLTIP            = 'ann-tooltip';
59    var CLS_ORPHAN_DRAWER      = 'ann-orphan-drawer';
60
61    // -----------------------------------------------------------------------
62    // State
63    // -----------------------------------------------------------------------
64
65    /** All annotations fetched from the server, keyed by id. @type {Map<string,object>} */
66    var _annotations = new Map();
67
68    /** Currently open panel element, or null. @type {HTMLElement|null} */
69    var _openPanel = null;
70
71    /** Anchor captured on tooltip button mousedown; consumed by click. @type {object|null} */
72    var _pendingAnchor = null;
73
74    /** ID of the annotation whose panel is open, or null. @type {string|null} */
75    var _openAnnId = null;
76
77    /** Current user info from JSINFO. @type {{pageId:string, enabled:bool}} */
78    var _info = {};
79
80    /** Lang strings (passed by PHP into JSINFO.annotations.lang). @type {object} */
81    var _lang = {};
82
83    /** The DokuWiki security token. @type {string} */
84    var _token = '';
85
86    /** Whether the current user is logged in. @type {bool} */
87    var _loggedIn = false;
88
89    /** Whether the current user is an admin. @type {bool} */
90    var _isAdmin = false;
91
92    // -----------------------------------------------------------------------
93    // Boot
94    // -----------------------------------------------------------------------
95
96    /**
97     * Entry point: wired to DOMContentLoaded.
98     */
99    function boot() {
100        var jsinfo = (typeof JSINFO !== 'undefined' && JSINFO) ? JSINFO : {};
101        var annInfo = jsinfo.annotations || {};
102
103        if (!annInfo.enabled) {
104            return; // user disabled annotations
105        }
106
107        _info      = annInfo;
108        // UI strings come from DokuWiki's per-plugin JS lang bundle, exposed as
109        // LANG.plugins.annotations (built from lang/<iso>/lang.php $lang['js']).
110        _lang      = uiLang();
111        // Token is injected into JSINFO.annotations by action.php (handleMetaHeader).
112        // getSecurityToken() on the server produces it from session_id + REMOTE_USER.
113        _token     = annInfo.token || '';
114
115        // DokuWiki's JSINFO doesn't include user identity; we inject
116        // user + isAdmin into JSINFO.annotations from PHP (action.php).
117        _loggedIn = !!(annInfo.user && annInfo.user !== '');
118        _isAdmin  = !!(annInfo.isAdmin);
119
120        var content = document.getElementById(CONTENT_ID);
121        if (!content) {
122            return; // not a page view
123        }
124
125        renderCounter(annInfo.stats || {total: 0, open: 0, resolved: 0}, 0);
126        loadAnnotations();
127        initSelectionCapture(content);
128
129        // Close the open panel when the user presses Escape.
130        document.addEventListener('keydown', function (e) {
131            if ((e.key === 'Escape' || e.key === 'Esc') && _openPanel) {
132                closePanel();
133            }
134        });
135
136        // Keep gutter markers aligned with their highlights when the viewport
137        // width changes: both the .page column and the highlights reflow.
138        window.addEventListener('resize', repositionMarkers);
139
140        // Annotations now render at DOMContentLoaded (the list ships inline),
141        // so late-loading images/web fonts can still shift the layout under the
142        // already-placed markers. Re-align them once everything has loaded.
143        window.addEventListener('load', repositionMarkers);
144    }
145
146    // -----------------------------------------------------------------------
147    // AJAX helpers
148    // -----------------------------------------------------------------------
149
150    /**
151     * POST a JSON payload to the AJAX endpoint.
152     *
153     * @param {object} payload
154     * @returns {Promise<object>} response data
155     */
156    function ajax(payload) {
157        payload.sectok = _token; // DokuWiki security token field name for AJAX
158        return fetch(AJAX_URL, {
159            method:  'POST',
160            headers: {'Content-Type': 'application/json'},
161            body:    JSON.stringify(payload),
162        }).then(function (res) {
163            return res.json();
164        });
165    }
166
167    // -----------------------------------------------------------------------
168    // Load and anchor annotations
169    // -----------------------------------------------------------------------
170
171    /**
172     * Load all annotations for the current page and render them.
173     *
174     * Fast path: action.php normally ships the list inline with the page (in
175     * JSINFO.annotations.annotations), so we render straight away with no
176     * round-trip. Only heavily-annotated pages omit the inline list, in which
177     * case we fall back to the GET 'load' endpoint.
178     */
179    function loadAnnotations() {
180        if (Array.isArray(_info.annotations)) {
181            ingestAnnotations(_info.annotations);
182            return;
183        }
184
185        // Fallback: the inline list was too large to embed. Fetch it instead.
186        // action.php's AJAX handler accepts action=load as a GET query.
187        fetch(AJAX_URL + '&action=load&id=' + encodeURIComponent(_info.pageId), {
188            method: 'GET',
189        }).then(function (res) {
190            return res.json();
191        }).then(function (data) {
192            if (!data || !Array.isArray(data.annotations)) {
193                return;
194            }
195            ingestAnnotations(data.annotations);
196        }).catch(function () {
197            // Graceful degradation: page still works without annotations.
198        });
199    }
200
201    /**
202     * Store a loaded annotation list (inline or fetched) and render everything.
203     *
204     * @param {Array} list  annotation objects from the server
205     */
206    function ingestAnnotations(list) {
207        list.forEach(function (ann) {
208            _annotations.set(ann.id, ann);
209        });
210        renderAll();
211    }
212
213    /**
214     * Re-render everything: highlights, gutter markers, counter.
215     */
216    function renderAll() {
217        clearHighlights();
218        clearGutterMarkers();
219
220        var content = document.getElementById(CONTENT_ID);
221        if (!content) return;
222
223        // Snapshot the page text ONCE, before any highlight is inserted.
224        // Re-collecting per annotation would exclude already-wrapped text
225        // (collectTextChunks skips our own UI), shifting every later anchor.
226        var chunks  = collectTextChunks(content);
227        var rawFull = chunks.map(function (c) { return c.text; }).join('');
228        var nm      = normalizeWithMap(rawFull);
229
230        // Phase 1 — locate every annotation against the clean snapshot.
231        var hits = [];
232        _annotations.forEach(function (ann) {
233            ann._range       = null;
234            ann._highlightEl = null;
235            var hit = ann.anchor ? locate(nm.norm, ann.anchor) : null;
236            if (hit) {
237                hits.push({ann: ann, pos: hit.pos, len: hit.len});
238                ann._orphaned = false;
239            } else {
240                ann._orphaned = true;
241            }
242        });
243
244        // Phase 2 — wrap later matches first, so wrapping (which splits text
245        // nodes) never invalidates the offsets of earlier, not-yet-wrapped ones.
246        hits.sort(function (a, b) { return b.pos - a.pos; });
247        hits.forEach(function (h) {
248            var range = buildRange(chunks, nm.map, h.pos, h.len);
249            if (range) {
250                h.ann._range = range; // cache for panel positioning
251                wrapHighlight(range, h.ann);
252            } else {
253                h.ann._orphaned = true;
254            }
255        });
256
257        renderGutterMarkers();
258        updateCounter(); // recounts orphans from the _orphaned flags set above
259    }
260
261    // -----------------------------------------------------------------------
262    // Text anchoring (re-anchoring)
263    // -----------------------------------------------------------------------
264
265    /**
266     * Locate an anchor's quoted text within the normalised page text.
267     *
268     * Algorithm:
269     *   1. Search for the exact quote (normalised).
270     *   2. If found multiple times, use prefix/suffix to disambiguate.
271     *   3. If still ambiguous, use the start offset hint.
272     *
273     * Returns offsets into the normalised string; buildRange maps them back
274     * to a DOM Range via the normalised→raw index map.
275     *
276     * @param {string} norm    normalised page text (from normalizeWithMap)
277     * @param {object} anchor  {exact, prefix, suffix, start}
278     * @returns {{pos:number, len:number}|null}
279     */
280    function locate(norm, anchor) {
281        if (!anchor || !anchor.exact) return null;
282
283        var exact = normalizeWS(anchor.exact);
284        if (exact === '') return null;
285        var prefix = normalizeWS(anchor.prefix || '');
286        var suffix = normalizeWS(anchor.suffix || '');
287        var hint   = anchor.start || 0;
288
289        // Find all occurrences of exact.
290        var positions = [];
291        var from = 0;
292        var idx;
293        while ((idx = norm.indexOf(exact, from)) !== -1) {
294            positions.push(idx);
295            from = idx + exact.length;
296        }
297
298        if (positions.length === 0) return null;
299
300        var chosen = positions[0];
301
302        if (positions.length > 1) {
303            // Disambiguate using prefix + suffix context, tie-break on the hint.
304            var bestScore = -1;
305            positions.forEach(function (pos) {
306                var pre = norm.slice(Math.max(0, pos - prefix.length), pos);
307                var suf = norm.slice(pos + exact.length, pos + exact.length + suffix.length);
308                var score = 0;
309                if (prefix && pre.indexOf(prefix) !== -1) score++;
310                if (suffix && suf.indexOf(suffix) !== -1) score++;
311                var distToHint = Math.abs(pos - hint);
312                if (score > bestScore ||
313                    (score === bestScore && distToHint < Math.abs(chosen - hint))) {
314                    bestScore = score;
315                    chosen    = pos;
316                }
317            });
318        }
319
320        return {pos: chosen, len: exact.length};
321    }
322
323    /**
324     * Walk the text nodes under root and return an array of
325     * {node, start, text} objects where start is the cumulative character
326     * offset of this node's text in the joined string.
327     *
328     * The joined string is NOT normalised here — we normalise the full string
329     * once above instead.
330     *
331     * @param {HTMLElement} root
332     * @returns {Array<{node:Text, start:number, text:string}>}
333     */
334    function collectTextChunks(root) {
335        var walker = document.createTreeWalker(
336            root,
337            NodeFilter.SHOW_TEXT,
338            null,
339            false
340        );
341        var chunks = [];
342        var offset = 0;
343        var node;
344        while ((node = walker.nextNode())) {
345            // Skip nodes inside our own UI elements.
346            if (isAnnotationUI(node.parentNode)) continue;
347            var text = node.nodeValue || '';
348            chunks.push({node: node, start: offset, text: text});
349            offset += text.length;
350        }
351        return chunks;
352    }
353
354    /**
355     * The first existing highlight span the given range overlaps, or null.
356     * Used to redirect a selection that touches an annotation into opening it,
357     * rather than offering to create a new (overlapping) one. intersectsNode is
358     * supported in Firefox 78 ESR.
359     *
360     * @param {Range} range
361     * @returns {HTMLElement|null}
362     */
363    function selectionHitsHighlight(range) {
364        var spans = document.querySelectorAll(
365            '.' + CLS_HIGHLIGHT_OPEN + ', .' + CLS_HIGHLIGHT_RESOLVED
366        );
367        for (var i = 0; i < spans.length; i++) {
368            if (range.intersectsNode(spans[i])) {
369                return spans[i];
370            }
371        }
372        return null;
373    }
374
375    /**
376     * True if the node sits in a region that must never receive a new
377     * annotation: our own annotation UI (panels, counter bar, tooltip,
378     * highlights), the table of contents (#dw__toc), the page-info line
379     * (.docInfo), or a section-edit button (.secedit). These all live inside
380     * #dokuwiki__content, so plain containment is not enough to gate selection.
381     *
382     * @param {Node} node
383     * @returns {bool}
384     */
385    function isInExcludedRegion(node) {
386        var el = (node && node.nodeType === 1) ? node : (node ? node.parentNode : null);
387        while (el && el !== document.body) {
388            if (el.nodeType === 1) {
389                var cls = el.className;
390                if (typeof cls === 'string') {
391                    if (cls.indexOf('ann-') !== -1 ||  // our own UI + highlights
392                        cls.indexOf('docInfo') !== -1 ||
393                        cls.indexOf('secedit') !== -1) {
394                        return true;
395                    }
396                }
397                if (el.id === 'dw__toc') return true;
398            }
399            el = el.parentNode;
400        }
401        return false;
402    }
403
404    /**
405     * True if the element (or its ancestor) is part of our annotation UI.
406     *
407     * @param {Node} el
408     * @returns {bool}
409     */
410    function isAnnotationUI(el) {
411        while (el && el !== document.body) {
412            if (el.nodeType === 1) {
413                var cls = el.className || '';
414                if (
415                    cls.indexOf('ann-') !== -1 ||
416                    cls.indexOf(CLS_PANEL) !== -1
417                ) {
418                    return true;
419                }
420            }
421            el = el.parentNode;
422        }
423        return false;
424    }
425
426    /**
427     * Turn a (start, length) offset in the normalised page text back into a
428     * DOM Range, using the normalised→raw index map.
429     *
430     * @param {Array<{node:Text, start:number, text:string}>} chunks
431     * @param {Array<number>} map       normalised index → raw index (normalizeWithMap)
432     * @param {number}        startOff  start offset in the normalised text
433     * @param {number}        length    length in normalised characters
434     * @returns {Range|null}
435     */
436    function buildRange(chunks, map, startOff, length) {
437        var rawStart = map[startOff];
438        var rawEnd   = map[startOff + length - 1];
439        if (rawStart === undefined || rawEnd === undefined) return null;
440        rawEnd++; // exclusive
441
442        // Find which chunks contain rawStart and rawEnd.
443        var startChunk = null, startOffset = 0;
444        var endChunk   = null, endOffset   = 0;
445
446        for (var i = 0; i < chunks.length; i++) {
447            var c = chunks[i];
448            var cEnd = c.start + c.text.length;
449
450            if (startChunk === null && c.start <= rawStart && rawStart < cEnd) {
451                startChunk  = c.node;
452                startOffset = rawStart - c.start;
453            }
454            if (endChunk === null && c.start < rawEnd && rawEnd <= cEnd) {
455                endChunk  = c.node;
456                endOffset = rawEnd - c.start;
457            }
458            if (startChunk && endChunk) break;
459        }
460
461        if (!startChunk || !endChunk) return null;
462
463        try {
464            var range = document.createRange();
465            range.setStart(startChunk, startOffset);
466            range.setEnd(endChunk, endOffset);
467            return range;
468        } catch (e) {
469            return null;
470        }
471    }
472
473    /**
474     * Normalise raw text exactly as normalizeWS does (collapse each whitespace
475     * run to a single space, trim both ends) while recording, for every
476     * character of the normalised string, the index of the raw character it
477     * came from. Returns {norm, map} with raw.charAt(map[i]) === norm.charAt(i)
478     * (a collapsed internal space maps to the first char of its run).
479     *
480     * Normalisation and the index map MUST stay in lockstep: an earlier
481     * version built the map without trimming, so a leading whitespace text
482     * node (DokuWiki indents its content markup, so there always is one)
483     * shifted every highlight one character to the left.
484     *
485     * @param {string} raw
486     * @returns {{norm:string, map:Array<number>}}
487     */
488    function normalizeWithMap(raw) {
489        var norm     = '';
490        var map      = [];
491        var inRun    = false;
492        var runStart = 0;
493        for (var i = 0; i < raw.length; i++) {
494            if (/\s/.test(raw[i])) {
495                if (!inRun) { inRun = true; runStart = i; }
496                continue;
497            }
498            if (inRun) {
499                inRun = false;
500                // internal run → one representative space; leading run → dropped
501                if (norm.length > 0) {
502                    norm += ' ';
503                    map.push(runStart);
504                }
505            }
506            norm += raw[i];
507            map.push(i);
508        }
509        // a trailing whitespace run is dropped (matches trim)
510        return {norm: norm, map: map};
511    }
512
513    // -----------------------------------------------------------------------
514    // Highlights
515    // -----------------------------------------------------------------------
516
517    /**
518     * Wrap a Range in a highlight <span> for the given annotation.
519     *
520     * @param {Range}  range
521     * @param {object} ann
522     */
523    function wrapHighlight(range, ann) {
524        var preview = ann.body || '';
525        var span = document.createElement('span');
526        span.className = ann.status === 'resolved'
527            ? CLS_HIGHLIGHT_RESOLVED
528            : CLS_HIGHLIGHT_OPEN;
529        span.dataset.annId = ann.id;
530        span.title = preview.slice(0, 80) + (preview.length > 80 ? '…' : '');
531        span.addEventListener('click', function (e) {
532            e.stopPropagation();
533            openPanel(ann.id);
534        });
535
536        try {
537            range.surroundContents(span);
538            ann._highlightEl = span;
539        } catch (e) {
540            // surroundContents throws if the range crosses element boundaries;
541            // fall back to extract + insert, reusing the same (still-empty) span.
542            try {
543                span.appendChild(range.extractContents());
544                range.insertNode(span);
545                ann._highlightEl = span;
546            } catch (e2) {
547                ann._highlightEl = null;
548            }
549        }
550    }
551
552    /**
553     * Remove all highlight spans, restoring the original text nodes.
554     */
555    function clearHighlights() {
556        var spans = document.querySelectorAll(
557            '.' + CLS_HIGHLIGHT_OPEN + ', .' + CLS_HIGHLIGHT_RESOLVED
558        );
559        Array.prototype.forEach.call(spans, function (span) {
560            var parent = span.parentNode;
561            if (!parent) return;
562            while (span.firstChild) {
563                parent.insertBefore(span.firstChild, span);
564            }
565            parent.removeChild(span);
566            parent.normalize();
567        });
568    }
569
570    // -----------------------------------------------------------------------
571    // Gutter markers
572    // -----------------------------------------------------------------------
573
574    /**
575     * Render a small marker for every anchored annotation. Markers are
576     * appended to document.body as absolutely-positioned elements so that
577     * template overflow rules on inner containers cannot clip them.
578     *
579     * All markers share the same X position — just to the left of the .page
580     * content column — so they form a tidy vertical column in the margin.
581     */
582    function renderGutterMarkers() {
583        var scrollTop  = window.pageYOffset || document.documentElement.scrollTop;
584        var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
585        var markerLeft = gutterMarkerLeft(scrollLeft);
586
587        // Speech bubble SVG — clearly communicates "annotation here".
588        var ICON_SVG =
589            '<svg viewBox="0 0 16 16" fill="currentColor" width="10" height="10" aria-hidden="true">' +
590            '<rect x="1" y="1" width="14" height="10" rx="2"/>' +
591            '<path d="M4 14 L4 11 L8 11 Z"/>' +
592            '</svg>';
593
594        _annotations.forEach(function (ann) {
595            if (!ann._highlightEl) return; // orphan
596
597            var rect = ann._highlightEl.getBoundingClientRect();
598
599            var marker = document.createElement('button');
600            marker.className      = CLS_GUTTER_MARKER;
601            marker.dataset.annId  = ann.id;
602            marker.dataset.status = ann.status || 'open'; // drives CSS amber/green colour
603            marker.setAttribute('aria-label', t('label_annotation', 'Annotation'));
604            marker.type      = 'button';
605            marker.innerHTML = ICON_SVG;
606            // Align vertically with the first line of the highlight.
607            marker.style.top  = (rect.top + scrollTop + 3) + 'px';
608            marker.style.left = markerLeft + 'px';
609            marker.addEventListener('click', function (e) {
610                e.stopPropagation();
611                openPanel(ann.id);
612            });
613            document.body.appendChild(marker);
614            ann._markerEl = marker;
615        });
616    }
617
618    /**
619     * Remove all gutter markers.
620     */
621    function clearGutterMarkers() {
622        var markers = document.querySelectorAll('.' + CLS_GUTTER_MARKER);
623        Array.prototype.forEach.call(markers, function (m) {
624            if (m.parentNode) m.parentNode.removeChild(m);
625        });
626    }
627
628    /**
629     * The shared X position (document coordinates) for every gutter marker:
630     * just inside the left padding of the .page content column, so the markers
631     * form a tidy vertical strip in the margin. Falls back to 4px when the
632     * column cannot be measured. Reads the theme's computed padding so it
633     * adapts to the template.
634     *
635     * @param {number} scrollLeft current horizontal scroll offset
636     * @returns {number}
637     */
638    function gutterMarkerLeft(scrollLeft) {
639        var pageEl = document.querySelector('.' + PAGE_CLS) || document.getElementById(CONTENT_ID);
640        if (!pageEl) return 4;
641        var pageRect = pageEl.getBoundingClientRect();
642        var padLeft  = parseInt(window.getComputedStyle(pageEl).paddingLeft, 10) || 32;
643        return pageRect.left + scrollLeft + Math.max(2, Math.floor(padLeft * 0.25));
644    }
645
646    /**
647     * Re-align every existing marker with its highlight without rebuilding the
648     * DOM. Highlights shift when a panel is inserted/removed or the window is
649     * resized, but markers live in document.body at absolute coordinates, so
650     * they would otherwise drift out of line. Cheap — only touches inline
651     * top/left on the handful of markers present.
652     */
653    function repositionMarkers() {
654        var scrollTop  = window.pageYOffset || document.documentElement.scrollTop;
655        var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
656        var markerLeft = gutterMarkerLeft(scrollLeft);
657        _annotations.forEach(function (ann) {
658            if (!ann._markerEl || !ann._highlightEl) return;
659            var rect = ann._highlightEl.getBoundingClientRect();
660            ann._markerEl.style.top  = (rect.top + scrollTop + 3) + 'px';
661            ann._markerEl.style.left = markerLeft + 'px';
662        });
663    }
664
665    // -----------------------------------------------------------------------
666    // Page counter
667    // -----------------------------------------------------------------------
668
669    /**
670     * Render (or update) the counter bubble above the content area.
671     *
672     * @param {object} stats        {total, open, resolved}
673     * @param {number} orphanCount
674     */
675    function renderCounter(stats, orphanCount) {
676        var existing = document.getElementById('ann-counter-bar');
677        if (existing) existing.parentNode.removeChild(existing);
678
679        if (stats.total === 0 && orphanCount === 0) return;
680
681        var bar = document.createElement('div');
682        bar.id = 'ann-counter-bar';
683        bar.className = CLS_COUNTER;
684
685        var total = stats.total || 0;
686        var label = total === 1
687            ? t('counter_annotation', '1 annotation')
688            : fmt(t('counter_annotations', '%d annotations'), total);
689        bar.appendChild(document.createTextNode(label));
690
691        if (orphanCount > 0) {
692            bar.appendChild(document.createTextNode(' · '));
693            var orphanLink = document.createElement('a');
694            orphanLink.href = '#ann-orphan-drawer';
695            orphanLink.className = 'ann-orphan-link';
696            orphanLink.textContent = fmt(t('counter_orphaned', '%d orphaned'), orphanCount);
697            orphanLink.addEventListener('click', function (e) {
698                e.preventDefault();
699                toggleOrphanDrawer();
700                repositionMarkers();
701            });
702            bar.appendChild(orphanLink);
703        }
704
705        if (_isAdmin && (stats.resolved > 0 || orphanCount > 0)) {
706            if (stats.resolved > 0) {
707                var btnCR = document.createElement('button');
708                btnCR.type = 'button';
709                btnCR.className = 'ann-btn ann-btn-admin';
710                btnCR.textContent = t('btn_clear_resolved', 'Clear resolved');
711                btnCR.addEventListener('click', function () { doClearResolved(btnCR); });
712                bar.appendChild(btnCR);
713            }
714            if (orphanCount > 0) {
715                var btnCO = document.createElement('button');
716                btnCO.type = 'button';
717                btnCO.className = 'ann-btn ann-btn-admin';
718                btnCO.textContent = t('btn_clear_orphaned', 'Clear orphaned');
719                btnCO.addEventListener('click', function () { doClearOrphaned(btnCO); });
720                bar.appendChild(btnCO);
721            }
722        }
723
724        // Insert inside .page, right after #dw__toc if present.
725        // The TOC is float:right so placing the bar after it (not before) lets
726        // it sit to the left of the float instead of pushing the TOC down.
727        var pageEl = document.querySelector('.' + PAGE_CLS);
728        if (pageEl) {
729            var toc = pageEl.querySelector('#dw__toc');
730            if (toc && toc.nextSibling) {
731                pageEl.insertBefore(bar, toc.nextSibling);
732            } else if (toc) {
733                pageEl.appendChild(bar);
734            } else {
735                pageEl.insertBefore(bar, pageEl.firstChild);
736            }
737        } else {
738            var content = document.getElementById(CONTENT_ID);
739            if (content) content.insertBefore(bar, content.firstChild);
740        }
741    }
742
743    /**
744     * Recount and re-render the counter from in-memory state.
745     */
746    function updateCounter(orphanCount) {
747        var open = 0, resolved = 0;
748        if (orphanCount === undefined) {
749            orphanCount = 0;
750        }
751        _annotations.forEach(function (ann) {
752            if (ann._orphaned) {
753                orphanCount++;
754            } else if (ann.status === 'resolved') {
755                resolved++;
756            } else {
757                open++;
758            }
759        });
760        renderCounter({total: open + resolved, open: open, resolved: resolved}, orphanCount);
761    }
762
763    // -----------------------------------------------------------------------
764    // Annotation panel
765    // -----------------------------------------------------------------------
766
767    /**
768     * Open the thread panel for the given annotation id.
769     * If that panel is already open, close it.
770     *
771     * @param {string}  annId
772     * @param {boolean} [focusReply]  focus the reply box once open (default true);
773     *                                reopenPanel passes false so re-rendering after
774     *                                an action doesn't yank the viewport to the form.
775     */
776    function openPanel(annId, focusReply) {
777        if (_openAnnId === annId) {
778            closePanel();
779            return;
780        }
781        closePanel();
782
783        var ann = _annotations.get(annId);
784        if (!ann) return;
785
786        var panel = buildPanel(ann);
787        _openPanel  = panel;
788        _openAnnId  = annId;
789
790        // Insert below the paragraph that contains the highlight.
791        var anchor = ann._highlightEl || null;
792        var insertAfter = findParagraph(anchor);
793        if (insertAfter && insertAfter.parentNode) {
794            insertAfter.parentNode.insertBefore(panel, insertAfter.nextSibling);
795        } else {
796            // Orphan or no paragraph found: show at the bottom of content.
797            var content = document.getElementById(CONTENT_ID);
798            if (content) content.appendChild(panel);
799        }
800
801        if (focusReply !== false) {
802            var input = panel.querySelector('.ann-body-input');
803            if (input) input.focus();
804        }
805
806        // The panel grew the document; nudge markers below it back into line.
807        repositionMarkers();
808    }
809
810    /**
811     * Close and remove the currently open panel.
812     */
813    function closePanel() {
814        if (_openPanel && _openPanel.parentNode) {
815            _openPanel.parentNode.removeChild(_openPanel);
816        }
817        _openPanel = null;
818        _openAnnId = null;
819        repositionMarkers();
820    }
821
822    /**
823     * Find the nearest block-level ancestor of el (p, li, h1-h6, etc.)
824     * that can receive a sibling element.
825     *
826     * @param {HTMLElement|null} el
827     * @returns {HTMLElement|null}
828     */
829    function findParagraph(el) {
830        var block = /^(P|LI|DT|DD|H[1-6]|BLOCKQUOTE|PRE|TABLE|DIV)$/;
831        var node = el;
832        while (node && node.id !== CONTENT_ID) {
833            if (node.nodeType === 1 && block.test(node.tagName)) {
834                return node;
835            }
836            node = node.parentNode;
837        }
838        return el; // fallback: use the element itself
839    }
840
841    /**
842     * Build and return the panel DOM element for one annotation.
843     *
844     * @param {object} ann
845     * @returns {HTMLElement}
846     */
847    function buildPanel(ann) {
848        var panel = document.createElement('div');
849        panel.className = CLS_PANEL;
850        panel.dataset.annId  = ann.id;
851        panel.dataset.status = ann.status || 'open'; // drives the resolved accent in style.css
852
853        // Main annotation thread entry (close button lives in its meta row).
854        var rootEntry = buildThreadEntry(ann, true);
855        var meta = rootEntry.querySelector('.ann-meta');
856        if (meta) {
857            var closeBtn = document.createElement('button');
858            closeBtn.type = 'button';
859            closeBtn.className = 'ann-btn ann-close';
860            closeBtn.setAttribute('aria-label', t('label_close', 'Close'));
861            closeBtn.textContent = '×'; // ×
862            closeBtn.style.marginLeft = 'auto';
863            closeBtn.addEventListener('click', closePanel);
864            meta.appendChild(closeBtn);
865        }
866        panel.appendChild(rootEntry);
867
868        // Replies: build hierarchy from flat list and render depth-indented.
869        appendReplyTree(panel, ann, buildReplyTree(ann.replies || []), 0);
870
871        // Reply form at the bottom for root-level replies.
872        if (_loggedIn) {
873            panel.appendChild(buildReplyForm(ann));
874        }
875
876        return panel;
877    }
878
879    /**
880     * Build the DOM for the top-level annotation entry.
881     *
882     * @param {object}  ann
883     * @param {boolean} isRoot  true for the annotation itself, false for replies
884     * @returns {HTMLElement}
885     */
886    function buildThreadEntry(ann, isRoot) {
887        var entry = document.createElement('div');
888        entry.className = 'ann-thread-entry ann-annotation';
889        entry.dataset.annId = ann.id;
890
891        // Meta row: avatar, author, time, status pill
892        entry.appendChild(buildMeta(ann.author, ann.created, ann.status));
893
894        // Body
895        var bodyEl = document.createElement('div');
896        bodyEl.className = 'ann-body';
897        bodyEl.textContent = ann.body;
898        entry.appendChild(bodyEl);
899
900        // Quoted text snippet
901        if (ann.anchor && ann.anchor.exact) {
902            var quote = document.createElement('blockquote');
903            quote.className = 'ann-quote';
904            quote.textContent = ann.anchor.exact;
905            entry.appendChild(quote);
906        }
907
908        // Action buttons
909        var actions = document.createElement('div');
910        actions.className = 'ann-actions';
911
912        // Resolve/Reopen (any reader)
913        if (_loggedIn) {
914            var resolveBtn = document.createElement('button');
915            resolveBtn.type = 'button';
916            resolveBtn.className = 'ann-btn ann-btn-primary';
917            resolveBtn.textContent = ann.status === 'resolved'
918                ? t('btn_reopen', 'Reopen')
919                : t('btn_resolve', 'Resolve');
920            resolveBtn.addEventListener('click', function () {
921                doResolve(ann.id, ann.status === 'resolved' ? 'open' : 'resolved', resolveBtn);
922            });
923            actions.appendChild(resolveBtn);
924        }
925
926        // Edit + Delete (own or admin)
927        var canEdit = _isAdmin || ann.author === currentUser();
928        if (canEdit && _loggedIn) {
929            var editBtn = document.createElement('button');
930            editBtn.type = 'button';
931            editBtn.className = 'ann-btn';
932            editBtn.textContent = t('btn_edit', 'Edit');
933            editBtn.addEventListener('click', function () {
934                showEditForm(entry, ann, 'annotation');
935            });
936            actions.appendChild(editBtn);
937
938            var delBtn = document.createElement('button');
939            delBtn.type = 'button';
940            delBtn.className = 'ann-btn ann-btn-danger';
941            delBtn.textContent = t('btn_delete', 'Delete');
942            delBtn.addEventListener('click', function () {
943                if (confirm(t('confirm_delete', 'Delete this annotation?'))) {
944                    doDeleteAnnotation(ann.id, delBtn);
945                }
946            });
947            actions.appendChild(delBtn);
948        }
949
950        entry.appendChild(actions);
951        return entry;
952    }
953
954    /**
955     * Build the DOM for one reply entry, indented according to its nesting depth.
956     *
957     * @param {object} ann    parent annotation
958     * @param {object} reply
959     * @param {number} depth  0 = direct reply to annotation; 1+ = nested
960     * @returns {HTMLElement}
961     */
962    function buildReplyEntry(ann, reply, depth) {
963        var entry = document.createElement('div');
964        entry.className = 'ann-thread-entry ann-reply';
965        entry.dataset.replyId = reply.id;
966        // Indent nested replies up to 4 levels (1.5 em each).
967        var indent = Math.min(depth, 4) * 1.5 + 1.5;
968        if (indent > 0) {
969            entry.style.marginLeft = indent + 'em';
970        }
971
972        entry.appendChild(buildMeta(reply.author, reply.created, null));
973
974        var bodyEl = document.createElement('div');
975        bodyEl.className = 'ann-body';
976        bodyEl.textContent = reply.body;
977        entry.appendChild(bodyEl);
978
979        var actions = document.createElement('div');
980        actions.className = 'ann-actions';
981
982        // "Reply to this reply" button for logged-in users.
983        if (_loggedIn) {
984            var replyToBtn = document.createElement('button');
985            replyToBtn.type = 'button';
986            replyToBtn.className = 'ann-btn ann-btn-primary';
987            replyToBtn.textContent = t('btn_reply', 'Reply');
988            replyToBtn.addEventListener('click', function () {
989                // Toggle an inline reply form directly after this entry.
990                var next = entry.nextSibling;
991                if (next && next.classList && next.classList.contains('ann-inline-reply')) {
992                    next.parentNode.removeChild(next);
993                    return;
994                }
995                var form = buildInlineReplyForm(ann, reply.id, depth + 1);
996                entry.parentNode.insertBefore(form, entry.nextSibling);
997                var ta = form.querySelector('.ann-body-input');
998                if (ta) ta.focus();
999            });
1000            actions.appendChild(replyToBtn);
1001        }
1002
1003        var canEdit = _isAdmin || reply.author === currentUser();
1004        if (canEdit && _loggedIn) {
1005            var editBtn = document.createElement('button');
1006            editBtn.type = 'button';
1007            editBtn.className = 'ann-btn';
1008            editBtn.textContent = t('btn_edit', 'Edit');
1009            editBtn.addEventListener('click', function () {
1010                showEditForm(entry, {annId: ann.id, replyId: reply.id, body: reply.body}, 'reply');
1011            });
1012            actions.appendChild(editBtn);
1013
1014            var delBtn = document.createElement('button');
1015            delBtn.type = 'button';
1016            delBtn.className = 'ann-btn ann-btn-danger';
1017            delBtn.textContent = t('btn_delete', 'Delete');
1018            delBtn.addEventListener('click', function () {
1019                if (confirm(t('confirm_delete_reply', 'Delete this reply?'))) {
1020                    doDeleteReply(ann.id, reply.id, delBtn);
1021                }
1022            });
1023            actions.appendChild(delBtn);
1024        }
1025
1026        entry.appendChild(actions);
1027        return entry;
1028    }
1029
1030    /**
1031     * Build a nested tree structure from a flat reply list. Replies without a
1032     * known parentId (including legacy replies with no parentId field) are
1033     * treated as root-level.
1034     *
1035     * @param {Array} replies  flat array of reply objects
1036     * @returns {Array}        array of {reply, children} nodes
1037     */
1038    function buildReplyTree(replies) {
1039        var map = {};
1040        var roots = [];
1041        replies.forEach(function (r) {
1042            map[r.id] = {reply: r, children: []};
1043        });
1044        replies.forEach(function (r) {
1045            var pid = r.parentId || '';
1046            if (pid && map[pid]) {
1047                map[pid].children.push(map[r.id]);
1048            } else {
1049                roots.push(map[r.id]);
1050            }
1051        });
1052        return roots;
1053    }
1054
1055    /**
1056     * Recursively append reply entries into the panel.
1057     *
1058     * @param {HTMLElement} panel
1059     * @param {object}      ann
1060     * @param {Array}       nodes  array of {reply, children} tree nodes
1061     * @param {number}      depth
1062     */
1063    function appendReplyTree(panel, ann, nodes, depth) {
1064        nodes.forEach(function (node) {
1065            panel.appendChild(buildReplyEntry(ann, node.reply, depth));
1066            if (node.children.length > 0) {
1067                appendReplyTree(panel, ann, node.children, depth + 1);
1068            }
1069        });
1070    }
1071
1072    /**
1073     * Build an inline reply form that appears directly below a reply entry.
1074     *
1075     * @param {object} ann           parent annotation
1076     * @param {string} parentReplyId id of the reply being replied to
1077     * @param {number} depth         visual nesting depth for the new reply
1078     * @returns {HTMLElement}
1079     */
1080    function buildInlineReplyForm(ann, parentReplyId, depth) {
1081        var form = document.createElement('div');
1082        form.className = 'ann-thread-entry ann-reply ann-inline-reply';
1083        var indent = Math.min(depth, 4) * 1.5 + 1.5;
1084        if (indent > 0) {
1085            form.style.marginLeft = indent + 'em';
1086        }
1087
1088        var ta = document.createElement('textarea');
1089        ta.className = 'ann-body-input';
1090        ta.placeholder = t('placeholder_reply', 'Write a reply…');
1091        ta.rows = 3;
1092        form.appendChild(ta);
1093
1094        var row = document.createElement('div');
1095        row.className = 'ann-form-row';
1096
1097        var submitBtn = document.createElement('button');
1098        submitBtn.type = 'button';
1099        submitBtn.className = 'ann-btn ann-btn-primary';
1100        submitBtn.textContent = t('btn_reply', 'Reply');
1101        submitBtn.addEventListener('click', function () {
1102            var body = ta.value.trim();
1103            if (!body) return;
1104            doAddReply(ann.id, body, function () {
1105                if (form.parentNode) form.parentNode.removeChild(form);
1106            }, submitBtn, parentReplyId);
1107        });
1108
1109        var cancelBtn = document.createElement('button');
1110        cancelBtn.type = 'button';
1111        cancelBtn.className = 'ann-btn';
1112        cancelBtn.textContent = t('btn_cancel', 'Cancel');
1113        cancelBtn.addEventListener('click', function () {
1114            if (form.parentNode) form.parentNode.removeChild(form);
1115        });
1116
1117        row.appendChild(submitBtn);
1118        row.appendChild(cancelBtn);
1119        form.appendChild(row);
1120        return form;
1121    }
1122
1123    /**
1124     * Build the meta row (avatar initials, author name, timestamp, status pill).
1125     *
1126     * @param {string}      author
1127     * @param {number}      timestamp  Unix seconds
1128     * @param {string|null} status     'open'|'resolved'|null
1129     * @returns {HTMLElement}
1130     */
1131    function buildMeta(author, timestamp, status) {
1132        var meta = document.createElement('div');
1133        meta.className = 'ann-meta';
1134
1135        var avatar = document.createElement('span');
1136        avatar.className = 'ann-avatar';
1137        avatar.textContent = (author || '?').slice(0, 2).toUpperCase();
1138        meta.appendChild(avatar);
1139
1140        var authorEl = document.createElement('span');
1141        authorEl.className = 'ann-author';
1142        authorEl.textContent = author || t('label_unknown', 'Unknown');
1143        meta.appendChild(authorEl);
1144
1145        var timeEl = document.createElement('time');
1146        timeEl.className = 'ann-time';
1147        var d = new Date(timestamp * 1000);
1148        timeEl.dateTime = d.toISOString();
1149        timeEl.textContent = formatDate(d);
1150        meta.appendChild(timeEl);
1151
1152        if (status) {
1153            var pill = document.createElement('span');
1154            pill.className = 'ann-status ann-status-' + status;
1155            pill.textContent = status === 'resolved'
1156                ? t('status_resolved', 'Resolved')
1157                : t('status_open', 'Open');
1158            meta.appendChild(pill);
1159        }
1160
1161        return meta;
1162    }
1163
1164    /**
1165     * Build a reply form at the bottom of the panel.
1166     *
1167     * @param {object} ann
1168     * @returns {HTMLElement}
1169     */
1170    function buildReplyForm(ann) {
1171        var form = document.createElement('div');
1172        form.className = 'ann-reply-form';
1173
1174        var ta = document.createElement('textarea');
1175        ta.className = 'ann-body-input';
1176        ta.placeholder = t('placeholder_reply', 'Write a reply…');
1177        ta.rows = 3;
1178        form.appendChild(ta);
1179
1180        var row = document.createElement('div');
1181        row.className = 'ann-form-row';
1182
1183        var submitBtn = document.createElement('button');
1184        submitBtn.type = 'button';
1185        submitBtn.className = 'ann-btn ann-btn-primary';
1186        submitBtn.textContent = t('btn_reply', 'Reply');
1187        submitBtn.addEventListener('click', function () {
1188            var body = ta.value.trim();
1189            if (!body) return;
1190            doAddReply(ann.id, body, function () {
1191                ta.value = '';
1192            }, submitBtn);
1193        });
1194        row.appendChild(submitBtn);
1195        form.appendChild(row);
1196
1197        return form;
1198    }
1199
1200    /**
1201     * Replace the body of an entry with an inline edit form.
1202     *
1203     * @param {HTMLElement} entry
1204     * @param {object}      data    {body, annId?, replyId?}  (annId = undefined → annotation)
1205     * @param {string}      type    'annotation' | 'reply'
1206     */
1207    function showEditForm(entry, data, type) {
1208        var bodyEl = entry.querySelector('.ann-body');
1209        if (!bodyEl) return;
1210
1211        var ta = document.createElement('textarea');
1212        ta.className = 'ann-body-input';
1213        ta.value = data.body || '';
1214        ta.rows = 3;
1215
1216        var row = document.createElement('div');
1217        row.className = 'ann-form-row';
1218
1219        var saveBtn = document.createElement('button');
1220        saveBtn.type = 'button';
1221        saveBtn.className = 'ann-btn ann-btn-primary';
1222        saveBtn.textContent = t('btn_save', 'Save');
1223        saveBtn.addEventListener('click', function () {
1224            var newBody = ta.value.trim();
1225            if (!newBody) return;
1226            if (type === 'annotation') {
1227                doEditAnnotation(data.id || _openAnnId, newBody, saveBtn);
1228            } else {
1229                doEditReply(data.annId, data.replyId, newBody, saveBtn);
1230            }
1231        });
1232
1233        var cancelBtn = document.createElement('button');
1234        cancelBtn.type = 'button';
1235        cancelBtn.className = 'ann-btn';
1236        cancelBtn.textContent = t('btn_cancel', 'Cancel');
1237        cancelBtn.addEventListener('click', function () {
1238            entry.removeChild(ta);
1239            entry.removeChild(row);
1240            bodyEl.style.display = '';
1241        });
1242
1243        row.appendChild(saveBtn);
1244        row.appendChild(cancelBtn);
1245
1246        bodyEl.style.display = 'none';
1247        entry.insertBefore(ta, bodyEl.nextSibling);
1248        entry.insertBefore(row, ta.nextSibling);
1249        ta.focus();
1250    }
1251
1252    // -----------------------------------------------------------------------
1253    // Orphan drawer
1254    // -----------------------------------------------------------------------
1255
1256    /**
1257     * Toggle the orphan drawer visibility.
1258     */
1259    function toggleOrphanDrawer() {
1260        var drawer = document.getElementById('ann-orphan-drawer');
1261        if (drawer) {
1262            drawer.parentNode.removeChild(drawer);
1263            return;
1264        }
1265        renderOrphanDrawer();
1266    }
1267
1268    /**
1269     * Keep the orphan drawer in step with the current orphan set after a
1270     * mutation (delete / clear). No-op when the drawer is closed. When it is
1271     * open, rebuild it from the live _orphaned flags so deleted entries
1272     * disappear; if no orphans remain, remove the drawer entirely instead of
1273     * leaving an empty shell behind.
1274     *
1275     * Must run after renderAll(), which recomputes every ann._orphaned flag.
1276     */
1277    function syncOrphanDrawer() {
1278        var drawer = document.getElementById('ann-orphan-drawer');
1279        if (!drawer) return; // drawer not open — nothing to do
1280
1281        var hasOrphans = false;
1282        _annotations.forEach(function (ann) {
1283            if (ann._orphaned) hasOrphans = true;
1284        });
1285
1286        if (drawer.parentNode) drawer.parentNode.removeChild(drawer);
1287        if (hasOrphans) {
1288            renderOrphanDrawer();
1289            repositionMarkers();
1290        }
1291    }
1292
1293    /**
1294     * Build and insert the orphan drawer at the bottom of the content area.
1295     */
1296    function renderOrphanDrawer() {
1297        var content = document.getElementById(CONTENT_ID);
1298        if (!content) return;
1299
1300        var drawer = document.createElement('div');
1301        drawer.id = 'ann-orphan-drawer';
1302        drawer.className = CLS_ORPHAN_DRAWER;
1303
1304        var heading = document.createElement('h4');
1305        heading.textContent = t('orphaned_heading', 'Orphaned annotations');
1306        drawer.appendChild(heading);
1307
1308        var note = document.createElement('p');
1309        note.className = 'ann-orphan-note';
1310        note.textContent = t('orphaned_note',
1311            'These annotations reference text that no longer appears on the page.');
1312        drawer.appendChild(note);
1313
1314        var found = false;
1315        _annotations.forEach(function (ann) {
1316            if (!ann._orphaned) return;
1317            found = true;
1318            var entry = buildThreadEntry(ann, true);
1319            drawer.appendChild(entry);
1320        });
1321
1322        if (!found) {
1323            var empty = document.createElement('p');
1324            empty.textContent = t('orphaned_none', 'None.');
1325            drawer.appendChild(empty);
1326        }
1327
1328        // Insert right below the counter bar, which lives inside .page.
1329        // All fallbacks also target .page so the drawer never stretches past
1330        // the content column.
1331        var bar = document.getElementById('ann-counter-bar');
1332        if (bar && bar.parentNode) {
1333            bar.parentNode.insertBefore(drawer, bar.nextSibling);
1334        } else {
1335            var pageEl2 = document.querySelector('.' + PAGE_CLS);
1336            if (pageEl2) {
1337                pageEl2.insertBefore(drawer, pageEl2.firstChild);
1338            } else {
1339                content.insertBefore(drawer, content.firstChild);
1340            }
1341        }
1342    }
1343
1344    // -----------------------------------------------------------------------
1345    // Selection capture
1346    // -----------------------------------------------------------------------
1347
1348    /**
1349     * Wire up mouseup/touchend listeners to detect text selection.
1350     *
1351     * @param {HTMLElement} content
1352     */
1353    function initSelectionCapture(content) {
1354        if (!_loggedIn) return; // anonymous users cannot annotate
1355
1356        document.addEventListener('mouseup', function (e) {
1357            handleSelectionEnd(e, content);
1358        });
1359        document.addEventListener('touchend', function (e) {
1360            // Small delay so the browser has committed the selection.
1361            setTimeout(function () { handleSelectionEnd(e, content); }, 50);
1362        });
1363
1364        // Close tooltip on click outside (but not when clicking the new-form).
1365        document.addEventListener('mousedown', function (e) {
1366            var tooltip = document.getElementById('ann-tooltip');
1367            if (tooltip && !tooltip.contains(e.target)) {
1368                var naf = document.getElementById('ann-new-form');
1369                if (!naf || !naf.contains(e.target)) {
1370                    hideTooltip();
1371                }
1372            }
1373        });
1374    }
1375
1376    /**
1377     * Handle end of selection: show the "Annotate" tooltip if there is a
1378     * non-empty selection inside the content area.
1379     *
1380     * @param {Event}       e
1381     * @param {HTMLElement} content
1382     */
1383    function handleSelectionEnd(e, content) {
1384        var sel = window.getSelection();
1385        if (!sel || sel.isCollapsed) {
1386            // Don't hide the tooltip if the mouseup came from inside it —
1387            // the click handler is responsible for cleanup in that case.
1388            var tip = document.getElementById('ann-tooltip');
1389            if (tip && tip.contains(e.target)) {
1390                return;
1391            }
1392            // Don't hide if a new-annotation form is open (user clicked
1393            // inside the form, collapsing the original selection).
1394            var naf = document.getElementById('ann-new-form');
1395            if (naf && naf.contains(e.target)) {
1396                return;
1397            }
1398            hideTooltip();
1399            return;
1400        }
1401        var range = sel.getRangeAt(0);
1402        if (!content.contains(range.commonAncestorContainer)) {
1403            hideTooltip();
1404            return;
1405        }
1406        // If the selection touches any existing annotation — even by a single
1407        // character, whether wholly inside it or overrunning it on either side —
1408        // open that annotation instead of offering to create a new one.
1409        var hitSpan = selectionHitsHighlight(range);
1410        if (hitSpan) {
1411            hideTooltip();
1412            openPanel(hitSpan.dataset.annId);
1413            return;
1414        }
1415        // Only real page prose can be annotated: skip our own UI (panels,
1416        // counter, tooltip), the TOC, the page-info line, and section-edit
1417        // buttons — all of which live inside #dokuwiki__content.
1418        if (isInExcludedRegion(range.startContainer) ||
1419            isInExcludedRegion(range.endContainer) ||
1420            isInExcludedRegion(range.commonAncestorContainer)) {
1421            hideTooltip();
1422            return;
1423        }
1424        var text = sel.toString().trim();
1425        if (text.length < 1) {
1426            hideTooltip();
1427            return;
1428        }
1429
1430        // If the tooltip is already showing (e.g. user moused up after
1431        // pressing the Annotate button), don't replace it with a fresh one —
1432        // that would orphan the button mid-click and break the click handler.
1433        if (document.getElementById('ann-tooltip')) {
1434            return;
1435        }
1436
1437        // Show the tooltip near the end of the selection.
1438        var rect = range.getBoundingClientRect();
1439        showTooltip(rect, range, sel, content);
1440    }
1441
1442    /**
1443     * Show the "Annotate" tooltip bubble.
1444     *
1445     * @param {DOMRect}     rect     bounding rect of the selection
1446     * @param {Range}       range
1447     * @param {Selection}   sel
1448     * @param {HTMLElement} content
1449     */
1450    function showTooltip(rect, range, sel, content) {
1451        hideTooltip();
1452
1453        var tip = document.createElement('div');
1454        tip.id = 'ann-tooltip';
1455        tip.className = CLS_TOOLTIP;
1456
1457        // Capture the anchor on mousedown while the selection is guaranteed
1458        // to still exist. By the time 'click' fires, many browsers have
1459        // already collapsed the selection, so captureAnchor would return null.
1460        // _pendingAnchor is module-level so it survives tooltip replacement.
1461        var btn = document.createElement('button');
1462        btn.type = 'button';
1463        btn.textContent = t('btn_annotate', 'Annotate');
1464        btn.className = 'ann-btn ann-btn-primary';
1465        btn.addEventListener('mousedown', function (e) {
1466            e.preventDefault(); // prevent focus-change deselection
1467            // Capture now, while the selection is still intact.
1468            _pendingAnchor = captureAnchor(sel, range, content);
1469        });
1470        btn.addEventListener('click', function () {
1471            var anchor = _pendingAnchor;
1472            _pendingAnchor = null;
1473            hideTooltip();
1474            if (anchor) {
1475                openNewAnnotationForm(anchor, range);
1476            }
1477        });
1478        tip.appendChild(btn);
1479
1480        document.body.appendChild(tip);
1481
1482        // Position below the selection's end.
1483        var scrollTop  = window.pageYOffset || document.documentElement.scrollTop;
1484        var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
1485        tip.style.top  = (rect.bottom + scrollTop  + 6) + 'px';
1486        tip.style.left = (rect.left   + scrollLeft)     + 'px';
1487    }
1488
1489    /**
1490     * Remove the tooltip if it exists.
1491     */
1492    function hideTooltip() {
1493        var tip = document.getElementById('ann-tooltip');
1494        if (tip && tip.parentNode) {
1495            tip.parentNode.removeChild(tip);
1496        }
1497        // Note: ann-new-form is NOT removed here — it has its own Cancel
1498        // button and must survive the mouseup that fires after the click.
1499    }
1500
1501    /**
1502     * Capture an anchor object from the current Selection.
1503     *
1504     * @param {Selection}   sel
1505     * @param {Range}       range
1506     * @param {HTMLElement} content
1507     * @returns {object|null} {exact, prefix, suffix, start}
1508     */
1509    function captureAnchor(sel, range, content) {
1510        var exact = normalizeWS(sel.toString());
1511        if (!exact) return null;
1512
1513        // Get full page text for prefix/suffix and start computation.
1514        var chunks   = collectTextChunks(content);
1515        var fullRaw  = chunks.map(function (c) { return c.text; }).join('');
1516        var nm       = normalizeWithMap(fullRaw);
1517        var fullNorm = nm.norm;
1518
1519        // Find where this text node + offset lands in the raw full text.
1520        var rawStart = 0;
1521        for (var i = 0; i < chunks.length; i++) {
1522            var c = chunks[i];
1523            if (c.node === range.startContainer) {
1524                rawStart = c.start + range.startOffset;
1525                break;
1526            }
1527        }
1528
1529        // Map that raw offset to an offset in the normalised text, using the
1530        // same map as re-anchoring so capture and find stay in agreement.
1531        var normStart = nm.norm.length;
1532        for (var j = 0; j < nm.map.length; j++) {
1533            if (nm.map[j] >= rawStart) {
1534                normStart = j;
1535                break;
1536            }
1537        }
1538
1539        // Context slice length comes from the plugin config (context_length),
1540        // injected into JSINFO.annotations; fall back to 30 when absent. The
1541        // PHP side caps the stored prefix/suffix to the same length.
1542        var CTX = (typeof _info.contextLen === 'number') ? _info.contextLen : 30;
1543        var prefix = fullNorm.slice(Math.max(0, normStart - CTX), normStart);
1544        var suffix = fullNorm.slice(normStart + exact.length, normStart + exact.length + CTX);
1545
1546        return {
1547            exact:  exact,
1548            prefix: prefix,
1549            suffix: suffix,
1550            start:  normStart,
1551        };
1552    }
1553
1554    /**
1555     * Open the new-annotation form below the paragraph containing the selection.
1556     *
1557     * @param {object} anchor  {exact, prefix, suffix, start}
1558     * @param {Range}  range
1559     */
1560    function openNewAnnotationForm(anchor, range) {
1561        closePanel();
1562
1563        var insertAfter = findParagraph(range.commonAncestorContainer);
1564        var form = document.createElement('div');
1565        form.id = 'ann-new-form';
1566        form.className = 'ann-new-form';
1567
1568        var quote = document.createElement('blockquote');
1569        quote.className = 'ann-quote';
1570        quote.textContent = anchor.exact;
1571        form.appendChild(quote);
1572
1573        var ta = document.createElement('textarea');
1574        ta.className = 'ann-body-input';
1575        ta.placeholder = t('placeholder_body', 'Add a comment…');
1576        ta.rows = 3;
1577        form.appendChild(ta);
1578
1579        var row = document.createElement('div');
1580        row.className = 'ann-form-row';
1581
1582        var submitBtn = document.createElement('button');
1583        submitBtn.type = 'button';
1584        submitBtn.className = 'ann-btn ann-btn-primary';
1585        submitBtn.textContent = t('btn_annotate', 'Annotate');
1586        submitBtn.addEventListener('click', function () {
1587            var body = ta.value.trim();
1588            if (!body) return;
1589            doCreate(anchor, body, function () {
1590                if (form.parentNode) form.parentNode.removeChild(form);
1591            }, submitBtn);
1592        });
1593
1594        var cancelBtn = document.createElement('button');
1595        cancelBtn.type = 'button';
1596        cancelBtn.className = 'ann-btn';
1597        cancelBtn.textContent = t('btn_cancel', 'Cancel');
1598        cancelBtn.addEventListener('click', function () {
1599            if (form.parentNode) form.parentNode.removeChild(form);
1600        });
1601
1602        row.appendChild(submitBtn);
1603        row.appendChild(cancelBtn);
1604        form.appendChild(row);
1605
1606        if (insertAfter && insertAfter.parentNode) {
1607            insertAfter.parentNode.insertBefore(form, insertAfter.nextSibling);
1608        } else {
1609            var content = document.getElementById(CONTENT_ID);
1610            if (content) content.appendChild(form);
1611        }
1612
1613        ta.focus();
1614    }
1615
1616    // -----------------------------------------------------------------------
1617    // AJAX actions
1618    // -----------------------------------------------------------------------
1619
1620    /**
1621     * POST create action and update state on success.
1622     *
1623     * @param {object}        anchor
1624     * @param {string}        body
1625     * @param {Function}      onSuccess
1626     * @param {HTMLElement}   [btn]  button to disable while the request is in flight
1627     */
1628    function doCreate(anchor, body, onSuccess, btn) {
1629        setBusy(btn, true);
1630        ajax({
1631            action: 'create',
1632            id:     _info.pageId,
1633            anchor: anchor,
1634            body:   body,
1635        }).then(function (data) {
1636            setBusy(btn, false);
1637            if (!data.success) {
1638                showError(t('error_save', 'Could not save — please try again.'), data);
1639                return;
1640            }
1641            var ann = data.annotation;
1642            _annotations.set(ann.id, ann);
1643            if (typeof onSuccess === 'function') onSuccess(ann);
1644            renderAll();
1645        }).catch(function () {
1646            setBusy(btn, false);
1647            alert(t('error_save', 'Could not save — please try again.'));
1648        });
1649    }
1650
1651    /**
1652     * Run a thread-level mutation (reply / edit annotation / edit reply /
1653     * delete reply): POST the payload, then on success store the returned
1654     * annotation — keeping the client-side render state via mergeClientProps —
1655     * and re-open its panel. The server returns the full updated annotation, so
1656     * no second GET is needed. These four actions share this exact shape;
1657     * create / delete-annotation / resolve differ (they re-render the whole
1658     * overlay) and stay separate below.
1659     *
1660     * @param {object}      payload  AJAX body; must carry annId
1661     * @param {HTMLElement} [btn]    button to show the busy spinner on
1662     * @param {string}      errKey   lang key for the failure message
1663     * @param {string}      errText  English fallback for that message
1664     * @param {Function}    [onOk]   optional callback run before re-rendering
1665     */
1666    function submitThreadAction(payload, btn, errKey, errText, onOk) {
1667        setBusy(btn, true);
1668        ajax(payload).then(function (data) {
1669            setBusy(btn, false);
1670            if (!data.success) {
1671                showError(t(errKey, errText), data);
1672                return;
1673            }
1674            _annotations.set(data.annotation.id, mergeClientProps(data.annotation));
1675            if (typeof onOk === 'function') onOk();
1676            reopenPanel(payload.annId);
1677            // If this annotation sits in the open orphan drawer, refresh it so
1678            // an edited body / changed reply count shows there too. (The anchor
1679            // is unchanged by these actions, so _orphaned flags stay valid.)
1680            syncOrphanDrawer();
1681        }).catch(function () {
1682            setBusy(btn, false);
1683            alert(t(errKey, errText));
1684        });
1685    }
1686
1687    /**
1688     * POST reply action and refresh the open panel.
1689     *
1690     * @param {string}      annId
1691     * @param {string}      body
1692     * @param {Function}    onSuccess
1693     * @param {HTMLElement} [btn]
1694     * @param {string}      [parentReplyId]  id of the reply being replied to, or ''
1695     */
1696    function doAddReply(annId, body, onSuccess, btn, parentReplyId) {
1697        submitThreadAction({
1698            action:   'reply',
1699            id:       _info.pageId,
1700            annId:    annId,
1701            body:     body,
1702            parentId: parentReplyId || '',
1703        }, btn, 'error_save', 'Could not save — please try again.', onSuccess);
1704    }
1705
1706    /**
1707     * POST edit_annotation and re-render.
1708     *
1709     * @param {string}      annId
1710     * @param {string}      body
1711     * @param {HTMLElement} [btn]
1712     */
1713    function doEditAnnotation(annId, body, btn) {
1714        submitThreadAction({
1715            action: 'edit_annotation',
1716            id:     _info.pageId,
1717            annId:  annId,
1718            body:   body,
1719        }, btn, 'error_save', 'Could not save — please try again.');
1720    }
1721
1722    /**
1723     * POST edit_reply and re-render.
1724     *
1725     * @param {string}      annId
1726     * @param {string}      replyId
1727     * @param {string}      body
1728     * @param {HTMLElement} [btn]
1729     */
1730    function doEditReply(annId, replyId, body, btn) {
1731        submitThreadAction({
1732            action:  'edit_reply',
1733            id:      _info.pageId,
1734            annId:   annId,
1735            replyId: replyId,
1736            body:    body,
1737        }, btn, 'error_save', 'Could not save — please try again.');
1738    }
1739
1740    /**
1741     * POST delete_annotation.
1742     *
1743     * @param {string}      annId
1744     * @param {HTMLElement} [btn]
1745     */
1746    function doDeleteAnnotation(annId, btn) {
1747        setBusy(btn, true);
1748        ajax({
1749            action: 'delete_annotation',
1750            id:     _info.pageId,
1751            annId:  annId,
1752        }).then(function (data) {
1753            setBusy(btn, false);
1754            if (!data.success) {
1755                showError(t('error_delete', 'Could not delete — please try again.'), data);
1756                return;
1757            }
1758            _annotations.delete(annId);
1759            closePanel();
1760            renderAll();
1761            // If this was deleted from the open orphan drawer, refresh it —
1762            // and remove it entirely once the last orphan is gone.
1763            syncOrphanDrawer();
1764        }).catch(function () {
1765            setBusy(btn, false);
1766        });
1767    }
1768
1769    /**
1770     * POST delete_reply and re-render.
1771     *
1772     * @param {string}      annId
1773     * @param {string}      replyId
1774     * @param {HTMLElement} [btn]
1775     */
1776    function doDeleteReply(annId, replyId, btn) {
1777        submitThreadAction({
1778            action:  'delete_reply',
1779            id:      _info.pageId,
1780            annId:   annId,
1781            replyId: replyId,
1782        }, btn, 'error_delete', 'Could not delete — please try again.');
1783    }
1784
1785    /**
1786     * POST resolve/reopen action.
1787     *
1788     * @param {string}      annId
1789     * @param {string}      status  'open' | 'resolved'
1790     * @param {HTMLElement} [btn]
1791     */
1792    function doResolve(annId, status, btn) {
1793        setBusy(btn, true);
1794        ajax({
1795            action: 'resolve',
1796            id:     _info.pageId,
1797            annId:  annId,
1798            status: status,
1799        }).then(function (data) {
1800            setBusy(btn, false);
1801            if (!data.success) {
1802                showError(t('error_status', 'Could not update the status — please try again.'), data);
1803                return;
1804            }
1805            _annotations.set(data.annotation.id, data.annotation);
1806            renderAll();
1807            reopenPanel(annId);
1808        }).catch(function () {
1809            setBusy(btn, false);
1810        });
1811    }
1812
1813    /**
1814     * POST clear_resolved (admin).
1815     *
1816     * @param {HTMLElement} [btn]  button to show the busy spinner on
1817     */
1818    function doClearResolved(btn) {
1819        if (!confirm(t('confirm_clear_resolved', 'Delete all resolved annotations on this page?'))) return;
1820        setBusy(btn, true);
1821        ajax({
1822            action: 'clear_resolved',
1823            id:     _info.pageId,
1824        }).then(function (data) {
1825            setBusy(btn, false);
1826            if (!data.success) {
1827                showError(t('error_clear', 'Could not clear — please try again.'), data);
1828                return;
1829            }
1830            // Remove resolved from local state.
1831            _annotations.forEach(function (ann, id) {
1832                if (ann.status === 'resolved') _annotations.delete(id);
1833            });
1834            closePanel();
1835            renderAll();
1836            // Deleting resolved orphans may empty the drawer — sync/remove it.
1837            syncOrphanDrawer();
1838        }).catch(function () {
1839            setBusy(btn, false);
1840            alert(t('error_clear', 'Could not clear — please try again.'));
1841        });
1842    }
1843
1844    /**
1845     * POST clear_orphaned (admin).
1846     *
1847     * @param {HTMLElement} [btn]  button to show the busy spinner on
1848     */
1849    function doClearOrphaned(btn) {
1850        if (!confirm(t('confirm_clear_orphaned', 'Delete all orphaned annotations on this page?'))) return;
1851        setBusy(btn, true);
1852        ajax({
1853            action: 'clear_orphaned',
1854            id:     _info.pageId,
1855        }).then(function (data) {
1856            setBusy(btn, false);
1857            if (!data.success) {
1858                showError(t('error_clear', 'Could not clear — please try again.'), data);
1859                return;
1860            }
1861            _annotations.forEach(function (ann, id) {
1862                if (ann._orphaned) _annotations.delete(id);
1863            });
1864            closePanel();
1865            renderAll();
1866            // All orphans are gone now — tear down the drawer if it is open.
1867            syncOrphanDrawer();
1868        }).catch(function () {
1869            setBusy(btn, false);
1870            alert(t('error_clear', 'Could not clear — please try again.'));
1871        });
1872    }
1873
1874    // -----------------------------------------------------------------------
1875    // Panel management helpers
1876    // -----------------------------------------------------------------------
1877
1878    /**
1879     * Close the current panel and re-open it (preserves scroll position and
1880     * re-renders the thread with fresh data).
1881     *
1882     * @param {string} annId
1883     */
1884    function reopenPanel(annId) {
1885        // closePanel() first clears _openAnnId so openPanel() rebuilds instead
1886        // of treating the same id as a toggle. focusReply=false keeps the
1887        // viewport put after resolve / edit / delete actions.
1888        closePanel();
1889        openPanel(annId, false);
1890    }
1891
1892    // -----------------------------------------------------------------------
1893    // Utilities
1894    // -----------------------------------------------------------------------
1895
1896    /**
1897     * Disable a button and show a spinner while an AJAX request is in flight;
1898     * restore label and width on completion.
1899     *
1900     * @param {HTMLElement|null|undefined} btn
1901     * @param {boolean}                   busy
1902     */
1903    function setBusy(btn, busy) {
1904        if (!btn) return;
1905        if (busy) {
1906            btn.disabled = true;
1907            btn.dataset.prevText = btn.textContent;
1908            // Lock the width before clearing text so the button doesn't shrink.
1909            btn.style.minWidth = btn.offsetWidth + 'px';
1910            btn.textContent = ' '; // non-breaking space keeps height
1911            btn.classList.add('ann-btn-busy');
1912        } else {
1913            btn.disabled = false;
1914            btn.classList.remove('ann-btn-busy');
1915            if (btn.dataset.prevText !== undefined) {
1916                btn.textContent = btn.dataset.prevText;
1917                delete btn.dataset.prevText;
1918            }
1919            btn.style.minWidth = '';
1920        }
1921    }
1922
1923    /**
1924     * Copy client-only runtime properties (_highlightEl, _markerEl,
1925     * _orphaned, _range) from the currently stored annotation onto a
1926     * freshly-returned server object before storing it, so that panels
1927     * reopen at the correct position instead of falling back to the
1928     * bottom of the page.
1929     *
1930     * @param {object} fresh  annotation object from the server
1931     * @returns {object}      the same object, augmented
1932     */
1933    function mergeClientProps(fresh) {
1934        var existing = _annotations.get(fresh.id);
1935        if (existing) {
1936            fresh._highlightEl = existing._highlightEl;
1937            fresh._markerEl    = existing._markerEl;
1938            fresh._orphaned    = existing._orphaned;
1939            fresh._range       = existing._range;
1940        }
1941        return fresh;
1942    }
1943
1944    /**
1945     * The per-plugin JS language bundle, exposed by DokuWiki as
1946     * LANG.plugins.annotations (built from lang/<iso>/lang.php $lang['js']).
1947     *
1948     * @returns {object}
1949     */
1950    function uiLang() {
1951        if (typeof LANG !== 'undefined' && LANG && LANG.plugins && LANG.plugins.annotations) {
1952            return LANG.plugins.annotations;
1953        }
1954        return {};
1955    }
1956
1957    /**
1958     * Look up a UI string by key, falling back to the supplied English text if
1959     * the bundle is missing the key (e.g. a lang file not yet updated).
1960     *
1961     * @param {string} key
1962     * @param {string} fallback  English default
1963     * @returns {string}
1964     */
1965    function t(key, fallback) {
1966        var s = _lang[key];
1967        return (s === undefined || s === null || s === '') ? fallback : s;
1968    }
1969
1970    /**
1971     * Substitute a single %d placeholder with a number.
1972     *
1973     * @param {string} str
1974     * @param {number} n
1975     * @returns {string}
1976     */
1977    function fmt(str, n) {
1978        return String(str).replace('%d', n);
1979    }
1980
1981    /**
1982     * Show a localised error, appending the server's reason in parentheses
1983     * when one is present.
1984     *
1985     * @param {string} base  localised message
1986     * @param {object} data  AJAX response ({error?:string})
1987     */
1988    function showError(base, data) {
1989        var reason = (data && data.error) ? data.error : '';
1990        alert(reason ? base + ' (' + reason + ')' : base);
1991    }
1992
1993    /**
1994     * Collapse consecutive whitespace to a single space and trim.
1995     *
1996     * @param {string} s
1997     * @returns {string}
1998     */
1999    function normalizeWS(s) {
2000        return String(s || '').replace(/\s+/g, ' ').trim();
2001    }
2002
2003    /**
2004     * Return the current DokuWiki username from JSINFO.
2005     *
2006     * @returns {string}
2007     */
2008    function currentUser() {
2009        var jsinfo = (typeof JSINFO !== 'undefined' && JSINFO) ? JSINFO : {};
2010        return (jsinfo.annotations && jsinfo.annotations.user) ? jsinfo.annotations.user : '';
2011    }
2012
2013    /**
2014     * Format a Date for display.
2015     *
2016     * @param {Date} d
2017     * @returns {string}
2018     */
2019    function formatDate(d) {
2020        var now  = new Date();
2021        var diff = (now - d) / 1000; // seconds
2022        if (diff < 60)        return t('time_now', 'just now');
2023        if (diff < 3600)      return fmt(t('time_minutes', '%dm ago'), Math.floor(diff / 60));
2024        if (diff < 86400)     return fmt(t('time_hours',   '%dh ago'), Math.floor(diff / 3600));
2025        if (diff < 86400 * 7) return fmt(t('time_days',    '%dd ago'), Math.floor(diff / 86400));
2026        return d.toLocaleDateString();
2027    }
2028
2029    // -----------------------------------------------------------------------
2030    // Init
2031    // -----------------------------------------------------------------------
2032
2033    if (document.readyState === 'loading') {
2034        document.addEventListener('DOMContentLoaded', boot);
2035    } else {
2036        boot();
2037    }
2038
2039}());
2040