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
feat(tour): turn the map panel into a draggable registry-style directory
nirholasf00236b2e338
diff --git a/src/feature-tour/README.md b/src/feature-tour/README.mdindex c4269ed91..02d95e3ff 100644--- a/src/feature-tour/README.md+++ b/src/feature-tour/README.md@@ -41,7 +41,7 @@ src/feature-tour/├── spotlight.js Spotlight: dims the page and rings the element being discussed├── narrator.js Narrator: platform TTS (/api/tts/speak) with paced-caption fallback, iOS unlock├── controls.js TourControls: playback bar (prev / play-pause / next / speed / roam / mute / exit)-├── chapters.js ChapterPanel: searchable chapter map, track/voice/speed/avatar settings drawer+├── chapters.js ChapterPanel: registry-style stop listing (title, narration summary, path) with search across all three, track/voice/speed/avatar settings; docked drawer or drag-to-float panel with a remembered position├── free-roam.js FreeRoam: paused mode where the visitor clicks/drags/keys the guide around└── explore.js ExploreMode: visitor-driven checkpoint quest on the real walk-sdk playground```diff --git a/src/feature-tour/chapters.js b/src/feature-tour/chapters.jsindex b51fd2aa7..f262993be 100644--- a/src/feature-tour/chapters.js+++ b/src/feature-tour/chapters.js@@ -1,8 +1,12 @@-// chapters.js — the tour's navigation drawer. An 85-stop tour needs a map, so-// this panel lays the whole curriculum out as chapters → stops, marks the one-// you're on, and lets you jump to any of them. It doubles as the settings-// surface: switch between the Quick-highlights and Full tracks, change the-// narration voice, set the playback speed, and search across every stop's title.+// chapters.js: the tour's navigation panel. A 264-stop tour needs a map, so+// this panel lays the whole curriculum out as chapters → stops in a+// registry-style listing (bold title, one-line summary of what the guide says,+// and the page path underneath), marks the stop you're on, and lets you jump to+// any of them. It doubles as the settings surface: switch tracks, change the+// narration voice, set the playback speed, and search across titles, paths, and+// narration. Docked, it slides in from the left; on desktop you can also drag+// it by its header to float it anywhere on screen (the position is remembered),+// which drops the scrim so the tour stays visible and clickable behind it.// It is pure UI — every action forwards to a handler the director supplies, and// the director calls setActive()/setTrack()/setVoice()/setSpeed() to keep it in// sync. Open/close is fully keyboard- and screen-reader-friendly.@@ -10,6 +14,8 @@import { createAvatarPicker } from '../../walk-sdk/src/picker.js';const Z_PANEL = 2147483450;+const POS_KEY = 'tws:tour:menu-pos';+const OPEN_KEY = 'tws:tour:menu-open';// A curated client-side slice of the platform voice catalog (api/_lib/tts-voices.js).// Kept small so the menu stays scannable; every id here renders on both the free@@ -36,11 +42,27 @@ export class ChapterPanel {this.assetBase = avatarConfig.assetBase || '';this.docsUrl = avatarConfig.docsUrl || null;this.open = false;+ this.floating = false;this.activeAbs = 0;this._query = '';+ this._pos = null;+ // Search matches title, path, and narration; lowercased once, not per keystroke.+ this._searchIndex = (curriculum.stops || []).map((s) =>+ `${s.title || ''} ${s.path || ''} ${s.narration || ''}`.toLowerCase(),+ );+ this._chapterCount = (curriculum.sections || []).filter((section) =>+ (curriculum.stops || []).some((s) => s.section === section.id),+ ).length;this._onKey = this._onKey.bind(this);+ this._onResize = this._onResize.bind(this);ensureStyles();this._build();+ // A floating map that was open when the tour navigated to the next stop+ // reopens itself in the same spot, so the companion survives page loads.+ // Focus stays with the page: a self-restoring panel must not steal it.+ if (this._readPos() && this._dragAllowed() && readSession(OPEN_KEY)) {+ this.show({ focus: false });+ }}_build() {@@ -50,8 +72,9 @@ export class ChapterPanel {<div class="tws-tour-menu__scrim" data-act="close"></div><aside class="tws-tour-menu__panel" role="dialog" aria-modal="false" aria-label="Tour chapters and settings" tabindex="-1"><div class="tws-tour-menu__head">- <div class="tws-tour-menu__title">Tour map</div>- <button class="tws-tour-menu__x" data-act="close" aria-label="Close menu" title="Close">✕</button>+ <div class="tws-tour-menu__title">Tour map <span class="tws-tour-menu__badge"></span></div>+ <button class="tws-tour-menu__hbtn" data-act="dock" aria-label="Dock the panel back to the side" title="Dock back to the side" hidden>⇤</button>+ <button class="tws-tour-menu__hbtn tws-tour-menu__x" data-act="close" aria-label="Close menu" title="Close">✕</button></div><div class="tws-tour-menu__settings"><label class="tws-tour-menu__field">@@ -80,26 +103,38 @@ export class ChapterPanel {}</div><div class="tws-tour-menu__search">- <input type="search" class="tws-tour-menu__input" placeholder="Search features…" aria-label="Search tour stops" autocomplete="off" spellcheck="false" />+ <input type="search" class="tws-tour-menu__input" placeholder="Search features, pages, or narration…" aria-label="Search tour stops" autocomplete="off" spellcheck="false" />+ <p class="tws-tour-menu__countline" aria-live="polite"></p></div><nav class="tws-tour-menu__list" aria-label="Tour chapters"></nav></aside>`;document.body.appendChild(root);this.root = root;this.panel = root.querySelector('.tws-tour-menu__panel');+ this.head = root.querySelector('.tws-tour-menu__head');+ this.badgeEl = root.querySelector('.tws-tour-menu__badge');+ this.dockBtn = root.querySelector('[data-act="dock"]');this.listEl = root.querySelector('.tws-tour-menu__list');+ this.countLine = root.querySelector('.tws-tour-menu__countline');this.trackSeg = root.querySelector('[data-group="track"]');this.speedSeg = root.querySelector('[data-group="speed"]');this.voiceSel = root.querySelector('[data-act="voice"]');this.avatarBtn = root.querySelector('[data-act="avatar"]');this.searchInput = root.querySelector('.tws-tour-menu__input');+ this.badgeEl.textContent = String((this.curriculum.stops || []).length);this._buildSegments();this._buildVoices();this._renderAvatarBtn();this._buildList();+ this._initDrag();+ window.addEventListener('resize', this._onResize);root.addEventListener('click', (e) => {+ if (e.target.closest('[data-act="dock"]')) {+ this._dock();+ return;+ }if (e.target.closest('[data-act="close"]')) this.close();});this.trackSeg.addEventListener('click', (e) => {@@ -120,7 +155,9 @@ export class ChapterPanel {const abs = e.target.closest('[data-abs]')?.dataset.abs;if (abs != null) {this.handlers.onJump?.(Number(abs));- this.close();+ // A floating map is a companion you jump around from; only the+ // docked drawer (which covers the page behind a scrim) self-closes.+ if (!this.floating) this.close();}});}@@ -210,25 +247,36 @@ export class ChapterPanel {const { sections, stops } = this.curriculum;const q = this._query;const rows = [];+ let shown = 0;for (const section of sections) {const items = stops.map((s, abs) => ({ s, abs })).filter(({ s }) => s.section === section.id)- .filter(({ s }) => !q || s.title.toLowerCase().includes(q));+ .filter(({ abs }) => !q || this._searchIndex[abs].includes(q));if (!items.length) continue;+ shown += items.length;rows.push(`<div class="tws-tour-chap"><span class="tws-tour-chap__t">${esc(section.title)}</span><span class="tws-tour-chap__n">${items.length}</span></div>`,);for (const { s, abs } of items) {+ const blurb = stopBlurb(s);rows.push(`<button class="tws-tour-stop${abs === this.activeAbs ? ' is-current' : ''}" data-abs="${abs}" aria-current="${abs === this.activeAbs ? 'true' : 'false'}">- <span class="tws-tour-stop__dot"${s.highlight ? ' data-hl="1"' : ''}></span>- <span class="tws-tour-stop__title">${esc(s.title)}</span>- ${s.highlight ? '<span class="tws-tour-stop__star" title="In the Quick highlights">★</span>' : ''}+ <span class="tws-tour-stop__row">+ <span class="tws-tour-stop__dot"${s.highlight ? ' data-hl="1"' : ''}></span>+ <span class="tws-tour-stop__title">${esc(s.title)}</span>+ ${s.highlight ? '<span class="tws-tour-stop__star" title="In the Quick highlights">★</span>' : ''}+ </span>+ ${blurb ? `<span class="tws-tour-stop__desc">${esc(blurb)}</span>` : ''}+ <span class="tws-tour-stop__meta">${esc(s.path || '')}</span></button>`,);}}+ const total = stops.length;+ this.countLine.textContent = q+ ? `${shown} of ${total} stops match`+ : `${total} stops · ${this._chapterCount} chapters`;this.listEl.innerHTML =rows.join('') ||`<div class="tws-tour-menu__empty">No features match “${esc(this._query)}”.</div>`;@@ -263,24 +311,136 @@ export class ChapterPanel {});}+ // ── Floating / drag ─────────────────────────────────────────────────────────+ // Desktop-only: grab the header to tear the drawer off into a floating panel+ // you can park anywhere. The scrim disappears so the page (and the tour) stays+ // interactive behind it, and the spot is remembered across pages and sessions.+ // The ⇤ button, small screens, and coarse pointers all fall back to the drawer.+ _dragAllowed() {+ try {+ return !window.matchMedia('(max-width: 640px), (pointer: coarse)').matches;+ } catch (_) {+ return false;+ }+ }++ _initDrag() {+ this.head.addEventListener('pointerdown', (e) => {+ if (!this._dragAllowed()) return;+ if (e.button !== 0 || e.target.closest('button')) return;+ e.preventDefault();+ const rect = this.panel.getBoundingClientRect();+ const startX = e.clientX;+ const startY = e.clientY;+ const offX = startX - rect.left;+ const offY = startY - rect.top;+ let dragging = false;+ const onMove = (ev) => {+ if (!dragging) {+ // A 5px threshold keeps plain clicks on the header from tearing off.+ if (Math.hypot(ev.clientX - startX, ev.clientY - startY) < 5) return;+ dragging = true;+ this._enterFloating();+ this.head.classList.add('is-dragging');+ }+ this._placeAt(ev.clientX - offX, ev.clientY - offY);+ };+ const onUp = () => {+ document.removeEventListener('pointermove', onMove);+ document.removeEventListener('pointerup', onUp);+ document.removeEventListener('pointercancel', onUp);+ this.head.classList.remove('is-dragging');+ if (dragging) this._savePos();+ };+ document.addEventListener('pointermove', onMove);+ document.addEventListener('pointerup', onUp);+ document.addEventListener('pointercancel', onUp);+ });+ }++ _enterFloating() {+ if (this.floating) return;+ this.floating = true;+ this.root.classList.add('is-floating');+ this.dockBtn.hidden = false;+ }++ _dock() {+ this.floating = false;+ this.root.classList.remove('is-floating');+ this.dockBtn.hidden = true;+ this.panel.style.left = '';+ this.panel.style.top = '';+ this._pos = null;+ try {+ localStorage.removeItem(POS_KEY);+ } catch (_) {}+ }++ _placeAt(x, y) {+ const w = this.panel.offsetWidth || 380;+ const h = this.panel.offsetHeight || 560;+ const nx = clamp(x, 8, Math.max(8, window.innerWidth - w - 8));+ const ny = clamp(y, 8, Math.max(8, window.innerHeight - h - 8));+ this.panel.style.left = nx + 'px';+ this.panel.style.top = ny + 'px';+ this._pos = { x: nx, y: ny };+ }++ _savePos() {+ if (!this._pos) return;+ try {+ localStorage.setItem(POS_KEY, JSON.stringify(this._pos));+ } catch (_) {}+ }++ _readPos() {+ try {+ const raw = localStorage.getItem(POS_KEY);+ if (!raw) return null;+ const pos = JSON.parse(raw);+ return pos && Number.isFinite(pos.x) && Number.isFinite(pos.y) ? pos : null;+ } catch (_) {+ return null;+ }+ }++ _onResize() {+ if (!this.floating) return;+ // Viewport shrank under a floating panel (rotation, window resize):+ // fall back to the drawer on small screens, otherwise re-clamp into view.+ if (!this._dragAllowed()) {+ this._dock();+ return;+ }+ if (this._pos) this._placeAt(this._pos.x, this._pos.y);+ }+// ── Open / close ────────────────────────────────────────────────────────────toggle() {this.open ? this.close() : this.show();}- show() {+ show({ focus = true } = {}) {if (this.open) return;this.open = true;+ const pos = this._readPos();+ if (pos && this._dragAllowed()) {+ this._enterFloating();+ this._placeAt(pos.x, pos.y);+ }this.root.classList.add('is-open');+ writeSession(OPEN_KEY, '1');this._scrollToActive();document.addEventListener('keydown', this._onKey, true);// Focus the search box for instant filter-and-jump.- requestAnimationFrame(() => this.searchInput.focus());+ if (focus) requestAnimationFrame(() => this.searchInput.focus());this.handlers.onOpenChange?.(true);}close() {if (!this.open) return;this.open = false;this.root.classList.remove('is-open');+ writeSession(OPEN_KEY, null);document.removeEventListener('keydown', this._onKey, true);this.handlers.onOpenChange?.(false);}@@ -298,10 +458,12 @@ export class ChapterPanel {this.close();return;}- // Trap Tab inside the open panel so keyboard focus can't wander behind the+ // Trap Tab inside the open drawer so keyboard focus can't wander behind the// modal scrim onto the obscured page. Recomputed each press because the- // stop list re-renders as the search filters.+ // stop list re-renders as the search filters. A floating panel has no scrim+ // and the page behind it is meant to stay usable, so no trap there.if (e.key === 'Tab') {+ if (this.floating) return;const panel = this.root?.querySelector('.tws-tour-menu__panel');if (!panel) return;const focusable = Array.from(@@ -327,7 +489,11 @@ export class ChapterPanel {}dispose() {+ // Dispose is a deliberate teardown (tour exit or finish), unlike a page+ // navigation mid-tour, so the self-reopen flag must not outlive it.+ writeSession(OPEN_KEY, null);document.removeEventListener('keydown', this._onKey, true);+ window.removeEventListener('resize', this._onResize);this._picker?.destroy();this._picker = null;this.root?.remove();@@ -335,6 +501,21 @@ export class ChapterPanel {}}+function readSession(key) {+ try {+ return sessionStorage.getItem(key);+ } catch (_) {+ return null;+ }+}++function writeSession(key, value) {+ try {+ if (value == null) sessionStorage.removeItem(key);+ else sessionStorage.setItem(key, value);+ } catch (_) {}+}+function esc(s) {return String(s == null ? '' : s).replace(/[&<>"']/g,@@ -342,6 +523,19 @@ function esc(s) {);}+function clamp(n, lo, hi) {+ return Math.min(hi, Math.max(lo, n));+}++// The narration opens with a "Here we have <title>." lead-in for the voice+// track; in a written list that reads as noise, so the summary starts at the+// substance ("Landing page. The pitch, live agent demos, …").+function stopBlurb(stop) {+ return String(stop.narration || '')+ .replace(/^Here we have [^.!?]*[.!?]\s*/, '')+ .trim();+}+let _stylesInjected = false;function ensureStyles() {if (_stylesInjected) return;@@ -352,12 +546,22 @@ function ensureStyles() {.tws-tour-menu{position:fixed;inset:0;z-index:${Z_PANEL};pointer-events:none;font-family:system-ui,-apple-system,'Segoe UI',sans-serif}.tws-tour-menu__scrim{position:absolute;inset:0;background:rgba(6,8,12,.5);opacity:0;transition:opacity .3s ease;pointer-events:none}.tws-tour-menu.is-open .tws-tour-menu__scrim{opacity:1;pointer-events:auto}-.tws-tour-menu__panel{position:absolute;left:0;top:0;height:100%;width:min(360px,86vw);display:flex;flex-direction:column;background:#0e1118;border-right:1px solid rgba(122,162,255,.18);box-shadow:24px 0 60px rgba(0,0,0,.5);transform:translateX(-104%);transition:transform .34s cubic-bezier(.4,0,.2,1);pointer-events:auto;color:#e7eaf2}+.tws-tour-menu__panel{position:absolute;left:0;top:0;height:100%;width:min(380px,86vw);display:flex;flex-direction:column;background:#0e1118;border-right:1px solid rgba(122,162,255,.18);box-shadow:24px 0 60px rgba(0,0,0,.5);transform:translateX(-104%);transition:transform .34s cubic-bezier(.4,0,.2,1);pointer-events:auto;color:#e7eaf2}.tws-tour-menu.is-open .tws-tour-menu__panel{transform:translateX(0)}-.tws-tour-menu__head{display:flex;align-items:center;justify-content:space-between;padding:16px 18px 12px;border-bottom:1px solid rgba(255,255,255,.07)}-.tws-tour-menu__title{font-weight:700;font-size:16px}-.tws-tour-menu__x{appearance:none;border:none;background:rgba(255,255,255,.06);color:#cfd5e2;width:30px;height:30px;border-radius:9px;cursor:pointer;font-size:13px;display:grid;place-items:center;transition:background .16s ease}+.tws-tour-menu.is-floating .tws-tour-menu__scrim{display:none}+.tws-tour-menu.is-floating .tws-tour-menu__panel{position:fixed;height:min(76vh,680px);border:1px solid rgba(122,162,255,.22);border-radius:16px;box-shadow:0 24px 70px rgba(0,0,0,.55);transform:translateY(10px) scale(.98);opacity:0;visibility:hidden;transition:transform .22s ease,opacity .22s ease,visibility .22s}+.tws-tour-menu.is-floating.is-open .tws-tour-menu__panel{transform:none;opacity:1;visibility:visible}+.tws-tour-menu__head{display:flex;align-items:center;gap:8px;padding:16px 18px 12px;border-bottom:1px solid rgba(255,255,255,.07)}+.tws-tour-menu__title{flex:1;display:flex;align-items:center;font-weight:700;font-size:16px;min-width:0}+.tws-tour-menu__badge{display:inline-flex;align-items:center;margin-left:9px;padding:3.5px 8px;border-radius:99px;background:rgba(122,162,255,.14);border:1px solid rgba(122,162,255,.3);color:#a9bcff;font-size:11px;font-weight:600;font-variant-numeric:tabular-nums;line-height:1}+.tws-tour-menu__hbtn{appearance:none;border:none;background:rgba(255,255,255,.06);color:#cfd5e2;width:30px;height:30px;border-radius:9px;cursor:pointer;font-size:13px;display:grid;place-items:center;flex:0 0 auto;transition:background .16s ease}+.tws-tour-menu__hbtn:hover{background:rgba(122,162,255,.28);color:#fff}+.tws-tour-menu__hbtn:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}.tws-tour-menu__x:hover{background:rgba(220,70,70,.8);color:#fff}+@media (min-width:641px) and (pointer:fine){+ .tws-tour-menu__head{cursor:grab;user-select:none;touch-action:none}+ .tws-tour-menu__head.is-dragging{cursor:grabbing}+}.tws-tour-menu__settings{padding:14px 18px;display:flex;flex-direction:column;gap:12px;border-bottom:1px solid rgba(255,255,255,.07)}.tws-tour-menu__field{display:flex;align-items:center;gap:12px;justify-content:space-between}.tws-tour-menu__lbl{font-size:12.5px;color:#9aa3b6;font-weight:600;flex:0 0 auto;width:48px}@@ -378,17 +582,23 @@ function ensureStyles() {.tws-tour-menu__input{width:100%;box-sizing:border-box;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12);border-radius:10px;color:#e7eaf2;font:500 13.5px/1 inherit;padding:10px 12px}.tws-tour-menu__input::placeholder{color:#7f8aa0}.tws-tour-menu__input:focus-visible{outline:2px solid #7aa2ff;outline-offset:1px}+.tws-tour-menu__countline{margin:8px 2px 0;font-size:11.5px;color:#7f8aa0;font-variant-numeric:tabular-nums}.tws-tour-menu__list{flex:1;overflow-y:auto;padding:4px 10px 18px;scrollbar-width:thin}-.tws-tour-chap{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:14px 8px 6px;font-size:11.5px;font-weight:700;letter-spacing:.05em;text-transform:uppercase;color:#7f8aa0;position:sticky;top:0;background:#0e1118}+.tws-tour-chap{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:14px 8px 6px;font-size:11.5px;font-weight:700;letter-spacing:.05em;text-transform:uppercase;color:#7f8aa0;position:sticky;top:0;background:#0e1118;z-index:1}.tws-tour-chap__n{font-weight:600;color:#5f697e;font-variant-numeric:tabular-nums}-.tws-tour-stop{display:flex;align-items:center;gap:10px;width:100%;text-align:left;appearance:none;border:none;background:transparent;color:#c4ccda;font:500 13.5px/1.3 inherit;padding:9px 8px;border-radius:9px;cursor:pointer;transition:background .14s ease,color .14s ease}+.tws-tour-stop{display:flex;flex-direction:column;align-items:stretch;gap:5px;width:100%;text-align:left;appearance:none;border:none;background:transparent;color:#c4ccda;font:500 13.5px/1.35 inherit;padding:11px 8px 12px;border-radius:10px;cursor:pointer;transition:background .14s ease,color .14s ease}+.tws-tour-stop + .tws-tour-stop{border-top:1px solid rgba(255,255,255,.055)}.tws-tour-stop:hover{background:rgba(255,255,255,.05);color:#fff}.tws-tour-stop.is-current{background:rgba(122,162,255,.16);color:#fff}+.tws-tour-stop__row{display:flex;align-items:center;gap:10px;min-width:0}.tws-tour-stop__dot{flex:0 0 auto;width:7px;height:7px;border-radius:50%;background:rgba(255,255,255,.22)}.tws-tour-stop__dot[data-hl="1"]{background:linear-gradient(135deg,#7aa2ff,#9d7bff)}.tws-tour-stop.is-current .tws-tour-stop__dot{background:#7aa2ff;box-shadow:0 0 0 3px rgba(122,162,255,.3)}-.tws-tour-stop__title{flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.tws-tour-stop__title{flex:1;font-weight:650;font-size:14px;color:#e7eaf2;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}+.tws-tour-stop:hover .tws-tour-stop__title,.tws-tour-stop.is-current .tws-tour-stop__title{color:#fff}.tws-tour-stop__star{flex:0 0 auto;color:#9d7bff;font-size:11px}+.tws-tour-stop__desc{display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;line-clamp:2;overflow:hidden;padding-left:17px;font-size:12.5px;line-height:1.45;color:#8b93a7;font-weight:400}+.tws-tour-stop__meta{padding-left:17px;font:500 11px/1 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;color:#5f697e;word-break:break-all}.tws-tour-menu__empty{padding:30px 14px;text-align:center;color:#7f8aa0;font-size:13px}@media (prefers-reduced-motion:reduce){.tws-tour-menu__panel{transition:none}.tws-tour-menu__scrim{transition:none}}`;diff --git a/tests/feature-tour-map-panel.test.js b/tests/feature-tour-map-panel.test.jsnew file mode 100644index 000000000..5bf6a2eb6--- /dev/null+++ b/tests/feature-tour-map-panel.test.js@@ -0,0 +1,199 @@+/**+ * Feature Tour map panel: unit tests.+ *+ * The Tour map (chapters.js) renders the curriculum as a registry-style+ * listing (bold title, a summary of what the guide says with the spoken+ * "Here we have X." lead-in stripped, and the page path) under chapter+ * headers with counts, plus a total-stops badge and a live results line.+ * On desktop the panel tears off its drawer when dragged by the header,+ * floats where dropped, remembers the spot, and docks back on demand.+ * These tests pin that contract.+ */++import { describe, it, expect, beforeAll, beforeEach, afterEach } from 'vitest';+import { JSDOM } from 'jsdom';++let ChapterPanel;+let dom;++const CURRICULUM = {+ sections: [+ { id: 'main', title: 'Main' },+ { id: 'build', title: 'Build' },+ ],+ tracks: [+ { id: 'full', title: 'Full tour', description: 'Everything.', estimatedMinutes: 100 },+ { id: 'quick', title: 'Quick highlights', description: 'The best.', estimatedMinutes: 7 },+ ],+ stops: [+ {+ id: 'home',+ path: '/',+ section: 'main',+ title: 'Home',+ narration: 'Here we have Home. Landing page. The front door to every flow.',+ highlight: true,+ },+ {+ id: 'markets',+ path: '/markets',+ section: 'main',+ title: 'Markets',+ narration: 'Here we have Markets. Live pump.fun market intelligence.',+ },+ {+ id: 'avatar-studio',+ path: '/avatar-studio',+ section: 'build',+ title: 'Avatar Studio',+ narration: 'Here we have Avatar Studio. Pose, dress, and animate your rig.',+ },+ ],+};++beforeAll(async () => {+ dom = new JSDOM('<!doctype html><html><body></body></html>', { url: 'http://localhost/' });+ global.window = dom.window;+ global.document = dom.window.document;+ global.localStorage = dom.window.localStorage;+ global.requestAnimationFrame = (cb) => setTimeout(() => cb(Date.now()), 0);+ global.cancelAnimationFrame = (id) => clearTimeout(id);+ // jsdom implements neither matchMedia nor scrollIntoView.+ global.matchMedia = (q) => ({+ matches: false, media: q,+ addEventListener() {}, removeEventListener() {}, addListener() {}, removeListener() {},+ });+ dom.window.matchMedia = global.matchMedia;+ global.sessionStorage = dom.window.sessionStorage;+ dom.window.Element.prototype.scrollIntoView = () => {};+ ({ ChapterPanel } = await import('../src/feature-tour/chapters.js'));+});++let panel;+let jumped;++beforeEach(() => {+ dom.window.localStorage.clear();+ dom.window.sessionStorage.clear();+ jumped = [];+ panel = new ChapterPanel(CURRICULUM, { onJump: (abs) => jumped.push(abs) });+});++afterEach(() => {+ panel?.dispose();+ document.body.innerHTML = '';+});++function drag(head, from, to) {+ head.dispatchEvent(+ new dom.window.MouseEvent('pointerdown', { bubbles: true, clientX: from.x, clientY: from.y, button: 0 }),+ );+ document.dispatchEvent(+ new dom.window.MouseEvent('pointermove', { bubbles: true, clientX: to.x, clientY: to.y }),+ );+ document.dispatchEvent(new dom.window.MouseEvent('pointerup', { bubbles: true }));+}++describe('ChapterPanel listing', () => {+ it('renders registry-style rows: title, lead-in-free summary, and path', () => {+ const rows = document.querySelectorAll('.tws-tour-stop');+ expect(rows.length).toBe(3);+ const home = rows[0];+ expect(home.querySelector('.tws-tour-stop__title').textContent).toBe('Home');+ const desc = home.querySelector('.tws-tour-stop__desc').textContent;+ expect(desc).toBe('Landing page. The front door to every flow.');+ expect(desc).not.toContain('Here we have');+ expect(home.querySelector('.tws-tour-stop__meta').textContent).toBe('/');+ expect(rows[1].querySelector('.tws-tour-stop__meta').textContent).toBe('/markets');+ });++ it('shows the total badge, chapter counts, and a summary line', () => {+ expect(document.querySelector('.tws-tour-menu__badge').textContent).toBe('3');+ const chapters = document.querySelectorAll('.tws-tour-chap');+ expect(chapters.length).toBe(2);+ expect(chapters[0].querySelector('.tws-tour-chap__n').textContent).toBe('2');+ expect(document.querySelector('.tws-tour-menu__countline').textContent).toBe(+ '3 stops · 2 chapters',+ );+ });++ it('search matches narration and paths, not just titles', () => {+ const input = document.querySelector('.tws-tour-menu__input');+ input.value = 'market intelligence'; // narration-only phrase+ input.dispatchEvent(new dom.window.Event('input', { bubbles: true }));+ const rows = document.querySelectorAll('.tws-tour-stop');+ expect(rows.length).toBe(1);+ expect(rows[0].querySelector('.tws-tour-stop__title').textContent).toBe('Markets');+ expect(document.querySelector('.tws-tour-menu__countline').textContent).toBe(+ '1 of 3 stops match',+ );+ });++ it('clicking a stop jumps to its absolute index', () => {+ panel.show();+ document.querySelectorAll('.tws-tour-stop')[2].click();+ expect(jumped).toEqual([2]);+ expect(panel.open).toBe(false); // docked drawer self-closes on jump+ });+});++describe('ChapterPanel floating mode', () => {+ it('drag tears the drawer off, floats it, and persists the spot', () => {+ panel.show();+ const head = document.querySelector('.tws-tour-menu__head');+ drag(head, { x: 40, y: 20 }, { x: 300, y: 200 });+ const root = document.querySelector('.tws-tour-menu');+ expect(root.classList.contains('is-floating')).toBe(true);+ expect(document.querySelector('[data-act="dock"]').hidden).toBe(false);+ const saved = JSON.parse(dom.window.localStorage.getItem('tws:tour:menu-pos'));+ expect(saved.x).toBeGreaterThan(8);+ expect(saved.y).toBeGreaterThan(8);+ });++ it('reopens floating at the remembered position, and jump keeps it open', () => {+ dom.window.localStorage.setItem('tws:tour:menu-pos', JSON.stringify({ x: 120, y: 90 }));+ panel.show();+ const root = document.querySelector('.tws-tour-menu');+ expect(root.classList.contains('is-floating')).toBe(true);+ const el = document.querySelector('.tws-tour-menu__panel');+ expect(el.style.left).toBe('120px');+ expect(el.style.top).toBe('90px');+ document.querySelectorAll('.tws-tour-stop')[1].click();+ expect(jumped).toEqual([1]);+ expect(panel.open).toBe(true); // floating map stays open as a companion+ });++ it('an open floating map self-restores on the next page, without stealing focus', () => {+ dom.window.localStorage.setItem('tws:tour:menu-pos', JSON.stringify({ x: 120, y: 90 }));+ dom.window.sessionStorage.setItem('tws:tour:menu-open', '1');+ // Simulate the next stop's page: a fresh panel over the same storage.+ const next = new ChapterPanel(CURRICULUM, { onJump: () => {} });+ expect(next.open).toBe(true);+ expect(next.floating).toBe(true);+ next.dispose();+ // Deliberate teardown (tour exit) clears the self-reopen flag.+ expect(dom.window.sessionStorage.getItem('tws:tour:menu-open')).toBe(null);+ });++ it('closing the floating map stops it from self-restoring', () => {+ dom.window.localStorage.setItem('tws:tour:menu-pos', JSON.stringify({ x: 120, y: 90 }));+ panel.show();+ expect(dom.window.sessionStorage.getItem('tws:tour:menu-open')).toBe('1');+ panel.close();+ expect(dom.window.sessionStorage.getItem('tws:tour:menu-open')).toBe(null);+ const next = new ChapterPanel(CURRICULUM, { onJump: () => {} });+ expect(next.open).toBe(false);+ next.dispose();+ });++ it('dock returns to the drawer and forgets the position', () => {+ dom.window.localStorage.setItem('tws:tour:menu-pos', JSON.stringify({ x: 120, y: 90 }));+ panel.show();+ document.querySelector('[data-act="dock"]').click();+ const root = document.querySelector('.tws-tour-menu');+ expect(root.classList.contains('is-floating')).toBe(false);+ expect(dom.window.localStorage.getItem('tws:tour:menu-pos')).toBe(null);+ const el = document.querySelector('.tws-tour-menu__panel');+ expect(el.style.left).toBe('');+ });+});