xref: /plugin/annotations/script.js (revision 108f92bd856af52ccb9e86517ad03d96f4a9273a)
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     * True if the given node is inside an existing highlight span.
356     * Used to block opening a new-annotation tooltip on already-annotated text.
357     *
358     * @param {Node} node
359     * @returns {bool}
360     */
361    function isInsideHighlight(node) {
362        var el = (node && node.nodeType === 1) ? node : (node ? node.parentNode : null);
363        while (el && el !== document.body) {
364            if (el.className &&
365                (el.className.indexOf(CLS_HIGHLIGHT_OPEN)     !== -1 ||
366                 el.className.indexOf(CLS_HIGHLIGHT_RESOLVED) !== -1)) {
367                return true;
368            }
369            el = el.parentNode;
370        }
371        return false;
372    }
373
374    /**
375     * True if the element (or its ancestor) is part of our annotation UI.
376     *
377     * @param {Node} el
378     * @returns {bool}
379     */
380    function isAnnotationUI(el) {
381        while (el && el !== document.body) {
382            if (el.nodeType === 1) {
383                var cls = el.className || '';
384                if (
385                    cls.indexOf('ann-') !== -1 ||
386                    cls.indexOf(CLS_PANEL) !== -1
387                ) {
388                    return true;
389                }
390            }
391            el = el.parentNode;
392        }
393        return false;
394    }
395
396    /**
397     * Turn a (start, length) offset in the normalised page text back into a
398     * DOM Range, using the normalised→raw index map.
399     *
400     * @param {Array<{node:Text, start:number, text:string}>} chunks
401     * @param {Array<number>} map       normalised index → raw index (normalizeWithMap)
402     * @param {number}        startOff  start offset in the normalised text
403     * @param {number}        length    length in normalised characters
404     * @returns {Range|null}
405     */
406    function buildRange(chunks, map, startOff, length) {
407        var rawStart = map[startOff];
408        var rawEnd   = map[startOff + length - 1];
409        if (rawStart === undefined || rawEnd === undefined) return null;
410        rawEnd++; // exclusive
411
412        // Find which chunks contain rawStart and rawEnd.
413        var startChunk = null, startOffset = 0;
414        var endChunk   = null, endOffset   = 0;
415
416        for (var i = 0; i < chunks.length; i++) {
417            var c = chunks[i];
418            var cEnd = c.start + c.text.length;
419
420            if (startChunk === null && c.start <= rawStart && rawStart < cEnd) {
421                startChunk  = c.node;
422                startOffset = rawStart - c.start;
423            }
424            if (endChunk === null && c.start < rawEnd && rawEnd <= cEnd) {
425                endChunk  = c.node;
426                endOffset = rawEnd - c.start;
427            }
428            if (startChunk && endChunk) break;
429        }
430
431        if (!startChunk || !endChunk) return null;
432
433        try {
434            var range = document.createRange();
435            range.setStart(startChunk, startOffset);
436            range.setEnd(endChunk, endOffset);
437            return range;
438        } catch (e) {
439            return null;
440        }
441    }
442
443    /**
444     * Normalise raw text exactly as normalizeWS does (collapse each whitespace
445     * run to a single space, trim both ends) while recording, for every
446     * character of the normalised string, the index of the raw character it
447     * came from. Returns {norm, map} with raw.charAt(map[i]) === norm.charAt(i)
448     * (a collapsed internal space maps to the first char of its run).
449     *
450     * Normalisation and the index map MUST stay in lockstep: an earlier
451     * version built the map without trimming, so a leading whitespace text
452     * node (DokuWiki indents its content markup, so there always is one)
453     * shifted every highlight one character to the left.
454     *
455     * @param {string} raw
456     * @returns {{norm:string, map:Array<number>}}
457     */
458    function normalizeWithMap(raw) {
459        var norm     = '';
460        var map      = [];
461        var inRun    = false;
462        var runStart = 0;
463        for (var i = 0; i < raw.length; i++) {
464            if (/\s/.test(raw[i])) {
465                if (!inRun) { inRun = true; runStart = i; }
466                continue;
467            }
468            if (inRun) {
469                inRun = false;
470                // internal run → one representative space; leading run → dropped
471                if (norm.length > 0) {
472                    norm += ' ';
473                    map.push(runStart);
474                }
475            }
476            norm += raw[i];
477            map.push(i);
478        }
479        // a trailing whitespace run is dropped (matches trim)
480        return {norm: norm, map: map};
481    }
482
483    // -----------------------------------------------------------------------
484    // Highlights
485    // -----------------------------------------------------------------------
486
487    /**
488     * Wrap a Range in a highlight <span> for the given annotation.
489     *
490     * @param {Range}  range
491     * @param {object} ann
492     */
493    function wrapHighlight(range, ann) {
494        var preview = ann.body || '';
495        var span = document.createElement('span');
496        span.className = ann.status === 'resolved'
497            ? CLS_HIGHLIGHT_RESOLVED
498            : CLS_HIGHLIGHT_OPEN;
499        span.dataset.annId = ann.id;
500        span.title = preview.slice(0, 80) + (preview.length > 80 ? '…' : '');
501        span.addEventListener('click', function (e) {
502            e.stopPropagation();
503            openPanel(ann.id);
504        });
505
506        try {
507            range.surroundContents(span);
508            ann._highlightEl = span;
509        } catch (e) {
510            // surroundContents throws if the range crosses element boundaries;
511            // fall back to extract + insert, reusing the same (still-empty) span.
512            try {
513                span.appendChild(range.extractContents());
514                range.insertNode(span);
515                ann._highlightEl = span;
516            } catch (e2) {
517                ann._highlightEl = null;
518            }
519        }
520    }
521
522    /**
523     * Remove all highlight spans, restoring the original text nodes.
524     */
525    function clearHighlights() {
526        var spans = document.querySelectorAll(
527            '.' + CLS_HIGHLIGHT_OPEN + ', .' + CLS_HIGHLIGHT_RESOLVED
528        );
529        Array.prototype.forEach.call(spans, function (span) {
530            var parent = span.parentNode;
531            if (!parent) return;
532            while (span.firstChild) {
533                parent.insertBefore(span.firstChild, span);
534            }
535            parent.removeChild(span);
536            parent.normalize();
537        });
538    }
539
540    // -----------------------------------------------------------------------
541    // Gutter markers
542    // -----------------------------------------------------------------------
543
544    /**
545     * Render a small marker for every anchored annotation. Markers are
546     * appended to document.body as absolutely-positioned elements so that
547     * template overflow rules on inner containers cannot clip them.
548     *
549     * All markers share the same X position — just to the left of the .page
550     * content column — so they form a tidy vertical column in the margin.
551     */
552    function renderGutterMarkers() {
553        var scrollTop  = window.pageYOffset || document.documentElement.scrollTop;
554        var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
555        var markerLeft = gutterMarkerLeft(scrollLeft);
556
557        // Speech bubble SVG — clearly communicates "annotation here".
558        var ICON_SVG =
559            '<svg viewBox="0 0 16 16" fill="currentColor" width="10" height="10" aria-hidden="true">' +
560            '<rect x="1" y="1" width="14" height="10" rx="2"/>' +
561            '<path d="M4 14 L4 11 L8 11 Z"/>' +
562            '</svg>';
563
564        _annotations.forEach(function (ann) {
565            if (!ann._highlightEl) return; // orphan
566
567            var rect = ann._highlightEl.getBoundingClientRect();
568
569            var marker = document.createElement('button');
570            marker.className      = CLS_GUTTER_MARKER;
571            marker.dataset.annId  = ann.id;
572            marker.dataset.status = ann.status || 'open'; // drives CSS amber/green colour
573            marker.setAttribute('aria-label', t('label_annotation', 'Annotation'));
574            marker.type      = 'button';
575            marker.innerHTML = ICON_SVG;
576            // Align vertically with the first line of the highlight.
577            marker.style.top  = (rect.top + scrollTop + 3) + 'px';
578            marker.style.left = markerLeft + 'px';
579            marker.addEventListener('click', function (e) {
580                e.stopPropagation();
581                openPanel(ann.id);
582            });
583            document.body.appendChild(marker);
584            ann._markerEl = marker;
585        });
586    }
587
588    /**
589     * Remove all gutter markers.
590     */
591    function clearGutterMarkers() {
592        var markers = document.querySelectorAll('.' + CLS_GUTTER_MARKER);
593        Array.prototype.forEach.call(markers, function (m) {
594            if (m.parentNode) m.parentNode.removeChild(m);
595        });
596    }
597
598    /**
599     * The shared X position (document coordinates) for every gutter marker:
600     * just inside the left padding of the .page content column, so the markers
601     * form a tidy vertical strip in the margin. Falls back to 4px when the
602     * column cannot be measured. Reads the theme's computed padding so it
603     * adapts to the template.
604     *
605     * @param {number} scrollLeft current horizontal scroll offset
606     * @returns {number}
607     */
608    function gutterMarkerLeft(scrollLeft) {
609        var pageEl = document.querySelector('.' + PAGE_CLS) || document.getElementById(CONTENT_ID);
610        if (!pageEl) return 4;
611        var pageRect = pageEl.getBoundingClientRect();
612        var padLeft  = parseInt(window.getComputedStyle(pageEl).paddingLeft, 10) || 32;
613        return pageRect.left + scrollLeft + Math.max(2, Math.floor(padLeft * 0.25));
614    }
615
616    /**
617     * Re-align every existing marker with its highlight without rebuilding the
618     * DOM. Highlights shift when a panel is inserted/removed or the window is
619     * resized, but markers live in document.body at absolute coordinates, so
620     * they would otherwise drift out of line. Cheap — only touches inline
621     * top/left on the handful of markers present.
622     */
623    function repositionMarkers() {
624        var scrollTop  = window.pageYOffset || document.documentElement.scrollTop;
625        var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
626        var markerLeft = gutterMarkerLeft(scrollLeft);
627        _annotations.forEach(function (ann) {
628            if (!ann._markerEl || !ann._highlightEl) return;
629            var rect = ann._highlightEl.getBoundingClientRect();
630            ann._markerEl.style.top  = (rect.top + scrollTop + 3) + 'px';
631            ann._markerEl.style.left = markerLeft + 'px';
632        });
633    }
634
635    // -----------------------------------------------------------------------
636    // Page counter
637    // -----------------------------------------------------------------------
638
639    /**
640     * Render (or update) the counter bubble above the content area.
641     *
642     * @param {object} stats        {total, open, resolved}
643     * @param {number} orphanCount
644     */
645    function renderCounter(stats, orphanCount) {
646        var existing = document.getElementById('ann-counter-bar');
647        if (existing) existing.parentNode.removeChild(existing);
648
649        if (stats.total === 0 && orphanCount === 0) return;
650
651        var bar = document.createElement('div');
652        bar.id = 'ann-counter-bar';
653        bar.className = CLS_COUNTER;
654
655        var total = stats.total || 0;
656        var label = total === 1
657            ? t('counter_annotation', '1 annotation')
658            : fmt(t('counter_annotations', '%d annotations'), total);
659        bar.appendChild(document.createTextNode(label));
660
661        if (orphanCount > 0) {
662            bar.appendChild(document.createTextNode(' · '));
663            var orphanLink = document.createElement('a');
664            orphanLink.href = '#ann-orphan-drawer';
665            orphanLink.className = 'ann-orphan-link';
666            orphanLink.textContent = fmt(t('counter_orphaned', '%d orphaned'), orphanCount);
667            orphanLink.addEventListener('click', function (e) {
668                e.preventDefault();
669                toggleOrphanDrawer();
670                repositionMarkers();
671            });
672            bar.appendChild(orphanLink);
673        }
674
675        if (_isAdmin && (stats.resolved > 0 || orphanCount > 0)) {
676            if (stats.resolved > 0) {
677                var btnCR = document.createElement('button');
678                btnCR.type = 'button';
679                btnCR.className = 'ann-btn ann-btn-admin';
680                btnCR.textContent = t('btn_clear_resolved', 'Clear resolved');
681                btnCR.addEventListener('click', doClearResolved);
682                bar.appendChild(btnCR);
683            }
684            if (orphanCount > 0) {
685                var btnCO = document.createElement('button');
686                btnCO.type = 'button';
687                btnCO.className = 'ann-btn ann-btn-admin';
688                btnCO.textContent = t('btn_clear_orphaned', 'Clear orphaned');
689                btnCO.addEventListener('click', doClearOrphaned);
690                bar.appendChild(btnCO);
691            }
692        }
693
694        // Insert inside .page, right after #dw__toc if present.
695        // The TOC is float:right so placing the bar after it (not before) lets
696        // it sit to the left of the float instead of pushing the TOC down.
697        var pageEl = document.querySelector('.' + PAGE_CLS);
698        if (pageEl) {
699            var toc = pageEl.querySelector('#dw__toc');
700            if (toc && toc.nextSibling) {
701                pageEl.insertBefore(bar, toc.nextSibling);
702            } else if (toc) {
703                pageEl.appendChild(bar);
704            } else {
705                pageEl.insertBefore(bar, pageEl.firstChild);
706            }
707        } else {
708            var content = document.getElementById(CONTENT_ID);
709            if (content) content.insertBefore(bar, content.firstChild);
710        }
711    }
712
713    /**
714     * Recount and re-render the counter from in-memory state.
715     */
716    function updateCounter(orphanCount) {
717        var open = 0, resolved = 0;
718        if (orphanCount === undefined) {
719            orphanCount = 0;
720        }
721        _annotations.forEach(function (ann) {
722            if (ann._orphaned) {
723                orphanCount++;
724            } else if (ann.status === 'resolved') {
725                resolved++;
726            } else {
727                open++;
728            }
729        });
730        renderCounter({total: open + resolved, open: open, resolved: resolved}, orphanCount);
731    }
732
733    // -----------------------------------------------------------------------
734    // Annotation panel
735    // -----------------------------------------------------------------------
736
737    /**
738     * Open the thread panel for the given annotation id.
739     * If that panel is already open, close it.
740     *
741     * @param {string}  annId
742     * @param {boolean} [focusReply]  focus the reply box once open (default true);
743     *                                reopenPanel passes false so re-rendering after
744     *                                an action doesn't yank the viewport to the form.
745     */
746    function openPanel(annId, focusReply) {
747        if (_openAnnId === annId) {
748            closePanel();
749            return;
750        }
751        closePanel();
752
753        var ann = _annotations.get(annId);
754        if (!ann) return;
755
756        var panel = buildPanel(ann);
757        _openPanel  = panel;
758        _openAnnId  = annId;
759
760        // Insert below the paragraph that contains the highlight.
761        var anchor = ann._highlightEl || null;
762        var insertAfter = findParagraph(anchor);
763        if (insertAfter && insertAfter.parentNode) {
764            insertAfter.parentNode.insertBefore(panel, insertAfter.nextSibling);
765        } else {
766            // Orphan or no paragraph found: show at the bottom of content.
767            var content = document.getElementById(CONTENT_ID);
768            if (content) content.appendChild(panel);
769        }
770
771        if (focusReply !== false) {
772            var input = panel.querySelector('.ann-body-input');
773            if (input) input.focus();
774        }
775
776        // The panel grew the document; nudge markers below it back into line.
777        repositionMarkers();
778    }
779
780    /**
781     * Close and remove the currently open panel.
782     */
783    function closePanel() {
784        if (_openPanel && _openPanel.parentNode) {
785            _openPanel.parentNode.removeChild(_openPanel);
786        }
787        _openPanel = null;
788        _openAnnId = null;
789        repositionMarkers();
790    }
791
792    /**
793     * Find the nearest block-level ancestor of el (p, li, h1-h6, etc.)
794     * that can receive a sibling element.
795     *
796     * @param {HTMLElement|null} el
797     * @returns {HTMLElement|null}
798     */
799    function findParagraph(el) {
800        var block = /^(P|LI|DT|DD|H[1-6]|BLOCKQUOTE|PRE|TABLE|DIV)$/;
801        var node = el;
802        while (node && node.id !== CONTENT_ID) {
803            if (node.nodeType === 1 && block.test(node.tagName)) {
804                return node;
805            }
806            node = node.parentNode;
807        }
808        return el; // fallback: use the element itself
809    }
810
811    /**
812     * Build and return the panel DOM element for one annotation.
813     *
814     * @param {object} ann
815     * @returns {HTMLElement}
816     */
817    function buildPanel(ann) {
818        var panel = document.createElement('div');
819        panel.className = CLS_PANEL;
820        panel.dataset.annId  = ann.id;
821        panel.dataset.status = ann.status || 'open'; // drives the resolved accent in style.css
822
823        // Main annotation thread entry (close button lives in its meta row).
824        var rootEntry = buildThreadEntry(ann, true);
825        var meta = rootEntry.querySelector('.ann-meta');
826        if (meta) {
827            var closeBtn = document.createElement('button');
828            closeBtn.type = 'button';
829            closeBtn.className = 'ann-btn ann-close';
830            closeBtn.setAttribute('aria-label', t('label_close', 'Close'));
831            closeBtn.textContent = '×'; // ×
832            closeBtn.style.marginLeft = 'auto';
833            closeBtn.addEventListener('click', closePanel);
834            meta.appendChild(closeBtn);
835        }
836        panel.appendChild(rootEntry);
837
838        // Replies: build hierarchy from flat list and render depth-indented.
839        appendReplyTree(panel, ann, buildReplyTree(ann.replies || []), 0);
840
841        // Reply form at the bottom for root-level replies.
842        if (_loggedIn) {
843            panel.appendChild(buildReplyForm(ann));
844        }
845
846        return panel;
847    }
848
849    /**
850     * Build the DOM for the top-level annotation entry.
851     *
852     * @param {object}  ann
853     * @param {boolean} isRoot  true for the annotation itself, false for replies
854     * @returns {HTMLElement}
855     */
856    function buildThreadEntry(ann, isRoot) {
857        var entry = document.createElement('div');
858        entry.className = 'ann-thread-entry ann-annotation';
859        entry.dataset.annId = ann.id;
860
861        // Meta row: avatar, author, time, status pill
862        entry.appendChild(buildMeta(ann.author, ann.created, ann.status));
863
864        // Body
865        var bodyEl = document.createElement('div');
866        bodyEl.className = 'ann-body';
867        bodyEl.textContent = ann.body;
868        entry.appendChild(bodyEl);
869
870        // Quoted text snippet
871        if (ann.anchor && ann.anchor.exact) {
872            var quote = document.createElement('blockquote');
873            quote.className = 'ann-quote';
874            quote.textContent = ann.anchor.exact;
875            entry.appendChild(quote);
876        }
877
878        // Action buttons
879        var actions = document.createElement('div');
880        actions.className = 'ann-actions';
881
882        // Resolve/Reopen (any reader)
883        if (_loggedIn) {
884            var resolveBtn = document.createElement('button');
885            resolveBtn.type = 'button';
886            resolveBtn.className = 'ann-btn ann-btn-primary';
887            resolveBtn.textContent = ann.status === 'resolved'
888                ? t('btn_reopen', 'Reopen')
889                : t('btn_resolve', 'Resolve');
890            resolveBtn.addEventListener('click', function () {
891                doResolve(ann.id, ann.status === 'resolved' ? 'open' : 'resolved', resolveBtn);
892            });
893            actions.appendChild(resolveBtn);
894        }
895
896        // Edit + Delete (own or admin)
897        var canEdit = _isAdmin || ann.author === currentUser();
898        if (canEdit && _loggedIn) {
899            var editBtn = document.createElement('button');
900            editBtn.type = 'button';
901            editBtn.className = 'ann-btn';
902            editBtn.textContent = t('btn_edit', 'Edit');
903            editBtn.addEventListener('click', function () {
904                showEditForm(entry, ann, 'annotation');
905            });
906            actions.appendChild(editBtn);
907
908            var delBtn = document.createElement('button');
909            delBtn.type = 'button';
910            delBtn.className = 'ann-btn ann-btn-danger';
911            delBtn.textContent = t('btn_delete', 'Delete');
912            delBtn.addEventListener('click', function () {
913                if (confirm(t('confirm_delete', 'Delete this annotation?'))) {
914                    doDeleteAnnotation(ann.id, delBtn);
915                }
916            });
917            actions.appendChild(delBtn);
918        }
919
920        entry.appendChild(actions);
921        return entry;
922    }
923
924    /**
925     * Build the DOM for one reply entry, indented according to its nesting depth.
926     *
927     * @param {object} ann    parent annotation
928     * @param {object} reply
929     * @param {number} depth  0 = direct reply to annotation; 1+ = nested
930     * @returns {HTMLElement}
931     */
932    function buildReplyEntry(ann, reply, depth) {
933        var entry = document.createElement('div');
934        entry.className = 'ann-thread-entry ann-reply';
935        entry.dataset.replyId = reply.id;
936        // Indent nested replies up to 4 levels (1.5 em each).
937        var indent = Math.min(depth, 4) * 1.5 + 1.5;
938        if (indent > 0) {
939            entry.style.marginLeft = indent + 'em';
940        }
941
942        entry.appendChild(buildMeta(reply.author, reply.created, null));
943
944        var bodyEl = document.createElement('div');
945        bodyEl.className = 'ann-body';
946        bodyEl.textContent = reply.body;
947        entry.appendChild(bodyEl);
948
949        var actions = document.createElement('div');
950        actions.className = 'ann-actions';
951
952        // "Reply to this reply" button for logged-in users.
953        if (_loggedIn) {
954            var replyToBtn = document.createElement('button');
955            replyToBtn.type = 'button';
956            replyToBtn.className = 'ann-btn ann-btn-primary';
957            replyToBtn.textContent = t('btn_reply', 'Reply');
958            replyToBtn.addEventListener('click', function () {
959                // Toggle an inline reply form directly after this entry.
960                var next = entry.nextSibling;
961                if (next && next.classList && next.classList.contains('ann-inline-reply')) {
962                    next.parentNode.removeChild(next);
963                    return;
964                }
965                var form = buildInlineReplyForm(ann, reply.id, depth + 1);
966                entry.parentNode.insertBefore(form, entry.nextSibling);
967                var ta = form.querySelector('.ann-body-input');
968                if (ta) ta.focus();
969            });
970            actions.appendChild(replyToBtn);
971        }
972
973        var canEdit = _isAdmin || reply.author === currentUser();
974        if (canEdit && _loggedIn) {
975            var editBtn = document.createElement('button');
976            editBtn.type = 'button';
977            editBtn.className = 'ann-btn';
978            editBtn.textContent = t('btn_edit', 'Edit');
979            editBtn.addEventListener('click', function () {
980                showEditForm(entry, {annId: ann.id, replyId: reply.id, body: reply.body}, 'reply');
981            });
982            actions.appendChild(editBtn);
983
984            var delBtn = document.createElement('button');
985            delBtn.type = 'button';
986            delBtn.className = 'ann-btn ann-btn-danger';
987            delBtn.textContent = t('btn_delete', 'Delete');
988            delBtn.addEventListener('click', function () {
989                if (confirm(t('confirm_delete_reply', 'Delete this reply?'))) {
990                    doDeleteReply(ann.id, reply.id, delBtn);
991                }
992            });
993            actions.appendChild(delBtn);
994        }
995
996        entry.appendChild(actions);
997        return entry;
998    }
999
1000    /**
1001     * Build a nested tree structure from a flat reply list. Replies without a
1002     * known parentId (including legacy replies with no parentId field) are
1003     * treated as root-level.
1004     *
1005     * @param {Array} replies  flat array of reply objects
1006     * @returns {Array}        array of {reply, children} nodes
1007     */
1008    function buildReplyTree(replies) {
1009        var map = {};
1010        var roots = [];
1011        replies.forEach(function (r) {
1012            map[r.id] = {reply: r, children: []};
1013        });
1014        replies.forEach(function (r) {
1015            var pid = r.parentId || '';
1016            if (pid && map[pid]) {
1017                map[pid].children.push(map[r.id]);
1018            } else {
1019                roots.push(map[r.id]);
1020            }
1021        });
1022        return roots;
1023    }
1024
1025    /**
1026     * Recursively append reply entries into the panel.
1027     *
1028     * @param {HTMLElement} panel
1029     * @param {object}      ann
1030     * @param {Array}       nodes  array of {reply, children} tree nodes
1031     * @param {number}      depth
1032     */
1033    function appendReplyTree(panel, ann, nodes, depth) {
1034        nodes.forEach(function (node) {
1035            panel.appendChild(buildReplyEntry(ann, node.reply, depth));
1036            if (node.children.length > 0) {
1037                appendReplyTree(panel, ann, node.children, depth + 1);
1038            }
1039        });
1040    }
1041
1042    /**
1043     * Build an inline reply form that appears directly below a reply entry.
1044     *
1045     * @param {object} ann           parent annotation
1046     * @param {string} parentReplyId id of the reply being replied to
1047     * @param {number} depth         visual nesting depth for the new reply
1048     * @returns {HTMLElement}
1049     */
1050    function buildInlineReplyForm(ann, parentReplyId, depth) {
1051        var form = document.createElement('div');
1052        form.className = 'ann-thread-entry ann-reply ann-inline-reply';
1053        var indent = Math.min(depth, 4) * 1.5 + 1.5;
1054        if (indent > 0) {
1055            form.style.marginLeft = indent + 'em';
1056        }
1057
1058        var ta = document.createElement('textarea');
1059        ta.className = 'ann-body-input';
1060        ta.placeholder = t('placeholder_reply', 'Write a reply…');
1061        ta.rows = 3;
1062        form.appendChild(ta);
1063
1064        var row = document.createElement('div');
1065        row.className = 'ann-form-row';
1066
1067        var submitBtn = document.createElement('button');
1068        submitBtn.type = 'button';
1069        submitBtn.className = 'ann-btn ann-btn-primary';
1070        submitBtn.textContent = t('btn_reply', 'Reply');
1071        submitBtn.addEventListener('click', function () {
1072            var body = ta.value.trim();
1073            if (!body) return;
1074            doAddReply(ann.id, body, function () {
1075                if (form.parentNode) form.parentNode.removeChild(form);
1076            }, submitBtn, parentReplyId);
1077        });
1078
1079        var cancelBtn = document.createElement('button');
1080        cancelBtn.type = 'button';
1081        cancelBtn.className = 'ann-btn';
1082        cancelBtn.textContent = t('btn_cancel', 'Cancel');
1083        cancelBtn.addEventListener('click', function () {
1084            if (form.parentNode) form.parentNode.removeChild(form);
1085        });
1086
1087        row.appendChild(submitBtn);
1088        row.appendChild(cancelBtn);
1089        form.appendChild(row);
1090        return form;
1091    }
1092
1093    /**
1094     * Build the meta row (avatar initials, author name, timestamp, status pill).
1095     *
1096     * @param {string}      author
1097     * @param {number}      timestamp  Unix seconds
1098     * @param {string|null} status     'open'|'resolved'|null
1099     * @returns {HTMLElement}
1100     */
1101    function buildMeta(author, timestamp, status) {
1102        var meta = document.createElement('div');
1103        meta.className = 'ann-meta';
1104
1105        var avatar = document.createElement('span');
1106        avatar.className = 'ann-avatar';
1107        avatar.textContent = (author || '?').slice(0, 2).toUpperCase();
1108        meta.appendChild(avatar);
1109
1110        var authorEl = document.createElement('span');
1111        authorEl.className = 'ann-author';
1112        authorEl.textContent = author || t('label_unknown', 'Unknown');
1113        meta.appendChild(authorEl);
1114
1115        var timeEl = document.createElement('time');
1116        timeEl.className = 'ann-time';
1117        var d = new Date(timestamp * 1000);
1118        timeEl.dateTime = d.toISOString();
1119        timeEl.textContent = formatDate(d);
1120        meta.appendChild(timeEl);
1121
1122        if (status) {
1123            var pill = document.createElement('span');
1124            pill.className = 'ann-status ann-status-' + status;
1125            pill.textContent = status === 'resolved'
1126                ? t('status_resolved', 'Resolved')
1127                : t('status_open', 'Open');
1128            meta.appendChild(pill);
1129        }
1130
1131        return meta;
1132    }
1133
1134    /**
1135     * Build a reply form at the bottom of the panel.
1136     *
1137     * @param {object} ann
1138     * @returns {HTMLElement}
1139     */
1140    function buildReplyForm(ann) {
1141        var form = document.createElement('div');
1142        form.className = 'ann-reply-form';
1143
1144        var ta = document.createElement('textarea');
1145        ta.className = 'ann-body-input';
1146        ta.placeholder = t('placeholder_reply', 'Write a reply…');
1147        ta.rows = 3;
1148        form.appendChild(ta);
1149
1150        var row = document.createElement('div');
1151        row.className = 'ann-form-row';
1152
1153        var submitBtn = document.createElement('button');
1154        submitBtn.type = 'button';
1155        submitBtn.className = 'ann-btn ann-btn-primary';
1156        submitBtn.textContent = t('btn_reply', 'Reply');
1157        submitBtn.addEventListener('click', function () {
1158            var body = ta.value.trim();
1159            if (!body) return;
1160            doAddReply(ann.id, body, function () {
1161                ta.value = '';
1162            }, submitBtn);
1163        });
1164        row.appendChild(submitBtn);
1165        form.appendChild(row);
1166
1167        return form;
1168    }
1169
1170    /**
1171     * Replace the body of an entry with an inline edit form.
1172     *
1173     * @param {HTMLElement} entry
1174     * @param {object}      data    {body, annId?, replyId?}  (annId = undefined → annotation)
1175     * @param {string}      type    'annotation' | 'reply'
1176     */
1177    function showEditForm(entry, data, type) {
1178        var bodyEl = entry.querySelector('.ann-body');
1179        if (!bodyEl) return;
1180
1181        var ta = document.createElement('textarea');
1182        ta.className = 'ann-body-input';
1183        ta.value = data.body || '';
1184        ta.rows = 3;
1185
1186        var row = document.createElement('div');
1187        row.className = 'ann-form-row';
1188
1189        var saveBtn = document.createElement('button');
1190        saveBtn.type = 'button';
1191        saveBtn.className = 'ann-btn ann-btn-primary';
1192        saveBtn.textContent = t('btn_save', 'Save');
1193        saveBtn.addEventListener('click', function () {
1194            var newBody = ta.value.trim();
1195            if (!newBody) return;
1196            if (type === 'annotation') {
1197                doEditAnnotation(data.id || _openAnnId, newBody, saveBtn);
1198            } else {
1199                doEditReply(data.annId, data.replyId, newBody, saveBtn);
1200            }
1201        });
1202
1203        var cancelBtn = document.createElement('button');
1204        cancelBtn.type = 'button';
1205        cancelBtn.className = 'ann-btn';
1206        cancelBtn.textContent = t('btn_cancel', 'Cancel');
1207        cancelBtn.addEventListener('click', function () {
1208            entry.removeChild(ta);
1209            entry.removeChild(row);
1210            bodyEl.style.display = '';
1211        });
1212
1213        row.appendChild(saveBtn);
1214        row.appendChild(cancelBtn);
1215
1216        bodyEl.style.display = 'none';
1217        entry.insertBefore(ta, bodyEl.nextSibling);
1218        entry.insertBefore(row, ta.nextSibling);
1219        ta.focus();
1220    }
1221
1222    // -----------------------------------------------------------------------
1223    // Orphan drawer
1224    // -----------------------------------------------------------------------
1225
1226    /**
1227     * Toggle the orphan drawer visibility.
1228     */
1229    function toggleOrphanDrawer() {
1230        var drawer = document.getElementById('ann-orphan-drawer');
1231        if (drawer) {
1232            drawer.parentNode.removeChild(drawer);
1233            return;
1234        }
1235        renderOrphanDrawer();
1236    }
1237
1238    /**
1239     * Build and insert the orphan drawer at the bottom of the content area.
1240     */
1241    function renderOrphanDrawer() {
1242        var content = document.getElementById(CONTENT_ID);
1243        if (!content) return;
1244
1245        var drawer = document.createElement('div');
1246        drawer.id = 'ann-orphan-drawer';
1247        drawer.className = CLS_ORPHAN_DRAWER;
1248
1249        var heading = document.createElement('h4');
1250        heading.textContent = t('orphaned_heading', 'Orphaned annotations');
1251        drawer.appendChild(heading);
1252
1253        var note = document.createElement('p');
1254        note.className = 'ann-orphan-note';
1255        note.textContent = t('orphaned_note',
1256            'These annotations reference text that no longer appears on the page.');
1257        drawer.appendChild(note);
1258
1259        var found = false;
1260        _annotations.forEach(function (ann) {
1261            if (!ann._orphaned) return;
1262            found = true;
1263            var entry = buildThreadEntry(ann, true);
1264            drawer.appendChild(entry);
1265        });
1266
1267        if (!found) {
1268            var empty = document.createElement('p');
1269            empty.textContent = t('orphaned_none', 'None.');
1270            drawer.appendChild(empty);
1271        }
1272
1273        // Insert right below the counter bar, which lives inside .page.
1274        // All fallbacks also target .page so the drawer never stretches past
1275        // the content column.
1276        var bar = document.getElementById('ann-counter-bar');
1277        if (bar && bar.parentNode) {
1278            bar.parentNode.insertBefore(drawer, bar.nextSibling);
1279        } else {
1280            var pageEl2 = document.querySelector('.' + PAGE_CLS);
1281            if (pageEl2) {
1282                pageEl2.insertBefore(drawer, pageEl2.firstChild);
1283            } else {
1284                content.insertBefore(drawer, content.firstChild);
1285            }
1286        }
1287    }
1288
1289    // -----------------------------------------------------------------------
1290    // Selection capture
1291    // -----------------------------------------------------------------------
1292
1293    /**
1294     * Wire up mouseup/touchend listeners to detect text selection.
1295     *
1296     * @param {HTMLElement} content
1297     */
1298    function initSelectionCapture(content) {
1299        if (!_loggedIn) return; // anonymous users cannot annotate
1300
1301        document.addEventListener('mouseup', function (e) {
1302            handleSelectionEnd(e, content);
1303        });
1304        document.addEventListener('touchend', function (e) {
1305            // Small delay so the browser has committed the selection.
1306            setTimeout(function () { handleSelectionEnd(e, content); }, 50);
1307        });
1308
1309        // Close tooltip on click outside (but not when clicking the new-form).
1310        document.addEventListener('mousedown', function (e) {
1311            var tooltip = document.getElementById('ann-tooltip');
1312            if (tooltip && !tooltip.contains(e.target)) {
1313                var naf = document.getElementById('ann-new-form');
1314                if (!naf || !naf.contains(e.target)) {
1315                    hideTooltip();
1316                }
1317            }
1318        });
1319    }
1320
1321    /**
1322     * Handle end of selection: show the "Annotate" tooltip if there is a
1323     * non-empty selection inside the content area.
1324     *
1325     * @param {Event}       e
1326     * @param {HTMLElement} content
1327     */
1328    function handleSelectionEnd(e, content) {
1329        var sel = window.getSelection();
1330        if (!sel || sel.isCollapsed) {
1331            // Don't hide the tooltip if the mouseup came from inside it —
1332            // the click handler is responsible for cleanup in that case.
1333            var tip = document.getElementById('ann-tooltip');
1334            if (tip && tip.contains(e.target)) {
1335                return;
1336            }
1337            // Don't hide if a new-annotation form is open (user clicked
1338            // inside the form, collapsing the original selection).
1339            var naf = document.getElementById('ann-new-form');
1340            if (naf && naf.contains(e.target)) {
1341                return;
1342            }
1343            hideTooltip();
1344            return;
1345        }
1346        var range = sel.getRangeAt(0);
1347        if (!content.contains(range.commonAncestorContainer)) {
1348            hideTooltip();
1349            return;
1350        }
1351        // Don't open a new annotation when the selection overlaps existing annotated text.
1352        if (isInsideHighlight(range.startContainer) || isInsideHighlight(range.endContainer)) {
1353            hideTooltip();
1354            return;
1355        }
1356        var text = sel.toString().trim();
1357        if (text.length < 1) {
1358            hideTooltip();
1359            return;
1360        }
1361
1362        // If the tooltip is already showing (e.g. user moused up after
1363        // pressing the Annotate button), don't replace it with a fresh one —
1364        // that would orphan the button mid-click and break the click handler.
1365        if (document.getElementById('ann-tooltip')) {
1366            return;
1367        }
1368
1369        // Show the tooltip near the end of the selection.
1370        var rect = range.getBoundingClientRect();
1371        showTooltip(rect, range, sel, content);
1372    }
1373
1374    /**
1375     * Show the "Annotate" tooltip bubble.
1376     *
1377     * @param {DOMRect}     rect     bounding rect of the selection
1378     * @param {Range}       range
1379     * @param {Selection}   sel
1380     * @param {HTMLElement} content
1381     */
1382    function showTooltip(rect, range, sel, content) {
1383        hideTooltip();
1384
1385        var tip = document.createElement('div');
1386        tip.id = 'ann-tooltip';
1387        tip.className = CLS_TOOLTIP;
1388
1389        // Capture the anchor on mousedown while the selection is guaranteed
1390        // to still exist. By the time 'click' fires, many browsers have
1391        // already collapsed the selection, so captureAnchor would return null.
1392        // _pendingAnchor is module-level so it survives tooltip replacement.
1393        var btn = document.createElement('button');
1394        btn.type = 'button';
1395        btn.textContent = t('btn_annotate', 'Annotate');
1396        btn.className = 'ann-btn ann-btn-primary';
1397        btn.addEventListener('mousedown', function (e) {
1398            e.preventDefault(); // prevent focus-change deselection
1399            // Capture now, while the selection is still intact.
1400            _pendingAnchor = captureAnchor(sel, range, content);
1401        });
1402        btn.addEventListener('click', function () {
1403            var anchor = _pendingAnchor;
1404            _pendingAnchor = null;
1405            hideTooltip();
1406            if (anchor) {
1407                openNewAnnotationForm(anchor, range);
1408            }
1409        });
1410        tip.appendChild(btn);
1411
1412        document.body.appendChild(tip);
1413
1414        // Position below the selection's end.
1415        var scrollTop  = window.pageYOffset || document.documentElement.scrollTop;
1416        var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
1417        tip.style.top  = (rect.bottom + scrollTop  + 6) + 'px';
1418        tip.style.left = (rect.left   + scrollLeft)     + 'px';
1419    }
1420
1421    /**
1422     * Remove the tooltip if it exists.
1423     */
1424    function hideTooltip() {
1425        var tip = document.getElementById('ann-tooltip');
1426        if (tip && tip.parentNode) {
1427            tip.parentNode.removeChild(tip);
1428        }
1429        // Note: ann-new-form is NOT removed here — it has its own Cancel
1430        // button and must survive the mouseup that fires after the click.
1431    }
1432
1433    /**
1434     * Capture an anchor object from the current Selection.
1435     *
1436     * @param {Selection}   sel
1437     * @param {Range}       range
1438     * @param {HTMLElement} content
1439     * @returns {object|null} {exact, prefix, suffix, start}
1440     */
1441    function captureAnchor(sel, range, content) {
1442        var exact = normalizeWS(sel.toString());
1443        if (!exact) return null;
1444
1445        // Get full page text for prefix/suffix and start computation.
1446        var chunks   = collectTextChunks(content);
1447        var fullRaw  = chunks.map(function (c) { return c.text; }).join('');
1448        var nm       = normalizeWithMap(fullRaw);
1449        var fullNorm = nm.norm;
1450
1451        // Find where this text node + offset lands in the raw full text.
1452        var rawStart = 0;
1453        for (var i = 0; i < chunks.length; i++) {
1454            var c = chunks[i];
1455            if (c.node === range.startContainer) {
1456                rawStart = c.start + range.startOffset;
1457                break;
1458            }
1459        }
1460
1461        // Map that raw offset to an offset in the normalised text, using the
1462        // same map as re-anchoring so capture and find stay in agreement.
1463        var normStart = nm.norm.length;
1464        for (var j = 0; j < nm.map.length; j++) {
1465            if (nm.map[j] >= rawStart) {
1466                normStart = j;
1467                break;
1468            }
1469        }
1470
1471        var CTX = 30;
1472        var prefix = fullNorm.slice(Math.max(0, normStart - CTX), normStart);
1473        var suffix = fullNorm.slice(normStart + exact.length, normStart + exact.length + CTX);
1474
1475        return {
1476            exact:  exact,
1477            prefix: prefix,
1478            suffix: suffix,
1479            start:  normStart,
1480        };
1481    }
1482
1483    /**
1484     * Open the new-annotation form below the paragraph containing the selection.
1485     *
1486     * @param {object} anchor  {exact, prefix, suffix, start}
1487     * @param {Range}  range
1488     */
1489    function openNewAnnotationForm(anchor, range) {
1490        closePanel();
1491
1492        var insertAfter = findParagraph(range.commonAncestorContainer);
1493        var form = document.createElement('div');
1494        form.id = 'ann-new-form';
1495        form.className = 'ann-new-form';
1496
1497        var quote = document.createElement('blockquote');
1498        quote.className = 'ann-quote';
1499        quote.textContent = anchor.exact;
1500        form.appendChild(quote);
1501
1502        var ta = document.createElement('textarea');
1503        ta.className = 'ann-body-input';
1504        ta.placeholder = t('placeholder_body', 'Add a comment…');
1505        ta.rows = 3;
1506        form.appendChild(ta);
1507
1508        var row = document.createElement('div');
1509        row.className = 'ann-form-row';
1510
1511        var submitBtn = document.createElement('button');
1512        submitBtn.type = 'button';
1513        submitBtn.className = 'ann-btn ann-btn-primary';
1514        submitBtn.textContent = t('btn_annotate', 'Annotate');
1515        submitBtn.addEventListener('click', function () {
1516            var body = ta.value.trim();
1517            if (!body) return;
1518            doCreate(anchor, body, function () {
1519                if (form.parentNode) form.parentNode.removeChild(form);
1520            }, submitBtn);
1521        });
1522
1523        var cancelBtn = document.createElement('button');
1524        cancelBtn.type = 'button';
1525        cancelBtn.className = 'ann-btn';
1526        cancelBtn.textContent = t('btn_cancel', 'Cancel');
1527        cancelBtn.addEventListener('click', function () {
1528            if (form.parentNode) form.parentNode.removeChild(form);
1529        });
1530
1531        row.appendChild(submitBtn);
1532        row.appendChild(cancelBtn);
1533        form.appendChild(row);
1534
1535        if (insertAfter && insertAfter.parentNode) {
1536            insertAfter.parentNode.insertBefore(form, insertAfter.nextSibling);
1537        } else {
1538            var content = document.getElementById(CONTENT_ID);
1539            if (content) content.appendChild(form);
1540        }
1541
1542        ta.focus();
1543    }
1544
1545    // -----------------------------------------------------------------------
1546    // AJAX actions
1547    // -----------------------------------------------------------------------
1548
1549    /**
1550     * POST create action and update state on success.
1551     *
1552     * @param {object}        anchor
1553     * @param {string}        body
1554     * @param {Function}      onSuccess
1555     * @param {HTMLElement}   [btn]  button to disable while the request is in flight
1556     */
1557    function doCreate(anchor, body, onSuccess, btn) {
1558        setBusy(btn, true);
1559        ajax({
1560            action: 'create',
1561            id:     _info.pageId,
1562            anchor: anchor,
1563            body:   body,
1564        }).then(function (data) {
1565            setBusy(btn, false);
1566            if (!data.success) {
1567                showError(t('error_save', 'Could not save — please try again.'), data);
1568                return;
1569            }
1570            var ann = data.annotation;
1571            _annotations.set(ann.id, ann);
1572            if (typeof onSuccess === 'function') onSuccess(ann);
1573            renderAll();
1574        }).catch(function () {
1575            setBusy(btn, false);
1576            alert(t('error_save', 'Could not save — please try again.'));
1577        });
1578    }
1579
1580    /**
1581     * Run a thread-level mutation (reply / edit annotation / edit reply /
1582     * delete reply): POST the payload, then on success store the returned
1583     * annotation — keeping the client-side render state via mergeClientProps —
1584     * and re-open its panel. The server returns the full updated annotation, so
1585     * no second GET is needed. These four actions share this exact shape;
1586     * create / delete-annotation / resolve differ (they re-render the whole
1587     * overlay) and stay separate below.
1588     *
1589     * @param {object}      payload  AJAX body; must carry annId
1590     * @param {HTMLElement} [btn]    button to show the busy spinner on
1591     * @param {string}      errKey   lang key for the failure message
1592     * @param {string}      errText  English fallback for that message
1593     * @param {Function}    [onOk]   optional callback run before re-rendering
1594     */
1595    function submitThreadAction(payload, btn, errKey, errText, onOk) {
1596        setBusy(btn, true);
1597        ajax(payload).then(function (data) {
1598            setBusy(btn, false);
1599            if (!data.success) {
1600                showError(t(errKey, errText), data);
1601                return;
1602            }
1603            _annotations.set(data.annotation.id, mergeClientProps(data.annotation));
1604            if (typeof onOk === 'function') onOk();
1605            reopenPanel(payload.annId);
1606        }).catch(function () {
1607            setBusy(btn, false);
1608            alert(t(errKey, errText));
1609        });
1610    }
1611
1612    /**
1613     * POST reply action and refresh the open panel.
1614     *
1615     * @param {string}      annId
1616     * @param {string}      body
1617     * @param {Function}    onSuccess
1618     * @param {HTMLElement} [btn]
1619     * @param {string}      [parentReplyId]  id of the reply being replied to, or ''
1620     */
1621    function doAddReply(annId, body, onSuccess, btn, parentReplyId) {
1622        submitThreadAction({
1623            action:   'reply',
1624            id:       _info.pageId,
1625            annId:    annId,
1626            body:     body,
1627            parentId: parentReplyId || '',
1628        }, btn, 'error_save', 'Could not save — please try again.', onSuccess);
1629    }
1630
1631    /**
1632     * POST edit_annotation and re-render.
1633     *
1634     * @param {string}      annId
1635     * @param {string}      body
1636     * @param {HTMLElement} [btn]
1637     */
1638    function doEditAnnotation(annId, body, btn) {
1639        submitThreadAction({
1640            action: 'edit_annotation',
1641            id:     _info.pageId,
1642            annId:  annId,
1643            body:   body,
1644        }, btn, 'error_save', 'Could not save — please try again.');
1645    }
1646
1647    /**
1648     * POST edit_reply and re-render.
1649     *
1650     * @param {string}      annId
1651     * @param {string}      replyId
1652     * @param {string}      body
1653     * @param {HTMLElement} [btn]
1654     */
1655    function doEditReply(annId, replyId, body, btn) {
1656        submitThreadAction({
1657            action:  'edit_reply',
1658            id:      _info.pageId,
1659            annId:   annId,
1660            replyId: replyId,
1661            body:    body,
1662        }, btn, 'error_save', 'Could not save — please try again.');
1663    }
1664
1665    /**
1666     * POST delete_annotation.
1667     *
1668     * @param {string}      annId
1669     * @param {HTMLElement} [btn]
1670     */
1671    function doDeleteAnnotation(annId, btn) {
1672        setBusy(btn, true);
1673        ajax({
1674            action: 'delete_annotation',
1675            id:     _info.pageId,
1676            annId:  annId,
1677        }).then(function (data) {
1678            setBusy(btn, false);
1679            if (!data.success) {
1680                showError(t('error_delete', 'Could not delete — please try again.'), data);
1681                return;
1682            }
1683            _annotations.delete(annId);
1684            closePanel();
1685            renderAll();
1686        }).catch(function () {
1687            setBusy(btn, false);
1688        });
1689    }
1690
1691    /**
1692     * POST delete_reply and re-render.
1693     *
1694     * @param {string}      annId
1695     * @param {string}      replyId
1696     * @param {HTMLElement} [btn]
1697     */
1698    function doDeleteReply(annId, replyId, btn) {
1699        submitThreadAction({
1700            action:  'delete_reply',
1701            id:      _info.pageId,
1702            annId:   annId,
1703            replyId: replyId,
1704        }, btn, 'error_delete', 'Could not delete — please try again.');
1705    }
1706
1707    /**
1708     * POST resolve/reopen action.
1709     *
1710     * @param {string}      annId
1711     * @param {string}      status  'open' | 'resolved'
1712     * @param {HTMLElement} [btn]
1713     */
1714    function doResolve(annId, status, btn) {
1715        setBusy(btn, true);
1716        ajax({
1717            action: 'resolve',
1718            id:     _info.pageId,
1719            annId:  annId,
1720            status: status,
1721        }).then(function (data) {
1722            setBusy(btn, false);
1723            if (!data.success) {
1724                showError(t('error_status', 'Could not update the status — please try again.'), data);
1725                return;
1726            }
1727            _annotations.set(data.annotation.id, data.annotation);
1728            renderAll();
1729            reopenPanel(annId);
1730        }).catch(function () {
1731            setBusy(btn, false);
1732        });
1733    }
1734
1735    /**
1736     * POST clear_resolved (admin).
1737     */
1738    function doClearResolved() {
1739        if (!confirm(t('confirm_clear_resolved', 'Delete all resolved annotations on this page?'))) return;
1740        ajax({
1741            action: 'clear_resolved',
1742            id:     _info.pageId,
1743        }).then(function (data) {
1744            if (!data.success) {
1745                showError(t('error_clear', 'Could not clear — please try again.'), data);
1746                return;
1747            }
1748            // Remove resolved from local state.
1749            _annotations.forEach(function (ann, id) {
1750                if (ann.status === 'resolved') _annotations.delete(id);
1751            });
1752            closePanel();
1753            renderAll();
1754        });
1755    }
1756
1757    /**
1758     * POST clear_orphaned (admin).
1759     */
1760    function doClearOrphaned() {
1761        if (!confirm(t('confirm_clear_orphaned', 'Delete all orphaned annotations on this page?'))) return;
1762        ajax({
1763            action: 'clear_orphaned',
1764            id:     _info.pageId,
1765        }).then(function (data) {
1766            if (!data.success) {
1767                showError(t('error_clear', 'Could not clear — please try again.'), data);
1768                return;
1769            }
1770            _annotations.forEach(function (ann, id) {
1771                if (ann._orphaned) _annotations.delete(id);
1772            });
1773            closePanel();
1774            renderAll();
1775        });
1776    }
1777
1778    // -----------------------------------------------------------------------
1779    // Panel management helpers
1780    // -----------------------------------------------------------------------
1781
1782    /**
1783     * Close the current panel and re-open it (preserves scroll position and
1784     * re-renders the thread with fresh data).
1785     *
1786     * @param {string} annId
1787     */
1788    function reopenPanel(annId) {
1789        // closePanel() first clears _openAnnId so openPanel() rebuilds instead
1790        // of treating the same id as a toggle. focusReply=false keeps the
1791        // viewport put after resolve / edit / delete actions.
1792        closePanel();
1793        openPanel(annId, false);
1794    }
1795
1796    // -----------------------------------------------------------------------
1797    // Utilities
1798    // -----------------------------------------------------------------------
1799
1800    /**
1801     * Disable a button and show a spinner while an AJAX request is in flight;
1802     * restore label and width on completion.
1803     *
1804     * @param {HTMLElement|null|undefined} btn
1805     * @param {boolean}                   busy
1806     */
1807    function setBusy(btn, busy) {
1808        if (!btn) return;
1809        if (busy) {
1810            btn.disabled = true;
1811            btn.dataset.prevText = btn.textContent;
1812            // Lock the width before clearing text so the button doesn't shrink.
1813            btn.style.minWidth = btn.offsetWidth + 'px';
1814            btn.textContent = ' '; // non-breaking space keeps height
1815            btn.classList.add('ann-btn-busy');
1816        } else {
1817            btn.disabled = false;
1818            btn.classList.remove('ann-btn-busy');
1819            if (btn.dataset.prevText !== undefined) {
1820                btn.textContent = btn.dataset.prevText;
1821                delete btn.dataset.prevText;
1822            }
1823            btn.style.minWidth = '';
1824        }
1825    }
1826
1827    /**
1828     * Copy client-only runtime properties (_highlightEl, _markerEl,
1829     * _orphaned, _range) from the currently stored annotation onto a
1830     * freshly-returned server object before storing it, so that panels
1831     * reopen at the correct position instead of falling back to the
1832     * bottom of the page.
1833     *
1834     * @param {object} fresh  annotation object from the server
1835     * @returns {object}      the same object, augmented
1836     */
1837    function mergeClientProps(fresh) {
1838        var existing = _annotations.get(fresh.id);
1839        if (existing) {
1840            fresh._highlightEl = existing._highlightEl;
1841            fresh._markerEl    = existing._markerEl;
1842            fresh._orphaned    = existing._orphaned;
1843            fresh._range       = existing._range;
1844        }
1845        return fresh;
1846    }
1847
1848    /**
1849     * The per-plugin JS language bundle, exposed by DokuWiki as
1850     * LANG.plugins.annotations (built from lang/<iso>/lang.php $lang['js']).
1851     *
1852     * @returns {object}
1853     */
1854    function uiLang() {
1855        if (typeof LANG !== 'undefined' && LANG && LANG.plugins && LANG.plugins.annotations) {
1856            return LANG.plugins.annotations;
1857        }
1858        return {};
1859    }
1860
1861    /**
1862     * Look up a UI string by key, falling back to the supplied English text if
1863     * the bundle is missing the key (e.g. a lang file not yet updated).
1864     *
1865     * @param {string} key
1866     * @param {string} fallback  English default
1867     * @returns {string}
1868     */
1869    function t(key, fallback) {
1870        var s = _lang[key];
1871        return (s === undefined || s === null || s === '') ? fallback : s;
1872    }
1873
1874    /**
1875     * Substitute a single %d placeholder with a number.
1876     *
1877     * @param {string} str
1878     * @param {number} n
1879     * @returns {string}
1880     */
1881    function fmt(str, n) {
1882        return String(str).replace('%d', n);
1883    }
1884
1885    /**
1886     * Show a localised error, appending the server's reason in parentheses
1887     * when one is present.
1888     *
1889     * @param {string} base  localised message
1890     * @param {object} data  AJAX response ({error?:string})
1891     */
1892    function showError(base, data) {
1893        var reason = (data && data.error) ? data.error : '';
1894        alert(reason ? base + ' (' + reason + ')' : base);
1895    }
1896
1897    /**
1898     * Collapse consecutive whitespace to a single space and trim.
1899     *
1900     * @param {string} s
1901     * @returns {string}
1902     */
1903    function normalizeWS(s) {
1904        return String(s || '').replace(/\s+/g, ' ').trim();
1905    }
1906
1907    /**
1908     * Return the current DokuWiki username from JSINFO.
1909     *
1910     * @returns {string}
1911     */
1912    function currentUser() {
1913        var jsinfo = (typeof JSINFO !== 'undefined' && JSINFO) ? JSINFO : {};
1914        return (jsinfo.annotations && jsinfo.annotations.user) ? jsinfo.annotations.user : '';
1915    }
1916
1917    /**
1918     * Format a Date for display.
1919     *
1920     * @param {Date} d
1921     * @returns {string}
1922     */
1923    function formatDate(d) {
1924        var now  = new Date();
1925        var diff = (now - d) / 1000; // seconds
1926        if (diff < 60)        return t('time_now', 'just now');
1927        if (diff < 3600)      return fmt(t('time_minutes', '%dm ago'), Math.floor(diff / 60));
1928        if (diff < 86400)     return fmt(t('time_hours',   '%dh ago'), Math.floor(diff / 3600));
1929        if (diff < 86400 * 7) return fmt(t('time_days',    '%dd ago'), Math.floor(diff / 86400));
1930        return d.toLocaleDateString();
1931    }
1932
1933    // -----------------------------------------------------------------------
1934    // Init
1935    // -----------------------------------------------------------------------
1936
1937    if (document.readyState === 'loading') {
1938        document.addEventListener('DOMContentLoaded', boot);
1939    } else {
1940        boot();
1941    }
1942
1943}());
1944