Project

General

Profile

Feature #43462 » original_js_code.txt

Jimmy Westberg, 2025-11-11 08:45

 
1
// Redmine History Timeline Navigator — Bracke Forest (v1.8.1)
2
// - Ingen visuell highlight vid första init (markerar endast internt)
3
// - Preview de-dup (ingen rubrik om saknas/duplicerad)
4
// - bf-pills: overflow-x:hidden + ellipsis
5
// - Borttagen "bounce/sprätt"; pills scrollar nu in i vy utan 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
  const HISTORY_SEL = '#tab-content-history';
22
  const NOTE_SEL = '.note[id^="note-"]';
23
  const JOURNAL_SEL = '.journal';
24

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

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

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

    
45
  ready(bootstrap);
46

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

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

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

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

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

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

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

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

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

    
144
    let excludeHidden = true;
145
    let notes = collectNotes(excludeHidden);
146
    if (!notes.length) { console.warn('Timeline: Inga anteckningar hittades.'); return; }
147
    const indexOf = (el) => notes.findIndex(n => n.el === el);
148
    let activeIndex = 0;
149

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

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

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

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

    
180
      #${PANEL_ID} .bf-controls { display:grid; grid-template-columns: auto 1fr auto; gap:8px; align-items:center; padding:10px 12px; }
181
      #${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; }
182
      #${PANEL_ID} .bf-btn:hover { background:#f3f4f6; }
183
      #${PANEL_ID} .bf-slider-wrap { display:flex; align-items:center; gap:10px; }
184
      #${PANEL_ID} .bf-edge { font-size:11px; color:#6b7280; user-select:none; }
185

    
186
      #${PANEL_ID} .bf-slider { -webkit-appearance: none; appearance: none; width: 100%; height: 18px; background: transparent; }
187
      #${PANEL_ID} .bf-slider::-webkit-slider-runnable-track { height: 4px; background: #e5e7eb; border-radius: 999px; border: 1px solid #d1d5db; }
188
      #${PANEL_ID} .bf-slider::-moz-range-track { height: 4px; background: #e5e7eb; border-radius: 999px; border: 1px solid #d1d5db; }
189
      #${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); }
190
      #${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); }
191

    
192
      #${PANEL_ID} .bf-toggles { display:flex; gap:10px; align-items:center; padding:0 12px 10px 12px; flex-wrap:wrap; }
193
      #${PANEL_ID} .bf-toggles label { font-size:12px; color:#374151; display:flex; gap:6px; align-items:center; }
194
      #${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; }
195

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

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

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

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

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

    
244
    const hoverZone = document.createElement('div'); hoverZone.id = HOVERZONE_ID;
245
    const launcher = document.createElement('button'); launcher.id = LAUNCH_ID; launcher.textContent = 'Snabbhopp';
246
    document.body.appendChild(hoverZone); document.body.appendChild(launcher);
247

    
248
    const panel = document.createElement('div');
249
    panel.id = PANEL_ID;
250
    panel.innerHTML = `
251
      <div class="bf-hdr">
252
        <span class="bf-title">Historiktidslinje</span>
253
        <span class="bf-counter"></span>
254
        <button class="bf-close" title="Stäng">Stäng</button>
255
      </div>
256
      <div class="bf-controls">
257
        <button class="bf-btn bf-prev" title="Föregående (p/k)">⟨</button>
258
        <div class="bf-slider-wrap">
259
          <span class="bf-edge">Äldst</span>
260
          <input type="range" class="bf-slider" min="0" value="0" step="1">
261
          <span class="bf-edge">Nyast</span>
262
        </div>
263
        <button class="bf-btn bf-next" title="Nästa (n/j)">⟩</button>
264
      </div>
265
      <div class="bf-toggles">
266
        <label title="Bockad = visa bara synliga anteckningar (ignorera dolda journaler). Avbockad = inkludera dolda.">
267
          <input type="checkbox" class="bf-toggle-onlynotes" checked> Bara anteckningar
268
        </label>
269
        <label><input type="checkbox" class="bf-toggle-long"> Hoppa bara till långa</label>
270
        <input type="text" class="bf-filter" placeholder="Filter: författare, datum eller #">
271
      </div>
272
      <div class="bf-pills" role="listbox" aria-label="Snabbhopp"></div>
273
      <div class="bf-help">Kortkommandon:<br><b>n/j</b> nästa, <b>p/k</b> föregående, <b>g</b> gå till #</div>
274
    `;
275
    document.body.appendChild(panel);
276

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

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

    
290
    let filteredIdxList = null;
291
    let pillEls = [];
292

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

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

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

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

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

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

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

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

    
368
      if (!filteredIdxList.length) {
369
        const none = document.createElement('div');
370
        none.style.color = '#6b7280'; none.style.fontSize = '12px';
371
        none.textContent = 'Inget matchar filtret.';
372
        pills.appendChild(none);
373
      }
374

    
375
      setActiveIndex(Math.min(activeIndex, notes.length - 1));
376
    }
377

    
378
    // Scrolla in aktiv pill utan animation; hantera om aktiv saknas i filtrerad vy
379
    function ensureActivePillVisible() {
380
      let pill = pillEls[activeIndex];
381

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

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

    
397
      // scrollIntoView utan smooth → inget studs
398
      if (pill.scrollIntoView) {
399
        pill.scrollIntoView({ block: 'nearest', inline: 'nearest' });
400
      } else {
401
        // fallback manuell
402
        const c = pills, pTop = pill.offsetTop, pBottom = pTop + pill.offsetHeight + 6;
403
        if (pTop < c.scrollTop) c.scrollTop = pTop - 6;
404
        else if (pBottom > c.scrollTop + c.clientHeight) c.scrollTop = pBottom - c.clientHeight;
405
      }
406
    }
407

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

    
416
    function rebuildAll() {
417
      notes = collectNotes(excludeHidden);
418
      rebuildPills();
419
    }
420

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

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

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

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

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

    
482
    rebuildAll();
483
    selectClosest(true);
484

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

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