Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Add reusable guided tour engine; wire dashboard orientation and first-meet tours
nirholasff0ab6d45528
diff --git a/data/changelog.json b/data/changelog.jsonindex e86ed1a9d..5bc6a4ba7 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -2756,6 +2756,15 @@"improvement"],"link": "/features"+ },+ {+ "date": "2026-06-16",+ "title": "Guided tour engine — spotlight coachmarks with server-backed persistence",+ "summary": "Built a reusable in-app tour engine that any page can use with a simple declarative step list. Tours spotlight DOM elements with an animated overlay, show contextual tooltips with Back/Next/Skip controls, handle keyboard navigation (arrows + Escape), announce each step to screen readers, and remember completion in both localStorage and the server (so tours don't re-appear across devices). The dashboard now shows a 4-step orientation tour to new accounts pointing out the nav, creations, KPIs, and quick actions.",+ "tags": [+ "feature"+ ],+ "link": "/dashboard"}]}diff --git a/public/tour.js b/public/tour.jsnew file mode 100644index 000000000..b6587470b--- /dev/null+++ b/public/tour.js@@ -0,0 +1,352 @@+/**+ * three.ws tour engine — reusable guided spotlight/coachmark system+ *+ * API:+ * startTour(steps, options) → Promise<'completed' | 'skipped'>+ *+ * steps: Array<{+ * target: string | (() => Element | null), // CSS selector or function+ * title: string,+ * body: string,+ * placement: 'auto' | 'above' | 'below', // default 'auto'+ * action?: (el: Element) => void, // called after spotlight+ * }>+ *+ * options: {+ * id: string, // namespaced key for persistence+ * onComplete: () => void,+ * onSkip: () => void,+ * }+ *+ * Persistence:+ * - localStorage key: `tour:${id}:done`+ * - When signed in, syncs to /api/dashboard/prefs (PATCH tours.${id} = true)+ * - isTourDone(id) checks both localStorage and prefs cache+ *+ * Accessibility:+ * - ARIA live region announces each step+ * - role="dialog" + aria-modal="false" on bubble+ * - focus moves to primary action button each step+ * - Escape → skip; ←/→ arrows navigate+ * - Backdrop click → skip+ */++const PREFS_URL = '/api/dashboard/prefs';+const _prefsCacheKey = 'tour:prefs:cache';+const _prefsCache = (() => {+ try { return JSON.parse(localStorage.getItem(_prefsCacheKey) || '{}'); } catch { return {}; }+})();++function _savePrefsCache() {+ try { localStorage.setItem(_prefsCacheKey, JSON.stringify(_prefsCache)); } catch {}+}++function _lsKey(id) { return `tour:${id}:done`; }++export function isTourDone(id) {+ if (localStorage.getItem(_lsKey(id))) return true;+ return !!_prefsCache.tours?.[id];+}++export function markTourDone(id) {+ localStorage.setItem(_lsKey(id), '1');+ // Best-effort server sync+ fetch(PREFS_URL, {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ prefs: { tours: { ..._prefsCache.tours, [id]: true } } }),+ }).then(r => {+ if (r.ok) {+ _prefsCache.tours = { ..._prefsCache.tours, [id]: true };+ _savePrefsCache();+ }+ }).catch(() => {});+}++// Pull latest prefs from server into local cache (called on page load if desired)+export function syncTourPrefs() {+ fetch(PREFS_URL, { credentials: 'include' })+ .then(r => r.ok ? r.json() : null)+ .then(data => {+ if (data?.prefs?.tours) {+ _prefsCache.tours = { ..._prefsCache.tours, ...data.prefs.tours };+ _savePrefsCache();+ // Mark any server-done tours done in localStorage too+ for (const [id, done] of Object.entries(data.prefs.tours)) {+ if (done) localStorage.setItem(_lsKey(id), '1');+ }+ }+ })+ .catch(() => {});+}++function esc(s) {+ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));+}++function waitFor(selector, ms = 2000) {+ return new Promise(resolve => {+ const el = document.querySelector(selector);+ if (el) { resolve(el); return; }+ const obs = new MutationObserver(() => {+ const found = document.querySelector(selector);+ if (found) { obs.disconnect(); resolve(found); }+ });+ obs.observe(document.body, { childList: true, subtree: true });+ setTimeout(() => { obs.disconnect(); resolve(null); }, ms);+ });+}++const SPOT_PAD = 8;++function positionBubble(bubble, targetRect, placement) {+ const vw = window.innerWidth;+ const vh = window.innerHeight;+ const bw = Math.min(300, vw - 32);+ bubble.style.width = `${bw}px`;++ // Horizontal centering over target+ const left = Math.max(16, Math.min(targetRect.left + targetRect.width / 2 - bw / 2, vw - bw - 16));+ bubble.style.left = `${left}px`;++ const spaceBelow = vh - targetRect.bottom;+ const spaceAbove = targetRect.top;+ const goBelow = placement === 'below' || (placement !== 'above' && spaceBelow >= 160) || spaceAbove < 160;++ if (goBelow) {+ bubble.style.top = `${targetRect.bottom + SPOT_PAD + 6}px`;+ bubble.style.bottom = '';+ } else {+ bubble.style.top = '';+ bubble.style.bottom = `${vh - targetRect.top + SPOT_PAD + 6}px`;+ }+}++function injectStyles() {+ if (document.getElementById('tour-engine-css')) return;+ const style = document.createElement('style');+ style.id = 'tour-engine-css';+ style.textContent = `+.tour-overlay {+ position: fixed; inset: 0; z-index: 10000;+ background: rgba(0,0,0,0.55);+ pointer-events: all;+}+.tour-spotlight {+ position: fixed; z-index: 10001;+ border-radius: 8px;+ box-shadow: 0 0 0 9999px rgba(0,0,0,0.55), 0 0 0 2px rgba(255,255,255,0.18);+ pointer-events: none;+ transition: top .22s, left .22s, width .22s, height .22s;+}+.tour-bubble {+ position: fixed; z-index: 10002;+ background: var(--panel, #18181b);+ border: 1px solid var(--border, rgba(255,255,255,0.1));+ border-radius: 12px;+ padding: 16px;+ box-shadow: 0 8px 32px rgba(0,0,0,0.45);+ pointer-events: all;+ animation: tourFadeIn .18s ease;+}+@keyframes tourFadeIn { from { opacity:0; transform:translateY(4px) } to { opacity:1; transform:none } }+.tour-meta {+ font-size: 11px;+ color: var(--ink-dim, rgba(255,255,255,0.4));+ margin-bottom: 4px;+ font-weight: 600;+ letter-spacing: .04em;+ text-transform: uppercase;+}+.tour-title {+ font-size: 15px;+ font-weight: 700;+ color: var(--text, #fff);+ margin-bottom: 6px;+ line-height: 1.3;+}+.tour-body {+ font-size: 13px;+ color: var(--ink-dim, rgba(255,255,255,0.65));+ margin: 0 0 14px;+ line-height: 1.5;+}+.tour-nav {+ display: flex;+ align-items: center;+ gap: 8px;+}+.tour-skip {+ font-size: 12px;+ color: var(--ink-dim, rgba(255,255,255,0.45));+ background: none;+ border: none;+ padding: 4px 0;+ cursor: pointer;+ margin-right: auto;+}+.tour-skip:hover { color: var(--text, #fff); }+.tour-btn-ghost {+ font-size: 13px;+ padding: 6px 12px;+ background: var(--panel-2, rgba(255,255,255,0.06));+ border: 1px solid var(--border, rgba(255,255,255,0.1));+ border-radius: 6px;+ color: var(--text, #fff);+ cursor: pointer;+ transition: background .15s;+}+.tour-btn-ghost:hover { background: var(--panel-3, rgba(255,255,255,0.12)); }+.tour-btn-primary {+ font-size: 13px;+ padding: 6px 14px;+ background: var(--accent, #6366f1);+ border: none;+ border-radius: 6px;+ color: #fff;+ font-weight: 600;+ cursor: pointer;+ transition: background .15s;+}+.tour-btn-primary:hover { background: var(--accent-hi, #818cf8); }+.tour-sr-only { position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; }+[data-tour-target] { position: relative; z-index: 10001; border-radius: 6px; outline: 2px solid rgba(99,102,241,0.6); outline-offset: 3px; }+`;+ document.head.appendChild(style);+}++export function startTour(steps, { id, onComplete, onSkip } = {}) {+ if (id && isTourDone(id)) return Promise.resolve('completed');++ injectStyles();++ return new Promise(resolve => {+ const overlay = document.createElement('div');+ overlay.className = 'tour-overlay';+ overlay.setAttribute('aria-hidden', 'true');++ const spotlight = document.createElement('div');+ spotlight.className = 'tour-spotlight';+ spotlight.setAttribute('aria-hidden', 'true');++ const bubble = document.createElement('div');+ bubble.className = 'tour-bubble';+ bubble.setAttribute('role', 'dialog');+ bubble.setAttribute('aria-modal', 'false');+ bubble.setAttribute('aria-label', 'Guided tour');+ bubble.setAttribute('tabindex', '-1');++ const sr = document.createElement('div');+ sr.className = 'tour-sr-only';+ sr.setAttribute('aria-live', 'polite');+ sr.setAttribute('aria-atomic', 'true');++ document.body.append(overlay, spotlight, bubble, sr);++ let idx = 0;+ let activeEl = null;+ let resizeObs = null;++ function cleanup() {+ overlay.remove();+ spotlight.remove();+ bubble.remove();+ sr.remove();+ if (activeEl) activeEl.removeAttribute('data-tour-target');+ document.removeEventListener('keydown', onKey);+ resizeObs?.disconnect();+ }++ function finish(outcome) {+ cleanup();+ if (outcome === 'completed') {+ if (id) markTourDone(id);+ onComplete?.();+ } else {+ onSkip?.();+ }+ resolve(outcome);+ }++ function updateSpotlight(el) {+ const rect = el.getBoundingClientRect();+ spotlight.style.top = `${rect.top - SPOT_PAD}px`;+ spotlight.style.left = `${rect.left - SPOT_PAD}px`;+ spotlight.style.width = `${rect.width + SPOT_PAD * 2}px`;+ spotlight.style.height = `${rect.height + SPOT_PAD * 2}px`;+ }++ async function goTo(i) {+ if (i >= steps.length) { finish('completed'); return; }++ const step = steps[i];+ idx = i;++ // Clear previous target+ if (activeEl) { activeEl.removeAttribute('data-tour-target'); activeEl = null; }++ // Resolve element+ let el = null;+ if (typeof step.target === 'function') {+ el = step.target();+ } else if (typeof step.target === 'string') {+ el = document.querySelector(step.target);+ if (!el) el = await waitFor(step.target, 2500);+ }+ if (!el) { goTo(i + 1); return; } // skip missing elements++ activeEl = el;+ el.setAttribute('data-tour-target', '');+ el.scrollIntoView({ block: 'nearest', inline: 'nearest' });++ updateSpotlight(el);++ // Track resize+ resizeObs?.disconnect();+ resizeObs = new ResizeObserver(() => { if (activeEl) updateSpotlight(activeEl); });+ resizeObs.observe(el);++ step.action?.(el);++ // Render bubble+ const isFirst = i === 0;+ const isLast = i === steps.length - 1;+ bubble.innerHTML = `+ <div class="tour-meta">${i + 1} / ${steps.length}</div>+ <div class="tour-title">${esc(step.title)}</div>+ <p class="tour-body">${esc(step.body)}</p>+ <div class="tour-nav">+ <button class="tour-skip" type="button" data-action="skip">Skip</button>+ ${!isFirst ? `<button class="tour-btn-ghost" type="button" data-action="back">← Back</button>` : ''}+ <button class="tour-btn-primary" type="button" data-action="next">${isLast ? 'Done ✓' : 'Next →'}</button>+ </div>+ `;++ const rect = el.getBoundingClientRect();+ positionBubble(bubble, rect, step.placement || 'auto');++ sr.textContent = `Step ${i + 1} of ${steps.length}: ${step.title}. ${step.body}`;++ bubble.querySelector('[data-action="next"]').addEventListener('click', () => goTo(i + 1));+ bubble.querySelector('[data-action="skip"]').addEventListener('click', () => finish('skipped'));+ bubble.querySelector('[data-action="back"]')?.addEventListener('click', () => goTo(i - 1));++ bubble.querySelector('[data-action="next"]').focus();+ }++ function onKey(e) {+ if (e.key === 'Escape') { finish('skipped'); return; }+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') { e.preventDefault(); goTo(idx + 1); }+ if ((e.key === 'ArrowLeft' || e.key === 'ArrowUp') && idx > 0) { e.preventDefault(); goTo(idx - 1); }+ }++ // Clicking the dark overlay skips the tour+ overlay.addEventListener('click', () => finish('skipped'));++ document.addEventListener('keydown', onKey);+ window.addEventListener('resize', () => { if (activeEl) updateSpotlight(activeEl); }, { passive: true });++ goTo(0);+ });+}diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.jsindex 4e650f724..76e0fce4b 100644--- a/src/dashboard-next/pages/home.js+++ b/src/dashboard-next/pages/home.js@@ -7,6 +7,7 @@import { mountShell } from '../shell.js';import { requireUser, get, esc, relTime, ApiError } from '../api.js';import { log } from '../../shared/log.js';+import { startTour, isTourDone, syncTourPrefs } from '../../shared/tour.js';import {cryptoOptionalBannerHTML,cryptoOptionalTagHTML,@@ -94,7 +95,8 @@ const STATE = {// First-run guided tour — fires once after wizard completion (?welcome=1)const _welcomeUrl = new URL(location.href);- if (_welcomeUrl.searchParams.get('welcome') === '1' && !localStorage.getItem('threews:tour:done')) {+ const fromWelcome = _welcomeUrl.searchParams.get('welcome') === '1';+ if (fromWelcome && !localStorage.getItem('threews:tour:done')) {_welcomeUrl.searchParams.delete('welcome');history.replaceState(null, '', _welcomeUrl.toString());@@ -115,6 +117,37 @@ const STATE = {onContinue() {},}).catch(log.error);}).catch(log.error);+ } else if (isNew && !fromWelcome) {+ // Dashboard orientation — fires once for new accounts on their first plain+ // visit. Skipped if the welcome tour already ran (first-meet covers it).+ syncTourPrefs(); // pull server state so we don't re-show a completed tour+ setTimeout(() => {+ startTour([+ {+ target: '.dn-rail',+ title: 'Navigation rail',+ body: 'Your Build, Grow, Money, and Account sections live here. Agents and avatars are in Build; payments and revenue are in Money.',+ placement: 'below',+ },+ {+ target: '.dnx-hero, .dnx-hero-card, [data-slot="hero"]',+ title: 'Your creations',+ body: 'Your avatars and agents appear here as live 3D previews. Click any to manage it or jump to the Live page.',+ },+ {+ target: '[data-slot="kpis"], .dnx-kpis',+ title: 'Performance at a glance',+ body: 'Revenue, views, chat sessions, and active avatars — updated every 30 seconds.',+ },+ {+ target: '[data-slot="quick"], .dnx-quick',+ title: 'Quick actions',+ body: 'Shortcut tiles to create, build, and monetize. Customize these from the directory below.',+ },+ ], {+ id: 'dashboard-orientation',+ }).catch(log.error);+ }, 800); // brief delay so slots finish painting}const refresh = async () => {diff --git a/src/first-meet.js b/src/first-meet.jsindex 2e5a4a7ce..7da14060e 100644--- a/src/first-meet.js+++ b/src/first-meet.js@@ -9,6 +9,7 @@* @returns {Promise<void>} resolves when user clicks either button*/import { log } from './shared/log.js';+import { startTour } from './shared/tour.js';export async function playFirstMeet({ viewer, agent, onShare, onContinue }) {const reducedMotion =typeof window !== 'undefined' &&@@ -197,34 +198,14 @@ export async function playFirstMeet({ viewer, agent, onShare, onContinue }) {btnContinue.addEventListener('click', () => {cleanup();onContinue?.();- // Launch guided tour unless already completed- if (!localStorage.getItem(TOUR_DONE_KEY)) {- runTour(agent).catch(log.error);- }+ runTour(agent).catch(log.error);resolve();});});}-// ── Tour constants ─────────────────────────────────────────────────────────────--const TOUR_DONE_KEY = 'threews:tour:done';-// ── Utility ───────────────────────────────────────────────────────────────────-function waitForEl(selector, timeoutMs = 3000) {- return new Promise((resolve) => {- const el = document.querySelector(selector);- if (el) return resolve(el);- const obs = new MutationObserver(() => {- const found = document.querySelector(selector);- if (found) { obs.disconnect(); resolve(found); }- });- obs.observe(document.body, { childList: true, subtree: true });- setTimeout(() => { obs.disconnect(); resolve(null); }, timeoutMs);- });-}-function escHtml(s) {return String(s ?? '').replace(/[&<>"']/g, (c) => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": ''',@@ -232,158 +213,31 @@ function escHtml(s) {}// ── Coach-mark tour ───────────────────────────────────────────────────────────+// Powered by src/shared/tour.js — id-namespaced, server-backed persistence.async function runTour(agent) {- if (localStorage.getItem(TOUR_DONE_KEY)) return;-- const STEPS = [+ const TOUR_ID = 'dashboard-first-meet';+ const outcome = await startTour([{- selectors: ['.dnx-hero-card'],+ target: '.dnx-hero-card',title: 'Your agent is live',- body: 'Click "Live page" to preview, "Edit" to customize the look, or "Embed" to deploy on any website.',+ body: 'Click "Live page" to preview, "Edit" to customize the look, or "Embed wizard" to deploy on any website.',},{- selectors: ['#dnx-onboarding', '.dnx-ob'],+ target: '#dnx-onboarding, .dnx-ob',title: 'Your setup checklist',body: 'Complete these steps to unlock your agent\'s full potential — from personality to payments.',},{- selectors: ['.dnx-shortcuts-grid', '.dnx-quick-card'],+ target: '.dnx-shortcuts-grid, .dnx-quick-card',title: 'Quick shortcuts',body: 'Shortcuts to your most-used tools. Pin any page from the directory below to customize this section.',},- ];-- // Screen-reader live region- const liveRegion = document.createElement('div');- liveRegion.className = 'fm-sr-only';- liveRegion.setAttribute('aria-live', 'polite');- liveRegion.setAttribute('aria-atomic', 'true');- document.body.appendChild(liveRegion);-- // Spotlight rect highlight- const spotlight = document.createElement('div');- spotlight.className = 'fm-spotlight';- spotlight.setAttribute('aria-hidden', 'true');- document.body.appendChild(spotlight);-- // Tooltip bubble- const bubble = document.createElement('div');- bubble.className = 'fm-tour-bubble';- bubble.setAttribute('role', 'dialog');- bubble.setAttribute('aria-modal', 'false');- bubble.setAttribute('aria-label', 'Guided tour');- document.body.appendChild(bubble);-- let activeTarget = null;- let stepIndex = 0;-- function finish() {- liveRegion.remove();- spotlight.remove();- bubble.remove();- if (activeTarget) activeTarget.removeAttribute('data-fm-tour-target');- document.removeEventListener('keydown', keyHandler);- localStorage.setItem(TOUR_DONE_KEY, '1');- showChecklist(agent);- }-- async function goToStep(idx) {- if (idx >= STEPS.length) { finish(); return; }-- const step = STEPS[idx];- stepIndex = idx;-- // Clear previous target- if (activeTarget) activeTarget.removeAttribute('data-fm-tour-target');-- // Find target — try each selector, wait for first one- let target = null;- for (const sel of step.selectors) {- target = document.querySelector(sel);- if (target) break;- }- if (!target) {- target = await waitForEl(step.selectors[0], 2000);- }- if (!target) {- // Skip this step — element not available- goToStep(idx + 1);- return;- }-- activeTarget = target;- target.setAttribute('data-fm-tour-target', '');-- // Position spotlight over target- const rect = target.getBoundingClientRect();- const PAD = 8;- spotlight.style.top = `${rect.top - PAD}px`;- spotlight.style.left = `${rect.left - PAD}px`;- spotlight.style.width = `${rect.width + PAD * 2}px`;- spotlight.style.height = `${rect.height + PAD * 2}px`;- spotlight.classList.add('fm-spotlight-on');-- // Render bubble- const isLast = idx === STEPS.length - 1;- bubble.innerHTML = `- <div class="fm-tour-meta">${idx + 1} / ${STEPS.length}</div>- <div class="fm-tour-title">${escHtml(step.title)}</div>- <p class="fm-tour-body">${escHtml(step.body)}</p>- <div class="fm-tour-nav">- ${idx > 0- ? `<button class="fm-tour-ghost" type="button" data-action="back" aria-label="Previous step">Back</button>`- : ''}- <button class="fm-tour-ghost fm-tour-skip" type="button" data-action="skip">Skip tour</button>- <button class="fm-tour-primary" type="button" data-action="next">- ${isLast ? 'Done' : 'Next →'}- </button>- </div>- `;-- // Position bubble near target- positionBubble(bubble, rect);-- liveRegion.textContent = `Tour step ${idx + 1} of ${STEPS.length}: ${step.title}. ${step.body}`;-- // Wire buttons- bubble.querySelector('[data-action="next"]').addEventListener('click', () => goToStep(idx + 1));- bubble.querySelector('[data-action="skip"]').addEventListener('click', finish);- const backBtn = bubble.querySelector('[data-action="back"]');- if (backBtn) backBtn.addEventListener('click', () => goToStep(idx - 1));-- // Move focus to primary action- bubble.querySelector('[data-action="next"]').focus();- }-- function positionBubble(el, targetRect) {- const bw = Math.min(300, window.innerWidth - 32);- el.style.width = `${bw}px`;-- const preferredLeft = Math.min(- Math.max(16, targetRect.left + targetRect.width / 2 - bw / 2),- window.innerWidth - bw - 16,- );- el.style.left = `${preferredLeft}px`;-- const spaceBelow = window.innerHeight - targetRect.bottom;- if (spaceBelow >= 160) {- el.style.top = `${targetRect.bottom + 14}px`;- el.style.bottom = '';- } else {- el.style.bottom = `${window.innerHeight - targetRect.top + 14}px`;- el.style.top = '';- }- }-- function keyHandler(e) {- if (e.key === 'Escape') finish();- if (e.key === 'ArrowRight' || e.key === 'ArrowDown') goToStep(stepIndex + 1);- if ((e.key === 'ArrowLeft' || e.key === 'ArrowUp') && stepIndex > 0) goToStep(stepIndex - 1);- }- document.addEventListener('keydown', keyHandler);-- goToStep(0);+ ], {+ id: TOUR_ID,+ onComplete: () => showChecklist(agent),+ });+ if (outcome === 'skipped') showChecklist(agent);}// ── Next-steps checklist ──────────────────────────────────────────────────────diff --git a/src/shared/tour.js b/src/shared/tour.jsnew file mode 100644index 000000000..b6587470b--- /dev/null+++ b/src/shared/tour.js@@ -0,0 +1,352 @@+/**+ * three.ws tour engine — reusable guided spotlight/coachmark system+ *+ * API:+ * startTour(steps, options) → Promise<'completed' | 'skipped'>+ *+ * steps: Array<{+ * target: string | (() => Element | null), // CSS selector or function+ * title: string,+ * body: string,+ * placement: 'auto' | 'above' | 'below', // default 'auto'+ * action?: (el: Element) => void, // called after spotlight+ * }>+ *+ * options: {+ * id: string, // namespaced key for persistence+ * onComplete: () => void,+ * onSkip: () => void,+ * }+ *+ * Persistence:+ * - localStorage key: `tour:${id}:done`+ * - When signed in, syncs to /api/dashboard/prefs (PATCH tours.${id} = true)+ * - isTourDone(id) checks both localStorage and prefs cache+ *+ * Accessibility:+ * - ARIA live region announces each step+ * - role="dialog" + aria-modal="false" on bubble+ * - focus moves to primary action button each step+ * - Escape → skip; ←/→ arrows navigate+ * - Backdrop click → skip+ */++const PREFS_URL = '/api/dashboard/prefs';+const _prefsCacheKey = 'tour:prefs:cache';+const _prefsCache = (() => {+ try { return JSON.parse(localStorage.getItem(_prefsCacheKey) || '{}'); } catch { return {}; }+})();++function _savePrefsCache() {+ try { localStorage.setItem(_prefsCacheKey, JSON.stringify(_prefsCache)); } catch {}+}++function _lsKey(id) { return `tour:${id}:done`; }++export function isTourDone(id) {+ if (localStorage.getItem(_lsKey(id))) return true;+ return !!_prefsCache.tours?.[id];+}++export function markTourDone(id) {+ localStorage.setItem(_lsKey(id), '1');+ // Best-effort server sync+ fetch(PREFS_URL, {+ method: 'PATCH',+ credentials: 'include',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ prefs: { tours: { ..._prefsCache.tours, [id]: true } } }),+ }).then(r => {+ if (r.ok) {+ _prefsCache.tours = { ..._prefsCache.tours, [id]: true };+ _savePrefsCache();+ }+ }).catch(() => {});+}++// Pull latest prefs from server into local cache (called on page load if desired)+export function syncTourPrefs() {+ fetch(PREFS_URL, { credentials: 'include' })+ .then(r => r.ok ? r.json() : null)+ .then(data => {+ if (data?.prefs?.tours) {+ _prefsCache.tours = { ..._prefsCache.tours, ...data.prefs.tours };+ _savePrefsCache();+ // Mark any server-done tours done in localStorage too+ for (const [id, done] of Object.entries(data.prefs.tours)) {+ if (done) localStorage.setItem(_lsKey(id), '1');+ }+ }+ })+ .catch(() => {});+}++function esc(s) {+ return String(s).replace(/[&<>"']/g, c => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));+}++function waitFor(selector, ms = 2000) {+ return new Promise(resolve => {+ const el = document.querySelector(selector);+ if (el) { resolve(el); return; }+ const obs = new MutationObserver(() => {+ const found = document.querySelector(selector);+ if (found) { obs.disconnect(); resolve(found); }+ });+ obs.observe(document.body, { childList: true, subtree: true });+ setTimeout(() => { obs.disconnect(); resolve(null); }, ms);+ });+}++const SPOT_PAD = 8;++function positionBubble(bubble, targetRect, placement) {+ const vw = window.innerWidth;+ const vh = window.innerHeight;+ const bw = Math.min(300, vw - 32);+ bubble.style.width = `${bw}px`;++ // Horizontal centering over target+ const left = Math.max(16, Math.min(targetRect.left + targetRect.width / 2 - bw / 2, vw - bw - 16));+ bubble.style.left = `${left}px`;++ const spaceBelow = vh - targetRect.bottom;+ const spaceAbove = targetRect.top;+ const goBelow = placement === 'below' || (placement !== 'above' && spaceBelow >= 160) || spaceAbove < 160;++ if (goBelow) {+ bubble.style.top = `${targetRect.bottom + SPOT_PAD + 6}px`;+ bubble.style.bottom = '';+ } else {+ bubble.style.top = '';+ bubble.style.bottom = `${vh - targetRect.top + SPOT_PAD + 6}px`;+ }+}++function injectStyles() {+ if (document.getElementById('tour-engine-css')) return;+ const style = document.createElement('style');+ style.id = 'tour-engine-css';+ style.textContent = `+.tour-overlay {+ position: fixed; inset: 0; z-index: 10000;+ background: rgba(0,0,0,0.55);+ pointer-events: all;+}+.tour-spotlight {+ position: fixed; z-index: 10001;+ border-radius: 8px;+ box-shadow: 0 0 0 9999px rgba(0,0,0,0.55), 0 0 0 2px rgba(255,255,255,0.18);+ pointer-events: none;+ transition: top .22s, left .22s, width .22s, height .22s;+}+.tour-bubble {+ position: fixed; z-index: 10002;+ background: var(--panel, #18181b);+ border: 1px solid var(--border, rgba(255,255,255,0.1));+ border-radius: 12px;+ padding: 16px;+ box-shadow: 0 8px 32px rgba(0,0,0,0.45);+ pointer-events: all;+ animation: tourFadeIn .18s ease;+}+@keyframes tourFadeIn { from { opacity:0; transform:translateY(4px) } to { opacity:1; transform:none } }+.tour-meta {+ font-size: 11px;+ color: var(--ink-dim, rgba(255,255,255,0.4));+ margin-bottom: 4px;+ font-weight: 600;+ letter-spacing: .04em;+ text-transform: uppercase;+}+.tour-title {+ font-size: 15px;+ font-weight: 700;+ color: var(--text, #fff);+ margin-bottom: 6px;+ line-height: 1.3;+}+.tour-body {+ font-size: 13px;+ color: var(--ink-dim, rgba(255,255,255,0.65));+ margin: 0 0 14px;+ line-height: 1.5;+}+.tour-nav {+ display: flex;+ align-items: center;+ gap: 8px;+}+.tour-skip {+ font-size: 12px;+ color: var(--ink-dim, rgba(255,255,255,0.45));+ background: none;+ border: none;+ padding: 4px 0;+ cursor: pointer;+ margin-right: auto;+}+.tour-skip:hover { color: var(--text, #fff); }+.tour-btn-ghost {+ font-size: 13px;+ padding: 6px 12px;+ background: var(--panel-2, rgba(255,255,255,0.06));+ border: 1px solid var(--border, rgba(255,255,255,0.1));+ border-radius: 6px;+ color: var(--text, #fff);+ cursor: pointer;+ transition: background .15s;+}+.tour-btn-ghost:hover { background: var(--panel-3, rgba(255,255,255,0.12)); }+.tour-btn-primary {+ font-size: 13px;+ padding: 6px 14px;+ background: var(--accent, #6366f1);+ border: none;+ border-radius: 6px;+ color: #fff;+ font-weight: 600;+ cursor: pointer;+ transition: background .15s;+}+.tour-btn-primary:hover { background: var(--accent-hi, #818cf8); }+.tour-sr-only { position:absolute; width:1px; height:1px; overflow:hidden; clip:rect(0,0,0,0); white-space:nowrap; }+[data-tour-target] { position: relative; z-index: 10001; border-radius: 6px; outline: 2px solid rgba(99,102,241,0.6); outline-offset: 3px; }+`;+ document.head.appendChild(style);+}++export function startTour(steps, { id, onComplete, onSkip } = {}) {+ if (id && isTourDone(id)) return Promise.resolve('completed');++ injectStyles();++ return new Promise(resolve => {+ const overlay = document.createElement('div');+ overlay.className = 'tour-overlay';+ overlay.setAttribute('aria-hidden', 'true');++ const spotlight = document.createElement('div');+ spotlight.className = 'tour-spotlight';+ spotlight.setAttribute('aria-hidden', 'true');++ const bubble = document.createElement('div');+ bubble.className = 'tour-bubble';+ bubble.setAttribute('role', 'dialog');+ bubble.setAttribute('aria-modal', 'false');+ bubble.setAttribute('aria-label', 'Guided tour');+ bubble.setAttribute('tabindex', '-1');++ const sr = document.createElement('div');+ sr.className = 'tour-sr-only';+ sr.setAttribute('aria-live', 'polite');+ sr.setAttribute('aria-atomic', 'true');++ document.body.append(overlay, spotlight, bubble, sr);++ let idx = 0;+ let activeEl = null;+ let resizeObs = null;++ function cleanup() {+ overlay.remove();+ spotlight.remove();+ bubble.remove();+ sr.remove();+ if (activeEl) activeEl.removeAttribute('data-tour-target');+ document.removeEventListener('keydown', onKey);+ resizeObs?.disconnect();+ }++ function finish(outcome) {+ cleanup();+ if (outcome === 'completed') {+ if (id) markTourDone(id);+ onComplete?.();+ } else {+ onSkip?.();+ }+ resolve(outcome);+ }++ function updateSpotlight(el) {+ const rect = el.getBoundingClientRect();+ spotlight.style.top = `${rect.top - SPOT_PAD}px`;+ spotlight.style.left = `${rect.left - SPOT_PAD}px`;+ spotlight.style.width = `${rect.width + SPOT_PAD * 2}px`;+ spotlight.style.height = `${rect.height + SPOT_PAD * 2}px`;+ }++ async function goTo(i) {+ if (i >= steps.length) { finish('completed'); return; }++ const step = steps[i];+ idx = i;++ // Clear previous target+ if (activeEl) { activeEl.removeAttribute('data-tour-target'); activeEl = null; }++ // Resolve element+ let el = null;+ if (typeof step.target === 'function') {+ el = step.target();+ } else if (typeof step.target === 'string') {+ el = document.querySelector(step.target);+ if (!el) el = await waitFor(step.target, 2500);+ }+ if (!el) { goTo(i + 1); return; } // skip missing elements++ activeEl = el;+ el.setAttribute('data-tour-target', '');+ el.scrollIntoView({ block: 'nearest', inline: 'nearest' });++ updateSpotlight(el);++ // Track resize+ resizeObs?.disconnect();+ resizeObs = new ResizeObserver(() => { if (activeEl) updateSpotlight(activeEl); });+ resizeObs.observe(el);++ step.action?.(el);++ // Render bubble+ const isFirst = i === 0;+ const isLast = i === steps.length - 1;+ bubble.innerHTML = `+ <div class="tour-meta">${i + 1} / ${steps.length}</div>+ <div class="tour-title">${esc(step.title)}</div>+ <p class="tour-body">${esc(step.body)}</p>+ <div class="tour-nav">+ <button class="tour-skip" type="button" data-action="skip">Skip</button>+ ${!isFirst ? `<button class="tour-btn-ghost" type="button" data-action="back">← Back</button>` : ''}+ <button class="tour-btn-primary" type="button" data-action="next">${isLast ? 'Done ✓' : 'Next →'}</button>+ </div>+ `;++ const rect = el.getBoundingClientRect();+ positionBubble(bubble, rect, step.placement || 'auto');++ sr.textContent = `Step ${i + 1} of ${steps.length}: ${step.title}. ${step.body}`;++ bubble.querySelector('[data-action="next"]').addEventListener('click', () => goTo(i + 1));+ bubble.querySelector('[data-action="skip"]').addEventListener('click', () => finish('skipped'));+ bubble.querySelector('[data-action="back"]')?.addEventListener('click', () => goTo(i - 1));++ bubble.querySelector('[data-action="next"]').focus();+ }++ function onKey(e) {+ if (e.key === 'Escape') { finish('skipped'); return; }+ if (e.key === 'ArrowRight' || e.key === 'ArrowDown') { e.preventDefault(); goTo(idx + 1); }+ if ((e.key === 'ArrowLeft' || e.key === 'ArrowUp') && idx > 0) { e.preventDefault(); goTo(idx - 1); }+ }++ // Clicking the dark overlay skips the tour+ overlay.addEventListener('click', () => finish('skipped'));++ document.addEventListener('keydown', onKey);+ window.addEventListener('resize', () => { if (activeEl) updateSpotlight(activeEl); }, { passive: true });++ goTo(0);+ });+}