/* 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 '