Project

General

Profile

Feature #43462 » text_js_code_for_this_page.js.txt

Jimmy Westberg, 2025-11-13 07:09

 
1
// Redmine History Timeline Navigator — Bracke Forest (v1.8.1)
2
// - No visual highlight on first init (only internal mark)
3
// - Preview de-dup (no heading if missing/duplicated)
4
// - bf-pills: overflow-x:hidden + ellipsis
5
// - Removed "bounce"; pills now scroll into view without animation
6

    
7
(function () {
8
  const CONFIG = {
9
    PANEL_WIDTH: 280,
10
    LEFT_OFFSET: 6,
11
    BOTTOM_OFFSET: 60,
12
    NOTE_TARGET_PAD: 80,
13
    LONG_THRESHOLD: 500,
14
    PREVIEW_MAX_CHARS: 220,
15
    PREVIEW_IMG_MAX_W: 160,
16
    PREVIEW_IMG_MAX_H: 100,
17
    HIGHLIGHT_RING: '0 0 0 2px rgba(37,99,235,.85)',
18
    HIGHLIGHT_FADE_MS: 700
19
  };
20

    
21
  // Matches #tab-content-history in your HTML
22
  const HISTORY_SEL = '#tab-content-history';
23
  // const NOTE_SEL = '.note[id^="note-"]';	// work with Redmine 6.0
24
  const NOTE_SEL = 'div[id^="note-"]';		// work with older Redmine installations
25
  const JOURNAL_SEL = '.journal';
26

    
27
  const PANEL_ID = 'bf-history-timeline-panel';
28
  const STYLE_ID = PANEL_ID + '-style';
29
  const LAUNCH_ID = 'bf-history-launcher';
30
  const HOVERZONE_ID = 'bf-history-hoverzone';
31
  const PREVIEW_ID = 'bf-history-preview';
32
  const HINT_ID = 'bf-history-hint';
33
  const NOTE_HL_CLASS = 'bf-note-highlight';
34

    
35
  if (window.__BF_HistoryTimeline?.destroy) {
36
    try { window.__BF_HistoryTimeline.destroy(); } catch(e){}
37
  }
38

    
39
  function ready(fn){
40
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
41
      setTimeout(fn, 0);
42
    } else {
43
      document.addEventListener('DOMContentLoaded', fn, { once: true });
44
    }
45
  }
46

    
47
  ready(bootstrap);
48

    
49
  let retryTimer = null;
50
  function bootstrap() {
51
    const tryInit = () => {
52
      const historyRoot = document.querySelector(HISTORY_SEL);
53
      if (!historyRoot) return false;
54
      init(historyRoot);
55
      return true;
56
    };
57
    if (!tryInit()) {
58
      let tries = 0;
59
      retryTimer = setInterval(() => {
60
        tries++;
61
        if (tryInit() || tries > 50) { clearInterval(retryTimer); retryTimer = null; }
62
      }, 200);
63
    }
64
  }
65

    
66
  function init(historyRoot){
67
    [PANEL_ID, STYLE_ID, LAUNCH_ID, HOVERZONE_ID, PREVIEW_ID, HINT_ID].forEach(id => document.getElementById(id)?.remove());
68
    document.querySelectorAll('.' + NOTE_HL_CLASS).forEach(el => el.classList.remove(NOTE_HL_CLASS));
69

    
70
    const esc = (s) => (s || '').replace(/[&<>"]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[m]));
71
    const by = (sel, root=document) => root.querySelector(sel);
72

    
73
    function jumpTo(el) {
74
      if (!el) return;
75
      const journal = el.closest(JOURNAL_SEL);
76
      if (journal && journal.style && journal.style.display === 'none') journal.style.display = '';
77
      const rect = el.getBoundingClientRect();
78
      const y = window.scrollY + rect.top - CONFIG.NOTE_TARGET_PAD;
79
      window.scrollTo({ top: Math.max(0, y), behavior: 'smooth' });
80
      highlight(el);
81
      setActiveIndex(indexOf(el));
82
    }
83

    
84
    function highlight(el, silent=false) {
85
      document.querySelectorAll('.' + NOTE_HL_CLASS).forEach(e => e.classList.remove(NOTE_HL_CLASS));
86
      if (silent) return;
87
      el.classList.add(NOTE_HL_CLASS);
88
      el.style.transition = 'box-shadow 0.6s ease';
89
      el.style.boxShadow = CONFIG.HIGHLIGHT_RING;
90
      setTimeout(() => { el.style.boxShadow = '0 0 0 0 rgba(37,99,235,0)'; }, CONFIG.HIGHLIGHT_FADE_MS);
91
    }
92

    
93
    function extractWhenFromHeader(header) {
94
      if (!header) return '';
95
      const links = Array.from(header.querySelectorAll('a[title]'));
96
      const dateLike = links.find(a => /\d{4}-\d{2}-\d{2}/.test(a.getAttribute('title') || ''));
97
      if (dateLike) return dateLike.getAttribute('title') || dateLike.textContent.trim();
98
      const act = links.find(a => /activity\?from=/.test(a.getAttribute('href') || ''));
99
      if (act) return act.getAttribute('title') || act.textContent.trim();
100
      const last = links[links.length - 1];
101
      return last ? (last.getAttribute('title') || last.textContent.trim()) : '';
102
    }
103

    
104
    function getSummaryAndBody(wikiEl) {
105
      const firstHeading = wikiEl.querySelector('h1,h2,h3,h4,h5,h6');
106
      const headingText = firstHeading?.innerText?.trim() || '';
107
      let bodyText = (wikiEl.innerText || '').replace(/\s+/g,' ').trim();
108
      const norm = s => (s||'').toLowerCase().replace(/[\s\p{P}\p{S}]+/gu,' ').trim();
109
      if (headingText && norm(bodyText).startsWith(norm(headingText))) {
110
        const idx = bodyText.toLowerCase().indexOf(headingText.toLowerCase());
111
        if (idx === 0) bodyText = bodyText.slice(headingText.length).trim();
112
      }
113
      const showTitle = !!headingText && !norm(bodyText.slice(0,100)).includes(norm(headingText));
114
      const summary = showTitle ? headingText : '';
115
      return { summary, bodyText };
116
    }
117

    
118
    const collectNotes = (excludeHiddenJournals) => {
119
      const notes = Array.from(historyRoot.querySelectorAll(NOTE_SEL))
120
        .filter(n => {
121
          if (!excludeHiddenJournals) return true;
122
          const j = n.closest(JOURNAL_SEL);
123
          return !(j && j.style && j.style.display === 'none');
124
        })
125
        .sort((a,b) => {
126
          const an = parseInt(a.id.replace('note-',''),10);
127
          const bn = parseInt(b.id.replace('note-',''),10);
128
          if (!isNaN(an) && !isNaN(bn)) return an - bn;
129
          return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
130
        });
131

    
132
      return notes.map((note, i) => {
133
        const num = parseInt(note.id.replace('note-',''),10);
134
        const journal = note.closest(JOURNAL_SEL);
135
        const header = note.querySelector('.note-header') || journal?.querySelector('.note-header');
136
        const author = header?.querySelector('a.user')?.textContent?.trim() || 'Unknown';
137
        const linkTxt = journal?.querySelector('.journal-link')?.textContent?.trim() || ('#' + (isNaN(num) ? (i+1) : num));
138
        const when = extractWhenFromHeader(header);
139
        const wiki = note.querySelector('.wiki') || note;
140
        const { summary, bodyText } = getSummaryAndBody(wiki);
141
        const imgSrc = (wiki.querySelector('img')?.getAttribute('src')) || null;
142
        return { el: note, num, author, linkTxt, when, textLen: bodyText.length, imgSrc, summary, fullText: bodyText };
143
      });
144
    };
145

    
146
    let excludeHidden = true;
147
    let notes = collectNotes(excludeHidden);
148
    if (!notes.length) { console.warn('Timeline: No notes found.'); return; }
149
    const indexOf = (el) => notes.findIndex(n => n.el === el);
150
    let activeIndex = 0;
151

    
152
    const css = document.createElement('style');
153
    css.id = STYLE_ID;
154
    css.textContent = `
155
      :root { --bf-width: ${CONFIG.PANEL_WIDTH}px; --bf-left: ${CONFIG.LEFT_OFFSET}px; --bf-bottom: ${CONFIG.BOTTOM_OFFSET}px; }
156

    
157
      #${HOVERZONE_ID} { position: fixed; left: 50%; transform: translateX(-50%); bottom: var(--bf-bottom); width: 360px; height: 42px; z-index: 9997; }
158
      #${LAUNCH_ID} {
159
        position: fixed; left: 50%; transform: translateX(-50%);
160
        bottom: calc(var(--bf-bottom) - 10px); z-index: 9998; opacity: 0; transition: opacity .2s ease, transform .2s ease;
161
        background: #f3f4f6; color: #374151; border: 1px solid #d1d5db; border-radius: 999px;
162
        padding: 6px 12px; font-weight: 600; font-size: 12px; box-shadow: 0 6px 18px rgba(0,0,0,.12); cursor: pointer;
163
      }
164
      #${HOVERZONE_ID}:hover + #${LAUNCH_ID}, #${LAUNCH_ID}:hover { opacity: 1; transform: translateX(-50%) translateY(-2px); }
165

    
166
      #${PANEL_ID} {
167
        position: fixed; width: var(--bf-width); left: var(--bf-left);
168
        bottom: calc(var(--bf-bottom) + 14px); max-width: calc(100vw - 24px); background: #f9fafb; color: #111827;
169
        border: 1px solid #e5e7eb; border-radius: 14px; box-shadow: 0 16px 40px rgba(0,0,0,.18);
170
        font-family: ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, 'Helvetica Neue', Arial, 'Noto Sans';
171
        overflow: hidden; user-select: none; z-index: 9999; transform: translate(-120%, 0); opacity: 0; pointer-events: none;
172
        transition: transform .28s ease, opacity .28s ease;
173
      }
174
      #${PANEL_ID}.open { transform: translate(0, 0); opacity: 1; pointer-events: auto; }
175

    
176
      #${PANEL_ID} .bf-hdr { display:flex; align-items:center; justify-content:space-between; padding:10px 12px; background:#f3f4f6; border-bottom:1px solid #e5e7eb; }
177
      #${PANEL_ID} .bf-title { font-weight:700; letter-spacing:.2px; color:#111827; }
178
      #${PANEL_ID} .bf-counter { opacity:.85; font-variant-numeric: tabular-nums; color:#374151; }
179
      #${PANEL_ID} .bf-close { background:#e5e7eb; color:#374151; border:1px solid #d1d5db; font-size:12px; padding:4px 8px; border-radius:8px; cursor:pointer; }
180
      #${PANEL_ID} .bf-close:hover { background:#d1d5db; }
181

    
182
      #${PANEL_ID} .bf-controls { display:grid; grid-template-columns: auto 1fr auto; gap:8px; align-items:center; padding:10px 12px; }
183
      #${PANEL_ID} .bf-btn { border:1px solid #d1d5db; padding:4px 8px; border-radius:8px; background:#ffffff; color:#374151; cursor:pointer; font-size:12px; line-height:1; }
184
      #${PANEL_ID} .bf-btn:hover { background:#f3f4f6; }
185
      #${PANEL_ID} .bf-slider-wrap { display:flex; align-items:center; gap:10px; }
186
      #${PANEL_ID} .bf-edge { font-size:11px; color:#6b7280; user-select:none; }
187

    
188
      #${PANEL_ID} .bf-slider { -webkit-appearance: none; appearance: none; width: 100%; height: 18px; background: transparent; }
189
      #${PANEL_ID} .bf-slider::-webkit-slider-runnable-track { height: 4px; background: #e5e7eb; border-radius: 999px; border: 1px solid #d1d5db; }
190
      #${PANEL_ID} .bf-slider::-moz-range-track { height: 4px; background: #e5e7eb; border-radius: 999px; border: 1px solid #d1d5db; }
191
      #${PANEL_ID} .bf-slider::-webkit-slider-thumb { -webkit-appearance: none; width: 14px; height: 14px; border-radius: 50%; background: #ffffff; border: 1px solid #9ca3af; margin-top: -6px; box-shadow: 0 1px 2px rgba(0,0,0,.12); }
192
      #${PANEL_ID} .bf-slider::-moz-range-thumb { width: 14px; height: 14px; border-radius: 50%; background: #ffffff; border: 1px solid #9ca3af; box-shadow: 0 1px 2px rgba(0,0,0,.12); }
193

    
194
      #${PANEL_ID} .bf-toggles { display:flex; gap:10px; align-items:center; padding:0 12px 10px 12px; flex-wrap:wrap; }
195
      #${PANEL_ID} .bf-toggles label { font-size:12px; color:#374151; display:flex; gap:6px; align-items:center; }
196
      #${PANEL_ID} .bf-filter { flex:1; min-width:120px; padding:6px 8px; border-radius:8px; border:1px solid #d1d5db; background:#ffffff; color:#111827; font-size:12px; }
197

    
198
      #${PANEL_ID} .bf-pills {
199
        display:flex;
200
        flex-wrap:wrap;
201
        gap:6px;
202
        padding:0 12px 12px 12px;
203
        max-height:160px;
204
        overflow-y:auto;
205
        overflow-x:hidden;
206
      }
207
      #${PANEL_ID} .bf-pill {
208
        font-size:12px;
209
        border:1px solid #d1d5db;
210
        background:#ffffff;
211
        color:#374151;
212
        border-radius:999px;
213
        padding:4px 8px;
214
        cursor:pointer;
215
        max-width:100%;
216
        overflow:hidden;
217
        text-overflow:ellipsis;
218
        white-space:nowrap;
219
      }
220
      #${PANEL_ID} .bf-pill:hover { background:#f3f4f6; }
221
      #${PANEL_ID} .bf-pill.active { border-color:#2563eb; box-shadow:0 0 0 2px rgba(37,99,235,.20) inset; }
222

    
223
      #${PANEL_ID} .bf-help { font-size:11px; color:#6b7280; padding:0 12px 12px 12px; }
224

    
225
      .${NOTE_HL_CLASS} { border-radius: inherit !important; }
226
      .${NOTE_HL_CLASS}::before { border-color: rgba(37,99,235,.85) !important; }
227

    
228
      #${PREVIEW_ID} {
229
        position: fixed; z-index: 10000; pointer-events: none;
230
        max-width: 340px; background: #ffffff; color:#111827; border:1px solid #e5e7eb; border-radius: 10px;
231
        box-shadow: 0 12px 30px rgba(0,0,0,.18); padding: 8px; font-size: 12px; display: none;
232
      }
233
      #${PREVIEW_ID} .ttl { font-weight: 700; margin-bottom: 4px; }
234
      #${PREVIEW_ID} .txt { color:#374151; line-height: 1.3; }
235
      #${PREVIEW_ID} .row { display:flex; gap:8px; align-items:flex-start; }
236
      #${PREVIEW_ID} img { display:block; max-width:${CONFIG.PREVIEW_IMG_MAX_W}px; max-height:${CONFIG.PREVIEW_IMG_MAX_H}px; border-radius:6px; border:1px solid #e5e7eb; }
237

    
238
      #${HINT_ID}{
239
        position: fixed; z-index: 10001; pointer-events: none;
240
        background:#111827; color:#ffffff; border-radius:6px; padding:4px 8px; font-size:11px;
241
        box-shadow: 0 6px 18px rgba(0,0,0,.18); display:none; white-space:nowrap;
242
      }
243
    `;
244
    document.head.appendChild(css);
245

    
246
    const hoverZone = document.createElement('div'); hoverZone.id = HOVERZONE_ID;
247
    const launcher = document.createElement('button'); launcher.id = LAUNCH_ID; launcher.textContent = 'Quick jump';
248
    document.body.appendChild(hoverZone); document.body.appendChild(launcher);
249

    
250
    const panel = document.createElement('div');
251
    panel.id = PANEL_ID;
252
    panel.innerHTML = `
253
      <div class="bf-hdr">
254
        <span class="bf-title">History timeline</span>
255
        <span class="bf-counter"></span>
256
        <button class="bf-close" title="Close">Close</button>
257
      </div>
258
      <div class="bf-controls">
259
        <button class="bf-btn bf-prev" title="Previous (p/k)">⟨</button>
260
        <div class="bf-slider-wrap">
261
          <span class="bf-edge">Oldest</span>
262
          <input type="range" class="bf-slider" min="0" value="0" step="1">
263
          <span class="bf-edge">Newest</span>
264
        </div>
265
        <button class="bf-btn bf-next" title="Next (n/j)">⟩</button>
266
      </div>
267
      <div class="bf-toggles">
268
        <label title="Checked = show only visible notes (ignores hidden journals). Unchecked = include hidden.">
269
          <input type="checkbox" class="bf-toggle-onlynotes" checked> Only notes
270
        </label>
271
        <label><input type="checkbox" class="bf-toggle-long"> Only jump to long notes</label>
272
        <input type="text" class="bf-filter" placeholder="Filter: author, date or #">
273
      </div>
274
      <div class="bf-pills" role="listbox" aria-label="Quick jump"></div>
275
      <div class="bf-help">Keyboard shortcuts:<br><b>n/j</b> next, <b>p/k</b> previous, <b>g</b> go to #</div>
276
    `;
277
    document.body.appendChild(panel);
278

    
279
    const preview = document.createElement('div'); preview.id = PREVIEW_ID; document.body.appendChild(preview);
280
    const hint = document.createElement('div'); hint.id = HINT_ID; document.body.appendChild(hint);
281

    
282
    const slider = by('.bf-slider', panel);
283
    const btnPrev = by('.bf-prev', panel);
284
    const btnNext = by('.bf-next', panel);
285
    const counter = by('.bf-counter', panel);
286
    const pills = by('.bf-pills', panel);
287
    const closeBtn = by('.bf-close', panel);
288
    const toggleOnlyNotes = by('.bf-toggle-onlynotes', panel);
289
    const toggleLong = by('.bf-toggle-long', panel);
290
    const filterInput = by('.bf-filter', panel);
291

    
292
    let filteredIdxList = null;
293
    let pillEls = [];
294

    
295
    function formatLabel(n) {
296
      const when = n.when ? n.when.replace(/\s+/g,' ').trim() : '—';
297
      const numTxt = isNaN(n.num) ? n.linkTxt : `#${n.num}`;
298
      return `${numTxt} · ${when} · ${n.author}`;
299
    }
300

    
301
    function buildPreviewHTML(n) {
302
      const useTitle = !!n.summary;
303
      const ttl = useTitle ? esc(n.summary) : '';
304
      const text = esc(n.fullText.slice(0, CONFIG.PREVIEW_MAX_CHARS));
305
      const textHTML = `<div class="txt">${text}${n.fullText.length > CONFIG.PREVIEW_MAX_CHARS ? '…' : ''}</div>`;
306
      return n.imgSrc
307
        ? `<div class="row"><img src="${n.imgSrc}"><div style="flex:1 1 auto;">${useTitle ? `<div class="ttl">${ttl}</div>` : ''}${textHTML}</div></div>`
308
        : `${useTitle ? `<div class="ttl">${ttl}</div>` : ''}${textHTML}`;
309
    }
310

    
311
    function showHint(e, text){
312
      hint.textContent = text;
313
      hint.style.display = 'block';
314
      const rectW = hint.offsetWidth || 120;
315
      const x = Math.min(window.innerWidth - rectW - 8, Math.max(8, e.clientX - rectW/2));
316
      const y = Math.max(8, e.clientY - 26);
317
      hint.style.left = `${x}px`;
318
      hint.style.top = `${y}px`;
319
    }
320
    function hideHint(){ hint.style.display = 'none'; }
321

    
322
    function attachPillPreview(pill, n) {
323
      pill.removeAttribute('title');
324
      pill.addEventListener('mouseenter', (e) => {
325
        preview.innerHTML = buildPreviewHTML(n);
326
        preview.style.display = 'block';
327
        movePreview(e);
328
        showHint(e, `Jump to ${isNaN(n.num) ? n.linkTxt : ('#' + n.num)}`);
329
      });
330
      pill.addEventListener('mousemove', (e) => { movePreview(e); showHint(e, hint.textContent); });
331
      pill.addEventListener('mouseleave', () => { preview.style.display = 'none'; hideHint(); });
332

    
333
      function movePreview(e) {
334
        const pad = 12;
335
        const vw = window.innerWidth, vh = window.innerHeight;
336
        let x = e.clientX + pad, y = e.clientY + pad;
337
        const rectW = preview.offsetWidth || 320, rectH = preview.offsetHeight || 140;
338
        if (x + rectW + 8 > vw) x = vw - rectW - 8;
339
        if (y + rectH + 8 > vh) y = vh - rectH - 8;
340
        preview.style.left = `${x}px`;
341
        preview.style.top = `${y}px`;
342
      }
343
    }
344

    
345
    function rebuildPills() {
346
      pills.innerHTML = '';
347
      pillEls = [];
348
      const term = filterInput.value.trim().toLowerCase();
349
      const useFilter = !!term;
350
      filteredIdxList = [];
351

    
352
      notes.forEach((n, idx) => {
353
        if (toggleLong.checked && n.textLen < CONFIG.LONG_THRESHOLD) return;
354
        if (useFilter) {
355
          const hay = `${n.author} ${n.num} ${n.linkTxt} ${n.when}`.toLowerCase();
356
          if (!hay.includes(term)) return;
357
        }
358
        filteredIdxList.push(idx);
359

    
360
        const pill = document.createElement('button');
361
        pill.className = 'bf-pill';
362
        pill.setAttribute('role', 'option');
363
        pill.textContent = formatLabel(n);
364
        pill.addEventListener('click', () => { setActiveIndex(idx); jumpTo(n.el); });
365
        attachPillPreview(pill, n);
366
        pills.appendChild(pill);
367
        pillEls[idx] = pill;
368
      });
369

    
370
      if (!filteredIdxList.length) {
371
        const none = document.createElement('div');
372
        none.style.color = '#6b7280'; none.style.fontSize = '12px';
373
        none.textContent = 'No results match the filter.';
374
        pills.appendChild(none);
375
      }
376

    
377
      setActiveIndex(Math.min(activeIndex, notes.length - 1));
378
    }
379

    
380
    // Scroll active pill into view without animation; handle when active is missing in filtered view
381
    function ensureActivePillVisible() {
382
      let pill = pillEls[activeIndex];
383

    
384
      if (!pill && filteredIdxList && filteredIdxList.length) {
385
        let nearest = filteredIdxList[0], best = Math.abs(nearest - activeIndex);
386
        for (const i of filteredIdxList) {
387
          const d = Math.abs(i - activeIndex);
388
          if (d < best) { best = d; nearest = i; }
389
        }
390
        activeIndex = nearest;
391
        pill = pillEls[activeIndex];
392
      }
393
      if (!pill) return;
394

    
395
      pill.classList.add('active');
396
      pillEls.forEach((p, i) => { if (p && i !== activeIndex) p.classList.remove('active'); });
397
      pillEls.forEach((p, i) => p && p.setAttribute('aria-selected', i === activeIndex ? 'true' : 'false'));
398

    
399
      // scrollIntoView without smooth → no bounce
400
      if (pill.scrollIntoView) {
401
        pill.scrollIntoView({ block: 'nearest', inline: 'nearest' });
402
      } else {
403
        // manual fallback
404
        const c = pills, pTop = pill.offsetTop, pBottom = pTop + pill.offsetHeight + 6;
405
        if (pTop < c.scrollTop) c.scrollTop = pTop - 6;
406
        else if (pBottom > c.scrollTop + c.clientHeight) c.scrollTop = pBottom - c.clientHeight;
407
      }
408
    }
409

    
410
    function setActiveIndex(i) {
411
      activeIndex = Math.max(0, Math.min(notes.length - 1, i));
412
      slider.max = String(Math.max(0, notes.length - 1));
413
      slider.value = String(activeIndex);
414
      counter.textContent = `${activeIndex + 1}/${notes.length}`;
415
      ensureActivePillVisible();
416
    }
417

    
418
    function rebuildAll() {
419
      notes = collectNotes(excludeHidden);
420
      rebuildPills();
421
    }
422

    
423
    function move(delta) {
424
      const insideFilter = (toggleLong.checked || (filterInput.value.trim().length > 0));
425
      if (insideFilter && filteredIdxList && filteredIdxList.length) {
426
        const currPos = filteredIdxList.indexOf(activeIndex);
427
        const nextPos = currPos === -1 ? 0 : Math.max(0, Math.min(filteredIdxList.length - 1, currPos + delta));
428
        const nextIdx = filteredIdxList[nextPos];
429
        setActiveIndex(nextIdx);
430
      } else {
431
        setActiveIndex(activeIndex + delta);
432
      }
433
      const n = notes[activeIndex];
434
      if (n) jumpTo(n.el);
435
    }
436

    
437
    const sliderInput = () => setActiveIndex(parseInt(slider.value,10) || 0);
438
    slider.addEventListener('input', sliderInput);
439
    slider.addEventListener('change', () => { const n = notes[activeIndex]; if (n) jumpTo(n.el); });
440
    btnPrev.addEventListener('click', () => move(-1));
441
    btnNext.addEventListener('click', () => move(1));
442
    toggleOnlyNotes.addEventListener('change', () => { excludeHidden = toggleOnlyNotes.checked; rebuildAll(); });
443
    toggleLong.addEventListener('change', rebuildPills);
444
    filterInput.addEventListener('input', rebuildPills);
445
    closeBtn.addEventListener('click', () => panel.classList.remove('open'));
446

    
447
    const launcherClick = () => {
448
      panel.classList.toggle('open');
449
      if (panel.classList.contains('open')) selectClosest(false);
450
    };
451
    launcher.addEventListener('click', launcherClick);
452

    
453
    const onKey = (e) => {
454
      if (!panel.classList.contains('open')) return;
455
      const tag = (e.target.tagName || '').toLowerCase();
456
      const isTyping = (tag === 'input' || tag === 'textarea' || tag === 'select');
457
      if (isTyping && e.target !== filterInput) return;
458
      if (e.key === 'j' || e.key === 'n') { e.preventDefault(); move(1); }
459
      else if (e.key === 'k' || e.key === 'p') { e.preventDefault(); move(-1); }
460
      else if (e.key.toLowerCase() === 'g') {
461
        e.preventDefault();
462
        const s = prompt('Go to comment # (e.g. 10):'); if (!s) return;
463
        const targetNum = parseInt(s, 10); if (isNaN(targetNum)) return;
464
        const idx = notes.findIndex(n => n.num === targetNum);
465
        if (idx >= 0) { setActiveIndex(idx); jumpTo(notes[idx].el); }
466
        else alert(`Could not find #${targetNum}`);
467
      }
468
    };
469
    window.addEventListener('keydown', onKey);
470

    
471
    function selectClosest(suppressHighlight=false) {
472
      const viewportMid = window.scrollY + window.innerHeight / 2;
473
      let bestIdx = 0, bestDist = Infinity;
474
      notes.forEach((n, i) => {
475
        const rect = n.el.getBoundingClientRect();
476
        const y = window.scrollY + rect.top;
477
        const d = Math.abs(y - viewportMid);
478
        if (d < bestDist) { bestDist = d; bestIdx = i; }
479
      });
480
      setActiveIndex(bestIdx);
481
      highlight(notes[bestIdx].el, suppressHighlight);
482
    }
483

    
484
    rebuildAll();
485
    selectClosest(true);
486

    
487
    const mo = new MutationObserver(() => {
488
      clearTimeout(mo._t);
489
      mo._t = setTimeout(() => {
490
        const now = collectNotes(excludeHidden);
491
        const beforeIds = notes.map(n => n.el.id).join(',');
492
        const afterIds  = now.map(n => n.el.id).join(',');
493
        if (beforeIds !== afterIds) { notes = now; rebuildPills(); }
494
      }, 200);
495
    });
496
    mo.observe(historyRoot, { childList: true, subtree: true, attributes: true, attributeFilter: ['style'] });
497

    
498
    window.__BF_HistoryTimeline = {
499
      refresh: rebuildAll,
500
      open: () => panel.classList.add('open'),
501
      close: () => panel.classList.remove('open'),
502
      setWidth: (px) => { document.documentElement.style.setProperty('--bf-width', px + 'px'); },
503
      setLeft: (px) => { document.documentElement.style.setProperty('--bf-left', px + 'px'); },
504
      setBottom: (px) => { document.documentElement.style.setProperty('--bf-bottom', px + 'px'); },
505
      destroy: () => {
506
        mo.disconnect();
507
        [panel, launcher, hoverZone, css, preview, hint].forEach(el=>el?.remove());
508
        window.removeEventListener('keydown', onKey);
509
      }
510
    };
511
  }
512
})();
(3-3/10)