/* Support Assistant - Guide Me v2, capture, health check and recorder ("living guides"). * --------------------------------------------------------------------------- * Loaded by widget.php on enabled-module pages (after widget.js). Everything works offline. * * SupportGuide.start(questionId, {mode:'guide'|'capture', step, lessonId, lesson}) * SupportGuide.resume() - continues a walkthrough / capture after a page change * SupportGuide.health() - resolves this page's published lesson targets, reports stale ones * SupportGuide.record.start(lessonId) / finish() / cancel() * SupportGuide.resolve(step) / derive(element) - the target matcher (also used by the HQ runner) * * A step target is a matcher, never a CSS class: * { id?, data?, onclick?, role?: button|menu|tab|field|combo|gridheader, text?, name?, legacyClass?, css? } * resolved inside `within` (a dialog body id such as "#dlg-stock") when given. */ (function () { if (window.SupportGuide || !window.SUPPORT_AGENT) { return; } var CFG = window.SUPPORT_AGENT; var ACCENT = CFG.color || '#9b59b6'; var Z = 99980; var $ = window.jQuery; /* ------------------------------------------------------------- utils */ function esc(s) { return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) { return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]; }); } function norm(s) { return String(s == null ? '' : s).replace(/\s+/g, ' ').trim().toLowerCase(); } function api(action, params, opts) { opts = opts || {}; var qs = Object.keys(params || {}).map(function (k) { return encodeURIComponent(k) + '=' + encodeURIComponent(params[k]); }).join('&'); 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; } return fetch(url, init).then(function (r) { return r.json(); }); } function store(key, val) { try { if (val === null) { sessionStorage.removeItem(key); } else { sessionStorage.setItem(key, JSON.stringify(val)); } } catch (e) {} } function load(key) { try { return JSON.parse(sessionStorage.getItem(key) || 'null'); } catch (e) { return null; } } 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) { 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) { // link to a step's page (menu links are extensionless) var p = normPage(stepPage); return CFG.base + p.replace(/\?/, '?'); } /* ----------------------------------------------------------- matcher */ function visible(el) { if (!el || !el.getClientRects) { return false; } if (!(el.offsetWidth || el.offsetHeight || el.getClientRects().length)) { return false; } var cs = getComputedStyle(el); return cs.visibility !== 'hidden' && cs.display !== 'none'; } function labelOf(el) { if (!el) { return ''; } var t = el.querySelector && el.querySelector('.l-btn-text, .menu-text, .tabs-title'); if (t) { return norm(t.textContent); } if (/^(INPUT|SELECT|TEXTAREA)$/.test(el.tagName) || /\bcombo\b/.test(el.className || '')) { var input = el.tagName === 'INPUT' || el.tagName === 'SELECT' || el.tagName === 'TEXTAREA' ? el : (el.previousElementSibling && /^(INPUT|SELECT)$/.test(el.previousElementSibling.tagName) ? el.previousElementSibling : null); if (input && /^(button|submit)$/i.test(input.type || '')) { return norm(input.value); } var lb = input && input.id ? document.querySelector('label[for="' + input.id + '"]') : null; if (!lb && input && input.closest) { lb = input.closest('label'); } if (lb) { return norm(lb.textContent).replace(/:$/, ''); } return norm((input && (input.placeholder || input.getAttribute('comboname') || input.name)) || ''); } return norm(el.textContent); } function genericId(id) { return !id || /^(_easyui|easyui|combo|datagrid-row|dg-|tooltip)/i.test(id) || /^\d+$/.test(id) || /\d{4,}/.test(id); } function presentable(el) { // EasyUI hides the original input behind a .combo wrapper if (!el) { return el; } if (!visible(el)) { var own = el.nextElementSibling; // EasyUI inserts the wrapper right after its input; several combos can share one parent if (own && /\bcombo\b|\bnumberbox\b|\bdatebox\b|\btextbox\b/.test(own.className || '') && visible(own)) { return own; } var c = el.parentNode && el.parentNode.querySelector && Array.from(el.parentNode.children).find(function (s) { return s !== el && /\bcombo\b|\bnumberbox\b|\bdatebox\b|\btextbox\b/.test(s.className || '') && visible(s); }); if (c) { return c; } var lb = el.closest && el.closest('a.l-btn'); if (lb && visible(lb)) { return lb; } } return el; } /* target.frame: the control lives in a same-origin iframe of the page (e.g. the Leave Calendar in #ThumbFrame on hr/schedule). null doc = frame missing or not loaded yet (unknown, not stale). */ function docFor(t) { if (!t || !t.frame) { return document; } var f = null; try { f = document.querySelector(t.frame); } catch (e) { f = null; } var d = null; try { d = f && f.contentDocument; } catch (e) { d = null; } return d && d.readyState === 'complete' && d.body ? d : null; } /* Rectangle of an element in THIS window's coordinates (adds the iframe offset for framed controls). */ function rectOf(el) { var r = el.getBoundingClientRect(); var fe = null; try { fe = el.ownerDocument !== document && el.ownerDocument.defaultView ? el.ownerDocument.defaultView.frameElement : null; } catch (e) { fe = null; } if (!fe) { return r; } var fr = fe.getBoundingClientRect(), dx = fr.left + fe.clientLeft, dy = fr.top + fe.clientTop; return { left: r.left + dx, top: r.top + dy, right: r.right + dx, bottom: r.bottom + dy, width: r.width, height: r.height, x: r.left + dx, y: r.top + dy }; } function scopeFor(step, doc) { doc = doc || document; if (!step || !step.within) { return { root: doc, closed: false }; } var w = null; try { w = doc.querySelector(step.within); } catch (e) { w = null; } if (!w) { return { root: doc, closed: true, missing: true }; } var win = w.closest('.window') || w; // the whole EasyUI window: toolbar + content + button bar return { root: win, closed: !visible(win) }; } function firstVisible(list, root) { var arr = Array.from(list || []).map(presentable).filter(function (el) { return el && visible(el) && (!root || root.nodeType === 9 || root.contains(el)); }); return arr; } var ROLE_SEL = { button: 'a.l-btn, button, input[type="button"], input[type="submit"], .easyui-linkbutton', menu: '#sidebar-menu a.menu-item, #sidebar-menu a', tab: '.tabs-title', gridheader: '.datagrid-header .datagrid-cell', field: 'input, select, textarea', combo: '.combo' }; function byText(root, role, text) { var want = norm(text); if (!want) { return []; } if (role === 'gridcell') { // the grid ROW whose cell text equals the label (e.g. a status) var rows = []; Array.from(root.querySelectorAll('.datagrid-btable tr.datagrid-row')).forEach(function (tr) { if (Array.from(tr.querySelectorAll('.datagrid-cell')).some(function (c) { return norm(c.textContent) === want; })) { rows.push(tr); } }); return rows; } var sel = ROLE_SEL[role] || (ROLE_SEL.button + ', ' + ROLE_SEL.menu + ', ' + ROLE_SEL.tab); var out = []; Array.from(root.querySelectorAll(sel)).forEach(function (el) { if (labelOf(el) === want) { out.push(role === 'gridheader' ? (el.closest('td') || el) : el); } }); if (!out.length && (role === 'field' || role === 'combo' || !role)) { // label text -> control Array.from(root.querySelectorAll('label')).forEach(function (lb) { if (norm(lb.textContent).replace(/:$/, '') === want.replace(/:$/, '')) { var ctrl = lb.htmlFor ? (lb.ownerDocument || document).getElementById(lb.htmlFor) : lb.querySelector('input, select, textarea'); if (ctrl) { out.push(ctrl); } } }); } return out; } /* resolve(step) -> { status: ok|ambiguous|closed|missing, el, matchedBy, label } */ function resolve(step) { var t = (step && step.target) || {}; var doc = docFor(t); if (!doc) { return { status: 'closed', el: null, matchedBy: '', label: '', frameNotReady: true }; } var sc = scopeFor(step, doc); if (sc.closed) { return { status: 'closed', el: null, matchedBy: '', label: '', dialogMissing: !!sc.missing }; } var root = sc.root; var tries = []; if (t.id) { tries.push(['id', function () { var el = doc.getElementById(t.id); return el ? [el] : []; }]); } if (t.data) { tries.push(['data', function () { return root.querySelectorAll('[data-guide="' + t.data.replace(/"/g, '') + '"]'); }]); } if (t.onclick) { tries.push(['onclick', function () { var want = norm(t.onclick).replace(/;\s*$/, ''); return Array.from(root.querySelectorAll('[onclick]')).filter(function (el) { return norm(el.getAttribute('onclick')).replace(/;\s*$/, '') === want; }); }]); } if (t.text) { tries.push(['text', function () { return byText(root, t.role, t.text); }]); } if (t.name) { tries.push(['name', function () { var n = t.name.replace(/"/g, ''); return root.querySelectorAll('[name="' + n + '"], [comboname="' + n + '"]'); }]); } if (t.legacyClass) { tries.push(['legacyClass', function () { return root.querySelectorAll('.' + t.legacyClass.replace(/[^a-zA-Z0-9_\-]/g, '')); }]); } if (t.css) { tries.push(['css', function () { try { return root.querySelectorAll(t.css); } catch (e) { return []; } }]); } for (var i = 0; i < tries.length; i++) { var found; try { found = firstVisible(tries[i][1](), root); } catch (e) { found = []; } if (found.length === 1) { return { status: 'ok', el: found[0], matchedBy: tries[i][0], label: labelOf(found[0]) }; } if (found.length > 1) { return { status: 'ambiguous', el: found[0], matchedBy: tries[i][0], label: labelOf(found[0]), count: found.length }; } } return { status: 'missing', el: null, matchedBy: '', label: '' }; } function waitFor(step, ms, cb) { var t0 = Date.now(); (function tick() { var r = resolve(step); if (r.status === 'ok' || r.status === 'ambiguous' || Date.now() - t0 > ms) { cb(r); return; } setTimeout(tick, 250); })(); } /* derive(el) -> {target, within, role, label, action} (recorder) */ function derive(el) { var hit = el.closest('a.l-btn, button, input[type="button"], input[type="submit"], #sidebar-menu a, .tabs-title, .datagrid-header td, .combo, label, input, select, textarea, a, [onclick]'); if (!hit) { return { el: null }; } // not a control (plain text, overlays, grid cells) if (hit.tagName === 'DIV' && !hit.getAttribute('onclick') && !hit.classList.contains('combo')) { return { el: null }; } var role = 'button', label = '', target = {}, action = 'click'; if (hit.closest('#sidebar-menu')) { role = 'menu'; hit = hit.closest('a') || hit; } else if (hit.classList.contains('tabs-title') || hit.closest('.tabs-title')) { role = 'tab'; hit = hit.closest('.tabs-title') || hit; } else if (hit.closest('.datagrid-header')) { role = 'gridheader'; hit = hit.closest('td') || hit; } else if (hit.classList.contains('combo') || hit.closest('.combo')) { role = 'combo'; hit = hit.closest('.combo') || hit; action = 'focus'; } else if (/^(INPUT|SELECT|TEXTAREA)$/.test(hit.tagName) && !/^(button|submit)$/i.test(hit.type || '')) { role = 'field'; action = 'focus'; } else if (hit.tagName === 'LABEL') { role = 'field'; action = 'focus'; var ctrl = hit.htmlFor ? document.getElementById(hit.htmlFor) : null; if (ctrl) { hit = ctrl; } } label = labelOf(hit); if (role === 'field' || role === 'combo') { var input = role === 'combo' ? (hit.previousElementSibling && /^(INPUT|SELECT)$/.test(hit.previousElementSibling.tagName) ? hit.previousElementSibling : hit.querySelector('input.combo-value') || hit) : hit; if (input && input.id && !genericId(input.id)) { target.id = input.id; } var name = (input && (input.getAttribute('comboname') || input.name)) || hit.getAttribute('comboname'); if (name && !target.id) { target.name = name; } var lb = input && input.id ? document.querySelector('label[for="' + input.id + '"]') : null; label = lb ? norm(lb.textContent).replace(/:$/, '') : (label || (input && input.placeholder ? norm(input.placeholder) : '')); if (label && !target.id && !target.name) { target.text = label; } } else { if (hit.id && !genericId(hit.id)) { target.id = hit.id; } if (hit.getAttribute('data-guide')) { target.data = hit.getAttribute('data-guide'); } var oc = hit.getAttribute('onclick'); if (oc && !target.id) { target.onclick = oc.trim(); } if (label) { target.text = label; } } if (label.length > 60) { return { el: null }; } // a whole panel's text is not a button label target.role = role; var within = null; var win = hit.closest('.window'); if (win) { var body = win.querySelector('.dialog-content[id], .panel-body[id], [id].dialog-content'); if (body && body.id) { within = '#' + body.id; } } var verb = role === 'field' ? 'Enter ' : role === 'combo' ? 'Choose ' : 'Click '; var caption = verb + (label ? label.replace(/\b\w/g, function (c) { return c.toUpperCase(); }) : 'here') + (within ? ' in the dialog.' : '.'); return { target: target, within: within, role: role, label: label, action: action, caption: caption, el: hit }; } /* ----------------------------------------------------------- overlay */ var ov = null, raf = 0, current = { el: null }; function ensureOverlay() { if (ov) { return ov; } var st = document.createElement('style'); st.textContent = '' + '#sag-hole{position:fixed;z-index:' + Z + ';pointer-events:none;border:3px solid #e53935;border-radius:6px;box-shadow:0 0 0 9999px rgba(0,0,0,.45);transition:all .15s;display:none}' + '#sag-hole.sag-light{box-shadow:0 0 0 9999px rgba(0,0,0,.18)}' + '#sag-hole.sag-nomask{box-shadow:none}' + '#sag-bubble{position:fixed;z-index:' + (Z + 2) + ';max-width:360px;background:#fffbe6;border:1px solid #e6c65c;border-radius:10px;box-shadow:0 10px 30px rgba(0,0,0,.35);font:13px/1.45 Arial,Helvetica,sans-serif;color:#2c3e50;padding:12px 14px;display:none}' + '#sag-bubble .sag-h{font-weight:700;color:#7a5a00;font-size:11px;text-transform:uppercase;letter-spacing:.4px;margin-bottom:4px}' + '#sag-bubble .sag-c{margin-bottom:10px;white-space:pre-line}' + '#sag-bubble .sag-a{display:flex;gap:6px;flex-wrap:wrap;align-items:center}' + '#sag-bubble button,#sag-bubble a.sag-btn{border:1px solid ' + ACCENT + ';background:#fff;color:' + ACCENT + ';border-radius:6px;padding:5px 10px;font-size:12px;cursor:pointer;text-decoration:none}' + '#sag-bubble button.sag-p{background:' + ACCENT + ';color:#fff}' + '#sag-bubble .sag-warn{color:#b23b3b;font-size:12px;margin-bottom:8px}' + '#sag-bubble .sag-arrow{position:absolute;width:0;height:0;border:9px solid transparent}' + '#sag-bubble.sag-below .sag-arrow{top:-18px;left:24px;border-bottom-color:#e6c65c}' + '#sag-bubble.sag-above .sag-arrow{bottom:-18px;left:24px;border-top-color:#e6c65c}' + '#sag-bubble img.sag-thumb{max-width:100%;border:1px solid #ddd;border-radius:4px;margin:6px 0}' + '#sag-rec{position:fixed;top:0;left:0;right:0;z-index:' + (Z + 5) + ';background:#e53935;color:#fff;font:600 13px Arial,sans-serif;padding:7px 14px;display:flex;gap:12px;align-items:center;box-shadow:0 2px 8px rgba(0,0,0,.3)}' + '#sag-rec .sag-dot{width:10px;height:10px;border-radius:50%;background:#fff;animation:sagblink 1s infinite}' + '#sag-rec button{border:1px solid #fff;background:transparent;color:#fff;border-radius:5px;padding:3px 9px;cursor:pointer;font-size:12px}' + '#sag-rec button.sag-p{background:#fff;color:#e53935}' + '@keyframes sagblink{50%{opacity:.2}}'; document.head.appendChild(st); var hole = document.createElement('div'); hole.id = 'sag-hole'; var bubble = document.createElement('div'); bubble.id = 'sag-bubble'; document.body.appendChild(hole); document.body.appendChild(bubble); bubble.addEventListener('click', function (e) { var b = e.target.closest('[data-sag]'); if (!b) { return; } var a = b.getAttribute('data-sag'); if (a === 'next') { next(); } else if (a === 'back') { back(); } else if (a === 'stop') { stop(); } else if (a === 'capture') { captureCurrent(); } else if (a === 'publish') { publishCurrent(); } else if (a === 'report') { reportCurrent(); } }); ov = { hole: hole, bubble: bubble }; return ov; } function placeBubble(rect) { var b = ov.bubble; b.style.display = 'block'; var bw = b.offsetWidth, bh = b.offsetHeight, vw = window.innerWidth, vh = window.innerHeight; var left = Math.min(Math.max(8, rect ? rect.left : (vw - bw) / 2), vw - bw - 8); var top; if (!rect) { top = vh - bh - 90; b.className = ''; } else if (rect.bottom + bh + 24 < vh) { top = rect.bottom + 14; b.className = 'sag-below'; } else if (rect.top - bh - 24 > 0) { top = rect.top - bh - 14; b.className = 'sag-above'; } else { top = Math.max(8, vh - bh - 20); b.className = ''; } b.style.left = left + 'px'; b.style.top = top + 'px'; } function highlight(el, light, noMask) { ensureOverlay(); current.el = el; cancelAnimationFrame(raf); (function loop() { if (current.el !== el) { return; } var r = rectOf(el); ov.hole.style.display = 'block'; ov.hole.className = noMask ? 'sag-nomask' : (light ? 'sag-light' : ''); ov.hole.style.left = (r.left - 6) + 'px'; ov.hole.style.top = (r.top - 6) + 'px'; ov.hole.style.width = (r.width + 12) + 'px'; ov.hole.style.height = (r.height + 12) + 'px'; raf = requestAnimationFrame(loop); })(); try { el.scrollIntoView({ block: 'center', inline: 'nearest' }); } catch (e) {} return rectOf(el); } function clearHighlight() { current.el = null; cancelAnimationFrame(raf); if (ov) { ov.hole.style.display = 'none'; ov.bubble.style.display = 'none'; } } /* ------------------------------------------------------------ runner */ var S = null; // {qid, lessonId, version, mode, step, lesson} function saveState() { store('sa_guide', S); } function clearLegacy() { ['steps', 'currenct_story_line_question_details', 'question_name', 'isLastStep', 'createdTooltips', 'tooltip_mode', 'setOnHardReloadTooltips', 'currentStep'].forEach(function (k) { try { sessionStorage.removeItem(k); } catch (e) {} }); } function start(questionId, opts) { opts = opts || {}; if ((opts.mode || 'guide') !== 'capture') { return; } // user-facing walkthroughs were retired (Read steps + slideshow + print instead) clearLegacy(); var go = function (lesson, lessonId) { if (!lesson || !lesson.steps || !lesson.steps.length) { alert('This lesson has no steps yet.'); return; } S = { qid: +questionId || 0, slug: opts.slug || lesson.slug || null, lessonId: lessonId || lesson.lesson_id || 0, version: lesson.version || 0, mode: opts.mode || 'guide', step: opts.step || 0, lesson: lesson }; saveState(); if (window.SupportAgent && window.SupportAgent.close) { window.SupportAgent.close(); } run(); }; if (opts.lesson) { go(opts.lesson, opts.lessonId); return; } var params = { draft: opts.mode === 'capture' ? 1 : 0 }; if (opts.slug) { params.slug = opts.slug; } else { params.id = questionId; } api('lesson_script', params).then(function (r) { if (!r.success) { alert(r.msg || 'Lesson not found.'); return; } go(r.data, r.data.lesson_id); }).catch(function () { alert('Could not load the lesson.'); }); } function stepHtml(step, extra, warn) { var n = S.step + 1, N = S.lesson.steps.length; var acts = ''; if (S.step > 0) { acts += ''; } if (S.mode === 'capture') { acts += ''; } acts += (S.step < N - 1) ? '' : (S.mode === 'capture' ? '' : ''); acts += ''; return '
' + esc(S.lesson.title || 'Guide') + ' · step ' + n + ' of ' + N + '
' + (warn ? '
' + warn + '
' : '') + '
' + esc(step.caption || '') + '
' + (extra || '') + '
' + acts + '
'; } var clickGuard = null; function armClickAdvance(el) { disarm(); clickGuard = function (e) { if (el && (el === e.target || el.contains(e.target))) { setTimeout(function () { if (S) { next(); } }, 650); } }; document.addEventListener('click', clickGuard, true); } function disarm() { if (clickGuard) { document.removeEventListener('click', clickGuard, true); clickGuard = null; } } function run() { if (!S) { return; } ensureOverlay(); var step = S.lesson.steps[S.step]; if (!step) { stop(); return; } if (!pageMatches(step.page)) { clearHighlight(); var href = pageHref(step.page); ov.bubble.innerHTML = '
' + esc(S.lesson.title || 'Guide') + ' · step ' + (S.step + 1) + ' of ' + S.lesson.steps.length + '
' + '
' + esc(step.caption || '') + '
' + '
This step happens on another screen.
' + '
Open that screen ›' + (S.step > 0 ? '' : '') + '
'; placeBubble(null); return; } waitFor(step, step.within ? 4000 : 1500, function (r) { if (!S) { return; } if (r.status === 'ok' || r.status === 'ambiguous') { var rect = highlight(r.el, S.mode === 'capture'); var warn = ''; if (step.label && r.label && norm(step.label) !== r.label) { warn = 'The button is now called "' + esc(r.label) + '" (was "' + esc(step.label) + '").'; } if (r.status === 'ambiguous') { warn += (warn ? ' ' : '') + 'Several matching controls were found; showing the first.'; } ov.bubble.innerHTML = stepHtml(step, step.shot_url && S.mode !== 'capture' ? '' : '', warn); placeBubble(rect); if (step.action === 'click' && S.mode === 'guide') { armClickAdvance(r.el); } else { disarm(); } } else { clearHighlight(); var why = r.status === 'closed' ? (r.dialogMissing ? 'The dialog this step refers to was not found on this screen.' : 'Open the dialog first (' + esc(step.within) + '), then press Next.') : 'The control for this step could not be found on this screen - it may have been renamed or moved.'; ov.bubble.innerHTML = stepHtml(step, '', why + (r.status === 'missing' ? ' ' : '')); placeBubble(null); if (r.status === 'missing') { reportStep(S.step, r); } } }); } function next() { if (!S) { return; } disarm(); if (S.step >= S.lesson.steps.length - 1) { stop(); return; } S.step++; saveState(); run(); } function back() { if (!S || S.step === 0) { return; } disarm(); S.step--; saveState(); run(); } function stop() { disarm(); clearHighlight(); S = null; store('sa_guide', null); } function resume() { var st = load('sa_guide'); if (!st || !st.lesson || st.mode !== 'capture') { store('sa_guide', null); return false; } S = st; setTimeout(run, 1200); // let EasyUI finish parsing return true; } /* ----------------------------------------------------------- capture */ var h2cLoading = null; function ensureHtml2canvas() { if (window.html2canvas) { return Promise.resolve(); } if (h2cLoading) { return h2cLoading; } h2cLoading = new Promise(function (res, rej) { var s = document.createElement('script'); s.src = CFG.base + 'js/html2canvas.min.js'; s.onload = function () { res(); }; s.onerror = function () { rej(new Error('html2canvas not available')); }; document.head.appendChild(s); }); return h2cLoading; } /* Capture the viewport (with the current highlight drawn), crop to the target's dialog or viewport, return a data URL. */ function capturePage(el, within) { return ensureHtml2canvas().then(function () { return (document.fonts && document.fonts.ready) ? document.fonts.ready : null; }).then(function () { var bubbleShown = ov && ov.bubble.style.display !== 'none'; if (ov) { ov.bubble.style.display = 'none'; ov.hole.style.boxShadow = 'none'; } // html2canvas paints the big spread shadow as a black block var hidden = []; ['sa-panel', 'sa-bubble', 'sag-rec'].forEach(function (id) { var e = document.getElementById(id); if (e && e.style.display !== 'none') { hidden.push([e, e.style.visibility]); e.style.visibility = 'hidden'; } }); var W = window.innerWidth, H = window.innerHeight; // Render from the document root: rendering document.body drops the fixed sidebar (tested 2026-09-15). return window.html2canvas(document.documentElement, { logging: false, useCORS: true, foreignObjectRendering: false, scale: Math.min(1.5, window.devicePixelRatio || 1), width: W, height: H, windowWidth: W, windowHeight: H, ignoreElements: function (n) { return n.tagName === 'IFRAME' || n.id === 'sa-panel' || n.id === 'sa-bubble' || n.id === 'sag-bubble' || n.id === 'sag-rec'; } }).then(function (canvas) { hidden.forEach(function (h) { h[0].style.visibility = h[1]; }); if (ov) { ov.hole.style.boxShadow = ''; if (bubbleShown) { ov.bubble.style.display = 'block'; } } var sc = canvas.width / W; var box = { x: 0, y: 0, w: W, h: H }; var win = null; if (within) { try { var d = document.querySelector(within); win = d && (d.closest('.window') || d); } catch (e) { win = null; } } if (win && visible(win)) { var r = win.getBoundingClientRect(), pad = 14; var x1 = Math.max(0, r.left - pad), y1 = Math.max(0, r.top - pad), x2 = Math.min(W, r.right + pad), y2 = Math.min(H, r.bottom + pad); if (el) { var er = el.getBoundingClientRect(); x1 = Math.min(x1, Math.max(0, er.left - pad)); y1 = Math.min(y1, Math.max(0, er.top - pad)); x2 = Math.max(x2, Math.min(W, er.right + pad)); y2 = Math.max(y2, Math.min(H, er.bottom + pad)); } box = { x: x1, y: y1, w: x2 - x1, h: y2 - y1 }; } var out = document.createElement('canvas'); out.width = Math.round(box.w * sc); out.height = Math.round(box.h * sc); out.getContext('2d').drawImage(canvas, Math.round(box.x * sc), Math.round(box.y * sc), out.width, out.height, 0, 0, out.width, out.height); var url = out.toDataURL('image/webp', 0.85); if (url.indexOf('image/webp') < 0) { url = out.toDataURL('image/png'); } return url; }); }); } function captureCurrent() { if (!S || !S.lessonId) { alert('Captures need a draft lesson (use Re-capture from the Lessons list).'); return; } var step = S.lesson.steps[S.step]; var el = current.el; var btn = ov.bubble.querySelector('[data-sag="capture"]'); if (btn) { btn.disabled = true; btn.textContent = 'Capturing…'; } capturePage(el, step.within).then(function (dataUrl) { return api('capture_save', { lesson_id: S.lessonId, step: S.step, image: dataUrl }, { post: true }); }).then(function (r) { if (!r.success) { throw new Error(r.msg || 'save failed'); } step.shot = r.data.shot; step.shot_url = r.data.shot_url; saveState(); ov.bubble.innerHTML = stepHtml(step, '', ''); var b2 = ov.bubble.querySelector('[data-sag="capture"]'); if (b2) { b2.textContent = '✓ Captured - retake'; } placeBubble(el ? el.getBoundingClientRect() : null); }).catch(function (e) { if (btn) { btn.disabled = false; btn.textContent = '📷 Capture'; } alert('Capture failed: ' + e.message); }); } function publishCurrent() { if (!S || !S.lessonId) { stop(); return; } var id = S.lessonId; api('lesson_publish', { lesson_id: id }, { post: true }).then(function (r) { if (!r.success) { alert(r.msg || 'Publish failed.'); return; } stop(); alert('Lesson published (version ' + r.data.version + ').'); if (window.SupportAgent && window.SupportAgent.open) { window.SupportAgent.open(); } }); } /* ------------------------------------------------------------ health */ function reportStep(i, r) { if (!S || !S.lessonId || S.lesson.status !== 'published') { return; } api('health_report', { lesson_id: S.lessonId, results: JSON.stringify([{ i: i, ok: false, matchedBy: '', reason: r.status, label_now: r.label || '' }]) }, { post: true }).catch(function () {}); } function reportCurrent() { if (S) { reportStep(S.step, { status: 'missing' }); alert('Thanks - the lesson has been flagged for review.'); } } /* Controls that exist only for a moment: an item of a drop-down list or menu (present when the list is open), a button of a question box ($.messager Yes / No / Ok / Cancel, shown only when the page asks), or a step marked "transient" in its lesson. Missing = unknown, never stale. */ function transientTarget(t) { t = t || {}; if (t.transient) { return true; } if (/combobox-item|menu-item|messager/.test(String(t.css || ''))) { return true; } return (t.role === 'button' || !t.role) && /^(yes|no|ok|cancel)$/i.test(String(t.text || '').trim()); } function health() { var key = 'sa_health:' + CFG.pageWithQuery; var seen = load(key) || {}; return api('health_targets', {}).then(function (r) { if (!r.success) { return; } (r.data.lessons || []).forEach(function (L) { var k = L.lesson_id + ':' + L.version; if (seen[k]) { return; } var results = []; L.steps.forEach(function (s) { var res = resolve({ within: s.within, target: s.target }); if (res.status === 'closed') { return; } // dialog not open: unknown, not stale var dataRow = s.target && (s.target.role === 'gridcell' || /datagrid-(row|cell|btable)/.test(String(s.target.css || ''))); if (res.status === 'missing' && dataRow) { return; } // a grid row depends on the data this user sees (and on the grid having loaded): unknown, not stale if (res.status === 'missing' && transientTarget(s.target)) { return; } // exists only for a moment (drop-down item, question box button): unknown, not stale results.push({ i: s.i, ok: res.status === 'ok' || res.status === 'ambiguous', matchedBy: res.matchedBy, reason: res.status, label_now: res.label }); }); if (!results.length) { return; } seen[k] = Date.now(); store(key, seen); api('health_report', { lesson_id: L.lesson_id, results: JSON.stringify(results) }, { post: true }).catch(function () {}); }); }).catch(function () {}); } /* ---------------------------------------------------------- recorder */ var R = null, recBar = null, recClick = null, lastRec = { el: null, t: 0 }; function recUi() { ensureOverlay(); if (recBar) { return recBar; } recBar = document.createElement('div'); recBar.id = 'sag-rec'; document.body.appendChild(recBar); recBar.addEventListener('click', function (e) { var b = e.target.closest('[data-rec]'); if (!b) { return; } var a = b.getAttribute('data-rec'); if (a === 'pause') { R.paused = !R.paused; store('sa_rec', R); renderRec(); } else if (a === 'finish') { recFinish(); } else if (a === 'cancel') { if (confirm('Discard this recording?')) { recCancel(); } } else if (a === 'undo') { if (R.steps.length) { R.steps.pop(); store('sa_rec', R); recSave(); renderRec(); } } }); return recBar; } function renderRec() { recUi().innerHTML = '' + (R.paused ? 'Recording paused' : 'Recording lesson') + ' · ' + R.steps.length + ' step' + (R.steps.length === 1 ? '' : 's') + '' + '' + (R.paused ? 'Clicks are not recorded.' : 'Do the task normally - every click becomes a step.') + '' + ''; } function recSave() { if (!R) { return Promise.resolve(); } return api('lesson_save', { lesson_id: R.lessonId, lesson: JSON.stringify({ version: 0, question_id: R.questionId || null, title: R.title || '', steps: R.steps }) }, { post: true }).catch(function () {}); } function recStart(lessonId, opts) { opts = opts || {}; R = { lessonId: +lessonId, questionId: opts.questionId || null, title: opts.title || '', steps: [], paused: false, active: true }; store('sa_rec', R); recListen(); renderRec(); if (window.SupportAgent && window.SupportAgent.close) { window.SupportAgent.close(); } } function recListen() { if (recClick) { return; } recClick = function (e) { if (!R || R.paused) { return; } if (e.isTrusted === false) { return; } // pages fire synthetic clicks (e.g. resetting checkboxes) - not user steps if (e.target.closest('#sag-rec, #sa-panel, #sa-bubble, #sag-bubble, #sa-video')) { return; } var d = derive(e.target); if (!d.el || (d.role === 'button' && !d.label && !d.target.id && !d.target.onclick)) { return; } if (lastRec.el === d.el && Date.now() - lastRec.t < 600) { return; } lastRec = { el: d.el, t: Date.now() }; var step = { page: normPage(CFG.pageWithQuery), within: d.within, target: d.target, action: d.action, caption: d.caption, label: d.label, shot: null }; R.steps.push(step); var idx = R.steps.length - 1; store('sa_rec', R); renderRec(); // picture: highlight synchronously (html2canvas clones the DOM at call time), upload asynchronously try { highlight(d.el, true); capturePage(d.el, d.within).then(function (url) { clearHighlight(); return api('capture_save', { lesson_id: R.lessonId, step: idx, image: url }, { post: true }); }).then(function (r) { if (r && r.success && R && R.steps[idx]) { R.steps[idx].shot = r.data.shot; store('sa_rec', R); } recSave(); }).catch(function () { clearHighlight(); recSave(); }); } catch (err) { clearHighlight(); recSave(); } }; document.addEventListener('click', recClick, true); } function recFinish() { var id = R.lessonId; recSave().then(function () { recTeardown(); if (window.SupportAgent && window.SupportAgent.reviewLesson) { window.SupportAgent.reviewLesson(id); } else { alert('Recording saved as draft #' + id + '. Open the Support Assistant › Lessons to review it.'); } }); } function recCancel() { var id = R.lessonId; recTeardown(); api('lesson_discard', { lesson_id: id }, { post: true }).catch(function () {}); } function recTeardown() { if (recClick) { document.removeEventListener('click', recClick, true); recClick = null; } if (recBar) { recBar.remove(); recBar = null; } clearHighlight(); R = null; store('sa_rec', null); } function recResume() { var r = load('sa_rec'); if (!r || !r.active) { return false; } R = r; recListen(); renderRec(); return true; } /* ------------------------------------------------------------ public */ window.SupportGuide = { start: start, resume: resume, stop: stop, next: next, back: back, run: run, health: health, resolve: resolve, derive: derive, capturePage: capturePage, highlight: highlight, clearHighlight: clearHighlight, rectOf: rectOf, transientTarget: transientTarget, pageMatches: pageMatches, normPage: normPage, record: { start: recStart, finish: recFinish, cancel: recCancel, resume: recResume, active: function () { return !!R; }, state: function () { return R; } }, state: function () { return S; } }; function boot() { if (!resume()) { recResume(); } setTimeout(health, 3500); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', boot); } else { boot(); } })();