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: page-agent entry + walk-sdk config/picker, avatar service tweaks
nirholasce7b2ce70a62
diff --git a/api/_lib/avatars.js b/api/_lib/avatars.jsindex e95f9bb94..a17f59e3a 100644--- a/api/_lib/avatars.js+++ b/api/_lib/avatars.js@@ -264,14 +264,12 @@ export async function searchPublicAvatars({// Rig classifier filter. Mirrors classifyRig() in src/shared/rig-classify.js// exactly so a server-filtered list and a client-painted badge never disagree:// a model is "rigged" iff source_meta.is_rigged is true OR it carries a- // positive skeleton_joint_count. CASE guards mean a malformed JSONB value- // degrades to "not rigged" instead of throwing a cast error.- // CASE (not AND) guards the cast: Postgres does not guarantee WHERE-clause- // AND short-circuits, so a bare `regex and (..)::int` can still evaluate the- // cast on a non-numeric string and throw. CASE is guaranteed to short-circuit.+ // positive skeleton_joint_count. The joint test uses a regex (matching any+ // integer ≥ 1) rather than an ::int cast so a malformed JSONB value can never+ // throw — it simply fails to match and the model reads as "not rigged".const RIG_SIGNAL = `((source_meta->>'is_rigged') = 'true'- or case when source_meta->>'skeleton_joint_count' ~ '^[1-9][0-9]*$' then true else false end+ or source_meta->>'skeleton_joint_count' ~ '^[1-9][0-9]*$')`;const rigState = normalizeRigFilter(rigged);if (rigState === 'rigged') {diff --git a/page-agent-sdk/src/page-agent.js b/page-agent-sdk/src/page-agent.jsnew file mode 100644index 000000000..2306959b5--- /dev/null+++ b/page-agent-sdk/src/page-agent.js@@ -0,0 +1,422 @@+/**+ * PageAgent — @three-ws/page-agent+ * ================================+ *+ * The product surface: a floating, rigged 3D agent docked in the corner of any+ * page that talks the visitor through it. Composes the three building blocks —+ * AvatarStage (renders + animates the rigged GLB), SpeechNarrator (TTS ++ * lipsync), AvatarPicker (visitor chooses their guide) — into one drop-in+ * controller, plus a control bar, caption bubble, drag-to-move, and an+ * auto-narration walk over the page's content.+ *+ * Public API (also surfaced on the <page-agent> element):+ * agent.narrate(text, { interrupt }) → Promise<void>+ * agent.narratePage({ selector }) → Promise<void> (sequential walk)+ * agent.stop() → cancel narration+ * agent.setAgent(id) → swap rigged avatar live+ * agent.openPicker() / closePicker()+ * agent.mute(bool) / collapse(bool)+ * agent.on(event, cb) / off(event, cb) events: ready, agentchange, state,+ * caption, segment, error+ */++import { AGENTS, DEFAULT_AGENT_ID, DEFAULT_ASSET_BASE, getAgent, agentUrl, filterAgents } from './catalog.js';+import { AvatarStage } from './stage.js';+import { SpeechNarrator } from './narrator.js';+import { AvatarPicker } from './picker.js';+import { injectStyles } from './styles.js';++const ICONS = {+ play: '<svg viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>',+ stop: '<svg viewBox="0 0 24 24" fill="currentColor"><rect x="6" y="6" width="12" height="12" rx="2"/></svg>',+ mute: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5 6 9H3v6h3l5 4z"/><path d="m22 9-6 6M16 9l6 6"/></svg>',+ unmute: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 5 6 9H3v6h3l5 4z"/><path d="M15.5 8.5a5 5 0 0 1 0 7M19 5a9 9 0 0 1 0 14"/></svg>',+ swap: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="8" r="4"/><path d="M4 21a8 8 0 0 1 16 0"/><path d="m17 3 3 2-3 2"/></svg>',+ min: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M5 12h14"/></svg>',+};++const EVENTS = ['ready', 'agentchange', 'state', 'caption', 'segment', 'error'];++export class PageAgent {+ /**+ * @param {{+ * mount?: HTMLElement, agent?: string, agents?: string[], assetBase?: string,+ * position?: 'bottom-right'|'bottom-left'|'top-right'|'top-left',+ * muted?: boolean, collapsed?: boolean, picker?: boolean, controls?: boolean,+ * greeting?: string, autoNarrate?: boolean|string, persistAgent?: boolean+ * }} [config]+ */+ constructor(config = {}) {+ if (typeof window === 'undefined') throw new Error('[page-agent] requires a browser environment');+ this.config = config;+ this.assetBase = config.assetBase || DEFAULT_ASSET_BASE;+ this.roster = config.agents?.length ? filterAgents({ ids: config.agents }) : AGENTS;+ if (!this.roster.length) this.roster = AGENTS;++ this._listeners = new Map(EVENTS.map((e) => [e, new Set()]));+ this._agent = null;+ this._narrationToken = 0;++ injectStyles();+ this._buildDom();++ this.stage = new AvatarStage(this._stageEl, { background: 'transparent' });+ this.narrator = new SpeechNarrator(this.stage, {+ muted: !!config.muted,+ onState: (s) => { this._root.dataset.state = s === 'speaking' ? 'speaking' : this._stateBase(); this._reflectPlay(); this._emit('state', s); },+ onCaption: (c) => { this._setCaption(c); this._emit('caption', c); },+ onError: (e) => this._emit('error', e),+ });++ if (config.picker !== false) {+ this.picker = new AvatarPicker(this.roster, {+ onSelect: (id) => this.setAgent(id),+ getCurrent: () => this._agent?.id,+ });+ }++ // Initial agent: explicit > persisted (if enabled) > default > first roster.+ const persisted = config.persistAgent !== false ? AvatarPicker.restore() : null;+ const initial = config.agent || persisted || DEFAULT_AGENT_ID;+ const startId = this.roster.find((a) => a.id === initial) ? initial : this.roster[0].id;++ this._muted = !!config.muted;+ this._collapsed = !!config.collapsed;+ this._root.dataset.state = this._stateBase();++ this.setAgent(startId).then(() => {+ this._emit('ready', this._agent);+ if (config.autoNarrate) {+ const sel = typeof config.autoNarrate === 'string' ? config.autoNarrate : undefined;+ this.narratePage({ selector: sel, greet: true });+ } else if (config.greeting) {+ this.narrate(config.greeting);+ }+ }).catch((e) => this._emit('error', e));+ }++ // ── DOM ──────────────────────────────────────────────────────────────────++ _buildDom() {+ const root = document.createElement('div');+ root.className = 'tw-pa-root';+ root.dataset.pos = this.config.position || 'bottom-right';++ // Launcher (collapsed state)+ const launcher = document.createElement('button');+ launcher.className = 'tw-pa-launcher';+ launcher.type = 'button';+ launcher.innerHTML = `<span class="tw-pa-orb" aria-hidden="true"></span><span class="tw-pa-launch-label">Ask a guide</span>`;+ launcher.setAttribute('aria-label', 'Open the 3D guide');+ launcher.addEventListener('click', () => this.collapse(false));++ const dock = document.createElement('div');+ dock.className = 'tw-pa-dock';++ const stage = document.createElement('div');+ stage.className = 'tw-pa-stage';++ const name = document.createElement('div');+ name.className = 'tw-pa-name';+ name.innerHTML = '<span class="tw-pa-name-text">Agent</span>';++ const caption = document.createElement('div');+ caption.className = 'tw-pa-caption';+ caption.setAttribute('aria-live', 'polite');+ caption.dataset.show = 'false';++ stage.append(name, caption);+ this._enableDrag(root, stage);++ // Control bar+ const bar = document.createElement('div');+ bar.className = 'tw-pa-bar';+ if (this.config.controls === false) bar.style.display = 'none';++ this._playBtn = mkBtn(ICONS.play, 'Play narration', () => this._togglePlay());+ this._muteBtn = mkBtn(ICONS.unmute, 'Mute', () => this.mute(!this._muted));+ this._swapBtn = mkBtn(ICONS.swap, 'Change agent', () => this.openPicker());+ if (this.config.picker === false) this._swapBtn.style.display = 'none';+ const spacer = document.createElement('div');+ spacer.className = 'tw-pa-spacer';+ this._minBtn = mkBtn(ICONS.min, 'Minimize', () => this.collapse(true));++ bar.append(this._playBtn, this._muteBtn, this._swapBtn, spacer, this._minBtn);++ dock.append(stage, bar);+ root.append(dock, launcher);+ document.body.appendChild(root);++ this._root = root;+ this._stageEl = stage;+ this._nameEl = name.querySelector('.tw-pa-name-text');+ this._captionEl = caption;+ this._launcher = launcher;+ }++ _enableDrag(root, handle) {+ let sx = 0, sy = 0, ox = 0, oy = 0, dragging = false, moved = false;+ const down = (e) => {+ if (e.target.closest('.tw-pa-caption')) return;+ const p = pointer(e);+ dragging = true; moved = false;+ sx = p.x; sy = p.y;+ const r = root.getBoundingClientRect();+ ox = r.left; oy = r.top;+ window.addEventListener('pointermove', move);+ window.addEventListener('pointerup', up);+ };+ const move = (e) => {+ if (!dragging) return;+ const p = pointer(e);+ const dx = p.x - sx, dy = p.y - sy;+ if (Math.abs(dx) + Math.abs(dy) > 4) moved = true;+ root.dataset.pos = '';+ root.style.left = clamp(ox + dx, 4, window.innerWidth - root.offsetWidth - 4) + 'px';+ root.style.top = clamp(oy + dy, 4, window.innerHeight - root.offsetHeight - 4) + 'px';+ root.style.right = 'auto';+ root.style.bottom = 'auto';+ };+ const up = () => {+ dragging = false;+ window.removeEventListener('pointermove', move);+ window.removeEventListener('pointerup', up);+ };+ handle.addEventListener('pointerdown', down);+ }++ // ── Agent lifecycle ────────────────────────────────────────────────────────++ /** Swap to a rigged agent by id. Loads its GLB and reframes. */+ async setAgent(id) {+ const agent = getAgent(id) || this.roster[0];+ if (!agent) return;+ this._agent = agent;+ this.narrator.setAgent(agent);+ this._nameEl.textContent = agent.name;+ this._root.style.setProperty('--tw-pa-accent', agent.accent);+ this._launcher.querySelector('.tw-pa-launch-label').textContent = `Ask ${agent.name}`;+ try {+ await this.stage.load(agentUrl(agent, this.assetBase), { framing: agent.framing });+ this._emit('agentchange', agent);+ } catch (e) {+ this._emit('error', new Error(`Failed to load agent "${agent.id}": ${e.message}`));+ throw e;+ }+ }++ // ── Narration ───────────────────────────────────────────────────────────────++ /** Speak a single line. @returns {Promise<void>} */+ narrate(text, opts = {}) {+ if (this._collapsed) this.collapse(false);+ return this.narrator.speak(text, opts);+ }++ /**+ * Walk the page and narrate it segment by segment. Pulls text from, in order+ * of preference: elements matching `selector`, then `[data-narrate]`, then a+ * sensible heading/paragraph fallback. Highlights the current segment.+ * @param {{ selector?: string, greet?: boolean }} [opts]+ * @returns {Promise<void>}+ */+ async narratePage(opts = {}) {+ const token = ++this._narrationToken;+ this.stop(); // clear any prior walk but keep our token+ this._narrationToken = token;+ if (this._collapsed) this.collapse(false);++ const segments = collectSegments(opts.selector);+ if (opts.greet && this._agent) {+ await this.narrator.speak(this._agent.persona);+ if (token !== this._narrationToken) return;+ }+ if (!segments.length) {+ await this.narrator.speak("There's not much text on this page for me to read, but I'm here if you need a hand.");+ return;+ }+ for (const seg of segments) {+ if (token !== this._narrationToken) return;+ this._highlight(seg.el, true);+ this._emit('segment', { text: seg.text, el: seg.el });+ try { seg.el?.scrollIntoView?.({ behavior: 'smooth', block: 'center' }); } catch { /* detached */ }+ await this.narrator.speak(seg.text);+ this._highlight(seg.el, false);+ }+ }++ /** Cancel any narration / walk in progress. */+ stop() {+ this._narrationToken++;+ this.narrator.cancel();+ this._clearHighlights();+ }++ _togglePlay() {+ if (this.narrator.speaking) this.stop();+ else this.narratePage({ selector: typeof this.config.autoNarrate === 'string' ? this.config.autoNarrate : undefined });+ }++ _reflectPlay() {+ const speaking = this.narrator.speaking;+ this._playBtn.innerHTML = speaking ? ICONS.stop : ICONS.play;+ this._playBtn.setAttribute('aria-label', speaking ? 'Stop narration' : 'Play narration');+ }++ // ── Controls ────────────────────────────────────────────────────────────────++ mute(on) {+ this._muted = !!on;+ this.narrator.setMuted(this._muted);+ this._muteBtn.innerHTML = this._muted ? ICONS.mute : ICONS.unmute;+ this._muteBtn.setAttribute('aria-pressed', String(this._muted));+ this._muteBtn.setAttribute('aria-label', this._muted ? 'Unmute' : 'Mute');+ }++ collapse(on) {+ this._collapsed = !!on;+ this._root.dataset.state = this._stateBase();+ if (this._collapsed) this.stop();+ }++ openPicker() {+ this.picker?.open();+ }++ closePicker() {+ this.picker?.close();+ }++ // ── Events ──────────────────────────────────────────────────────────────────++ on(event, cb) { this._listeners.get(event)?.add(cb); return this; }+ off(event, cb) { this._listeners.get(event)?.delete(cb); return this; }+ _emit(event, payload) {+ for (const cb of this._listeners.get(event) || []) {+ try { cb(payload); } catch (e) { console.error('[page-agent] listener error', e); }+ }+ }++ get currentAgent() { return this._agent; }++ // ── Internals ─────────────────────────────────────────────────────────────────++ _stateBase() { return this._collapsed ? 'collapsed' : 'idle'; }++ _setCaption(text) {+ if (!text) { this._captionEl.dataset.show = 'false'; return; }+ this._captionEl.textContent = text;+ this._captionEl.dataset.show = 'true';+ }++ _highlight(el, on) {+ if (!el) return;+ if (on) {+ el.dataset._twPaPrevOutline = el.style.outline || '';+ el.style.outline = `2px solid ${this._agent?.accent || '#6366f1'}`;+ el.style.outlineOffset = '3px';+ el.style.borderRadius = el.style.borderRadius || '6px';+ this._highlighted = el;+ } else {+ el.style.outline = el.dataset._twPaPrevOutline || '';+ delete el.dataset._twPaPrevOutline;+ if (this._highlighted === el) this._highlighted = null;+ }+ }++ _clearHighlights() {+ if (this._highlighted) this._highlight(this._highlighted, false);+ }++ dispose() {+ this.stop();+ this.narrator?.dispose();+ this.stage?.dispose();+ this.picker?.dispose();+ this._root?.remove();+ }+}++// ── Page content extraction ──────────────────────────────────────────────────++/**+ * Build an ordered list of narration segments from the live DOM.+ * Priority: explicit selector → [data-narrate] → heading/lead fallback.+ * @param {string} [selector]+ * @returns {{ el: Element, text: string }[]}+ */+export function collectSegments(selector) {+ const pick = (els) => Array.from(els)+ .map((el) => ({ el, text: narrationText(el) }))+ .filter((s) => s.text.length > 1);++ if (selector) {+ const found = pick(document.querySelectorAll(selector));+ if (found.length) return found;+ }+ const tagged = pick(document.querySelectorAll('[data-narrate]'));+ if (tagged.length) {+ // Honor explicit ordering via data-narrate-order when present.+ return tagged.sort((a, b) => order(a.el) - order(b.el));+ }+ // Fallback: headings + their following lead paragraph, in document order.+ const out = [];+ const heads = document.querySelectorAll('main h1, main h2, main h3, article h1, article h2, article h3, h1, h2');+ const seen = new Set();+ for (const h of heads) {+ if (seen.has(h) || !isVisible(h)) continue;+ seen.add(h);+ let text = narrationText(h);+ const lead = nextParagraph(h);+ if (lead && !seen.has(lead)) { seen.add(lead); text += '. ' + narrationText(lead); }+ if (text.length > 1) out.push({ el: h, text });+ if (out.length >= 12) break; // keep a page tour reasonable+ }+ return out;+}++function narrationText(el) {+ const explicit = el.getAttribute?.('data-narrate');+ if (explicit && explicit.trim()) return explicit.trim();+ return (el.textContent || '').replace(/\s+/g, ' ').trim().slice(0, 600);+}++function order(el) {+ const v = parseInt(el.getAttribute('data-narrate-order') || '', 10);+ return Number.isFinite(v) ? v : 1e6;+}++function nextParagraph(h) {+ let n = h.nextElementSibling;+ let hops = 0;+ while (n && hops < 4) {+ if (n.tagName === 'P' && isVisible(n)) return n;+ if (/^H[1-6]$/.test(n.tagName)) return null;+ n = n.nextElementSibling; hops++;+ }+ return null;+}++function isVisible(el) {+ if (!el || !el.getClientRects().length) return false;+ const s = getComputedStyle(el);+ return s.visibility !== 'hidden' && s.display !== 'none';+}++// ── tiny helpers ──────────────────────────────────────────────────────────────++function mkBtn(svg, label, onClick) {+ const b = document.createElement('button');+ b.className = 'tw-pa-btn';+ b.type = 'button';+ b.innerHTML = svg;+ b.setAttribute('aria-label', label);+ b.addEventListener('click', onClick);+ return b;+}++function pointer(e) {+ return { x: e.clientX ?? e.touches?.[0]?.clientX ?? 0, y: e.clientY ?? e.touches?.[0]?.clientY ?? 0 };+}++function clamp(n, lo, hi) { return Math.max(lo, Math.min(hi, n)); }diff --git a/src/dashboard-next/pages/avatars.js b/src/dashboard-next/pages/avatars.jsindex a0ed0ea65..3d5493d1f 100644--- a/src/dashboard-next/pages/avatars.js+++ b/src/dashboard-next/pages/avatars.js@@ -617,6 +617,7 @@ function communityCard(root, a) {</div><div class="dn-av-meta">${onchain}+ ${rigBadgeHTML(a, { size: 'sm' })}${tagBits}${views ? `<span class="dn-av-rel">${compactNum.format(views)} views</span>` : ''}<span class="dn-av-rel">${esc(relTime(a.created_at))}</span>@@ -800,6 +801,7 @@ function avatarCard(root, a) {</div><div class="dn-av-meta">${visibilityTag(a.visibility)}+ ${rigBadgeHTML(a, { size: 'sm' })}<span class="dn-av-rel">${esc(relTime(a.updated_at || a.created_at))}</span></div>${avatarWalletChip(a)}diff --git a/walk-sdk/src/config.js b/walk-sdk/src/config.jsnew file mode 100644index 000000000..996056c86--- /dev/null+++ b/walk-sdk/src/config.js@@ -0,0 +1,60 @@+// Configuration resolution for the Walk SDK.+// ===========================================+// One options object flows to both the companion and the playground. Defaults+// match the three.ws app exactly — including the localStorage/sessionStorage+// keys — so dropping the SDK in is behaviourally identical to the hand-written+// modules it replaces, and an existing visitor's saved state carries over.++import { WALK_AVATARS, DEFAULT_AVATAR_ID, getAvatar, makeApiAvatarEntry } from './roster.js';++// Routes that already own the viewport with their own full-screen 3D, where a+// corner mascot would be redundant or intrusive.+export const DEFAULT_EXCLUDED_PREFIXES = [+ '/walk',+ '/walk-embed',+ '/embed',+ '/play',+ '/club',+ '/city',+ '/xr',+ '/ar',+ '/pose',+ '/mocap-studio',+ '/avatar-studio',+];++export function resolveConfig(opts = {}) {+ const prefix = opts.storagePrefix || 'walk';+ return {+ avatars: opts.avatars || WALK_AVATARS,+ defaultAvatarId: opts.defaultAvatarId || DEFAULT_AVATAR_ID,+ assetBase: opts.assetBase || '',+ apiBase: opts.apiBase || '',+ manifestUrl: opts.manifestUrl || '/animations/manifest.json',+ excludedRoutes: opts.excludedRoutes || DEFAULT_EXCLUDED_PREFIXES,+ enablePicker: opts.enablePicker !== false,+ greeting: typeof opts.greeting === 'function' ? opts.greeting : null,+ docsUrl: opts.docsUrl || null,+ keys: {+ enabled: `${prefix}:companion:enabled`,+ state: `${prefix}:companion:state`,+ avatar: `${prefix}:companion:avatar`,+ greet: `${prefix}:companion:greet`,+ invited: `${prefix}:companion:invited`,+ resume: `${prefix}:playground:resume`,+ mode: `${prefix}:playground:mode`,+ },+ };+}++/**+ * Resolve a stored/queried avatar id into a roster entry. An id that isn't in+ * the static roster is assumed to be a user-generated avatar served by the GLB+ * proxy, so it becomes an on-the-fly API entry.+ */+export function resolveAvatarEntry(id, config) {+ if (!id) return getAvatar(config.defaultAvatarId) || config.avatars[0];+ const fromRoster = config.avatars.find((a) => a.id === id) || getAvatar(id);+ if (fromRoster) return fromRoster;+ return makeApiAvatarEntry(id);+}diff --git a/walk-sdk/src/picker.js b/walk-sdk/src/picker.jsnew file mode 100644index 000000000..9506e1e55--- /dev/null+++ b/walk-sdk/src/picker.js@@ -0,0 +1,221 @@+// Walk avatar picker — the panel where a visitor chooses who walks their pages.+// ============================================================================+// A self-contained, accessible popover: a searchable, category-grouped grid of+// the roster. It owns no 3D — selecting an avatar fires `onSelect(entry)` and+// the host (companion/playground) hot-swaps the live rig. Keyboard-navigable+// (arrows + Enter), closes on Escape or an outside click, and remembers nothing+// itself (persistence is the host's job).++import { isCoarsePointer } from './internal/storage.js';++let _stylesInjected = false;+function ensureStyles() {+ if (_stylesInjected || typeof document === 'undefined') return;+ _stylesInjected = true;+ const style = document.createElement('style');+ style.id = 'walk-picker-style';+ style.textContent = `+.walk-picker{position:fixed;z-index:2147483200;width:320px;max-width:calc(100vw - 24px);max-height:min(70vh,560px);display:flex;flex-direction:column;background:rgba(16,18,26,.97);color:#eef1f6;border:1px solid rgba(255,255,255,.12);border-radius:16px;box-shadow:0 24px 64px rgba(0,0,0,.5);backdrop-filter:blur(10px);opacity:0;transform:translateY(8px) scale(.98);transform-origin:bottom right;transition:opacity .2s ease,transform .2s ease;font:400 13px/1.4 system-ui,-apple-system,'Segoe UI',sans-serif;overflow:hidden}+.walk-picker.is-in{opacity:1;transform:translateY(0) scale(1)}+.walk-picker-head{display:flex;align-items:center;gap:8px;padding:12px 12px 8px}+.walk-picker-title{font-weight:700;font-size:13.5px;letter-spacing:.01em}+.walk-picker-title small{display:block;font-weight:400;font-size:11px;color:#9aa3b2;margin-top:1px}+.walk-picker-close{margin-left:auto;width:26px;height:26px;border:none;border-radius:8px;background:rgba(255,255,255,.06);color:#cfd6e2;font-size:16px;line-height:1;cursor:pointer;display:grid;place-items:center;transition:background .15s ease}+.walk-picker-close:hover{background:rgba(255,255,255,.14)}+.walk-picker-close:focus-visible{outline:2px solid #7aa2ff;outline-offset:2px}+.walk-picker-search{margin:0 12px 8px;display:flex;align-items:center;gap:7px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.08);border-radius:10px;padding:7px 10px}+.walk-picker-search:focus-within{border-color:rgba(122,162,255,.7)}+.walk-picker-search input{flex:1;min-width:0;background:none;border:none;outline:none;color:#eef1f6;font:inherit}+.walk-picker-search input::placeholder{color:#7e8696}+.walk-picker-list{overflow-y:auto;padding:0 12px 12px;scrollbar-width:thin}+.walk-picker-cat{font-size:10.5px;font-weight:700;letter-spacing:.08em;text-transform:uppercase;color:#7e8696;margin:12px 2px 7px}+.walk-picker-grid{display:grid;grid-template-columns:repeat(3,1fr);gap:8px}+.walk-picker-tile{position:relative;border:1px solid rgba(255,255,255,.1);border-radius:12px;padding:10px 6px 8px;cursor:pointer;background:rgba(255,255,255,.02);text-align:center;transition:transform .12s ease,border-color .15s ease,background .15s ease;color:inherit;font:inherit;display:flex;flex-direction:column;align-items:center;gap:5px;overflow:hidden}+.walk-picker-tile:hover{transform:translateY(-2px);background:rgba(255,255,255,.06)}+.walk-picker-tile:focus-visible{outline:2px solid #7aa2ff;outline-offset:1px}+.walk-picker-tile.is-active{border-color:var(--wp-accent,#7aa2ff);background:rgba(122,162,255,.12)}+.walk-picker-tile.is-active::after{content:'✓';position:absolute;top:5px;right:6px;font-size:11px;color:var(--wp-accent,#7aa2ff)}+.walk-picker-orb{width:46px;height:46px;border-radius:50%;display:grid;place-items:center;font-size:22px;background:radial-gradient(circle at 35% 30%,rgba(255,255,255,.35),transparent 60%),var(--wp-accent,#7aa2ff);box-shadow:inset 0 -6px 12px rgba(0,0,0,.25);background-size:cover;background-position:center}+.walk-picker-name{font-size:11.5px;font-weight:600;line-height:1.1}+.walk-picker-empty{padding:24px 8px;text-align:center;color:#7e8696;font-size:12.5px}+.walk-picker-foot{padding:8px 12px;border-top:1px solid rgba(255,255,255,.08);font-size:11px;color:#7e8696;display:flex;justify-content:space-between;gap:8px}+.walk-picker-foot a{color:#9bb8ff;text-decoration:none}+.walk-picker-foot a:hover{text-decoration:underline}+@media (max-width:520px){.walk-picker{width:calc(100vw - 24px)}.walk-picker-grid{grid-template-columns:repeat(4,1fr)}}+@media (prefers-reduced-motion:reduce){.walk-picker,.walk-picker-tile{transition:none}}+`;+ document.head.appendChild(style);+}++/**+ * @param {object} opts+ * @param {Array} opts.avatars roster entries to show+ * @param {string|null} opts.currentId currently selected avatar id+ * @param {(entry:object)=>void} opts.onSelect called with the chosen entry+ * @param {{right:number,bottom:number}} [opts.anchor] viewport anchor (px from edges)+ * @param {string} [opts.assetBase] base for thumbnail urls+ * @param {string} [opts.docsUrl] optional "make your own" link+ */+export function createAvatarPicker(opts) {+ ensureStyles();+ const { avatars = [], onSelect, anchor = { right: 16, bottom: 16 }, assetBase = '', docsUrl } = opts;+ let currentId = opts.currentId || null;+ let query = '';++ const root = document.createElement('div');+ root.className = 'walk-picker';+ root.setAttribute('role', 'dialog');+ root.setAttribute('aria-label', 'Choose your walking avatar');+ root.style.right = `${anchor.right}px`;+ root.style.bottom = `${anchor.bottom}px`;++ root.innerHTML = `+ <div class="walk-picker-head">+ <div class="walk-picker-title">Walking avatar<small>Pick who roams your pages</small></div>+ <button type="button" class="walk-picker-close" aria-label="Close avatar picker">×</button>+ </div>+ <label class="walk-picker-search">+ <span aria-hidden="true">🔍</span>+ <input type="search" placeholder="Search avatars…" aria-label="Search avatars" />+ </label>+ <div class="walk-picker-list" role="listbox" aria-label="Avatars"></div>+ ${docsUrl ? `<div class="walk-picker-foot"><span>${avatars.length} avatars</span><a href="${docsUrl}">Make your own →</a></div>` : ''}+ `;++ const listEl = root.querySelector('.walk-picker-list');+ const inputEl = root.querySelector('.walk-picker-search input');+ const closeBtn = root.querySelector('.walk-picker-close');++ function tileFor(entry) {+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = 'walk-picker-tile' + (entry.id === currentId ? ' is-active' : '');+ btn.setAttribute('role', 'option');+ btn.setAttribute('aria-selected', String(entry.id === currentId));+ btn.dataset.id = entry.id;+ btn.title = entry.blurb || entry.name;+ if (entry.accent) btn.style.setProperty('--wp-accent', entry.accent);+ const orbStyle = entry.thumb ? ` style="background-image:url('${assetBase}${entry.thumb}')"` : '';+ btn.innerHTML = `+ <span class="walk-picker-orb"${orbStyle}>${entry.thumb ? '' : entry.emoji || '🧍'}</span>+ <span class="walk-picker-name">${entry.name}</span>+ `;+ btn.addEventListener('click', () => choose(entry));+ return btn;+ }++ function render() {+ const q = query.trim().toLowerCase();+ const matches = avatars.filter((a) => {+ if (!q) return true;+ return (+ a.name.toLowerCase().includes(q) ||+ a.category.toLowerCase().includes(q) ||+ (a.tags || []).some((t) => t.includes(q))+ );+ });+ listEl.innerHTML = '';+ if (!matches.length) {+ const empty = document.createElement('div');+ empty.className = 'walk-picker-empty';+ empty.textContent = `No avatars match “${query}”.`;+ listEl.appendChild(empty);+ return;+ }+ const cats = [];+ for (const a of matches) if (!cats.includes(a.category)) cats.push(a.category);+ for (const cat of cats) {+ const h = document.createElement('div');+ h.className = 'walk-picker-cat';+ h.textContent = cat;+ listEl.appendChild(h);+ const grid = document.createElement('div');+ grid.className = 'walk-picker-grid';+ for (const a of matches.filter((m) => m.category === cat)) grid.appendChild(tileFor(a));+ listEl.appendChild(grid);+ }+ }++ function choose(entry) {+ currentId = entry.id;+ render();+ onSelect?.(entry);+ close();+ }++ // ── Open / close lifecycle ────────────────────────────────────────────────+ let open = false;+ const onDocPointer = (e) => {+ if (!root.contains(e.target) && !e.target.closest?.('[data-walk-picker-toggle]')) close();+ };+ const onKey = (e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ close();+ return;+ }+ const tiles = [...listEl.querySelectorAll('.walk-picker-tile')];+ const i = tiles.indexOf(document.activeElement);+ if (['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp'].includes(e.key) && tiles.length) {+ e.preventDefault();+ const cols = matchMedia('(max-width:520px)').matches ? 4 : 3;+ let next = i;+ if (e.key === 'ArrowRight') next = i + 1;+ else if (e.key === 'ArrowLeft') next = i - 1;+ else if (e.key === 'ArrowDown') next = i + cols;+ else if (e.key === 'ArrowUp') next = i - cols;+ next = Math.max(0, Math.min(tiles.length - 1, next));+ tiles[next]?.focus();+ }+ };++ inputEl.addEventListener('input', () => {+ query = inputEl.value;+ render();+ });+ closeBtn.addEventListener('click', close);+ root.addEventListener('keydown', onKey);++ function show() {+ if (open) return;+ open = true;+ render();+ document.body.appendChild(root);+ requestAnimationFrame(() => {+ root.classList.add('is-in');+ // Focus search on desktop; avoid popping the keyboard on touch.+ if (!isCoarsePointer()) inputEl.focus();+ });+ setTimeout(() => document.addEventListener('pointerdown', onDocPointer, true), 0);+ }++ function close() {+ if (!open) return;+ open = false;+ root.classList.remove('is-in');+ document.removeEventListener('pointerdown', onDocPointer, true);+ setTimeout(() => {+ if (!open && root.parentNode) root.parentNode.removeChild(root);+ }, 200);+ }++ function destroy() {+ close();+ root.removeEventListener('keydown', onKey);+ }++ return {+ el: root,+ show,+ close,+ toggle() {+ open ? close() : show();+ },+ isOpen: () => open,+ setCurrent(id) {+ currentId = id;+ if (open) render();+ },+ destroy,+ };+}