/* Support Assistant widget (tier 1, offline). * Floating "?" bubble -> panel with: lessons for the current page, free-text search over the * standalone guides (role-filtered, translated), "Read steps" (captions + pictures), "Play" * (slideshow of the pictures) and Print. Guide me retired 2026-09-16; legacy videos only if corpus_legacy=1. * A guide being read is followed across pages (sessionStorage sa_follow): the panel re-opens on the * next page at the current step. Guide admins also get: Edit (words, pictures, steps), Delete, display order, Synonyms, Lessons list (health, re-capture, publish), Record a lesson, review editor. * Vanilla JS; guide.js provides window.SupportGuide. */ (function () { if (window.__supportAgentLoaded || !window.SUPPORT_AGENT) { return; } window.__supportAgentLoaded = true; var CFG = window.SUPPORT_AGENT; var ACCENT = '#3498db'; // the same blue in every module (client request 2026-09-17); the per-module colours in bootstrap.php are no longer used for the panel var state = { open: false, lastQuery: '', logId: 0, timer: null, ctrl: null, view: 'home', admin: null, slides: null }; function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); } function textToHtml(s) { var t = esc(s).replace(/<br\s*\/?>/gi, '
').replace(/<(\/?)(b|i|u|strong|em)>/gi, '<$1$2>'); return t.replace(/\n/g, '
'); } function api(action, params, opts) { opts = opts || {}; var qs = Object.keys(params || {}).map(function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]); }).join('&'); // the page is always sent in the URL: the API derives the module (and its "enabled" state) from it, for POSTs too var url = CFG.api + '?action=' + encodeURIComponent(action) + '&page=' + encodeURIComponent(CFG.pageWithQuery) + (opts.post ? '' : (qs ? '&' + qs : '')); var init = { credentials: 'same-origin', headers: { 'X-Requested-With': 'XMLHttpRequest' } }; if (opts.post) { init.method = 'POST'; init.headers['Content-Type'] = 'application/x-www-form-urlencoded'; init.body = qs; } if (opts.signal) { init.signal = opts.signal; } return fetch(url, init).then(function (r) { return r.json(); }); } function guide() { return window.SupportGuide || null; } function body() { return document.getElementById('sa-body'); } /* ------------------------------------------------ follow a guide across pages */ var FOLLOW_KEY = 'sa_follow', FOLLOW_TTL = 90 * 60 * 1000; // forgotten after 90 min without a click function loadFollow() { try { return JSON.parse(sessionStorage.getItem(FOLLOW_KEY) || 'null'); } catch (e) { return null; } } function saveFollow(f) { try { f.at = Date.now(); sessionStorage.setItem(FOLLOW_KEY, JSON.stringify(f)); } catch (e) {} } function clearFollow() { try { sessionStorage.removeItem(FOLLOW_KEY); } catch (e) {} } function normPage(p) { p = String(p || '').replace(/\\/g, '/').replace(/^(\.\.\/)+/, '').replace(/\.php(\?|$)/i, '$1'); var m = p.match(/^([^?#]*)\?([^&#=]+)/); return m ? m[1] + '?' + m[2] : p.replace(/[?#].*$/, ''); } function pageMatches(stepPage, cur) { // same rule as guide.js: dir/file by suffix, ?key optional stepPage = normPage(stepPage); cur = normPage(cur || CFG.pageWithQuery); if (!stepPage || stepPage === '*') { return true; } // "*": a step that works on every page (Memos) var sb = stepPage.split('?')[0], sq = stepPage.split('?')[1] || ''; var cb = cur.split('?')[0], cq = cur.split('?')[1] || ''; var baseOk = sb === cb || cb.slice(-(sb.length + 1)) === '/' + sb || sb.slice(-(cb.length + 1)) === '/' + cb; return baseOk && (!sq || sq === cq); } function pageHref(stepPage) { // absolute link to a step's page (adds .php before the ?key) var p = normPage(stepPage); return CFG.base + p.replace(/^([^?]*?)(\.php)?(\?|$)/i, '$1.php$3'); } /* ------------------------------------------------------------------ CSS */ var css = '' + '#sa-bubble{position:fixed;right:22px;bottom:22px;z-index:99990;width:54px;height:54px;border-radius:50%;background:' + ACCENT + ';color:#fff;border:0;box-shadow:0 6px 18px rgba(0,0,0,.28);cursor:pointer;display:flex;align-items:center;justify-content:center;font:700 22px/1 Arial,sans-serif;transition:transform .15s}' + '#sa-bubble:hover{transform:scale(1.06)}' + '#sa-bubble .sa-badge{position:absolute;right:-4px;top:-4px;background:#e74c3c;color:#fff;font:700 11px/18px Arial;min-width:18px;height:18px;border-radius:9px;text-align:center;padding:0 4px;display:none}' + '#sa-panel{position:fixed;right:22px;bottom:86px;z-index:99990;width:420px;max-width:calc(100vw - 30px);height:600px;max-height:calc(100vh - 110px);background:#fff;border-radius:14px;box-shadow:0 12px 40px rgba(0,0,0,.3);display:none;flex-direction:column;overflow:hidden;font:13px/1.45 Arial,Helvetica,sans-serif;color:#2c3e50;text-align:left}' + '#sa-panel.open{display:flex}' + '#sa-head{background:' + ACCENT + ';color:#fff;padding:12px 14px;display:flex;align-items:center;gap:10px;cursor:move;user-select:none;-webkit-user-select:none}' + '#sa-panel.sa-dragging{transition:none;box-shadow:0 18px 50px rgba(0,0,0,.45)}' + '#sa-head .sa-title{font-weight:700;font-size:15px;flex:1}' + '#sa-head .sa-sub{font-size:11px;opacity:.9}' + '#sa-head button{background:rgba(255,255,255,.18);border:0;color:#fff;width:28px;height:28px;border-radius:6px;cursor:pointer;font-size:16px}' + '#sa-search{padding:10px 12px;border-bottom:1px solid #eee;display:flex;gap:8px}' + '#sa-search input{flex:1;border:1px solid #cfd8dc;border-radius:8px;padding:9px 11px;font-size:13px;outline:none;min-width:0}' + '#sa-search input:focus{border-color:' + ACCENT + '}' + '#sa-search button{border:0;background:' + ACCENT + ';color:#fff;border-radius:8px;padding:0 14px;cursor:pointer;font-weight:700}' + '#sa-body{flex:1;overflow:auto;padding:10px 12px;background:#f7f8fa}' + '#sa-foot{border-top:1px solid #eee;padding:8px 12px;display:flex;gap:12px;font-size:12px;background:#fff;flex-wrap:wrap}' + '#sa-foot a{color:' + ACCENT + ';text-decoration:none;cursor:pointer}' + '.sa-sect{font-size:11px;text-transform:uppercase;letter-spacing:.5px;color:#7f8c8d;margin:6px 0 8px;display:flex;align-items:center;gap:8px}' + '.sa-sect .sa-sp{flex:1}' + '.sa-card{background:#fff;border:1px solid #e6e9ee;border-radius:10px;padding:10px 12px;margin-bottom:8px}' + '.sa-card .sa-t{font-weight:700;font-size:13px}' + '.sa-card .sa-m{font-size:11px;color:#7f8c8d;margin-top:2px}' + '.sa-card .sa-m .sa-other{color:#e67e22}' + '.sa-acts{display:flex;flex-wrap:wrap;gap:6px;margin-top:8px}' + '.sa-acts button,.sa-btn{border:1px solid ' + ACCENT + ';background:#fff;color:' + ACCENT + ';border-radius:6px;padding:5px 10px;font-size:12px;cursor:pointer}' + '.sa-acts button.sa-primary,.sa-btn.sa-primary{background:' + ACCENT + ';color:#fff}' + '.sa-acts button.sa-danger{border-color:#c0392b;color:#c0392b}' + '.sa-acts button:disabled{opacity:.5;cursor:default}' + '.sa-steps{margin:8px 0 0;padding:0;list-style:none;counter-reset:sastep}' + '.sa-steps li{margin:0 0 10px;padding-left:30px;position:relative;counter-increment:sastep}' + '.sa-steps li:before{content:counter(sastep);position:absolute;left:0;top:0;width:22px;height:22px;border-radius:50%;background:' + ACCENT + ';color:#fff;font:700 12px/22px Arial;text-align:center}' + '.sa-steps img{display:block;max-width:100%;border:1px solid #dfe3e8;border-radius:6px;margin-top:6px;cursor:zoom-in}' + '.sa-answer{margin-top:8px;padding:8px 10px;background:#fbf7ff;border-left:3px solid ' + ACCENT + ';border-radius:4px}' + '.sa-fb{margin-top:8px;font-size:12px;color:#7f8c8d;display:flex;align-items:center;gap:6px}' + '.sa-fb button{border:1px solid #dfe3e8;background:#fff;border-radius:6px;padding:3px 8px;cursor:pointer}' + '.sa-empty{color:#7f8c8d;padding:14px 4px}' + '.sa-chip{display:inline-block;margin:4px 6px 0 0;padding:4px 10px;border-radius:14px;background:#eef0f4;cursor:pointer;font-size:12px}' + '.sa-msg{background:#fff;border-radius:10px;padding:10px 12px;margin-bottom:10px;border:1px solid #e6e9ee}' + '.sa-pill{display:inline-block;font-size:10px;padding:1px 7px;border-radius:9px;background:#eef0f4;color:#5b6b7a;margin-left:4px;vertical-align:middle}' + '.sa-pill.ok{background:#e8f8ef;color:#1e8449}.sa-pill.stale{background:#fdecea;color:#c0392b}.sa-pill.legacy{background:#fff4e0;color:#b9770e}.sa-pill.draft{background:#eaf2ff;color:#2f6fd6}' + '.sa-ed textarea,.sa-ed input[type=text],.sa-ed select{width:100%;box-sizing:border-box;border:1px solid #cfd8dc;border-radius:6px;padding:6px 8px;font:13px Arial,sans-serif;margin-top:4px}' + '.sa-ed .sa-step{background:#fff;border:1px solid #e6e9ee;border-radius:8px;padding:8px 10px;margin-bottom:8px}' + '.sa-ed .sa-step img{max-width:100%;border:1px solid #dfe3e8;border-radius:4px;margin-top:6px}' + '.sa-ed .sa-tiny{font-size:11px;color:#7f8c8d}' + '.sa-ed .sa-row{display:flex;gap:6px;align-items:center;margin-top:6px}' + '.sa-ed .sa-row button{border:1px solid #cfd8dc;background:#fff;border-radius:5px;padding:2px 7px;cursor:pointer;font-size:11px}' + '#sa-video{position:fixed;top:0;left:0;right:0;bottom:0;z-index:99995;background:rgba(0,0,0,.84);display:none;align-items:center;justify-content:center;flex-direction:column;overflow:auto}' + '#sa-video.open{display:flex}' + '#sa-video video{max-width:92vw;max-height:78vh;background:#000;border-radius:8px}' + '#sa-video .sa-vt{color:#fff;font:700 15px Arial;margin-bottom:10px;max-width:92vw;text-align:center}' + '#sa-video .sa-vc{position:absolute;top:16px;right:20px;color:#fff;background:rgba(255,255,255,.15);border:0;border-radius:6px;width:36px;height:36px;font-size:20px;cursor:pointer}' + '#sa-slides{display:none;flex-direction:column;align-items:center;max-width:92vw}' + '#sa-slides img{max-width:92vw;max-height:66vh;border-radius:8px;background:#fff;box-shadow:0 10px 40px rgba(0,0,0,.5)}' + '#sa-slides .sa-cap{color:#fff;font:15px/1.5 Arial;max-width:800px;text-align:center;margin:14px 0 10px;white-space:pre-line}' + '#sa-slides .sa-ctl{display:flex;gap:8px;align-items:center;color:#ddd;font:12px Arial}' + '#sa-slides .sa-ctl button{border:1px solid #fff;background:transparent;color:#fff;border-radius:6px;padding:6px 12px;cursor:pointer;font-size:13px}' + '#sa-slides .sa-ctl button.sa-primary{background:#fff;color:#222}' + '#sa-slides .sa-ctl button.sa-lb{border:0;background:#f39c12;color:#1b1b1b;font:700 13px Arial;padding:7px 16px;border-radius:7px;box-shadow:0 3px 10px rgba(0,0,0,.4)}' // Previous / Next Lesson: orange, at both ends of the row (the class keeps the page's button:not([class]) rule off them) + '#sa-slides .sa-ctl button.sa-lb:hover{background:#ffb13b}' + '#sa-slides .sa-ctl button[data-sl="prevlesson"]{margin-right:14px}' + '#sa-slides .sa-ctl button[data-sl="nextlesson"]{margin-left:14px}' + '#sa-slides.sa-big{max-width:98vw}' + '#sa-slides.sa-big img{max-width:98vw;max-height:calc(100vh - 96px);border-radius:4px}' + '#sa-slides.sa-big .sa-cap{margin:6px 0 4px;font-size:14px;max-width:96vw}' + '.sa-follow{display:flex;align-items:center;gap:6px;background:#f3eefb;border:1px solid #d9cdf0;border-radius:8px;padding:6px 10px;margin:6px 0;font-size:12px;color:#4a3a6e}' + '.sa-follow .sa-sp{flex:1}.sa-follow button{border:1px solid #b9a7dc;background:#fff;color:#4a3a6e;border-radius:6px;padding:2px 9px;cursor:pointer;font-size:13px;line-height:1.3}' + '.sa-follow button[data-act="fw-done"]{background:#6c4bb6;color:#fff;border-color:#6c4bb6}' + '.sa-hint{font-size:11px;color:#777;margin:0 0 6px 2px}' + '.sa-pill.rr{background:#fff4e0;color:#b9770e}.sa-pill.rr-done{background:#e8f8ef;color:#1e8449}.sa-pill.rr-failed{background:#fdecea;color:#c0392b}' + '.sa-rr{margin-top:8px;padding:10px;border:1px dashed #f39c12;border-radius:8px;background:#fffaf2}' + '.sa-rr .sa-rr-t{font-weight:700;font-size:12px;margin-bottom:4px}' + '.sa-rr .sa-tiny{font-size:11px;color:#6b7a89;margin:3px 0}' + '.sa-rr code{font:11px Consolas,monospace;background:#f3f4f6;padding:0 3px;border-radius:3px;word-break:break-all}' + '.sa-rr textarea{width:100%;box-sizing:border-box;min-height:110px;margin-top:6px;font:12px/1.4 Arial,sans-serif;border:1px solid #cfd6dd;border-radius:6px;padding:6px;resize:vertical}' + '.sa-rr .sa-rr-open{background:#fff;border:1px solid #f5d7a3;border-radius:6px;padding:6px 8px;margin:6px 0;font-size:12px}' + '.sa-rr .sa-rr-h{margin:8px 0 0;padding:0;list-style:none;font-size:11px;color:#555}' + '.sa-rr .sa-rr-h li{border-top:1px solid #f0e2c8;padding:4px 0}' + '.sa-rr .sa-rr-p{white-space:pre-wrap;color:#333}' + '.sa-steps li{cursor:pointer;border-left:3px solid transparent;border-radius:4px;padding:2px 4px 2px 30px}' + '.sa-steps li.sa-cur{border-left-color:#6c4bb6;background:#f8f5fd}.sa-steps li.sa-done{color:#888}' + '.sa-steps li.sa-done img{opacity:.6}' + '.sa-here{display:block;width:max-content;background:#6c4bb6;color:#fff;font-size:10px;font-weight:bold;border-radius:10px;padding:1px 7px;margin:0 6px 2px 0;vertical-align:middle;text-transform:uppercase;letter-spacing:.3px}' + '.sa-goto{display:inline-block;margin:4px 0 2px 6px;padding:4px 12px;background:#f39c12;color:#fff;font-size:12px;font-weight:bold;text-decoration:none;border-radius:6px;box-shadow:0 1px 3px rgba(0,0,0,.3)}.sa-goto:hover{background:#d35400;color:#fff}' + '.sa-upl{display:inline-block;border:1px solid #b9a7dc;color:#4a3a6e;background:#fff;border-radius:6px;padding:3px 9px;cursor:pointer;font-size:12px}' + '.sa-upl.busy{opacity:.5;pointer-events:none}' + '.sa-ord{display:inline-flex;gap:2px;margin-left:auto}.sa-ord button{padding:2px 7px;font-size:11px}' + '.sa-ed textarea.sa-ed-summary{min-height:54px}' + '.sa-syn label{display:block;font-size:11px;color:#777;margin:6px 0 2px}.sa-syn input{width:100%;box-sizing:border-box;border:1px solid #ccd;border-radius:6px;padding:6px 8px;font:13px Arial}' + '.sa-syn-row{display:flex;align-items:flex-start;gap:8px;padding:7px 2px;border-bottom:1px solid #eef}.sa-syn-row .sa-w{font-weight:bold;min-width:90px}.sa-syn-row .sa-a{flex:1;color:#555}' + '.sa-syn-row button{padding:2px 8px;font-size:11px}' + '.sa-def{margin:6px 0 10px;padding:10px 12px;background:#fbf7ff;border-left:3px solid ' + ACCENT + ';border-radius:6px;font-size:13px;line-height:1.5}.sa-def .sa-tiny{margin-top:6px}' + '.sa-blurb{font-size:12px;color:#555;margin:3px 0 4px;line-height:1.4}' + '@media (max-width:600px){#sa-panel{right:8px;bottom:80px;width:calc(100vw - 16px)}#sa-bubble{right:14px;bottom:14px}}'; /* ------------------------------------------------------------------ DOM */ function build() { var st = document.createElement('style'); if (CFG.corner === 'left') { // e.g. the POS selling screen, whose action buttons sit bottom-right css += '#sa-bubble{left:22px;right:auto}#sa-panel{left:22px;right:auto}@media (max-width:600px){#sa-bubble{left:14px;right:auto}#sa-panel{left:8px;right:auto}}'; } st.textContent = css; document.head.appendChild(st); var bubble = document.createElement('button'); bubble.id = 'sa-bubble'; bubble.type = 'button'; bubble.title = 'Support Assistant - ask how to do something'; bubble.innerHTML = '?'; bubble.addEventListener('click', toggle); var panel = document.createElement('div'); panel.id = 'sa-panel'; panel.innerHTML = '' + '
Support Assistant
' + esc(CFG.label) + ' · works offline
' + '
' + '' + '
' + '
Home' + (CFG.canEdit ? 'LessonsSynonyms● Record a lesson' : '') + '
'; var video = document.createElement('div'); video.id = 'sa-video'; video.innerHTML = '
' + '
'; document.body.appendChild(bubble); document.body.appendChild(panel); document.body.appendChild(video); panel.querySelector('#sa-close').addEventListener('click', toggle); makeDraggable(panel, panel.querySelector('#sa-head')); panel.querySelector('#sa-go').addEventListener('click', function () { search(true); }); var input = panel.querySelector('#sa-q'); input.addEventListener('keydown', function (e) { if (e.key === 'Enter') { e.preventDefault(); search(true); } if (e.key === 'Escape') { toggle(); } }); input.addEventListener('input', function () { clearTimeout(state.timer); state.timer = setTimeout(function () { search(false); }, 350); }); panel.querySelector('#sa-home-link').addEventListener('click', function () { state.lastQuery = ''; input.value = ''; showHome(); }); if (CFG.canEdit) { panel.querySelector('#sa-lessons-link').addEventListener('click', showLessons); panel.querySelector('#sa-synonyms-link').addEventListener('click', showSynonyms); panel.querySelector('#sa-record-link').addEventListener('click', function () { startRecording(0, ''); }); } video.querySelector('.sa-vc').addEventListener('click', closeVideo); video.addEventListener('click', function (e) { if (e.target === video) { closeVideo(); } var b = e.target.closest('[data-sl]'); if (b) { slideCtl(b.getAttribute('data-sl')); } }); document.addEventListener('keydown', function (e) { if (!video.classList.contains('open')) { return; } if (e.key === 'Escape') { closeVideo(); } if (state.slides && e.key === 'ArrowRight') { slideCtl('next'); } if (state.slides && e.key === 'ArrowLeft') { slideCtl('prev'); } }); body().addEventListener('click', onBodyClick); body().addEventListener('change', onBodyChange); body().addEventListener('keydown', onBodyKey); refreshBadge(); resumeFollow(); } /* Drag the panel by its header so it can be moved off buttons it covers. The position is remembered in this browser (localStorage); double-click the header to return it to the corner. */ function makeDraggable(panel, handle) { var drag = null, KEY = 'sa_panel_pos'; function place(x, y) { var w = panel.offsetWidth || 420, h = panel.offsetHeight || 600; x = Math.max(0, Math.min(window.innerWidth - w, x)); y = Math.max(0, Math.min(window.innerHeight - h, y)); panel.style.left = x + 'px'; panel.style.top = y + 'px'; panel.style.right = 'auto'; panel.style.bottom = 'auto'; } function remember() { try { localStorage.setItem(KEY, JSON.stringify({ x: panel.offsetLeft, y: panel.offsetTop })); } catch (e) {} } function start(cx, cy) { var r = panel.getBoundingClientRect(); drag = { dx: cx - r.left, dy: cy - r.top }; panel.classList.add('sa-dragging'); } function end() { if (!drag) { return; } drag = null; panel.classList.remove('sa-dragging'); remember(); } handle.addEventListener('mousedown', function (e) { if (e.button !== 0 || e.target.closest('#sa-close')) { return; } start(e.clientX, e.clientY); e.preventDefault(); }); document.addEventListener('mousemove', function (e) { if (drag) { place(e.clientX - drag.dx, e.clientY - drag.dy); } }); document.addEventListener('mouseup', end); handle.addEventListener('touchstart', function (e) { if (e.target.closest('#sa-close')) { return; } var t = e.touches[0]; start(t.clientX, t.clientY); }, { passive: true }); document.addEventListener('touchmove', function (e) { if (drag) { var t = e.touches[0]; place(t.clientX - drag.dx, t.clientY - drag.dy); } }, { passive: true }); document.addEventListener('touchend', end); handle.addEventListener('dblclick', function (e) { if (e.target.closest('#sa-close')) { return; } panel.style.left = panel.style.top = panel.style.right = panel.style.bottom = ''; try { localStorage.removeItem(KEY); } catch (e2) {} }); var saved = null; try { saved = JSON.parse(localStorage.getItem(KEY) || 'null'); } catch (e) {} if (saved && typeof saved.x === 'number' && typeof saved.y === 'number') { place(saved.x, saved.y); } window.addEventListener('resize', function () { if (panel.style.left) { place(panel.offsetLeft, panel.offsetTop); } }); } function refreshBadge() { if (!CFG.canEdit) { return; } api('status', { page: CFG.pageWithQuery }).then(function (r) { var b = document.getElementById('sa-badge'); if (r.success && r.data.stale_count > 0) { b.textContent = r.data.stale_count; b.style.display = 'block'; b.title = r.data.stale_count + ' lesson(s) need review'; } else { b.style.display = 'none'; } }).catch(function () {}); } function toggle() { var panel = document.getElementById('sa-panel'); state.open = !state.open; panel.classList.toggle('open', state.open); if (!state.open) { clearFollow(); } // closing the panel ends the followed guide: nothing re-opens on the next page if (state.open) { if (state.view === 'follow') { state.view = 'home'; state.lastQuery = ''; } // the bubble always opens on this page's lessons if (!state.lastQuery && state.view === 'home') { showHome(); } setTimeout(function () { document.getElementById('sa-q').focus(); }, 50); } } /* ---------------------------------------------------------------- views */ function showHome() { state.view = 'home'; var b = body(); b.innerHTML = '
' + textToHtml(CFG.welcome) + '
Loading lessons for this page…
'; api('page_lessons', { page: CFG.pageWithQuery }).then(function (r) { if (state.lastQuery || state.view !== 'home') { return; } var html = '
' + textToHtml(CFG.welcome) + '
'; if (r.success && r.data.lessons.length) { state.pageLessons = r.data.lessons.filter(function (l) { return l.type !== 'video'; }).map(function (l) { return { slug: l.slug || '', qid: l.question_id || 0, title: l.title }; }); // the slideshow's "Next Slide" follows this order html += '
On this page
' + r.data.lessons.map(card).join(''); } else { html += '
No lessons are linked to this page yet. Type a question above.
'; } b.innerHTML = html; }).catch(function () { b.innerHTML = '
' + textToHtml(CFG.welcome) + '
'; }); } function card(item) { var meta = []; if (item.type === 'video') { meta.push('Tutorial video'); if (item.module) { meta.push(item.module); } } else { if (item.chapter) { meta.push(item.chapter.replace(/^Chapter\s*\d+\s*-\s*/i, '')); } if (item.category) { meta.push(item.category); } } var other = item.other_module ? '· other module' : ''; var acts = ''; if (item.type === 'video') { acts = ''; } else { var report = item.module === 'reports' && item.page && !pageMatches(item.page); // a report found from another page: open it straight away acts = (report ? '📊 Open report ↗' : '') + '' + (item.video ? '' : ''); } return '
' + esc(item.title) + '
' + (item.blurb ? '
' + esc(item.blurb) + '
' : '') + (meta.length ? '
' + esc(meta.join(' · ')) + ' ' + other + '
' : '') + '
' + acts + '
'; } function search(force) { var q = document.getElementById('sa-q').value.trim(); if (!q) { state.lastQuery = ''; showHome(); return; } if (!force && q.length < 3) { return; } if (q === state.lastQuery && !force) { return; } state.lastQuery = q; state.view = 'search'; if (state.ctrl) { state.ctrl.abort(); } state.ctrl = window.AbortController ? new AbortController() : null; var b = body(); b.innerHTML = '
Searching…
'; api('search', { q: q, page: CFG.pageWithQuery }, { signal: state.ctrl && state.ctrl.signal }).then(function (r) { if (q !== state.lastQuery) { return; } if (!r.success) { b.innerHTML = '
' + esc(r.msg || 'Search failed.') + '
'; return; } state.logId = r.data.log_id || 0; var html = ''; if (r.data.results.length) { var top = r.data.results[0]; if (r.data.intent === 'define' && top && top.summary) { html += '
' + textToHtml(top.summary) + '
From the guide ' + esc(top.title) + ' - open Read steps below for the how-to.
'; } html += '
' + (r.data.widened ? 'Best matches (including other modules)' : 'Best matches') + '
' + r.data.results.map(card).join(''); html += '
Was this helpful?
'; } else { html += '
I could not find a lesson for "' + esc(q) + '".'; if (r.data.suggestions.length) { html += '

Nearest topics:
' + r.data.suggestions.map(function (s) { return '' + esc(s.title) + ''; }).join(''); } html += '
'; html += '
Report a gap?
'; } b.innerHTML = html; }).catch(function (e) { if (e && e.name === 'AbortError') { return; } b.innerHTML = '
The assistant is unreachable right now. Please try again.
'; }); } /* ---------------------------------------------------------- read steps */ function toggleSteps(btn, startStep, preloaded) { var cardEl = btn.closest('.sa-card'); var detail = cardEl.querySelector('.sa-detail'); if (!detail) { detail = document.createElement('div'); detail.className = 'sa-detail'; cardEl.appendChild(detail); } // admin Lessons cards have no detail box until first use if (detail.innerHTML) { detail.innerHTML = ''; detail.__lesson = null; btn.textContent = 'Read steps'; clearFollow(); return; } btn.disabled = true; var qid = btn.getAttribute('data-id'), slug = btn.getAttribute('data-slug') || ''; var req = preloaded ? Promise.resolve(preloaded) : api('lesson', slug ? { slug: slug, page: CFG.pageWithQuery } : { id: qid, page: CFG.pageWithQuery }); req.then(function (r) { btn.disabled = false; if (!r.success) { detail.innerHTML = '
' + esc(r.msg) + '
'; return; } var d = r.data, script = d.script; var steps = (script && script.steps && script.steps.length) ? script.steps : (d.steps || []).map(function (s) { return { caption: s.text, shot_url: null, page: '' }; }); detail.__script = script; detail.__lesson = { qid: qid, slug: slug, title: d.title, answer: d.answer_text, steps: steps }; var cur = Math.max(0, Math.min(steps.length - 1, typeof startStep === 'number' ? startStep : 0)); renderSteps(detail, cur, cur > 0); btn.textContent = 'Hide steps'; if (cur === 0) { scrollCardToTop(cardEl); } // the opened lesson rises to the top of the panel, out of the long list if (steps.length) { saveFollow({ slug: slug, qid: qid, title: d.title, step: cur, page: CFG.pageWithQuery }); } }).catch(function () { btn.disabled = false; detail.innerHTML = '
Could not load the steps.
'; }); } /* scroll the panel body so the card starts at its top edge (smooth when the browser supports it) */ function scrollCardToTop(cardEl) { var b = body(); if (!b || !cardEl) { return; } setTimeout(function () { var top = cardEl.getBoundingClientRect().top - b.getBoundingClientRect().top + b.scrollTop - 6; try { b.scrollTo({ top: Math.max(0, top), behavior: 'smooth' }); } catch (e) { b.scrollTop = Math.max(0, top); } }, 30); } /* The step list: the current step is marked "You are here"; click a step to move the marker. Steps that happen on another page get an "open page" link; the guide re-opens there. */ function renderSteps(detail, cur, scrollTo) { var L = detail.__lesson, steps = L.steps, qid = L.qid, slug = L.slug, html = ''; detail.__cur = cur; var pics = steps.filter(function (s) { return s.shot_url; }).length; if (steps.length) { html += '
Step ' + (cur + 1) + ' of ' + steps.length + '' + '' + '' + '
'; } if (L.answer) { html += '
' + textToHtml(L.answer) + '
'; } if (steps.length) { html += '
    ' + steps.map(function (s, i) { var cls = i === cur ? 'sa-cur' : (i < cur ? 'sa-done' : ''); var goto = s.page && !pageMatches(s.page) ? ' open page ↗' : ''; return '
  1. ' + (i === cur ? 'You are here' : '') + textToHtml(s.caption) + goto + (s.shot_url ? '' : '') + '
  2. '; }).join('') + '
'; if (pics) { html += '
'; } else if (CFG.canEdit) { html += '
'; } } else if (!L.answer) { html += '
This lesson has no written steps yet.
'; } detail.innerHTML = html; if (scrollTo) { var li = detail.querySelector('li.sa-cur'); if (li && li.scrollIntoView) { setTimeout(function () { li.scrollIntoView({ block: 'center' }); }, 30); } } if (steps[cur]) { setTimeout(function () { showTarget(steps[cur]); }, 80); } // keep the panel off the control this step is about } /* The control a step talks about: outline it for a moment and, when the panel covers it, slide the panel to a free side of the window (the dragged position is not saved over). */ function showTarget(step) { var g = guide(); if (!g || !g.resolve || !step || !step.target) { return; } var r; try { r = g.resolve({ within: step.within, target: step.target }); } catch (e) { return; } if (!r || !r.el || (r.status !== 'ok' && r.status !== 'ambiguous')) { return; } var el = r.el, panel = document.getElementById('sa-panel'); var t = g.rectOf ? g.rectOf(el) : el.getBoundingClientRect(); // framed controls: add the iframe offset if (t.width === 0 && t.height === 0) { return; } if (panel.classList.contains('open')) { var p = panel.getBoundingClientRect(), w = p.width, h = p.height, vw = window.innerWidth, vh = window.innerHeight; var overlaps = function (a, b) { return a.left < b.right && a.right > b.left && a.top < b.bottom && a.bottom > b.top; }; if (overlaps(t, p)) { var spots = [{ left: 22, top: p.top }, { left: vw - w - 22, top: p.top }, { left: p.left, top: vh - h - 20 }, { left: p.left, top: 10 }, { left: 22, top: vh - h - 20 }, { left: 22, top: 10 }, { left: vw - w - 22, top: 10 }]; for (var i = 0; i < spots.length; i++) { var c = spots[i]; c.left = Math.max(0, Math.min(vw - w, c.left)); c.top = Math.max(0, Math.min(vh - h, c.top)); if (!overlaps(t, { left: c.left, top: c.top, right: c.left + w, bottom: c.top + h })) { panel.style.left = c.left + 'px'; panel.style.top = c.top + 'px'; panel.style.right = 'auto'; panel.style.bottom = 'auto'; break; } } } } if (g.highlight && g.clearHighlight) { try { g.highlight(el, true, true); setTimeout(function () { try { g.clearHighlight(); } catch (e) {} }, 2500); } catch (e) {} } } function moveStep(detail, cur) { var L = detail.__lesson; if (!L || !L.steps.length) { return; } cur = Math.max(0, Math.min(L.steps.length - 1, cur)); renderSteps(detail, cur, true); saveFollow({ slug: L.slug, qid: L.qid, title: L.title, step: cur, page: CFG.pageWithQuery }); } /* On page load: if a guide was being followed, re-open the panel on it. When the page changed, and the current step is not on this page, the marker moves to the next step that belongs here. */ function resumeFollow() { var f = loadFollow(); if (!f || !(f.slug || f.qid)) { return; } if (Date.now() - (f.at || 0) > FOLLOW_TTL) { clearFollow(); return; } api('lesson', f.slug ? { slug: f.slug, page: CFG.pageWithQuery } : { id: f.qid, page: CFG.pageWithQuery }).then(function (r) { if (!r.success) { clearFollow(); return; } var d = r.data, script = d.script; var steps = (script && script.steps && script.steps.length) ? script.steps : (d.steps || []); var cur = f.step || 0; if (steps[cur] && steps[cur].page && !pageMatches(steps[cur].page)) { // the current step is on another page: move to the next step that belongs here for (var i = cur + 1; i < steps.length; i++) { if (steps[i].page && pageMatches(steps[i].page)) { cur = i; break; } } } state.view = 'follow'; state.lastQuery = ''; if (!state.open) { state.open = true; document.getElementById('sa-panel').classList.add('open'); } // open directly: toggle() is the bubble path and shows this page's lessons var b = body(); b.innerHTML = '
Continuing your guide
' + card({ question_id: f.qid || 0, slug: f.slug || '', title: d.title, chapter: d.chapter, category: d.category, video: null }); var btn = b.querySelector('[data-act="steps"]'); if (btn) { toggleSteps(btn, cur, r); } }).catch(function () {}); } /* walkthroughs were retired: Read steps, slideshow and print are the user-facing features */ /* ------------------------------------------------------ video / slides */ function openVideo(file, title) { var wrap = document.getElementById('sa-video'); var v = wrap.querySelector('video'); document.getElementById('sa-slides').style.display = 'none'; v.style.display = 'block'; state.slides = null; wrap.querySelector('.sa-vt').textContent = title || ''; v.src = CFG.base + 'videos/stream.php?file=' + encodeURIComponent(file); wrap.classList.add('open'); if (v.play) { var p = v.play(); if (p && p.catch) { p.catch(function () {}); } } } function openSlides(title, steps, startAt, ref) { var wrap = document.getElementById('sa-video'); var v = wrap.querySelector('video'); v.pause(); v.removeAttribute('src'); v.load(); v.style.display = 'none'; wrap.querySelector('.sa-vt').textContent = title || ''; var frames = steps.map(function (s, i) { return { src: CFG.base + s.shot_url, caption: (i + 1) + '. ' + (s.caption || ''), ok: !!s.shot_url }; }).filter(function (f) { return f.ok; }); if (!frames.length) { return; } state.slides = { frames: frames, i: Math.max(0, Math.min(frames.length - 1, startAt || 0)), timer: null, playing: true, ref: ref || null, title: title || '' }; document.getElementById('sa-slides').style.display = 'flex'; document.getElementById('sa-slides').classList.add('sa-big'); // opens zoomed out (almost full screen) by default; Zoom in returns to the normal size wrap.classList.add('open'); renderSlide(); slideTimer(); } function renderSlide() { var s = state.slides; if (!s) { return; } var box = document.getElementById('sa-slides'); box.querySelector('img').src = s.frames[s.i].src; box.querySelector('.sa-cap').textContent = s.frames[s.i].caption; box.querySelector('.sa-pos').textContent = (s.i + 1) + ' / ' + s.frames.length; box.querySelector('[data-sl="play"]').innerHTML = s.playing ? '▮▮ Pause' : '▶ Play'; var last = s.i === s.frames.length - 1, nl = adjacentLesson(s.ref, 1), pl = adjacentLesson(s.ref, -1); box.querySelector('[data-sl="next"]').innerHTML = last ? 'Close' : 'Next ›'; // the last picture closes the show var nb = box.querySelector('[data-sl="nextlesson"]'), pb = box.querySelector('[data-sl="prevlesson"]'); nb.style.visibility = (last && nl) ? 'visible' : 'hidden'; nb.title = nl ? 'Open the next lesson: ' + nl.title : ''; // only on the last picture pb.style.visibility = (s.i === 0 && pl) ? 'visible' : 'hidden'; pb.title = pl ? 'Open the previous lesson: ' + pl.title : ''; // only on the first picture box.querySelector('[data-sl="size"]').innerHTML = box.classList.contains('sa-big') ? '⤡ Zoom in' : '⤢ Zoom out'; // wording chosen by the client: Zoom out = enlarge, Zoom in = back to normal } function slideTimer() { var s = state.slides; if (!s) { return; } clearTimeout(s.timer); if (s.playing) { s.timer = setTimeout(function () { if (!state.slides) { return; } if (s.i < s.frames.length - 1) { s.i++; renderSlide(); slideTimer(); } else { s.playing = false; renderSlide(); } }, 3500); } } function slideCtl(what) { var s = state.slides; if (!s) { return; } if (what === 'next') { if (s.i >= s.frames.length - 1) { closeVideo(); return; } s.i++; } else if (what === 'nextlesson' || what === 'prevlesson') { var dir = what === 'nextlesson' ? 1 : -1, al = adjacentLesson(s.ref, dir); if (al) { openLesson(al, dir); } return; } else if (what === 'prev') { s.i = Math.max(0, s.i - 1); } else if (what === 'play') { s.playing = !s.playing; if (s.playing && s.i === s.frames.length - 1) { s.i = 0; } } else if (what === 'size') { var boxS = document.getElementById('sa-slides'); boxS.classList.toggle('sa-big', !boxS.classList.contains('sa-big')); } // almost full screen for pictures of the whole page renderSlide(); slideTimer(); } /* the lesson before (dir -1) or after (dir 1) `ref` in this page's "On this page" order; null at either end or when the lesson is not on this page */ function adjacentLesson(ref, dir) { var list = state.pageLessons || []; if (!ref || !list.length) { return null; } for (var i = 0; i < list.length; i++) { if ((ref.slug && list[i].slug === ref.slug) || (!ref.slug && ref.qid && +list[i].qid === +ref.qid)) { return list[i + dir] || null; } } return null; } /* open a lesson's pictures at picture 1, paused (Previous / Next Lesson); lessons without pictures are skipped in the same direction */ function openLesson(item, dir) { api('lesson', item.slug ? { slug: item.slug, page: CFG.pageWithQuery } : { id: item.qid, page: CFG.pageWithQuery }).then(function (r) { var script = r.success && r.data ? r.data.script : null; var pics = script && script.steps && script.steps.some(function (st) { return st.shot_url; }); if (pics) { openSlides(r.data.title || item.title, script.steps, 0, { slug: item.slug, qid: item.qid }); if (state.slides) { state.slides.playing = false; clearTimeout(state.slides.timer); renderSlide(); } return; } var beyond = adjacentLesson({ slug: item.slug, qid: item.qid }, dir); if (beyond) { openLesson(beyond, dir); } }).catch(function () {}); } function closeVideo() { var wrap = document.getElementById('sa-video'); var v = wrap.querySelector('video'); v.pause(); v.removeAttribute('src'); v.load(); if (state.slides) { clearTimeout(state.slides.timer); state.slides = null; } wrap.classList.remove('open'); } function feedback(v, holder) { holder.innerHTML = 'Thanks for the feedback.'; if (!state.logId) { return; } api('feedback', { log_id: state.logId, helpful: v, page: CFG.pageWithQuery }, { post: true }).catch(function () {}); } /* ------------------------------------------------------- admin: lessons */ function pill(l) { if (l.state === 'published') { return 'v' + l.version + (l.health === 'stale' ? ' · needs review' : (l.health === 'ok' ? ' · OK' : ' · unchecked')) + ''; } if (l.state === 'legacy') { return 'old steps'; } return 'no steps'; } function showLessons() { state.view = 'lessons'; state.lastQuery = ''; var b = body(); b.innerHTML = '
Loading lessons…
'; api('lessons_admin', { page: CFG.pageWithQuery }).then(function (r) { if (!r.success) { b.innerHTML = '
' + esc(r.msg) + '
'; return; } state.admin = r.data; if (!r.data.installed) { b.innerHTML = '
Run support-agent/install.sql to enable living guides (support_lessons table missing).
'; return; } var html = '
Lessons in ' + esc(CFG.label) + '
' + '
Edit changes the words and pictures (published as the next version). ▲ ▼ set the order guides are shown in on the page.
'; html += r.data.lessons.map(function (l) { var sl = esc(l.slug || ''); return '
' + esc(l.title) + ' ' + pill(l) + (l.draft_id ? 'draft #' + l.draft_id + '' : '') + rrPill(l.rerecord) + '
' + '
' + (l.roles && l.roles.length ? 'for: ' + esc(l.roles.join(', ')) + ' ' : 'everyone ') + esc(l.category) + ' · ' + l.steps + ' step' + (l.steps === 1 ? '' : 's') + (l.state === 'published' ? ' · ' + l.pictures + ' picture' + (l.pictures === 1 ? '' : 's') : '') + (l.checked_at ? ' · checked ' + esc(String(l.checked_at).slice(0, 16)) : '') + '
' + '
' + (l.steps ? '' : '') + (l.slug && l.state === 'published' && !l.draft_id ? '' : '') + '' + (l.slug && l.state === 'published' ? '' : '') + (l.draft_id ? '' : '') + '' + (l.slug ? '' + '' : '') + '
'; }).join(''); b.innerHTML = html; }); } function startRecording(questionId, title, slug) { var g = guide(); if (!g) { alert('guide.js did not load on this page.'); return; } if (!questionId && !slug) { title = prompt('Title of the new lesson (e.g. "How to transfer items")', '') || ''; if (!title.trim()) { return; } } api('lesson_start', { question_id: questionId || 0, slug: slug || '', title: title || '', mode: 'record' }, { post: true }).then(function (r) { if (!r.success) { alert(r.msg || 'Could not start recording.'); return; } g.record.start(r.data.lesson_id, { questionId: questionId || null, title: title || '' }); }); } function startRecapture(questionId, slug) { var g = guide(); if (!g) { alert('guide.js did not load on this page.'); return; } api('lesson_start', { question_id: questionId || 0, slug: slug || '', mode: 'recapture' }, { post: true }).then(function (r) { if (!r.success) { alert(r.msg || 'Could not start.'); return; } g.start(+questionId || 0, { mode: 'capture', slug: slug || null, lessonId: r.data.lesson_id, lesson: r.data.script }); }); } /* ----------------------------------------- admin: Auto Record again (queue) */ var RR_LABEL = { pending: 'waiting to be recorded', in_progress: 'being recorded', done: 'recorded again', failed: 'recording failed', cancelled: 'cancelled' }; function rrPill(rr) { if (!rr || rr.status === 'cancelled') { return ''; } var cls = rr.status === 'done' ? 'rr-done' : (rr.status === 'failed' ? 'rr-failed' : 'rr'); var when = String((rr.status === 'done' || rr.status === 'failed' ? rr.finished_at : rr.requested_at) || '').slice(0, 10); return '⚙ ' + esc(RR_LABEL[rr.status] || rr.status) + (when ? ' ' + esc(when) : '') + ''; } function rrDetail(cardEl) { var d = cardEl.querySelector('.sa-detail'); if (!d) { d = document.createElement('div'); d.className = 'sa-detail'; cardEl.appendChild(d); } return d; } function openRerecord(btn) { var cardEl = btn.closest('.sa-card'), slug = btn.getAttribute('data-slug'); var d = rrDetail(cardEl); if (d.querySelector('.sa-rr')) { d.innerHTML = ''; return; } // second click closes it d.innerHTML = '
Loading…
'; api('rerecord_history', { slug: slug }).then(function (r) { if (!r.success) { d.innerHTML = '
' + esc(r.msg || 'Could not load.') + '
'; return; } var x = r.data, open = x.open; var hist = (x.history || []).filter(function (h) { return !open || h.request_key !== open.request_key; }); var html = '
⚙ Auto Record again
' + '
Write what should change in this guide, for example which record or month to show, a step to add or drop, or wording to use. Leave it empty to record the guide again as it is on the current screens. After Proceed, the guide is recorded again by Claude Code, with new pictures, slideshow and PDF, and published as the next version.
' + '
Guide script: ' + (x.lesson_file ? 'pms/support-agent/' + esc(x.lesson_file) + '' : 'no lesson file found (it can still be queued; Claude Code will create one)') + '
' + '
Instructions are kept in pms/support-agent/' + esc(x.prompt_file) + ' so the same guide can be regenerated on any computer.
'; if (open) { html += '
' + esc(RR_LABEL[open.status] || open.status) + ' since ' + esc(String(open.requested_at).slice(0, 16)) + ' (' + esc(open.request_key) + ')' + '
' + esc(open.prompts || '(no instructions: record as it is)') + '
' + (open.status === 'pending' ? '
' : '') + '
To run it: open Claude Code in the karibu-pms folder and say Process the Support Assistant re-record requests.
'; } else { html += '' + '
'; } if (hist.length) { html += ''; } d.innerHTML = html + '
'; var ta = d.querySelector('.sa-rr-text'); if (ta) { ta.focus(); } }); } function submitRerecord(btn) { var box = btn.closest('.sa-rr'), slug = box.getAttribute('data-slug'); var text = (box.querySelector('.sa-rr-text') || {}).value || ''; btn.disabled = true; api('rerecord_request', { slug: slug, prompts: text }, { post: true }).then(function (r) { btn.disabled = false; if (!r.success) { alert(r.msg || 'Could not queue the request.'); return; } var req = r.data.request; box.innerHTML = '
⚙ Auto Record again: request saved
' + '
Reference ' + esc(req.request_key) + '. The instructions were saved' + (r.data.prompt_file_written ? ' in pms/support-agent/' + esc(r.data.prompt_file) + ' and' : '') + ' in the recording queue.
' + '
To record it now: open Claude Code in the karibu-pms folder (this computer or any computer with this project) and say Process the Support Assistant re-record requests. The guide is recorded again with your instructions and published as the next version; its card here then shows recorded again.
' + '
'; var t = box.closest('.sa-card').querySelector('.sa-t'); if (t && !t.querySelector('.sa-pill.rr')) { t.insertAdjacentHTML('beforeend', rrPill({ key: req.request_key, status: 'pending', requested_at: req.requested_at })); } }); } /* ------------------------------------------------- admin: review draft */ function reviewLesson(lessonId) { if (!state.open) { toggle(); } state.view = 'review'; state.lastQuery = ''; var b = body(); b.innerHTML = '
Loading draft…
'; Promise.all([api('lesson_draft', { lesson_id: lessonId, page: CFG.pageWithQuery }), state.admin ? Promise.resolve({ success: true, data: state.admin }) : api('lessons_admin', { page: CFG.pageWithQuery })]).then(function (rs) { var r = rs[0], a = rs[1]; if (!r.success) { b.innerHTML = '
' + esc(r.msg) + '
'; return; } state.admin = a.success ? a.data : state.admin; var L = r.data; var qOpts = '' + ((state.admin && state.admin.lessons) || []).filter(function (l) { return l.question_id > 0; }).map(function (l) { return ''; }).join(''); var cOpts = ((state.admin && state.admin.categories) || []).map(function (c) { return ''; }).join(''); var roleList = (state.admin && state.admin.roles) || []; var current = (L.audience && L.audience.roles) || []; var rOpts = roleList.map(function (r) { return ''; }).join(''); var legacyAttach = (((state.admin && state.admin.categories) || []).length && qOpts.indexOf('