Skip to content
fossil-skin Artifact [61243c4ac9]
Login

Artifact [61243c4ac9]

Artifact 61243c4ac938ffe840d780123379f91cc074c84687606105c5fdfc00b39d7c37:


/**
 * fossil.craftdesign.group — Accessibility enhancements
 *
 * Loaded via <script defer src="/a11y.js"> in the Fossil skin header.
 * Served as a static asset by Caddy; satisfies `script-src 'self'` CSP.
 *
 * Execution timing (defer):
 *   1. HTML fully parsed
 *   2. Deferred scripts run (this file) — window.fossil already set up by
 *      Fossil's earlier inline scripts, so we can patch config immediately
 *   3. DOMContentLoaded fires
 *   4. window.load fires — Fossil's timeline renderer creates graph elements
 *
 * We re-run timeline fixes on window.load to cover the graph elements
 * that Fossil's JS inserts after the initial parse.
 */
(function () {
  'use strict';

  /* ─────────────────────────────────────────────────────────────────────
     1. isDark patch
     Fossil's C code hard-codes isDark:false for all custom skins,
     ignoring the skin-detail config key. Patch it here after Fossil's
     inline scripts have already run (guaranteed by defer).
  ───────────────────────────────────────────────────────────────────── */
  function patchIsDark() {
    /* Only for the dark variant: the light build of this skin embeds the
       same script, and its stylesheet declares color-scheme: light. */
    if (getComputedStyle(document.documentElement).colorScheme.indexOf('dark') < 0) return;
    if (window.fossil && window.fossil.config && window.fossil.config.skin) {
      window.fossil.config.skin.isDark = true;
    }
    document.body.classList.add('fossil-dark-style');
  }

  /* ─────────────────────────────────────────────────────────────────────
     2. Main landmark
     div.content is Fossil's primary content wrapper but has no landmark
     role. Adding role="main" lets screen reader users jump to content.
  ───────────────────────────────────────────────────────────────────── */
  function addMainLandmark() {
    var content = document.querySelector('div.content');
    if (content && !content.getAttribute('role')) {
      content.setAttribute('role', 'main');
    }
  }

  /* ─────────────────────────────────────────────────────────────────────
     3. Hamburger menu — the worst accessibility failure in the skin
     ----------------------------------------------------------------
     What Fossil gives us:
       <a id="hbbtn" href="/repo/sitemap" aria-label="Site Map">☰</a>
       <nav id="hbdrop" class="hbdrop" title="sitemap"></nav>

     Problems:
       - No aria-expanded: screen readers can't tell if the menu is open
       - No aria-controls: no programmatic link between button and panel
       - hbdrop has no role or accessible name beyond an unhelpful title
       - When the menu opens, focus stays on hbbtn — user cannot reach
         the menu links by keyboard without realising the menu opened
       - Escape key does not close the menu
       - hbmenu.js controls visibility via style.display; we use
         MutationObserver to stay in sync rather than patching the JS

     Fixes applied:
       - aria-expanded / aria-controls on hbbtn
       - role="navigation" + aria-label on hbdrop
       - MutationObserver: sync aria-expanded on every show/hide
       - On open: move focus to the first link in the dropdown
       - On Escape inside dropdown: close panel, return focus to hbbtn
  ───────────────────────────────────────────────────────────────────── */
  function fixHamburgerMenu() {
    var btn  = document.getElementById('hbbtn');
    var drop = document.getElementById('hbdrop');
    if (!btn || !drop) return;

    var nav = btn.closest('nav.mainmenu') || btn.parentNode;
    if (!nav) return;

    /* Position the dropdown using position:fixed so it overlays content
       regardless of DOM structure. We set --nav-bottom as a CSS variable
       so the dropdown's top edge tracks the nav bar's bottom edge. */
    function setNavBottom() {
      var bottom = Math.max(0, nav.getBoundingClientRect().bottom);
      document.documentElement.style.setProperty('--nav-bottom', bottom + 'px');
    }
    setNavBottom();
    window.addEventListener('resize', setNavBottom);
    /* Measure again on every open (capture: before hbmenu.js shows the
       panel), so the menu opens under the nav bar wherever the page is. */
    btn.addEventListener('click', setNavBottom, true);
    /* Open by touch or mouse vs keyboard: only the keyboard gets focus moved */
    var openedByPointer = false;
    btn.addEventListener('pointerdown', function () { openedByPointer = true; });
    btn.addEventListener('keydown', function () { openedByPointer = false; });

    /* Static button semantics (JS will keep aria-expanded in sync) */
    btn.setAttribute('aria-expanded', 'false');
    btn.setAttribute('aria-controls', 'hbdrop');

    /* Panel semantics */
    drop.setAttribute('role', 'navigation');
    drop.setAttribute('aria-label', 'Site map');

    /* Sync aria-expanded whenever hbmenu.js toggles panel visibility.
       hbmenu.js uses style.display to show/hide — observe that attribute. */
    var menuObserver = new MutationObserver(function () {
      var open = getComputedStyle(drop).display !== 'none';
      btn.setAttribute('aria-expanded', open ? 'true' : 'false');

      /* Move focus into the panel when it opens so keyboard users
         can immediately navigate the links without guessing. */
      if (open) {
        /* The nav bar may now be stuck to the top (see the skin CSS) */
        requestAnimationFrame(setNavBottom);
        if (!openedByPointer) {
          var firstLink = drop.querySelector('a');
          if (firstLink) firstLink.focus({ preventScroll: true });
        }
      }
    });
    menuObserver.observe(drop, { attributes: true, attributeFilter: ['style'] });

    /* Escape inside the dropdown: close the panel and return focus.
       We set display directly — this also triggers the MutationObserver
       which will update aria-expanded to 'false'. */
    drop.addEventListener('keydown', function (e) {
      if (e.key === 'Escape' || e.keyCode === 27) {
        drop.style.display = 'none';
        btn.focus();
      }
    });
  }

  /* ─────────────────────────────────────────────────────────────────────
     4. Timeline table
     ----------------------------------------------------------------
     Structure Fossil generates:

       <table class="timelineTable">
         <tr class="timelineDateRow">
           <td><div class="timelineDate">2026-03-14</div></td>
           <td></td>   <- empty filler for graph column
           <td></td>   <- empty filler for comment column
         </tr>
         <tr>
           <td class="timelineTime">20:16</td>
           <td class="timelineGraph">
             <div class="tl-nodemark"></div>  <- JS draws SVG here later
           </td>
           <td class="timelineModernCell" id="mc1">
             <span class="timelineModernComment">commit message</span>
             <span class="timelineModernDetail">...</span>
           </td>
         </tr>
       </table>

     Fixes applied:
       - aria-label="Commit timeline" on each .timelineTable
       - aria-hidden="true" on all td.timelineGraph cells
       - aria-hidden="true" on filler cells in timelineDateRow rows
       - aria-label="Time: HH:MM" on timelineTime cells

     Run at defer-time AND on window.load because Fossil's timeline JS
     inserts SVG canvas elements into the graph cells on window.load.
  ───────────────────────────────────────────────────────────────────── */
  function fixTimeline() {
    /* Label each timeline table */
    document.querySelectorAll('table.timelineTable').forEach(function (tbl) {
      if (!tbl.getAttribute('aria-label') && !tbl.querySelector('caption')) {
        tbl.setAttribute('aria-label', 'Commit timeline');
      }
    });

    /* Hide the graph column — purely visual SVG/canvas drawn by Fossil JS */
    document.querySelectorAll('td.timelineGraph').forEach(function (td) {
      td.setAttribute('aria-hidden', 'true');
    });

    /* Hide filler cells in date-separator rows */
    document.querySelectorAll('tr.timelineDateRow').forEach(function (tr) {
      tr.querySelectorAll('td + td').forEach(function (td) {
        td.setAttribute('aria-hidden', 'true');
      });
    });

    /* Give bare time cells a descriptive label.
       Strip stray </a> text artefact Fossil emits in anonymous mode. */
    document.querySelectorAll('td.timelineTime').forEach(function (td) {
      var text = td.textContent.trim();
      if (text && !td.getAttribute('aria-label')) {
        td.setAttribute('aria-label', 'Time: ' + text);
      }
    });
  }

  /* ─────────────────────────────────────────────────────────────────────
     5. Sortable table headers — add scope="col"
     Fossil generates <th> elements in branch, tag, file, and ticket
     tables but never includes scope. Screen readers cannot correctly
     associate header text with the cells in each column.
  ───────────────────────────────────────────────────────────────────── */
  function fixTableHeaders() {
    var selector = [
      'table.sortable th',
      'table.filelistTable th',
      'table.branchlistTable th',
      'table.taglistTable th',
      'table.userlistTable th',
      'table.report th',
    ].join(', ');
    document.querySelectorAll(selector).forEach(function (th) {
      if (!th.getAttribute('scope')) {
        th.setAttribute('scope', 'col');
      }
    });
  }

  /* ─────────────────────────────────────────────────────────────────────
     6. Submenu select labels
     Fossil renders <select> controls in the page submenu with no
     associated <label>. We add aria-label from the preceding sibling
     label text, falling back to a class-name lookup table.
  ───────────────────────────────────────────────────────────────────── */
  var SELECT_LABELS = {
    'smc-ss': 'View style',
    'smc-ci': 'Check-in',
    'smc-v':  'Version',
    'smc-r':  'Repository',
    'smc-b':  'Branch',
    'smc-t':  'Tag',
    'smc-u':  'User',
  };

  /* Charts Fossil draws as <svg width= height=> with no viewBox cannot be
     scaled by CSS. Give them one; the skin's "svg.fit" rule does the rest. */
  function fitCharts() {
    document.querySelectorAll('.content svg[width][height]:not([viewBox])').forEach(function (s) {
      var w = parseFloat(s.getAttribute('width')), h = parseFloat(s.getAttribute('height'));
      if (!(w > 0 && h > 0)) return;
      s.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
      s.classList.add('fit');
    });
  }

  /* Sortable column headers respond to clicks only. Put them in the tab
     order and let Enter or Space do what a click does. */
  function fixSortableHeaders() {
    document.querySelectorAll('table.sortable th').forEach(function (th) {
      if (th.hasAttribute('tabindex')) return;
      th.setAttribute('tabindex', '0');
      th.addEventListener('keydown', function (e) {
        if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); th.click(); }
      });
    });
  }

  /* The menu bar scrolls sideways on narrow screens. Bring the current
     page's entry into view, without moving the page itself. */
  function showActiveMenuItem() {
    var nav = document.querySelector('nav.mainmenu');
    var a = nav && nav.querySelector('a.active');
    var hb = document.getElementById('hbbtn');
    if (!a || a === hb || nav.scrollWidth <= nav.clientWidth) return;
    var left = a.offsetLeft - nav.offsetLeft, pinned = hb ? hb.offsetWidth : 0;
    if (left - pinned < nav.scrollLeft || left + a.offsetWidth > nav.scrollLeft + nav.clientWidth - 28) {
      nav.scrollLeft = Math.max(0, left - pinned - 12);
    }
  }

  function fixSubmenuSelects() {
    document.querySelectorAll('div.submenu select, div.sectionmenu select').forEach(function (sel) {
      if (sel.getAttribute('aria-label') || sel.getAttribute('aria-labelledby')) return;

      /* Walk backwards through siblings to find a .label text node */
      var prev = sel.previousElementSibling;
      while (prev) {
        if (prev.classList.contains('label') && prev.textContent.trim()) {
          sel.setAttribute('aria-label', prev.textContent.trim());
          return;
        }
        prev = prev.previousElementSibling;
      }

      /* Class-name lookup */
      var classes = Array.from(sel.classList);
      for (var i = 0; i < classes.length; i++) {
        if (SELECT_LABELS[classes[i]]) {
          sel.setAttribute('aria-label', SELECT_LABELS[classes[i]]);
          return;
        }
      }

      sel.setAttribute('aria-label', 'Filter');
    });
  }

  /* ─────────────────────────────────────────────────────────────────────
     7. Day of week on each timeline date
     Fossil's date rows carry only the date ("2026-11-11"). This puts the
     full weekday on a small line above it. The weekday comes from Ben
     Joffe's branchless method (benjoffe.com/fast-day-of-week), as zit
     uses it: one multiply and two shifts, exact for every 32-bit day
     number. It is read from the date Fossil prints, so it always matches
     that date whether the timeline shows UTC or local time. The skin CSS
     reserves the line before this runs, so setting the name moves nothing.
  ───────────────────────────────────────────────────────────────────── */
  var WEEKDAYS = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
  var SHORT_WEEKDAYS = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
  function weekdayOf(dayNumber) {   /* days since 1970-01-01 -> 0 = Sunday */
    return ((Math.imul(dayNumber, 613566756) + 0x95000000 +
             (dayNumber >> 1) + (dayNumber >> 4)) >>> 0) >>> 29;
  }
  function addWeekdays() {
    var rows = document.querySelectorAll('div.timelineDate');
    for (var i = 0; i < rows.length; i++) {
      if (rows[i].hasAttribute('data-dow')) continue;
      var m = /^(\d{4})-(\d\d)-(\d\d)$/.exec(rows[i].textContent.trim());
      if (!m) continue;
      /* The skin CSS shows this in a line it reserves above the date */
      rows[i].setAttribute('data-dow', WEEKDAYS[weekdayOf(Date.UTC(+m[1], m[2] - 1, +m[3]) / 864e5)]);
    }
    /* Prefix ticket timestamps (list, table, detail, events, backlinks, sidebar, attachments)
       with the short weekday using the same branchless calculation. */
    var tktDates = document.querySelectorAll(
      '.tkt-shell .tkt-row-meta span, .tkt-shell td.c-muted, .tkt-shell .tkt-card-hdr > span:last-child, ' +
      '.tkt-shell .tkt-event-time, .tkt-shell .tkt-sidebar .tkt-field-val, ' +
      'section.attachlist a[href*="timeline?c="], details.attachlist a[href*="timeline?c="]'
    );
    for (var j = 0; j < tktDates.length; j++) {
      var el = tktDates[j];
      if (el.hasAttribute('data-dow-done') || el.hasAttribute('data-tkt-time') || el.children.length > 0) continue;
      var txt = el.textContent;
      var tm = /(\d{4})-(\d\d)-(\d\d)(?=\s+\d\d:\d\d|$)/.exec(txt);
      if (!tm) continue;
      var dIdx = weekdayOf(Date.UTC(+tm[1], tm[2] - 1, +tm[3]) / 864e5);
      el.setAttribute('data-dow-done', '1');
      el.textContent = txt.slice(0, tm.index) + SHORT_WEEKDAYS[dIdx] + ' ' + txt.slice(tm.index);
      if (!el.getAttribute('title')) {
        el.setAttribute('title', WEEKDAYS[dIdx] + ', ' + tm[0]);
      }
    }
  }

  /* ─────────────────────────────────────────────────────────────────────
     8. Ticket UI progressive enhancements (Option B)
     Route-gated on .tkt-shell[data-tkt-page] so non-ticket pages pay zero cost.
     Everything degrades cleanly when scripting is disabled.
  ───────────────────────────────────────────────────────────────────── */
  function enhanceTickets() {
    var shell = document.querySelector('.tkt-shell[data-tkt-page]');
    if (!shell) return;
    var page = shell.getAttribute('data-tkt-page');

    /* 8a. Auto-submit GET facet forms on select change, and recover immediately when clearing search */
    shell.querySelectorAll('form[data-tkt-auto-submit]').forEach(function (form) {
      form.addEventListener('change', function (e) {
        if (e.target && e.target.tagName === 'SELECT') {
          if (form.requestSubmit) form.requestSubmit();
          else form.submit();
        }
      });
    });
    var searchInp = shell.querySelector('input[data-tkt-search]');
    if (searchInp && searchInp.form) {
      var hadQuery = searchInp.value.trim().length > 0;
      searchInp.addEventListener('input', function () {
        if (hadQuery && searchInp.value.trim() === '') {
          hadQuery = false;
          if (searchInp.form.requestSubmit) searchInp.form.requestSubmit();
          else searchInp.form.submit();
        }
      });
      searchInp.addEventListener('keydown', function (e) {
        if (e.key === 'Escape' && searchInp.value) {
          e.preventDefault();
          searchInp.value = '';
          if (searchInp.form.requestSubmit) searchInp.form.requestSubmit();
          else searchInp.form.submit();
        }
      });
    }

    /* 8b. Inline sidebar auto-save on tktview (handles <details> submit buttons and text inputs) */
    var sideForm = shell.querySelector('form[data-tkt-autosave]');
    if (sideForm) {
      sideForm.classList.add('is-js');
      var saveMsg = sideForm.querySelector('[data-tkt-save-msg]');
      function postSideField(fieldName, fieldValue, onOk) {
        if (saveMsg) saveMsg.textContent = 'saving...';
        var fd = new FormData();
        var csrfInp = sideForm.querySelector('input[name="csrf"]');
        if (csrfInp) fd.append('csrf', csrfInp.value);
        fd.append('submit', '1');
        fd.append(fieldName, fieldValue);
        fetch(sideForm.action, { method: 'POST', body: fd, credentials: 'same-origin' })
          .then(function (res) {
            if (!res.ok) throw new Error('HTTP ' + res.status);
            if (fieldName === 'status' || fieldName === 'resolution') {
              window.location.reload();
              return;
            }
            if (onOk) onOk();
            if (saveMsg) {
              saveMsg.textContent = 'saved';
              setTimeout(function () { saveMsg.textContent = 'auto-save'; }, 1800);
            }
          })
          .catch(function () {
            if (saveMsg) saveMsg.textContent = 'save failed';
            sideForm.classList.remove('is-js');
          });
      }
      sideForm.addEventListener('submit', function (e) {
        var sub = e.submitter;
        if (!sub || !sub.name || sub.classList.contains('tkt-side-submit')) return;
        e.preventDefault();
        var det = sub.closest('details.tkt-side-pop');
        if (det) det.open = false;
        postSideField(sub.name, sub.value, function () {
          if (!det) return;
          var sumLbl = det.querySelector('summary > span');
          if (sumLbl) sumLbl.textContent = sub.value || '(unset)';
          det.querySelectorAll('.tkt-fpop-item').forEach(function (it) {
            it.classList.remove('is-cur');
            var chk = it.querySelector('.tkt-fpop-cnt');
            if (chk) chk.remove();
          });
          sub.classList.add('is-cur');
          var mark = document.createElement('span');
          mark.className = 'tkt-fpop-cnt';
          mark.textContent = '\u2713';
          sub.appendChild(mark);
        });
      });
      sideForm.addEventListener('change', function (e) {
        if (!e.target || !e.target.name) return;
        if (e.target.classList.contains('tkt-fpop-search')) return;
        postSideField(e.target.name, e.target.value);
      });
    }

    /* 8b2. Popover menus (Reports, facet filters, board columns, sidebar pickers):
       single-open accordion, viewport edge-flip, outside click / Escape close,
       and live quick-filter search for high-cardinality menus (>12 items). */
    var popovers = shell.querySelectorAll('details[data-tkt-popover]');
    if (popovers.length) {
      var finePtr = window.matchMedia && window.matchMedia('(pointer: fine)').matches;
      popovers.forEach(function (p) {
        var menu = p.querySelector('.tkt-fpop-menu');
        var searchBox = null;
        if (menu) {
          var items = Array.from(menu.querySelectorAll('.tkt-fpop-item'));
          if (items.length > 12) {
            searchBox = document.createElement('input');
            searchBox.type = 'search';
            searchBox.className = 'tkt-fpop-search';
            searchBox.placeholder = 'Filter...';
            searchBox.setAttribute('aria-label', 'Filter options');
            searchBox.addEventListener('input', function () {
              var q = searchBox.value.trim().toLowerCase();
              items.forEach(function (it) {
                var txt = (it.textContent || '').toLowerCase();
                it.hidden = q !== '' && txt.indexOf(q) === -1;
              });
            });
            menu.insertBefore(searchBox, menu.firstChild);
          }
        }
        p.addEventListener('toggle', function () {
          if (p.open) {
            popovers.forEach(function (other) { if (other !== p && other.open) other.open = false; });
            if (menu) {
              menu.classList.remove('is-right');
              var rect = menu.getBoundingClientRect();
              if (rect.right > window.innerWidth - 8) menu.classList.add('is-right');
            }
            if (searchBox) {
              searchBox.value = '';
              menu.querySelectorAll('.tkt-fpop-item').forEach(function (it) { it.hidden = false; });
              if (finePtr) searchBox.focus();
            }
          } else if (searchBox && searchBox.value) {
            searchBox.value = '';
            menu.querySelectorAll('.tkt-fpop-item').forEach(function (it) { it.hidden = false; });
          }
        });
      });
      document.addEventListener('click', function (e) {
        popovers.forEach(function (p) { if (p.open && !p.contains(e.target)) p.open = false; });
      });
      document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') popovers.forEach(function (p) { p.open = false; });
      });
    }

    /* 8b3. Viewer-local Human ToD timestamps with click-to-cycle on reportlist
       Modes: human (Today morning / Yesterday evening / Sat night / Wed 2026-09-23)
       -> updated (day only) -> created (day only) -> relative (hours/days/months/years). */
    var timeBtns = shell.querySelectorAll('button[data-tkt-time]');
    if (timeBtns.length) {
      var DATE_MODES = ['human', 'updated', 'created', 'relative'];
      var dateMode = 'human';
      try {
        var savedMode = sessionStorage.getItem('fsl-tkt-datemode');
        if (savedMode && DATE_MODES.indexOf(savedMode) !== -1) dateMode = savedMode;
      } catch (_) {}
      var userTz = 'local';
      try {
        userTz = Intl.DateTimeFormat().resolvedOptions().timeZone || 'local';
      } catch (_) {}

      function pad2(n) { return n < 10 ? '0' + n : String(n); }
      function parseUtc(s) {
        if (!s) return null;
        var d = new Date(String(s).replace(' ', 'T') + 'Z');
        return isNaN(d.getTime()) ? null : d;
      }
      function localYmd(d) {
        return d.getFullYear() + '-' + pad2(d.getMonth() + 1) + '-' + pad2(d.getDate());
      }
      function fmtLocalDay(d) {
        return SHORT_WEEKDAYS[d.getDay()] + ' ' + localYmd(d);
      }
      function fmtLocalExact(d) {
        return fmtLocalDay(d) + ' ' + pad2(d.getHours()) + ':' + pad2(d.getMinutes()) + ':' + pad2(d.getSeconds()) + ' (' + userTz + ')';
      }
      function fmtRelative(d) {
        var sec = Math.round((Date.now() - d.getTime()) / 1000);
        if (sec < 60) return 'just now';
        var min = Math.round(sec / 60);
        if (min < 60) return min + (min === 1 ? ' min ago' : ' mins ago');
        var hr = Math.round(sec / 3600);
        if (hr < 24) return hr + (hr === 1 ? ' hour ago' : ' hours ago');
        var days = Math.round(sec / 86400);
        if (days < 45) return days + (days === 1 ? ' day ago' : ' days ago');
        if (days < 548) {
          var mo = Math.max(1, Math.round(days / 30.4375));
          return mo + (mo === 1 ? ' month ago' : ' months ago');
        }
        var yr = Math.max(1, Math.round(days / 365.25));
        return yr + (yr === 1 ? ' year ago' : ' years ago');
      }
      function fmtHumanTod(d) {
        var diffDays = (Date.now() - d.getTime()) / 86400000;
        if (diffDays > 7 || diffDays < -1) return fmtLocalDay(d);
        var h = d.getHours();
        var bucket = (h >= 5 && h < 12) ? 'morning'
          : (h >= 12 && h < 17) ? 'afternoon'
          : (h >= 17 && h < 21) ? 'evening' : 'night';
        var now = new Date();
        var sameDay = d.getFullYear() === now.getFullYear() && d.getMonth() === now.getMonth() && d.getDate() === now.getDate();
        var yest = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1);
        var isYest = d.getFullYear() === yest.getFullYear() && d.getMonth() === yest.getMonth() && d.getDate() === yest.getDate();
        var dayLbl = sameDay ? 'Today' : (isYest ? 'Yesterday' : SHORT_WEEKDAYS[d.getDay()]);
        return dayLbl + ' ' + bucket;
      }

      var dateHdr = shell.querySelector('a[data-tkt-date-hdr]');
      function renderAllDates() {
        if (dateHdr) {
          var sortMark = dateHdr.getAttribute('data-tkt-sort-mark') || '';
          var baseLbl = dateMode === 'created' ? 'Created' : (dateMode === 'relative' ? 'Updated (ago)' : 'Updated');
          dateHdr.textContent = baseLbl + sortMark;
        }
        timeBtns.forEach(function (btn) {
          var dMod = parseUtc(btn.getAttribute('data-tkt-mod'));
          var dCre = parseUtc(btn.getAttribute('data-tkt-cre'));
          var kind = btn.getAttribute('data-tkt-kind') || 'list';
          if (!dMod) return;
          var tip = 'Updated ' + fmtLocalExact(dMod) + ' (' + fmtRelative(dMod) + ')';
          if (dCre) tip += ' \u00b7 Created ' + fmtLocalExact(dCre) + ' (' + fmtRelative(dCre) + ')';
          tip += ' \u2014 click to cycle';
          btn.title = tip;

          var txt = '';
          if (dateMode === 'human') {
            txt = kind === 'list' ? ('Updated ' + fmtHumanTod(dMod)) : fmtHumanTod(dMod);
          } else if (dateMode === 'created') {
            var dUse = dCre || dMod;
            txt = kind === 'table' ? fmtLocalDay(dUse) : ('Created ' + fmtLocalDay(dUse));
          } else if (dateMode === 'relative') {
            txt = kind === 'list' ? ('Updated ' + fmtRelative(dMod)) : fmtRelative(dMod);
          } else {
            txt = kind === 'list' ? ('Updated ' + fmtLocalDay(dMod)) : fmtLocalDay(dMod);
          }
          btn.textContent = txt;
        });
      }

      renderAllDates();
      shell.addEventListener('click', function (e) {
        var btn = e.target.closest('button[data-tkt-time]');
        if (!btn) return;
        dateMode = DATE_MODES[(DATE_MODES.indexOf(dateMode) + 1) % DATE_MODES.length];
        try { sessionStorage.setItem('fsl-tkt-datemode', dateMode); } catch (_) {}
        renderAllDates();
      });
    }

    /* 8c. Kanban board in-place Move + HTML5 drag-and-drop + Undo banner */
    var board = shell.querySelector('[data-tkt-board]');
    if (board && board.getAttribute('data-tkt-writable') === '1') {
      var grp = board.getAttribute('data-tkt-group') || 'status';
      var banner = document.getElementById('tkt-moved-banner');
      var csrfForm = document.getElementById('tkt-board-csrf');
      var csrfInp = csrfForm ? csrfForm.querySelector('input[name="csrf"]') : null;
      var dragCard = null;

      function updateColCounts(srcCol, dstCol) {
        if (srcCol && dstCol && srcCol !== dstCol) {
          var sTot = parseInt(srcCol.getAttribute('data-col-total') || '', 10);
          var dTot = parseInt(dstCol.getAttribute('data-col-total') || '', 10);
          if (!isNaN(sTot) && sTot > 0) srcCol.setAttribute('data-col-total', String(sTot - 1));
          if (!isNaN(dTot)) dstCol.setAttribute('data-col-total', String(dTot + 1));
        }
        board.querySelectorAll('.tkt-col').forEach(function (col) {
          var cards = col.querySelectorAll('.tkt-bcard');
          var cnt = col.querySelector('.tkt-col-cnt');
          var totAttr = col.getAttribute('data-col-total');
          if (cnt) cnt.textContent = totAttr !== null ? totAttr : String(cards.length);
          var empty = col.querySelector('.tkt-col-empty');
          if (cards.length > 0 && empty) empty.remove();
          if (cards.length === 0 && !empty) {
            var d = document.createElement('div');
            d.className = 'tkt-empty tkt-col-empty';
            d.textContent = 'No tickets';
            var foot = col.querySelector('.tkt-col-foot');
            if (foot) col.insertBefore(d, foot); else col.appendChild(d);
          }
        });
      }

      function performBoardMove(cardId, fromVal, toVal, skipBanner) {
        var card = board.querySelector('.tkt-bcard[data-card-id="' + cardId + '"]');
        var targetCol = board.querySelector('.tkt-col[data-drop-col="' + toVal + '"]');
        var sourceCol = card ? card.closest('.tkt-col') : null;
        if (!card || !targetCol || fromVal === toVal) return;
        var fd = new FormData();
        if (csrfInp) fd.append('csrf', csrfInp.value);
        fd.append('submit', '1');
        fd.append(grp, toVal);
        fetch('tktedit/' + encodeURIComponent(cardId), { method: 'POST', body: fd, credentials: 'same-origin' })
          .then(function (res) {
            if (!res.ok) throw new Error('HTTP ' + res.status);
            var det = card.querySelector('details.tkt-mv-wrap');
            if (det) det.open = false;
            var foot = targetCol.querySelector('.tkt-col-foot');
            if (foot) targetCol.insertBefore(card, foot); else targetCol.appendChild(card);
            updateColCounts(sourceCol, targetCol);
            if (banner && !skipBanner) {
              var titleEl = card.querySelector('.tkt-bcard-title');
              var titleTxt = titleEl ? titleEl.textContent : cardId;
              banner.innerHTML = '';
              var sp = document.createElement('span');
              sp.textContent = 'Moved "' + titleTxt + '" from ' + fromVal + ' to ' + toVal + '.';
              var undo = document.createElement('button');
              undo.type = 'button';
              undo.className = 'tkt-btn';
              undo.textContent = 'Undo';
              undo.addEventListener('click', function () {
                banner.hidden = true;
                performBoardMove(cardId, toVal, fromVal, true);
              });
              banner.appendChild(sp);
              banner.appendChild(undo);
              banner.hidden = false;
            }
          })
          .catch(function () { window.location.reload(); });
      }

      board.addEventListener('submit', function (e) {
        var f = e.target.closest('form[data-tkt-move-form]');
        if (!f) return;
        e.preventDefault();
        performBoardMove(f.getAttribute('data-tkt-card'), f.getAttribute('data-tkt-from'), f.getAttribute('data-tkt-to'), false);
      });

      board.addEventListener('dragstart', function (e) {
        var card = e.target.closest('.tkt-bcard');
        if (!card) return;
        dragCard = card;
        card.classList.add('is-held');
        if (e.dataTransfer) e.dataTransfer.effectAllowed = 'move';
      });
      board.addEventListener('dragend', function () {
        if (dragCard) dragCard.classList.remove('is-held');
        board.querySelectorAll('.tkt-col.is-over').forEach(function (c) { c.classList.remove('is-over'); });
        dragCard = null;
      });
      board.addEventListener('dragover', function (e) {
        var col = e.target.closest('.tkt-col[data-drop-col]');
        if (!col || !dragCard) return;
        e.preventDefault();
        board.querySelectorAll('.tkt-col.is-over').forEach(function (c) { if (c !== col) c.classList.remove('is-over'); });
        col.classList.add('is-over');
      });
      board.addEventListener('drop', function (e) {
        var col = e.target.closest('.tkt-col[data-drop-col]');
        if (!col || !dragCard) return;
        e.preventDefault();
        col.classList.remove('is-over');
        var fromCol = dragCard.closest('.tkt-col[data-drop-col]');
        var fromVal = fromCol ? fromCol.getAttribute('data-drop-col') : '';
        performBoardMove(dragCard.getAttribute('data-card-id'), fromVal, col.getAttribute('data-drop-col'), false);
        dragCard = null;
      });
    }

    /* 8d. Slash-command Markdown snippets + sessionStorage draft recovery */
    var SLASH_SNIPS = [
      { key: 'h2', label: 'Heading', hint: '## ', text: '## ' },
      { key: 'code', label: 'Code block', hint: '```', text: '```\n\n```' },
      { key: 'quote', label: 'Quote', hint: '> ', text: '> ' },
      { key: 'ul', label: 'Bullet list', hint: '- ', text: '- ' },
      { key: 'task', label: 'Task list', hint: '- [ ]', text: '- [ ] ' },
      { key: 'details', label: 'Collapsible details', hint: '<details>', text: '<details>\n<summary>Details</summary>\n\n</details>' },
      { key: 'table', label: 'Table', hint: '| col |', text: '| Column | Value |\n| --- | --- |\n|  |  |' }
    ];

    shell.querySelectorAll('textarea[data-tkt-draft]').forEach(function (ta) {
      var key = 'tkt-draft:' + ta.getAttribute('data-tkt-draft');
      var badge = shell.querySelector('[data-tkt-draft-badge="' + ta.getAttribute('data-tkt-draft') + '"]');
      var form = ta.closest('form');
      try {
        var saved = sessionStorage.getItem(key);
        if (saved && !ta.value.trim()) {
          ta.value = saved;
          if (badge) badge.hidden = false;
        }
      } catch (_) {}
      ta.addEventListener('input', function () {
        try {
          if (ta.value.trim()) {
            sessionStorage.setItem(key, ta.value);
            if (badge) badge.hidden = false;
          } else {
            sessionStorage.removeItem(key);
            if (badge) badge.hidden = true;
          }
        } catch (_) {}
      });
      if (form) {
        form.addEventListener('submit', function () {
          try { sessionStorage.removeItem(key); } catch (_) {}
        });
      }
    });

    shell.querySelectorAll('textarea[data-tkt-slash]').forEach(function (ta) {
      var wrap = ta.closest('.tkt-composer-wrap');
      if (!wrap) return;
      var menu = document.createElement('div');
      menu.className = 'tkt-slash-menu';
      menu.setAttribute('role', 'listbox');
      menu.setAttribute('aria-label', 'Markdown snippets');
      menu.hidden = true;
      wrap.appendChild(menu);
      var matches = [];
      var idx = 0;

      function closeMenu() { menu.hidden = true; matches = []; }
      function insertSnip(text) {
        var pos = ta.selectionStart;
        var val = ta.value;
        var lineStart = val.lastIndexOf('\n', pos - 1) + 1;
        ta.value = val.slice(0, lineStart) + text + val.slice(pos);
        var nextPos = lineStart + text.length;
        ta.focus();
        ta.setSelectionRange(nextPos, nextPos);
        ta.dispatchEvent(new Event('input', { bubbles: true }));
        closeMenu();
      }

      ta.addEventListener('input', function () {
        var pos = ta.selectionStart;
        var lineStart = ta.value.lastIndexOf('\n', pos - 1) + 1;
        var line = ta.value.slice(lineStart, pos);
        if (line.charAt(0) === '/' && line.indexOf(' ') < 0) {
          var needle = line.slice(1).toLowerCase();
          matches = SLASH_SNIPS.filter(function (s) {
            return s.key.indexOf(needle) >= 0 || s.label.toLowerCase().indexOf(needle) >= 0;
          });
          if (matches.length) {
            idx = 0;
            menu.innerHTML = '';
            matches.forEach(function (s, i) {
              var b = document.createElement('button');
              b.type = 'button';
              b.className = 'tkt-slash-item' + (i === 0 ? ' is-active' : '');
              b.innerHTML = '<span></span><code></code>';
              b.firstChild.textContent = s.label;
              b.lastChild.textContent = s.hint;
              b.addEventListener('mousedown', function (ev) { ev.preventDefault(); insertSnip(s.text); });
              menu.appendChild(b);
            });
            menu.hidden = false;
            return;
          }
        }
        closeMenu();
      });

      ta.addEventListener('keydown', function (e) {
        if (menu.hidden || !matches.length) return;
        if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
          e.preventDefault();
          idx = (idx + (e.key === 'ArrowDown' ? 1 : -1) + matches.length) % matches.length;
          menu.querySelectorAll('.tkt-slash-item').forEach(function (el, i) { el.classList.toggle('is-active', i === idx); });
        } else if (e.key === 'Enter' || e.key === 'Tab') {
          e.preventDefault();
          insertSnip(matches[idx].text);
        } else if (e.key === 'Escape') {
          e.preventDefault();
          closeMenu();
        }
      });
      document.addEventListener('click', function (e) { if (!wrap.contains(e.target)) closeMenu(); });
    });

    /* 8e. New ticket: type templates, client-side similar-ticket check, keyboard shortcuts */
    if (page === 'tktnew') {
      var titleInp = document.getElementById('tkt-new-title');
      var descTa = document.getElementById('tkt-new-desc');
      var formNew = shell.closest('form');
      if (titleInp && !titleInp.value) titleInp.focus();

      var tmpls = {};
      shell.querySelectorAll('template[data-tkt-tmpl]').forEach(function (tp) {
        tmpls[tp.getAttribute('data-tkt-tmpl')] = tp.innerHTML.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&');
      });
      if (descTa) {
        var dirty = descTa.value.trim().length > 0;
        var checkedRadio = shell.querySelector('input[name="type"]:checked');
        if (!dirty && checkedRadio && tmpls[checkedRadio.value]) {
          descTa.value = tmpls[checkedRadio.value];
        }
        descTa.addEventListener('input', function () {
          var v = descTa.value;
          var isTmpl = Object.keys(tmpls).some(function (k) { return tmpls[k] === v; });
          dirty = !isTmpl && v.trim().length > 0;
        });
        shell.querySelectorAll('input[name="type"]').forEach(function (r) {
          r.addEventListener('change', function () {
            if (!dirty && tmpls[r.value]) descTa.value = tmpls[r.value];
          });
        });
      }

      var simBox = document.getElementById('tkt-similar');
      var simList = document.getElementById('tkt-similar-list');
      var simData = document.getElementById('tkt-similar-data');
      if (titleInp && simBox && simList && simData) {
        var STOP = { 'the':1,'and':1,'for':1,'with':1,'not':1,'when':1,'from':1,'that':1,'this':1,'into':1,'are':1,'was':1,'but':1,'all':1,'can':1,'has':1,'have':1,'does':1,'new':1,'page':1,'should':1,'shows':1,'show':1 };
        var CLOSED = { 'Fixed':1,'Tested':1,'Closed':1,'Deferred':1 };
        function wordsOf(s) {
          var seen = {}, out = [];
          String(s || '').toLowerCase().split(/[^a-z0-9]+/).forEach(function (w) {
            if (w.length >= 3 && !STOP[w] && !seen[w]) { seen[w] = 1; out.push(w); }
          });
          return out.slice(0, 8);
        }
        var index = Array.from(simData.querySelectorAll('li')).map(function (li) {
          return { id: li.getAttribute('data-id'), st: li.getAttribute('data-st'), title: li.textContent, words: wordsOf(li.textContent) };
        });
        titleInp.addEventListener('input', function () {
          var w = wordsOf(titleInp.value);
          if (!w.length) { simBox.hidden = true; return; }
          var need = w.length <= 2 ? 1 : 2;
          var hits = [];
          index.forEach(function (item) {
            var shared = 0;
            w.forEach(function (x) { if (item.words.indexOf(x) >= 0) shared++; });
            if (shared >= need) hits.push({ item: item, shared: shared });
          });
          hits.sort(function (a, b) {
            var ca = CLOSED[a.item.st] ? 1 : 0, cb = CLOSED[b.item.st] ? 1 : 0;
            return (ca - cb) || (b.shared - a.shared);
          });
          if (!hits.length) { simBox.hidden = true; return; }
          simList.innerHTML = '';
          hits.slice(0, 3).forEach(function (h) {
            var li = document.createElement('li');
            var tag = document.createElement('span');
            tag.className = 'tkt-tag';
            tag.textContent = h.item.st;
            var a = document.createElement('a');
            a.href = 'tktview/' + encodeURIComponent(h.item.id);
            a.textContent = h.item.title;
            var code = document.createElement('code');
            code.textContent = h.item.id.slice(0, 8);
            li.appendChild(tag); li.appendChild(a); li.appendChild(code);
            simList.appendChild(li);
          });
          simBox.hidden = false;
        });
      }

      document.addEventListener('keydown', function (e) {
        if ((e.metaKey || e.ctrlKey) && e.key === 'Enter' && formNew) {
          e.preventDefault();
          if (pvApi && pvApi.needsPreview('new')) {
            pvApi.openPreview('new');
            return;
          }
          var btn = formNew.querySelector(e.shiftKey ? 'input[name="submitandnew"]' : 'input[name="submit"]');
          if (btn && !btn.disabled) btn.click();
          return;
        }
        var ae = document.activeElement;
        var tag = ae ? ae.tagName : '';
        if (tag === 'SELECT' && /^[1-9]$/.test(e.key)) {
          var n = parseInt(e.key, 10) - 1;
          if (n < ae.options.length) { e.preventDefault(); ae.selectedIndex = n; }
          return;
        }
        if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || e.metaKey || e.ctrlKey || e.altKey) return;
        var chip = shell.querySelector('.tkt-chip-field[data-tkt-key="' + e.key.toLowerCase() + '"]');
        if (chip) {
          var ctrl = chip.querySelector('select, input');
          if (ctrl) { e.preventDefault(); ctrl.focus(); }
        }
      });
    }

    /* 8g. In-place Write / Preview tabs + /ajax/preview-text forced-preview gate */
    var pvUrl = shell.getAttribute('data-tkt-preview-url');
    var pvState = {};
    var pvApi = null;
    if (pvUrl && shell.querySelector('[data-pv-scope]')) {
      function previewFilenameFor(scopeEl) {
        var mu = scopeEl.querySelector('select[name="mutype"], input[name="mutype"]');
        var v = mu ? mu.value : 'Markdown';
        if (v === 'Wiki') return 'ticket.wiki';
        if (v === 'HTML') return 'ticket.html';
        if (v === 'Plain Text' || v === '[links only]') return 'ticket.txt';
        return 'ticket.md';
      }

      function syncGate(name) {
        var st = pvState[name];
        if (!st) return;
        var hasText = st.ta.value.trim().length > 0;
        var isPrev = hasText && st.previewed === st.ta.value && st.previewedFmt === previewFilenameFor(st.scopeEl);
        st.tabs.forEach(function (t) {
          t.setAttribute('aria-selected', String(t.getAttribute('data-pv-tab') === st.mode));
        });
        st.ta.hidden = (st.mode === 'preview');
        st.pane.hidden = (st.mode !== 'preview');
        if (st.pvBtn) {
          var lbl = st.mode === 'preview' ? 'Back to Write' : 'Preview';
          if (st.pvBtn.tagName === 'INPUT') st.pvBtn.value = lbl;
          else st.pvBtn.textContent = lbl;
        }
        if (st.dot) {
          st.dot.hidden = !hasText;
          st.dot.classList.toggle('is-ok', isPrev);
        }
        st.reqBtns.forEach(function (b) { b.disabled = !isPrev; });
        st.optBtns.forEach(function (b) { b.disabled = hasText && !isPrev; });
        if (st.gate) {
          st.gate.classList.toggle('is-ready', isPrev);
          if (!hasText) {
            st.gate.textContent = name === 'view'
              ? 'Preview Markdown before posting (empty close/reopen needs no preview).'
              : (name === 'edit'
                ? 'Field-only edits save immediately; typing a comment requires Preview first.'
                : 'Empty description allowed, or write Markdown and preview before creating.');
          } else if (isPrev) {
            st.gate.textContent = 'Preview matches current text. Ready to submit.';
          } else {
            st.gate.textContent = 'Click Preview (or Cmd/Ctrl+Enter) before submitting.';
          }
        }
      }

      function openPreview(name) {
        var st = pvState[name];
        if (!st) return;
        var text = st.ta.value;
        var fname = previewFilenameFor(st.scopeEl);
        st.mode = 'preview';
        st.pane.innerHTML = '<div class="tkt-preview-meta"><span>Rendering via /ajax/preview-text...</span></div>';
        syncGate(name);
        if (!text.trim()) {
          st.pane.innerHTML = '<p class="tkt-help">Nothing to preview.</p>';
          return;
        }
        var params = new URLSearchParams();
        params.set('filename', fname);
        params.set('content', text);
        params.set('render_mode', '0');
        fetch(pvUrl, { method: 'POST', body: params, credentials: 'same-origin' })
          .then(function (r) {
            if (!r.ok) throw new Error('HTTP ' + r.status);
            return r.text();
          })
          .then(function (html) {
            st.previewed = text;
            st.previewedFmt = fname;
            st.pane.innerHTML = '<div class="tkt-preview-meta"><span>Fossil C preview (' + fname + ')</span><span>matches current text</span></div>' + html;
            syncGate(name);
          })
          .catch(function () {
            st.pane.innerHTML = '<p class="tkt-help">In-place preview failed; click Preview again to use server preview.</p>';
            st.mode = 'write';
            st.optBtns.forEach(function (b) { b.disabled = false; });
            st.reqBtns.forEach(function (b) { b.disabled = false; });
          });
      }

      shell.querySelectorAll('[data-pv-scope]').forEach(function (scopeEl) {
        var name = scopeEl.getAttribute('data-pv-scope');
        var ta = scopeEl.querySelector('[data-pv-input="' + name + '"]');
        var pane = scopeEl.querySelector('[data-pv-pane="' + name + '"]');
        if (!ta || !pane) return;
        var st = pvState[name] = {
          scopeEl: scopeEl,
          ta: ta,
          pane: pane,
          tabs: Array.from(scopeEl.querySelectorAll('[data-pv-tab][data-pv-for="' + name + '"]')),
          dot: scopeEl.querySelector('[data-pv-dot="' + name + '"]'),
          gate: scopeEl.querySelector('[data-pv-gate="' + name + '"]'),
          pvBtn: scopeEl.querySelector('[data-pv-btn="' + name + '"]'),
          reqBtns: Array.from(scopeEl.querySelectorAll('[data-pv-submit="' + name + '"]')),
          optBtns: Array.from(scopeEl.querySelectorAll('[data-pv-submit-optional="' + name + '"]')),
          mode: 'write',
          previewed: null,
          previewedFmt: null
        };
        /* If server already rendered a preview box (no-JS round-trip), accept initial text as previewed */
        if (shell.querySelector('.tkt-preview-box') && ta.value.trim()) {
          st.previewed = ta.value;
          st.previewedFmt = previewFilenameFor(scopeEl);
        }
        ta.addEventListener('input', function () { syncGate(name); });
        var muSel = scopeEl.querySelector('select[name="mutype"]');
        if (muSel) muSel.addEventListener('change', function () {
          st.previewed = null;
          if (st.mode === 'preview') openPreview(name);
          else syncGate(name);
        });
        st.tabs.forEach(function (tab) {
          tab.addEventListener('click', function () {
            if (tab.getAttribute('data-pv-tab') === 'preview') openPreview(name);
            else { st.mode = 'write'; syncGate(name); ta.focus(); }
          });
        });
        if (st.pvBtn) {
          st.pvBtn.addEventListener('click', function (e) {
            e.preventDefault();
            if (st.mode === 'preview') { st.mode = 'write'; syncGate(name); ta.focus(); }
            else openPreview(name);
          });
        }
        var form = scopeEl.tagName === 'FORM' ? scopeEl : scopeEl.closest('form');
        if (form) {
          form.addEventListener('keydown', function (e) {
            if (name === 'new') return;
            if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
              e.preventDefault();
              if (pvApi.needsPreview(name)) {
                openPreview(name);
              } else {
                var sub = scopeEl.querySelector('[data-pv-submit="' + name + '"], [data-pv-submit-optional="' + name + '"]');
                if (sub && !sub.disabled) sub.click();
              }
            }
          });
        }
        syncGate(name);
      });

      /* Keep type-template swap in sync with preview gate on tktnew */
      if (page === 'tktnew') {
        shell.querySelectorAll('input[name="type"]').forEach(function (r) {
          r.addEventListener('change', function () {
            if (pvState['new']) {
              pvState['new'].previewed = null;
              if (pvState['new'].mode === 'preview') openPreview('new');
              else syncGate('new');
            }
          });
        });
      }

      pvApi = {
        needsPreview: function (name) {
          var st = pvState[name];
          if (!st) return false;
          return st.ta.value.trim().length > 0 && (st.previewed !== st.ta.value || st.previewedFmt !== previewFilenameFor(st.scopeEl));
        },
        openPreview: openPreview
      };
    }

    /* 8h. Zero-schema Option C: hydrate exact Old -> New field diffs from /tkthistory */
    if (page === 'tktview') {
      var histUrl = shell.getAttribute('data-tkt-history-url');
      var ridEls = shell.querySelectorAll('[data-tkt-rid]');
      if (histUrl && ridEls.length) {
        var TRACKED = { status:1, resolution:1, priority:1, severity:1, subsystem:1, type:1, foundin:1, title:1, assignee:1 };
        var ARROW_SVG = '<span class="tkt-diff-arrow" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M3 8h10M9.5 4.5L13 8l-3.5 3.5"/></svg></span>';
        fetch(histUrl, { credentials: 'same-origin' })
          .then(function (r) { return r.ok ? r.text() : ''; })
          .then(function (html) {
            if (!html) return;
            var doc = new DOMParser().parseFromString(html, 'text/html');
            var items = doc.querySelectorAll('ol.tkt-changes > li');
            if (!items.length) return;
            var prev = {};
            var diffsByRid = {};
            items.forEach(function (li, idx) {
              var p = li.querySelector('p');
              var m = p ? /\(rid\s+(\d+)\)/.exec(p.textContent) : null;
              var rid = m ? m[1] : null;
              var changes = [];
              li.querySelectorAll('ol > li').forEach(function (fli) {
                var raw = fli.textContent.trim();
                var pre = fli.querySelector('pre');
                var fm = /^(?:Untracked field\s+)?([a-zA-Z0-9_]+)\s+(?:initialized to|changed to|):/.exec(raw);
                if (!fm) return;
                var field = fm[1].toLowerCase();
                if (!TRACKED[field]) return;
                var val = '';
                if (pre) {
                  val = pre.textContent.trim();
                } else {
                  var qm = /:\s*"([\s\S]*)"\s*$/.exec(raw);
                  val = qm ? qm[1] : raw.slice(fm[0].length).trim();
                }
                if (idx > 0 && prev[field] !== val) {
                  changes.push({ field: field, from: prev[field] || '', to: val });
                }
                prev[field] = val;
              });
              if (rid && changes.length) diffsByRid[rid] = changes;
            });

            function buildDiffFrag(changes) {
              var frag = document.createDocumentFragment();
              changes.forEach(function (c, i) {
                if (i > 0) frag.appendChild(document.createTextNode(', '));
                frag.appendChild(document.createTextNode('changed '));
                var b = document.createElement('strong');
                b.textContent = c.field;
                frag.appendChild(b);
                frag.appendChild(document.createTextNode(' '));
                if (c.from) {
                  var oldSp = document.createElement('span');
                  oldSp.className = 'tkt-diff-val tkt-diff-old';
                  oldSp.textContent = c.from.replace(/_/g, ' ');
                  frag.appendChild(oldSp);
                  var ar = document.createElement('span');
                  ar.innerHTML = ARROW_SVG;
                  frag.appendChild(document.createTextNode(' '));
                  frag.appendChild(ar.firstChild);
                  frag.appendChild(document.createTextNode(' '));
                } else {
                  frag.appendChild(document.createTextNode('to '));
                }
                var newSp = document.createElement('span');
                newSp.className = 'tkt-diff-val';
                newSp.textContent = (c.to || '(cleared)').replace(/_/g, ' ');
                frag.appendChild(newSp);
              });
              return frag;
            }

            shell.querySelectorAll('.tkt-event-row[data-tkt-rid]').forEach(function (row) {
              var changes = diffsByRid[row.getAttribute('data-tkt-rid')];
              var msgEl = row.querySelector('.tkt-event-msg');
              if (!changes || !msgEl) return;
              msgEl.textContent = '';
              msgEl.appendChild(buildDiffFrag(changes));
            });

            shell.querySelectorAll('.tktCommentEntry[data-tkt-rid]').forEach(function (card) {
              var changes = diffsByRid[card.getAttribute('data-tkt-rid')];
              if (!changes) return;
              var ev = document.createElement('div');
              ev.className = 'tkt-event-row';
              ev.innerHTML = '<span class="tkt-event-ico" aria-hidden="true"><svg viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1.6"><circle cx="8" cy="8" r="5"/><path d="M8 5v3l2 1.5"/></svg></span>';
              var body = document.createElement('span');
              var who = card.querySelector('.tktDspCommenter strong');
              if (who) {
                var w = document.createElement('strong');
                w.textContent = who.textContent + ' ';
                body.appendChild(w);
              }
              body.appendChild(buildDiffFrag(changes));
              ev.appendChild(body);
              card.parentNode.insertBefore(ev, card.nextSibling);
            });
          })
          .catch(function () {});
      }
    }

    /* 8i. Zero-schema Option C: hover/focus reference popovers (refpop) */
    var refPop = document.createElement('div');
    refPop.id = 'tkt-refpop';
    refPop.setAttribute('role', 'tooltip');
    refPop.hidden = true;
    document.body.appendChild(refPop);
    var refCache = {};
    var refTimer = null;
    var refActive = null;

    function isRefLink(a) {
      if (!a || !a.href) return false;
      if (a.classList.contains('tkt-btn') || a.closest('.tkt-seg')) return false;
      try {
        var u = new URL(a.href, window.location.href);
        if (u.origin !== window.location.origin) return false;
        return /\/(tktview|info|forumpost)\/[0-9a-f]{6,}/i.test(u.pathname);
      } catch (_) { return false; }
    }

    function placePop(el) {
      var r = el.getBoundingClientRect();
      var pw = refPop.offsetWidth || 300;
      var ph = refPop.offsetHeight || 120;
      var left = Math.min(window.innerWidth - pw - 12, Math.max(12, r.left));
      var top = r.bottom + 8;
      if (top + ph > window.innerHeight - 12) top = Math.max(12, r.top - ph - 8);
      refPop.style.left = left + 'px';
      refPop.style.top = top + 'px';
    }

    function renderPop(el, data) {
      if (refActive !== el || !data) return;
      refPop.innerHTML = '';
      var top = document.createElement('div');
      top.className = 'rp-top';
      var k = document.createElement('span');
      k.className = 'rp-kind';
      k.textContent = data.kind;
      top.appendChild(k);
      if (data.badge) {
        var b = document.createElement('span');
        b.className = 'tkt-tag tkt-tag-info';
        b.textContent = data.badge;
        top.appendChild(b);
      }
      var title = document.createElement('div');
      title.className = 'rp-title';
      title.textContent = data.title;
      refPop.appendChild(top);
      refPop.appendChild(title);
      if (data.body) {
        var body = document.createElement('div');
        body.className = 'rp-body';
        body.textContent = data.body;
        refPop.appendChild(body);
      }
      if (data.foot) {
        var foot = document.createElement('div');
        foot.className = 'rp-foot';
        foot.textContent = data.foot;
        refPop.appendChild(foot);
      }
      refPop.hidden = false;
      placePop(el);
    }

    function parseRefHtml(url, html) {
      var doc = new DOMParser().parseFromString(html, 'text/html');
      var kind = /\/tktview\//i.test(url) ? 'Ticket' : (/\/forumpost\//i.test(url) ? 'Forum post' : 'Artifact');
      var titleEl = doc.querySelector('.tkt-title, .forumPostBody h1, .content h2, title');
      var title = titleEl ? titleEl.textContent.trim() : url;
      var badgeEl = doc.querySelector('.tkt-head-sub .tkt-tag, .branch-name');
      var badge = badgeEl ? badgeEl.textContent.trim() : '';
      var bodyEl = doc.querySelector('.tkt-card-body p, .tkt-card-body, .forumPostBody p, table.label-value td.infoComment');
      var body = bodyEl ? bodyEl.textContent.trim().replace(/\s+/g, ' ').slice(0, 150) : '';
      if (body.length === 150) body += '...';
      var footParts = [];
      doc.querySelectorAll('.tkt-sidebar .tkt-field').forEach(function (f) {
        var lbl = f.querySelector('.tkt-field-label');
        var val = f.querySelector('select, .tkt-side-pop > summary > span, input[type="text"], .tkt-field-val');
        if (!lbl || !val) return;
        var k = lbl.textContent.trim();
        if (k === 'Priority' || k === 'Subsystem' || k === 'Type') {
          var v = (val.tagName === 'SELECT' || val.tagName === 'INPUT') ? val.value : val.textContent.trim();
          if (v && v !== '(unset)') footParts.push(v.replace(/_/g, ' '));
        }
      });
      return { kind: kind, badge: badge, title: title, body: body, foot: footParts.join(' · ') };
    }

    function openRef(a) {
      refActive = a;
      var key = a.href;
      if (refCache[key]) {
        renderPop(a, refCache[key]);
        return;
      }
      fetch(key, { credentials: 'same-origin' })
        .then(function (r) { return r.ok ? r.text() : ''; })
        .then(function (html) {
          if (!html) return;
          refCache[key] = parseRefHtml(key, html);
          renderPop(a, refCache[key]);
        })
        .catch(function () {});
    }

    function closeRef() {
      clearTimeout(refTimer);
      refActive = null;
      refPop.hidden = true;
    }

    shell.addEventListener('mouseover', function (e) {
      var a = e.target.closest('a');
      if (!isRefLink(a)) return;
      clearTimeout(refTimer);
      refTimer = setTimeout(function () { openRef(a); }, 180);
    });
    shell.addEventListener('mouseout', function (e) {
      if (e.target.closest('a')) closeRef();
    });
    shell.addEventListener('focusin', function (e) {
      var a = e.target.closest('a');
      if (isRefLink(a)) openRef(a);
    });
    shell.addEventListener('focusout', function (e) {
      if (e.target.closest('a')) closeRef();
    });

    /* 8f. Attachment image thumbnail grid + native <dialog> lightbox on tktview */
    if (page === 'tktview') {
      var attSec = document.querySelector('section.attachlist, details.attachlist');
      if (attSec) {
        var items = Array.from(attSec.querySelectorAll('li'));
        var imgs = [];
        items.forEach(function (li) {
          var dl = li.querySelector('a[href*="attachdownload"]');
          var nameA = li.querySelector('a');
          if (!dl || !nameA) return;
          var fname = nameA.textContent.trim();
          if (/\.(png|jpe?g|gif|webp|svg)$/i.test(fname)) {
            imgs.push({ name: fname, url: dl.getAttribute('href') });
          }
        });
        if (imgs.length) {
          var dlg = document.createElement('dialog');
          dlg.className = 'tkt-lightbox';
          dlg.innerHTML = '<div class="tkt-lb-bar"><strong class="tkt-lb-title"></strong><button type="button" class="tkt-btn tkt-lb-close">Close</button></div><div class="tkt-lb-body"><img alt=""></div>';
          document.body.appendChild(dlg);
          var dlgTitle = dlg.querySelector('.tkt-lb-title');
          var dlgImg = dlg.querySelector('img');
          dlg.querySelector('.tkt-lb-close').addEventListener('click', function () { dlg.close(); });
          dlg.addEventListener('click', function (ev) { if (ev.target === dlg) dlg.close(); });

          var grid = document.createElement('div');
          grid.className = 'tkt-attach-grid';
          imgs.forEach(function (im) {
            var card = document.createElement('div');
            card.className = 'tkt-attach-card';
            var btn = document.createElement('button');
            btn.type = 'button';
            btn.className = 'tkt-attach-thumb';
            btn.setAttribute('aria-label', 'Preview ' + im.name);
            var imgEl = document.createElement('img');
            imgEl.src = im.url;
            imgEl.alt = im.name;
            imgEl.loading = 'lazy';
            btn.appendChild(imgEl);
            btn.addEventListener('click', function () {
              dlgTitle.textContent = im.name;
              dlgImg.src = im.url;
              dlgImg.alt = im.name;
              dlg.showModal();
            });
            var meta = document.createElement('div');
            meta.className = 'tkt-attach-meta';
            var nm = document.createElement('span');
            nm.className = 'tkt-attach-name';
            nm.textContent = im.name;
            var link = document.createElement('a');
            link.href = im.url;
            link.textContent = 'download';
            meta.appendChild(nm); meta.appendChild(link);
            card.appendChild(btn); card.appendChild(meta);
            grid.appendChild(card);
          });
          var ul = attSec.querySelector('ul');
          if (ul) attSec.insertBefore(grid, ul);
          else attSec.appendChild(grid);
        }
      }
    }
  }

  /* ─────────────────────────────────────────────────────────────────────
     9. Chat embedded attachments (fossil-rendered Markdown / Wiki / text)
     Fossil's /chat-download?render returns bare HTML with no stylesheet or
     color-scheme, so embedded iframes render white-on-black Times New Roman.
     Theme unstyled same-origin chat iframes using the active skin tokens and
     re-measure height so Fossil's initial resize does not clip the content.
  ───────────────────────────────────────────────────────────────────── */
  function styleChatEmbeds() {
    if (!document.body || !document.body.classList.contains('chat')) return;

    var fontFaces = '';
    try {
      for (var i = 0; i < document.styleSheets.length; i++) {
        var rules = document.styleSheets[i].cssRules;
        if (!rules) continue;
        for (var j = 0; j < rules.length; j++) {
          if (rules[j].type === CSSRule.FONT_FACE_RULE) {
            fontFaces += rules[j].cssText + '\n';
          }
        }
      }
    } catch (_) {}

    function buildEmbedCss() {
      var cs = getComputedStyle(document.documentElement);
      function tok(name, fb) {
        var v = cs.getPropertyValue(name).trim();
        return v || fb;
      }
      var scheme = cs.colorScheme || 'dark';
      return fontFaces + [
        ':root { color-scheme: ' + scheme + '; }',
        'html, body { background: ' + tok('--bg', '#1c1e22') + '; color: ' + tok('--text', '#e8e9eb') + '; font-family: ' + tok('--font', 'system-ui, sans-serif') + '; line-height: 1.5; margin: 0; padding: 14px 18px; overflow-wrap: anywhere; }',
        'a { color: ' + tok('--link', '#7fb6ef') + '; text-decoration: none; }',
        'a:hover { color: ' + tok('--link-hover', '#a3cbf5') + '; text-decoration: underline; }',
        'a:visited { color: ' + tok('--visited', '#a6b8e8') + '; }',
        'h1, h2, h3, h4, h5, h6 { color: ' + tok('--text', '#e8e9eb') + '; line-height: 1.28; margin: 1.1em 0 0.45em; }',
        'body > :first-child { margin-top: 0; }',
        'body > :last-child { margin-bottom: 0; }',
        'hr { border: 0; border-top: 1px solid ' + tok('--border', '#41454e') + '; margin: 1em 0; }',
        'code, pre, tt, kbd { font-family: ' + tok('--mono', 'ui-monospace, monospace') + '; }',
        ':not(pre) > code { background: ' + tok('--surface', '#272a30') + '; border: 1px solid ' + tok('--border', '#41454e') + '; border-radius: 3px; padding: 0.06em 0.35em; font-size: 0.92em; }',
        'pre { background: ' + tok('--surface', '#272a30') + '; border: 1px solid ' + tok('--border', '#41454e') + '; border-radius: 5px; padding: 10px 12px; overflow-x: auto; line-height: 1.38; font-size: 0.92em; }',
        'blockquote { border-left: 3px solid ' + tok('--link', '#7fb6ef') + '; background: ' + tok('--surface', '#272a30') + '; margin: 0.75em 0; padding: 0.35em 1em; border-radius: 0 4px 4px 0; }',
        'table { border-collapse: collapse; background: ' + tok('--surface', '#272a30') + '; border: 1px solid ' + tok('--border', '#41454e') + '; margin: 0.75em 0; max-width: 100%; }',
        'th, td { border: 1px solid ' + tok('--border', '#41454e') + '; padding: 5px 9px; text-align: left; }',
        'th { background: ' + tok('--surface2', '#31353d') + '; }',
        'img, svg { max-width: 100%; height: auto; }'
      ].join('\n');
    }

    function applyToFrame(iframe) {
      try {
        var doc = iframe.contentDocument;
        if (!doc || !doc.body) return;
        if (doc.documentElement.tagName.toLowerCase() === 'svg') return;
        /* Leave custom HTML attachments that ship their own stylesheet alone */
        if (doc.querySelector('link[rel="stylesheet"], style:not(#fossil-skin-embed-style)')) return;
        var st = doc.getElementById('fossil-skin-embed-style');
        if (!st) {
          st = doc.createElement('style');
          st.id = 'fossil-skin-embed-style';
          (doc.head || doc.documentElement).appendChild(st);
        }
        st.textContent = buildEmbedCss();
        requestAnimationFrame(function () {
          try {
            if (!iframe.classList.contains('hidden') && doc.documentElement) {
              iframe.style.height = '0px';
              iframe.style.maxHeight = '';
              var h = doc.documentElement.scrollHeight;
              if (h > 0) {
                iframe.style.maxHeight = iframe.style.height = h + 'px';
              }
            }
          } catch (_) {}
        });
      } catch (_) {}
    }

    function watchFrame(iframe) {
      if (iframe.getAttribute('data-skin-embed')) return;
      iframe.setAttribute('data-skin-embed', '1');
      iframe.addEventListener('load', function () { applyToFrame(iframe); });
      if (iframe.contentDocument && iframe.contentDocument.readyState === 'complete') {
        applyToFrame(iframe);
      }
    }

    document.querySelectorAll('.message-widget-content iframe').forEach(watchFrame);
    var mo = new MutationObserver(function (muts) {
      for (var i = 0; i < muts.length; i++) {
        var added = muts[i].addedNodes;
        for (var j = 0; j < added.length; j++) {
          var n = added[j];
          if (n.nodeType !== 1) continue;
          if (n.tagName === 'IFRAME' && n.closest('.message-widget-content')) {
            watchFrame(n);
          } else if (n.querySelectorAll) {
            n.querySelectorAll('.message-widget-content iframe').forEach(watchFrame);
          }
        }
      }
    });
    mo.observe(document.body, { childList: true, subtree: true });
  }

  /* ─────────────────────────────────────────────────────────────────────
     Execute all fixes
     The script is deferred so the DOM is fully parsed when this runs.
     Fossil's inline config scripts have already executed, so
     window.fossil exists and we can patch isDark immediately.
  ───────────────────────────────────────────────────────────────────── */
  patchIsDark();
  addMainLandmark();
  fixHamburgerMenu();
  fixTimeline();
  fixTableHeaders();
  fixSubmenuSelects();
  fitCharts();
  showActiveMenuItem();
  fixSortableHeaders();
  addWeekdays();
  enhanceTickets();
  styleChatEmbeds();

  /* Re-run after window.load: Fossil's timeline renderer inserts
     .tl-canvas SVG elements into td.timelineGraph on load, and
     Fossil's own load handlers may reset isDark. */
  window.addEventListener('load', function () {
    patchIsDark();
    fixTimeline();
    fixTableHeaders();
    fixSubmenuSelects();
  });

}());