Project

General

Profile

Feature #43462 » vanilla_styling_and_more_settings_v1.9.11.js.txt

Jimmy Westberg, 2025-11-14 09:20

 
1
// Redmine History Timeline Navigator — Quick Jump (v1.9.11)
2
// - Panel docks left/right via CONFIG.SIDE
3
// - Separate bottom offsets for Quick Jump trigger vs. panel
4
// - Minimal custom styling to blend with page theme
5
// - Configurable pill border-radius (CONFIG.PILL_RADIUS)
6
// - Configurable highlight colors via CONFIG.HIGHLIGHT_COLOR / HIGHLIGHT_SOFT_COLOR
7
// - All UI text configurable via CONFIG.TEXT (except console output)
8
// - Configurable z-index base via CONFIG.ZINDEX_BASE (all layers offset from this)
9
// - Panel width/height fixed via CONFIG.PANEL_WIDTH / CONFIG.PANEL_HEIGHT
10
// - Preview opens to the opposite side of the panel (left when panel is on the right)
11
// - Panel & preview & slider thumb reuse nearest non-transparent background color
12
// - No visual highlight on first init (only internal mark)
13
// - Preview de-dup (no heading if missing/duplicated)
14
// - Pills: overflow-x:hidden + ellipsis, always stacked (no spreading)
15
// - "Only notes" hides journals with only .has-details (no .has-notes) and hidden journals
16
// - "Only jump to long notes" uses CONFIG.LONG_NOTES_CHARACTER_THRESHOLD
17
// - Slider & counter respect filters (including "no results" → 0/0)
18
// - No "bounce" when scrolling active pill into view
19
// - Fix highlight to also style the tab, added TITLE for "long notes"
20

    
21
(function () {
22
  const CONFIG = {
23
    PANEL_WIDTH: 280,
24
    PANEL_HEIGHT: 380,
25

    
26
    // 'left' | 'right'
27
    SIDE: 'left',
28

    
29
    // Horizontal offset from chosen side
30
    SIDE_OFFSET: 6,
31

    
32
    // Bottom offsets
33
    BOTTOM_OFFSET_QUICK: 60,  // Quick Jump button / hover zone
34
    BOTTOM_OFFSET_PANEL: 65,  // Panel
35

    
36
    // Pill appearance
37
    PILL_RADIUS: 999,         // px, e.g. 999 for capsule, 6 for rounded
38

    
39
    // Threshold for "long notes" (characters)
40
    LONG_NOTES_CHARACTER_THRESHOLD: 500,
41

    
42
    NOTE_TARGET_PAD: 80,
43
    PREVIEW_MAX_CHARS: 220,
44
    PREVIEW_IMG_MAX_W: 160,
45
    PREVIEW_IMG_MAX_H: 100,
46

    
47
    // Highlight colors
48
    HIGHLIGHT_COLOR: 'rgba(37,99,235,0.85)',
49
    HIGHLIGHT_SOFT_COLOR: 'rgba(37,99,235,0.6)',
50
    HIGHLIGHT_FADE_MS: 700,
51

    
52
    // Base z-index (all other layers are relative to this)
53
    // hoverzone:      ZINDEX_BASE
54
    // launcher:       ZINDEX_BASE + 1
55
    // panel:          ZINDEX_BASE + 2
56
    // preview-popup:  ZINDEX_BASE + 3
57
    // hint-tooltip:   ZINDEX_BASE + 4
58
    ZINDEX_BASE: 9990,
59

    
60
    // All user-visible text (except console)
61
    TEXT: {
62
      LAUNCHER_LABEL: 'Quick jump',
63
      PANEL_TITLE: 'History timeline',
64
      CLOSE_LABEL: 'Close',
65
      CLOSE_TITLE: 'Close',
66
      PREV_BUTTON: '⟨',
67
      PREV_TITLE: 'Previous (p/k)',
68
      NEXT_BUTTON: '⟩',
69
      NEXT_TITLE: 'Next (n/j)',
70
      EDGE_OLDEST: 'Oldest',
71
      EDGE_NEWEST: 'Newest',
72
      ONLY_NOTES_LABEL: 'Only notes',
73
      ONLY_NOTES_TITLE: 'Checked = show only journals with notes (has-notes) and ignore hidden journals. Unchecked = include all entries.',
74
      ONLY_LONG_LABEL: 'Only jump to long notes',
75
      ONLY_LONG_TITLE: 'Checked = only jump to notes longer than {N} characters.',
76
      FILTER_PLACEHOLDER: 'Filter: author, date or #',
77
      PILLS_ARIA_LABEL: 'Quick jump',
78
      HELP_HTML: 'Keyboard shortcuts:<br><b>n/j</b> next, <b>p/k</b> previous, <b>g</b> go to #',
79
      NO_RESULTS: 'No results match the filter.',
80
      PROMPT_GOTO: 'Go to comment # (e.g. 10):',
81
      ALERT_GOTO_NOT_FOUND_PREFIX: 'Could not find #',
82
      HINT_JUMP_PREFIX: 'Jump to '
83
    }
84
  };
85

    
86
  const HISTORY_SEL = '#tab-content-history';
87
  // const NOTE_SEL = '.note[id^="note-"]';  // Redmine 6
88
  const NOTE_SEL = 'div[id^="note-"]';       // older Redmine
89
  const JOURNAL_SEL = '.journal';
90

    
91
  const PANEL_ID = 'qj-history-timeline-panel';
92
  const STYLE_ID = PANEL_ID + '-style';
93
  const LAUNCH_ID = 'qj-history-launcher';
94
  const HOVERZONE_ID = 'qj-history-hoverzone';
95
  const PREVIEW_ID = 'qj-history-preview';
96
  const HINT_ID = 'qj-history-hint';
97
  const NOTE_HL_CLASS = 'qj-note-highlight';
98
  const NOTE_HEADER_HL_CLASS = 'qj-note-header-highlight';
99

    
100
  const HIGHLIGHT_RING = '0 0 0 2px ' + CONFIG.HIGHLIGHT_COLOR;
101

    
102
  if (window.__QJ_HistoryTimeline?.destroy) {
103
    try { window.__QJ_HistoryTimeline.destroy(); } catch (e) {}
104
  }
105

    
106
  function ready(fn) {
107
    if (document.readyState === 'complete' || document.readyState === 'interactive') {
108
      setTimeout(fn, 0);
109
    } else {
110
      document.addEventListener('DOMContentLoaded', fn, { once: true });
111
    }
112
  }
113

    
114
  ready(bootstrap);
115

    
116
  let retryTimer = null;
117
  function bootstrap() {
118
    const tryInit = () => {
119
      const historyRoot = document.querySelector(HISTORY_SEL);
120
      if (!historyRoot) return false;
121
      init(historyRoot);
122
      return true;
123
    };
124
    if (!tryInit()) {
125
      let tries = 0;
126
      retryTimer = setInterval(() => {
127
        tries++;
128
        if (tryInit() || tries > 50) { clearInterval(retryTimer); retryTimer = null; }
129
      }, 200);
130
    }
131
  }
132

    
133
  // Find closest non-transparent background color starting from a given element.
134
  function findEffectiveBackgroundColor(rootEl) {
135
    const isTransparent = (bg) => {
136
      if (!bg) return true;
137
      bg = bg.trim().toLowerCase();
138
      if (bg === 'transparent') return true;
139
      return /^rgba?\(\s*0\s*,\s*0\s*,\s*0\s*,\s*0\s*\)$/.test(bg);
140
    };
141

    
142
    let el = rootEl;
143
    while (el) {
144
      const cs = window.getComputedStyle(el);
145
      const bg = cs && cs.backgroundColor;
146
      if (!isTransparent(bg)) return bg;
147
      el = el.parentElement;
148
    }
149

    
150
    const htmlBg = window.getComputedStyle(document.documentElement).backgroundColor;
151
    if (!isTransparent(htmlBg)) return htmlBg;
152

    
153
    const bodyBg = window.getComputedStyle(document.body).backgroundColor;
154
    if (!isTransparent(bodyBg)) return bodyBg;
155

    
156
    return '#ffffff';
157
  }
158

    
159
  function init(historyRoot) {
160
    [PANEL_ID, STYLE_ID, LAUNCH_ID, HOVERZONE_ID, PREVIEW_ID, HINT_ID].forEach(id => document.getElementById(id)?.remove());
161
    document.querySelectorAll('.' + NOTE_HL_CLASS).forEach(el => el.classList.remove(NOTE_HL_CLASS));
162

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

    
166
    function jumpTo(el) {
167
      if (!el) return;
168
      const journal = el.closest(JOURNAL_SEL);
169
      if (journal && journal.style && journal.style.display === 'none') journal.style.display = '';
170
      const rect = el.getBoundingClientRect();
171
      const y = window.scrollY + rect.top - CONFIG.NOTE_TARGET_PAD;
172
      window.scrollTo({ top: Math.max(0, y), behavior: 'smooth' });
173
      highlight(el);
174
      setActiveIndex(indexOf(el));
175
    }
176

    
177
    function highlight(el, silent = false) {
178
      // Remove any existing highlight classes
179
      document.querySelectorAll('.' + NOTE_HL_CLASS).forEach(e => e.classList.remove(NOTE_HL_CLASS));
180
      document.querySelectorAll('.' + NOTE_HEADER_HL_CLASS).forEach(h => h.classList.remove(NOTE_HEADER_HL_CLASS));
181

    
182
      // Also clear any previous box-shadow so we don't stack effects
183
      document.querySelectorAll(NOTE_SEL).forEach(e => {
184
        e.style.boxShadow = 'none';
185
        e.style.transition = '';
186
      });
187

    
188
      if (silent) return;
189

    
190
      // Mark current note (for CSS hooks)
191
      el.classList.add(NOTE_HL_CLASS);
192

    
193
      // Add temporary highlight on the header "tab" of this note
194
      const header = el.querySelector('h4');
195
      if (header) {
196
        header.classList.add(NOTE_HEADER_HL_CLASS);
197
      }
198

    
199
      // Add a box-shadow ring around the whole note and fade it out
200
      el.style.transition = 'box-shadow 0.6s ease';
201
      el.style.boxShadow = HIGHLIGHT_RING;
202

    
203
      setTimeout(() => {
204
        el.style.boxShadow = '0 0 0 0 transparent';
205
        if (header) {
206
          header.classList.remove(NOTE_HEADER_HL_CLASS);
207
        }
208
      }, CONFIG.HIGHLIGHT_FADE_MS);
209
    }
210

    
211
    function extractWhenFromHeader(header) {
212
      if (!header) return '';
213
      const links = Array.from(header.querySelectorAll('a[title]'));
214
      const dateLike = links.find(a => /\d{4}-\d{2}-\d{2}/.test(a.getAttribute('title') || ''));
215
      if (dateLike) return dateLike.getAttribute('title') || dateLike.textContent.trim();
216
      const act = links.find(a => /activity\?from=/.test(a.getAttribute('href') || ''));
217
      if (act) return act.getAttribute('title') || act.textContent.trim();
218
      const last = links[links.length - 1];
219
      return last ? (last.getAttribute('title') || last.textContent.trim()) : '';
220
    }
221

    
222
    function getSummaryAndBody(wikiEl) {
223
      const firstHeading = wikiEl.querySelector('h1,h2,h3,h4,h5,h6');
224
      const headingText = firstHeading?.innerText?.trim() || '';
225
      let bodyText = (wikiEl.innerText || '').replace(/\s+/g, ' ').trim();
226
      const norm = s => (s || '').toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, ' ').trim();
227
      if (headingText && norm(bodyText).startsWith(norm(headingText))) {
228
        const idx = bodyText.toLowerCase().indexOf(headingText.toLowerCase());
229
        if (idx === 0) bodyText = bodyText.slice(headingText.length).trim();
230
      }
231
      const showTitle = !!headingText && !norm(bodyText.slice(0, 100)).includes(norm(headingText));
232
      const summary = showTitle ? headingText : '';
233
      return { summary, bodyText };
234
    }
235

    
236
    const collectNotes = (excludeHiddenJournals, onlyNotesFlag) => {
237
      const notes = Array.from(historyRoot.querySelectorAll(NOTE_SEL))
238
        .filter(n => {
239
          const j = n.closest(JOURNAL_SEL);
240

    
241
          // Hide hidden journals if requested
242
          if (excludeHiddenJournals && j && j.style && j.style.display === 'none') {
243
            return false;
244
          }
245

    
246
          // If we only want "real notes":
247
          // skip journals that are only .has-details and NOT .has-notes
248
          if (onlyNotesFlag && j) {
249
            const jc = j.classList;
250
            if (jc.contains('has-details') && !jc.contains('has-notes')) {
251
              return false;
252
            }
253
          }
254

    
255
          return true;
256
        })
257
        .sort((a, b) => {
258
          const an = parseInt(a.id.replace('note-', ''), 10);
259
          const bn = parseInt(b.id.replace('note-', ''), 10);
260
          if (!isNaN(an) && !isNaN(bn)) return an - bn;
261
          return a.compareDocumentPosition(b) & Node.DOCUMENT_POSITION_FOLLOWING ? -1 : 1;
262
        });
263

    
264
      return notes.map((note, i) => {
265
        const num = parseInt(note.id.replace('note-', ''), 10);
266
        const journal = note.closest(JOURNAL_SEL);
267
        const header = note.querySelector('.note-header') || journal?.querySelector('.note-header');
268
        const author = header?.querySelector('a.user')?.textContent?.trim() || 'Unknown';
269
        const linkTxt = journal?.querySelector('.journal-link')?.textContent?.trim() || ('#' + (isNaN(num) ? (i + 1) : num));
270
        const when = extractWhenFromHeader(header);
271
        const wiki = note.querySelector('.wiki') || note;
272
        const { summary, bodyText } = getSummaryAndBody(wiki);
273
        const imgSrc = (wiki.querySelector('img')?.getAttribute('src')) || null;
274
        return { el: note, num, author, linkTxt, when, textLen: bodyText.length, imgSrc, summary, fullText: bodyText };
275
      });
276
    };
277

    
278
    let excludeHidden = true;
279
    let onlyNotes = true;
280
    let notes = collectNotes(excludeHidden, onlyNotes);
281
    if (!notes.length) { console.warn('QuickJump: No notes found.'); return; }
282
    const indexOf = (el) => notes.findIndex(n => n.el === el);
283
    let activeIndex = 0;
284

    
285
    const bottomQuick = CONFIG.BOTTOM_OFFSET_QUICK ?? CONFIG.BOTTOM_OFFSET ?? 60;
286
    const bottomPanel = CONFIG.BOTTOM_OFFSET_PANEL ?? CONFIG.BOTTOM_OFFSET ?? bottomQuick;
287
    const sideOffset = CONFIG.SIDE_OFFSET ?? 6;
288
    const side = (CONFIG.SIDE === 'right') ? 'right' : 'left';
289

    
290
    const zBase = CONFIG.ZINDEX_BASE ?? 9990;
291
    const zHover = zBase;
292
    const zLaunch = zBase + 1;
293
    const zPanel = zBase + 2;
294
    const zPreview = zBase + 3;
295
    const zHint = zBase + 4;
296

    
297
    const css = document.createElement('style');
298
    css.id = STYLE_ID;
299
    css.textContent = `
300
      :root {
301
        --qj-width: ${CONFIG.PANEL_WIDTH}px;
302
        --qj-height: ${CONFIG.PANEL_HEIGHT}px;
303
        --qj-bottom-quick: ${bottomQuick}px;
304
        --qj-bottom-panel: ${bottomPanel}px;
305
        --qj-side-offset: ${sideOffset}px;
306
        --qj-bg: #ffffff;
307
        --qj-highlight: ${CONFIG.HIGHLIGHT_COLOR};
308
        --qj-highlight-soft: ${CONFIG.HIGHLIGHT_SOFT_COLOR};
309
      }
310
      #${HOVERZONE_ID} {
311
        position: fixed;
312
        left: 50%;
313
        transform: translateX(-50%);
314
        bottom: var(--qj-bottom-quick);
315
        width: 360px;
316
        height: 42px;
317
        z-index: ${zHover};
318
      }
319
      #${LAUNCH_ID} {
320
        position: fixed;
321
        left: 50%;
322
        transform: translateX(-50%);
323
        bottom: calc(var(--qj-bottom-quick) - 10px);
324
        z-index: ${zLaunch};
325
        opacity: 0;
326
        transition: opacity .2s ease, transform .2s ease;
327
        cursor: pointer;
328
        padding: 4px 10px;
329
        font-size: 0.95em;
330
        white-space: nowrap;
331
      }
332
      #${HOVERZONE_ID}:hover + #${LAUNCH_ID},
333
      #${LAUNCH_ID}:hover {
334
        opacity: 1;
335
        transform: translateX(-50%) translateY(-2px);
336
      }
337
      #${PANEL_ID} {
338
        position: fixed;
339
        width: var(--qj-width);
340
        height: var(--qj-height);
341
        bottom: calc(var(--qj-bottom-panel) + 14px);
342
        max-width: calc(100vw - 24px);
343
        border: 1px solid rgba(0,0,0,0.12);
344
        border-radius: 10px;
345
        box-shadow: 0 8px 24px rgba(0,0,0,0.15);
346
        overflow: hidden;
347
        user-select: none;
348
        z-index: ${zPanel};
349
        opacity: 0;
350
        pointer-events: none;
351
        transition: transform .2s ease, opacity .2s ease;
352
        background-color: var(--qj-bg);
353
        display: flex;
354
        flex-direction: column;
355
      }
356
      #${PANEL_ID}.side-left {
357
        left: var(--qj-side-offset);
358
        right: auto;
359
        transform: translate(-120%, 0);
360
      }
361
      #${PANEL_ID}.side-right {
362
        right: var(--qj-side-offset);
363
        left: auto;
364
        transform: translate(120%, 0);
365
      }
366
      #${PANEL_ID}.open {
367
        transform: translate(0, 0);
368
        opacity: 1;
369
        pointer-events: auto;
370
      }
371
      #${PANEL_ID} .qj-hdr {
372
        display: flex;
373
        align-items: center;
374
        justify-content: space-between;
375
        padding: 6px 10px;
376
        border-bottom: 1px solid rgba(0,0,0,0.08);
377
        font-size: 0.95em;
378
      }
379
      #${PANEL_ID} .qj-title {
380
        font-weight: 600;
381
      }
382
      #${PANEL_ID} .qj-counter {
383
        opacity: 0.8;
384
        font-variant-numeric: tabular-nums;
385
      }
386
      #${PANEL_ID} .qj-close {
387
        font-size: 0.9em;
388
        padding: 2px 6px;
389
        cursor: pointer;
390
      }
391
      #${PANEL_ID} .qj-controls {
392
        display: grid;
393
        grid-template-columns: auto 1fr auto;
394
        gap: 6px;
395
        align-items: center;
396
        padding: 6px 10px;
397
        font-size: 0.95em;
398
      }
399
      #${PANEL_ID} .qj-btn {
400
        cursor: pointer;
401
        padding: 2px 6px;
402
        font-size: 0.95em;
403
      }
404
      #${PANEL_ID} .qj-slider-wrap {
405
        display: flex;
406
        align-items: center;
407
        gap: 6px;
408
      }
409
      #${PANEL_ID} .qj-edge {
410
        font-size: 0.85em;
411
        opacity: 0.8;
412
        user-select: none;
413
      }
414
      #${PANEL_ID} .qj-slider {
415
        -webkit-appearance: none;
416
        appearance: none;
417
        width: 100%;
418
        height: 16px;
419
        background: transparent;
420
      }
421
      #${PANEL_ID} .qj-slider::-webkit-slider-runnable-track {
422
        height: 3px;
423
        background: rgba(0,0,0,0.12);
424
        border-radius: 999px;
425
      }
426
      #${PANEL_ID} .qj-slider::-moz-range-track {
427
        height: 3px;
428
        background: rgba(0,0,0,0.12);
429
        border-radius: 999px;
430
      }
431
      #${PANEL_ID} .qj-slider::-webkit-slider-thumb {
432
        -webkit-appearance: none;
433
        width: 12px;
434
        height: 12px;
435
        border-radius: 50%;
436
        border: 1px solid rgba(0,0,0,0.3);
437
        margin-top: -5px;
438
        background-color: var(--qj-bg);
439
      }
440
      #${PANEL_ID} .qj-slider::-moz-range-thumb {
441
        width: 12px;
442
        height: 12px;
443
        border-radius: 50%;
444
        border: 1px solid rgba(0,0,0,0.3);
445
        background-color: var(--qj-bg);
446
      }
447
      #${PANEL_ID} .qj-toggles {
448
        display: flex;
449
        gap: 8px;
450
        align-items: center;
451
        padding: 0 10px 6px 10px;
452
        flex-wrap: wrap;
453
        font-size: 0.95em;
454
      }
455
      #${PANEL_ID} .qj-toggles label {
456
        display: flex;
457
        gap: 4px;
458
        align-items: center;
459
      }
460
      #${PANEL_ID} .qj-filter {
461
        flex: 1;
462
        min-width: 120px;
463
        padding: 2px 6px;
464
        font-size: 0.95em;
465
      }
466
      #${PANEL_ID} .qj-pills {
467
        display: flex;
468
        flex-wrap: wrap;
469
        justify-content: flex-start;
470
        align-content: flex-start;
471
        gap: 4px;
472
        padding: 0 10px 8px 10px;
473
        overflow-y: auto;
474
        overflow-x: hidden;
475
        flex: 1 1 auto;
476
      }
477
      #${PANEL_ID} .qj-pill {
478
        font-size: 0.9em;
479
        padding: 2px 8px;
480
        border-radius: ${CONFIG.PILL_RADIUS}px;
481
        cursor: pointer;
482
        max-width: 100%;
483
        overflow: hidden;
484
        text-overflow: ellipsis;
485
        white-space: nowrap;
486
        border: 1px solid rgba(0,0,0,0.18);
487
      }
488
      #${PANEL_ID} .qj-pill.active {
489
        outline: 1px solid var(--qj-highlight-soft);
490
        outline-offset: 0;
491
      }
492
      #${PANEL_ID} .qj-help {
493
        font-size: 0.85em;
494
        opacity: 0.8;
495
        padding: 0 10px 8px 10px;
496
      }
497

    
498
      .${NOTE_HL_CLASS} { border-radius: inherit !important; }
499
      .${NOTE_HEADER_HL_CLASS}::before {
500
        border-right-color: var(--qj-highlight) !important;
501
      }
502

    
503
      #${PREVIEW_ID} {
504
        position: fixed;
505
        z-index: ${zPreview};
506
        pointer-events: none;
507
        max-width: 340px;
508
        border: 1px solid rgba(0,0,0,0.12);
509
        border-radius: 8px;
510
        box-shadow: 0 8px 24px rgba(0,0,0,0.18);
511
        padding: 6px;
512
        font-size: 0.85em;
513
        display: none;
514
        background-color: var(--qj-bg);
515
      }
516
      #${PREVIEW_ID} .ttl { font-weight: 600; margin-bottom: 4px; }
517
      #${PREVIEW_ID} .txt { line-height: 1.3; }
518
      #${PREVIEW_ID} .row {
519
        display: flex;
520
        gap: 6px;
521
        align-items: flex-start;
522
      }
523
      #${PREVIEW_ID} img {
524
        display: block;
525
        max-width: ${CONFIG.PREVIEW_IMG_MAX_W}px;
526
        max-height: ${CONFIG.PREVIEW_IMG_MAX_H}px;
527
        border-radius: 4px;
528
        border: 1px solid rgba(0,0,0,0.1);
529
      }
530
      #${HINT_ID} {
531
        position: fixed;
532
        z-index: ${zHint};
533
        pointer-events: none;
534
        background: #111;
535
        color: #fff;
536
        border-radius: 4px;
537
        padding: 2px 6px;
538
        font-size: 0.8em;
539
        box-shadow: 0 6px 18px rgba(0,0,0,0.2);
540
        display: none;
541
        white-space: nowrap;
542
      }
543
    `;
544
    document.head.appendChild(css);
545

    
546
    const hoverZone = document.createElement('div'); hoverZone.id = HOVERZONE_ID;
547
    const launcher = document.createElement('button'); launcher.id = LAUNCH_ID; launcher.textContent = CONFIG.TEXT.LAUNCHER_LABEL;
548
    document.body.appendChild(hoverZone); document.body.appendChild(launcher);
549

    
550
    const panel = document.createElement('div');
551
    panel.id = PANEL_ID;
552
    panel.className = (side === 'right') ? 'side-right' : 'side-left';
553
    const longTitle = (CONFIG.TEXT.ONLY_LONG_TITLE || '').replace('{N}', CONFIG.LONG_NOTES_CHARACTER_THRESHOLD);
554
    panel.innerHTML = `
555
      <div class="qj-hdr">
556
        <span class="qj-title">${esc(CONFIG.TEXT.PANEL_TITLE)}</span>
557
        <span class="qj-counter"></span>
558
        <button class="qj-close" title="${esc(CONFIG.TEXT.CLOSE_TITLE)}">${esc(CONFIG.TEXT.CLOSE_LABEL)}</button>
559
      </div>
560
      <div class="qj-controls">
561
        <button class="qj-btn qj-prev" title="${esc(CONFIG.TEXT.PREV_TITLE)}">${esc(CONFIG.TEXT.PREV_BUTTON)}</button>
562
        <div class="qj-slider-wrap">
563
          <span class="qj-edge">${esc(CONFIG.TEXT.EDGE_OLDEST)}</span>
564
          <input type="range" class="qj-slider" min="0" value="0" step="1">
565
          <span class="qj-edge">${esc(CONFIG.TEXT.EDGE_NEWEST)}</span>
566
        </div>
567
        <button class="qj-btn qj-next" title="${esc(CONFIG.TEXT.NEXT_TITLE)}">${esc(CONFIG.TEXT.NEXT_BUTTON)}</button>
568
      </div>
569
      <div class="qj-toggles">
570
        <label title="${esc(CONFIG.TEXT.ONLY_NOTES_TITLE)}">
571
          <input type="checkbox" class="qj-toggle-onlynotes" checked> ${esc(CONFIG.TEXT.ONLY_NOTES_LABEL)}
572
        </label>
573
        <label title="${esc(longTitle)}">
574
          <input type="checkbox" class="qj-toggle-long"> ${esc(CONFIG.TEXT.ONLY_LONG_LABEL)}
575
        </label>
576
        <input type="text" class="qj-filter" placeholder="${esc(CONFIG.TEXT.FILTER_PLACEHOLDER)}">
577
      </div>
578
      <div class="qj-pills" role="listbox" aria-label="${esc(CONFIG.TEXT.PILLS_ARIA_LABEL)}"></div>
579
      <div class="qj-help">${CONFIG.TEXT.HELP_HTML}</div>
580
    `;
581

    
582
    document.body.appendChild(panel);
583

    
584
    const preview = document.createElement('div'); preview.id = PREVIEW_ID; document.body.appendChild(preview);
585
    const hint = document.createElement('div'); hint.id = HINT_ID; document.body.appendChild(hint);
586

    
587
    // Apply effective background color from nearest ancestor to CSS variable
588
    const baseBg = findEffectiveBackgroundColor(historyRoot);
589
    document.documentElement.style.setProperty('--qj-bg', baseBg);
590

    
591
    const slider = by('.qj-slider', panel);
592
    const btnPrev = by('.qj-prev', panel);
593
    const btnNext = by('.qj-next', panel);
594
    const counter = by('.qj-counter', panel);
595
    const pills = by('.qj-pills', panel);
596
    const closeBtn = by('.qj-close', panel);
597
    const toggleOnlyNotes = by('.qj-toggle-onlynotes', panel);
598
    const toggleLong = by('.qj-toggle-long', panel);
599
    const filterInput = by('.qj-filter', panel);
600

    
601
    let filteredIdxList = [];
602
    let pillEls = [];
603

    
604
    function formatLabel(n) {
605
      const when = n.when ? n.when.replace(/\s+/g, ' ').trim() : '—';
606
      const numTxt = isNaN(n.num) ? n.linkTxt : `#${n.num}`;
607
      return `${numTxt} · ${when} · ${n.author}`;
608
    }
609

    
610
    function buildPreviewHTML(n) {
611
      const useTitle = !!n.summary;
612
      const ttl = useTitle ? esc(n.summary) : '';
613
      const text = esc(n.fullText.slice(0, CONFIG.PREVIEW_MAX_CHARS));
614
      const textHTML = `<div class="txt">${text}${n.fullText.length > CONFIG.PREVIEW_MAX_CHARS ? '…' : ''}</div>`;
615
      return n.imgSrc
616
        ? `<div class="row"><img src="${n.imgSrc}"><div style="flex:1 1 auto;">${useTitle ? `<div class="ttl">${ttl}</div>` : ''}${textHTML}</div></div>`
617
        : `${useTitle ? `<div class="ttl">${ttl}</div>` : ''}${textHTML}`;
618
    }
619

    
620
    function showHint(e, text) {
621
      hint.textContent = text;
622
      hint.style.display = 'block';
623
      const rectW = hint.offsetWidth || 120;
624
      const x = Math.min(window.innerWidth - rectW - 8, Math.max(8, e.clientX - rectW / 2));
625
      const y = Math.max(8, e.clientY - 26);
626
      hint.style.left = `${x}px`;
627
      hint.style.top = `${y}px`;
628
    }
629

    
630
    function hideHint() { hint.style.display = 'none'; }
631

    
632
    function attachPillPreview(pill, n) {
633
      pill.removeAttribute('title');
634
      pill.addEventListener('mouseenter', (e) => {
635
        preview.innerHTML = buildPreviewHTML(n);
636
        preview.style.display = 'block';
637
        movePreview(e);
638
        const label = `${CONFIG.TEXT.HINT_JUMP_PREFIX}${isNaN(n.num) ? n.linkTxt : ('#' + n.num)}`;
639
        showHint(e, label);
640
      });
641
      pill.addEventListener('mousemove', (e) => { movePreview(e); showHint(e, hint.textContent); });
642
      pill.addEventListener('mouseleave', () => { preview.style.display = 'none'; hideHint(); });
643

    
644
      function movePreview(e) {
645
        const pad = 12;
646
        const vw = window.innerWidth, vh = window.innerHeight;
647
        const rectW = preview.offsetWidth || 320;
648
        const rectH = preview.offsetHeight || 140;
649

    
650
        let x;
651
        let y = e.clientY + pad;
652

    
653
        if (side === 'right') {
654
          x = e.clientX - pad - rectW;
655
        } else {
656
          x = e.clientX + pad;
657
        }
658

    
659
        if (x < 8) x = 8;
660
        if (x + rectW + 8 > vw) x = vw - rectW - 8;
661
        if (y + rectH + 8 > vh) y = vh - rectH - 8;
662
        if (y < 8) y = 8;
663

    
664
        preview.style.left = `${x}px`;
665
        preview.style.top = `${y}px`;
666
      }
667
    }
668

    
669
    function rebuildPills() {
670
      pills.innerHTML = '';
671
      pillEls = [];
672
      const term = filterInput.value.trim().toLowerCase();
673
      const useFilter = !!term;
674
      filteredIdxList = [];
675

    
676
      notes.forEach((n, idx) => {
677
        if (toggleLong.checked && n.textLen < CONFIG.LONG_NOTES_CHARACTER_THRESHOLD) return;
678
        if (useFilter) {
679
          const hay = `${n.author} ${n.num} ${n.linkTxt} ${n.when}`.toLowerCase();
680
          if (!hay.includes(term)) return;
681
        }
682
        filteredIdxList.push(idx);
683

    
684
        const pill = document.createElement('button');
685
        pill.className = 'qj-pill';
686
        pill.setAttribute('role', 'option');
687
        pill.textContent = formatLabel(n);
688
        pill.addEventListener('click', () => { setActiveIndex(idx); jumpTo(n.el); });
689
        attachPillPreview(pill, n);
690
        pills.appendChild(pill);
691
        pillEls[idx] = pill;
692
      });
693

    
694
      if (!filteredIdxList.length) {
695
        const none = document.createElement('div');
696
        none.style.opacity = '0.7';
697
        none.style.fontSize = '0.9em';
698
        none.textContent = CONFIG.TEXT.NO_RESULTS;
699
        pills.appendChild(none);
700
      }
701

    
702
      setActiveIndex(Math.min(activeIndex, notes.length - 1));
703
    }
704

    
705
    // Returns the current "active" index list (filtered or full)
706
    function getActiveIndexList() {
707
      const hasFilter =
708
        toggleLong.checked || (filterInput.value.trim().length > 0);
709

    
710
      if (!hasFilter) {
711
        return notes.map((_, i) => i);
712
      }
713

    
714
      if (filteredIdxList && filteredIdxList.length) {
715
        return filteredIdxList.slice();
716
      }
717
      return [];
718
    }
719

    
720
    function ensureActivePillVisible() {
721
      const pill = pillEls[activeIndex];
722
      if (!pill) return;
723

    
724
      pill.classList.add('active');
725
      pillEls.forEach((p, i) => { if (p && i !== activeIndex) p.classList.remove('active'); });
726
      pillEls.forEach((p, i) => p && p.setAttribute('aria-selected', i === activeIndex ? 'true' : 'false'));
727

    
728
      if (pill.scrollIntoView) {
729
        pill.scrollIntoView({ block: 'nearest', inline: 'nearest' });
730
      } else {
731
        const c = pills, pTop = pill.offsetTop, pBottom = pTop + pill.offsetHeight + 4;
732
        if (pTop < c.scrollTop) c.scrollTop = pTop - 4;
733
        else if (pBottom > c.scrollTop + c.clientHeight) c.scrollTop = pBottom - c.clientHeight;
734
      }
735
    }
736

    
737
    function setActiveIndex(noteIdx) {
738
      if (!notes.length) return;
739
      const maxIdx = notes.length - 1;
740
      activeIndex = Math.max(0, Math.min(maxIdx, noteIdx));
741

    
742
      const activeList = getActiveIndexList();
743
      if (!activeList.length) {
744
        slider.max = '0';
745
        slider.value = '0';
746
        counter.textContent = `0/0`;
747
        return;
748
      }
749

    
750
      let logicalIndex = activeList.indexOf(activeIndex);
751
      if (logicalIndex === -1) {
752
        let nearest = activeList[0];
753
        let best = Math.abs(nearest - activeIndex);
754
        for (const idx of activeList) {
755
          const d = Math.abs(idx - activeIndex);
756
          if (d < best) { best = d; nearest = idx; }
757
        }
758
        activeIndex = nearest;
759
        logicalIndex = activeList.indexOf(activeIndex);
760
      }
761

    
762
      slider.max = String(Math.max(0, activeList.length - 1));
763
      slider.value = String(Math.max(0, logicalIndex));
764
      counter.textContent = `${logicalIndex + 1}/${activeList.length}`;
765

    
766
      ensureActivePillVisible();
767
    }
768

    
769
    function rebuildAll() {
770
      notes = collectNotes(excludeHidden, onlyNotes);
771
      rebuildPills();
772
    }
773

    
774
    function move(delta) {
775
      const activeList = getActiveIndexList();
776
      if (!activeList.length) return;
777

    
778
      const currPos = activeIndex === -1 ? -1 : activeList.indexOf(activeIndex);
779
      const currentLogical = currPos === -1 ? 0 : currPos;
780
      const nextPos = Math.max(0, Math.min(activeList.length - 1, currentLogical + delta));
781
      const nextIdx = activeList[nextPos];
782
      setActiveIndex(nextIdx);
783
      const n = notes[activeIndex];
784
      if (n) jumpTo(n.el);
785
    }
786

    
787
    const sliderInput = () => {
788
      const activeList = getActiveIndexList();
789
      if (!activeList.length) return;
790
      const logical = Math.max(0, Math.min(activeList.length - 1, parseInt(slider.value, 10) || 0));
791
      const idx = activeList[logical];
792
      setActiveIndex(idx);
793
    };
794

    
795
    slider.addEventListener('input', sliderInput);
796
    slider.addEventListener('change', () => {
797
      const n = notes[activeIndex];
798
      if (n) jumpTo(n.el);
799
    });
800
    btnPrev.addEventListener('click', () => move(-1));
801
    btnNext.addEventListener('click', () => move(1));
802

    
803
    toggleOnlyNotes.addEventListener('change', () => {
804
      onlyNotes = toggleOnlyNotes.checked;
805
      excludeHidden = toggleOnlyNotes.checked; // "Only notes" also ignores hidden journals
806
      rebuildAll();
807
    });
808

    
809
    toggleLong.addEventListener('change', rebuildPills);
810
    filterInput.addEventListener('input', rebuildPills);
811
    closeBtn.addEventListener('click', () => panel.classList.remove('open'));
812

    
813
    const launcherClick = () => {
814
      panel.classList.toggle('open');
815
      if (panel.classList.contains('open')) selectClosest(false);
816
    };
817
    launcher.addEventListener('click', launcherClick);
818

    
819
    const onKey = (e) => {
820
      if (!panel.classList.contains('open')) return;
821
      const tag = (e.target.tagName || '').toLowerCase();
822
      const isTyping = (tag === 'input' || tag === 'textarea' || tag === 'select');
823
      if (isTyping && e.target !== filterInput) return;
824
      if (e.key === 'j' || e.key === 'n') { e.preventDefault(); move(1); }
825
      else if (e.key === 'k' || e.key === 'p') { e.preventDefault(); move(-1); }
826
      else if (e.key.toLowerCase() === 'g') {
827
        e.preventDefault();
828
        const s = prompt(CONFIG.TEXT.PROMPT_GOTO); if (!s) return;
829
        const targetNum = parseInt(s, 10); if (isNaN(targetNum)) return;
830
        const idx = notes.findIndex(n => n.num === targetNum);
831
        if (idx >= 0) { setActiveIndex(idx); jumpTo(notes[idx].el); }
832
        else alert(CONFIG.TEXT.ALERT_GOTO_NOT_FOUND_PREFIX + targetNum);
833
      }
834
    };
835
    window.addEventListener('keydown', onKey);
836

    
837
    function selectClosest(suppressHighlight = false) {
838
      const viewportMid = window.scrollY + window.innerHeight / 2;
839
      let bestIdx = 0, bestDist = Infinity;
840
      notes.forEach((n, i) => {
841
        const rect = n.el.getBoundingClientRect();
842
        const y = window.scrollY + rect.top;
843
        const d = Math.abs(y - viewportMid);
844
        if (d < bestDist) { bestDist = d; bestIdx = i; }
845
      });
846
      setActiveIndex(bestIdx);
847
      highlight(notes[bestIdx].el, suppressHighlight);
848
    }
849

    
850
    rebuildAll();
851
    selectClosest(true);
852

    
853
    const mo = new MutationObserver(() => {
854
      clearTimeout(mo._t);
855
      mo._t = setTimeout(() => {
856
        const now = collectNotes(excludeHidden, onlyNotes);
857
        const beforeIds = notes.map(n => n.el.id).join(',');
858
        const afterIds = now.map(n => n.el.id).join(',');
859
        if (beforeIds !== afterIds) { notes = now; rebuildPills(); }
860
      }, 200);
861
    });
862
    mo.observe(historyRoot, { childList: true, subtree: true, attributes: true, attributeFilter: ['style'] });
863

    
864
    window.__QJ_HistoryTimeline = {
865
      refresh: rebuildAll,
866
      open: () => panel.classList.add('open'),
867
      close: () => panel.classList.remove('open'),
868
      setWidth: (px) => {
869
        document.documentElement.style.setProperty('--qj-width', px + 'px');
870
      },
871
      setHeight: (px) => {
872
        document.documentElement.style.setProperty('--qj-height', px + 'px');
873
      },
874
      setLeft: (px) => {
875
        document.documentElement.style.setProperty('--qj-side-offset', px + 'px');
876
      },
877
      setBottom: (px) => {
878
        document.documentElement.style.setProperty('--qj-bottom-quick', px + 'px');
879
        document.documentElement.style.setProperty('--qj-bottom-panel', px + 'px');
880
      },
881
      setBottomQuick: (px) => {
882
        document.documentElement.style.setProperty('--qj-bottom-quick', px + 'px');
883
      },
884
      setBottomPanel: (px) => {
885
        document.documentElement.style.setProperty('--qj-bottom-panel', px + 'px');
886
      },
887
      setSide: (sideVal) => {
888
        const isRight = (String(sideVal).toLowerCase() === 'right');
889
        panel.classList.toggle('side-right', isRight);
890
        panel.classList.toggle('side-left', !isRight);
891
      },
892
      setPillRadius: (px) => {
893
        const styleEl = document.getElementById(STYLE_ID);
894
        if (!styleEl) return;
895
        styleEl.textContent = styleEl.textContent.replace(
896
          /border-radius:\s*\d+px;(?=.*\.qj-pill)/,
897
          `border-radius: ${px}px;`
898
        );
899
      },
900
      destroy: () => {
901
        mo.disconnect();
902
        [panel, launcher, hoverZone, css, preview, hint].forEach(el => el?.remove());
903
        window.removeEventListener('keydown', onKey);
904
      }
905
    };
906
  }
907
})();
(8-8/10)