Skip to content

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.

refactor(character-library): lift the view logic out of the DOM so it can be tested

nirholas9f949db89c40
diff --git a/.gitignore b/.gitignore
index 0fb1e19c1..ab08446e5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -490,3 +490,6 @@ packages/node-operator/models/
# Dev-server logs from `npm run dev` on an alternate port (.vite<port>.log).
.vite*.log
+
+# Scratch capture of an `npm test` run (.npmtest-<label>.log).
+.npmtest-*.log
diff --git a/src/character-library.js b/src/character-library.js
index 359213f4f..a02a58c75 100644
--- a/src/character-library.js
+++ b/src/character-library.js
@@ -10,7 +10,17 @@
//
// The library is small (a hundred or so entries) so the whole manifest is
// fetched once and filtered/sorted client-side: no pagination round-trips,
-// instant search.
+// instant search. The search, sort, card copy and deep links are pure functions
+// of the manifest and live in shared/character-library-view.js, under test in
+// tests/character-library-view.test.js.
+
+import {
+ cardMeta,
+ characterName,
+ viewerLinks,
+ viewState,
+ visibleCharacters,
+} from './shared/character-library-view.js';
const els = {
grid: document.querySelector('[data-role="grid"]'),
@@ -46,10 +56,18 @@ function show(el, on) {
if (el) el.hidden = !on;
}
-function formatBytes(n) {
- if (!n) return '';
- const mb = n / 1024 / 1024;
- return mb >= 1 ? `${mb.toFixed(1)} MB` : `${Math.round(n / 1024)} KB`;
+// Exactly one of the page's five states is on screen at a time; showing the next
+// one is always "hide the other four".
+const PANELS = {
+ loading: () => els.loading,
+ grid: () => els.grid,
+ empty: () => els.empty,
+ 'empty-search': () => els.emptySearch,
+ error: () => els.error,
+};
+
+function showOnly(name) {
+ for (const [key, el] of Object.entries(PANELS)) show(el(), key === name);
}
// A card's <model-viewer> is deliberately control-free. model-viewer reads
@@ -67,16 +85,29 @@ function formatBytes(n) {
// native lazy loading and off-thread decoding on the way.
function renderCard(a) {
const glbUrl = a.url || '';
- const previewUrl = glbUrl ? `/app#model=${encodeURIComponent(glbUrl)}` : '#';
- const useUrl = glbUrl ? `/studio?model=${encodeURIComponent(glbUrl)}` : '#';
- const animateUrl = glbUrl ? `/pose?src=${encodeURIComponent(glbUrl)}&title=${encodeURIComponent(a.label || a.name)}` : '#';
+ const links = viewerLinks(a);
const thumb = a.thumb || '';
- const alt = a.label || a.name || 'Character';
+ const alt = characterName(a) || 'Character';
+
+ // A row with no GLB gets a plain, unlinked tile rather than an anchor to "#":
+ // the three viewers all take the model URL, so with none there is nothing for
+ // them to open.
+ const openTag = links
+ ? `<a class="ch-card-thumb" href="${escapeAttr(links.preview)}" aria-label="Preview ${escapeAttr(alt)} in 3D">`
+ : '<div class="ch-card-thumb">';
+ const closeTag = links ? '</a>' : '</div>';
+ const actions = links
+ ? `<div class="ch-card-actions">
+ <a class="ch-btn ch-btn--primary" href="${escapeAttr(links.use)}" title="Use in Widget Studio">Use</a>
+ <a class="ch-btn ch-btn--ghost" href="${escapeAttr(links.animate)}" title="Animate in the Animation Studio">Animate</a>
+ <a class="ch-btn ch-btn--ghost" href="${escapeAttr(links.preview)}" title="Open in the 3D viewer">Preview</a>
+ </div>`
+ : '';
const card = document.createElement('article');
card.className = 'ch-card';
card.innerHTML = `
- <a class="ch-card-thumb" href="${escapeAttr(previewUrl)}" aria-label="Preview ${escapeAttr(alt)} in 3D">
+ ${openTag}
<model-viewer
src="${escapeAttr(glbUrl)}"
alt="${escapeAttr(alt)}"
@@ -92,17 +123,13 @@ function renderCard(a) {
>${thumb ? `<img slot="poster" class="ch-card-poster" src="${escapeAttr(thumb)}" alt="" loading="lazy" decoding="async" />` : ''}</model-viewer>
<span class="ch-card-pill">Rigged</span>
<span class="ch-card-play" aria-hidden="true">▶</span>
- </a>
+ ${closeTag}
<div class="ch-card-body">
- <h3 class="ch-card-name">${escapeHtml(a.label || a.name)}</h3>
+ <h3 class="ch-card-name">${escapeHtml(alt)}</h3>
<div class="ch-card-meta">
- <span title="Skinned mesh, ready to animate">Mixamo · ${escapeHtml(formatBytes(a.bytes))}</span>
- </div>
- <div class="ch-card-actions">
- <a class="ch-btn ch-btn--primary" href="${escapeAttr(useUrl)}" title="Use in Widget Studio">Use</a>
- <a class="ch-btn ch-btn--ghost" href="${escapeAttr(animateUrl)}" title="Animate in the Animation Studio">Animate</a>
- <a class="ch-btn ch-btn--ghost" href="${escapeAttr(previewUrl)}" title="Open in the 3D viewer">Preview</a>
+ <span title="Skinned mesh, ready to animate">${escapeHtml(cardMeta(a))}</span>
</div>
+ ${actions}
</div>
`;
return card;
@@ -168,38 +195,12 @@ function wireReveal() {
}
function applyView() {
- const q = state.query.trim().toLowerCase();
- let list = state.all;
- if (q) list = list.filter((a) => (a.label || a.name || '').toLowerCase().includes(q));
-
- list = list.slice().sort((a, b) => {
- const la = (a.label || a.name || '').toLowerCase();
- const lb = (b.label || b.name || '').toLowerCase();
- if (state.sort === 'za') return lb.localeCompare(la);
- if (state.sort === 'largest') return (b.bytes || 0) - (a.bytes || 0);
- if (state.sort === 'smallest') return (a.bytes || 0) - (b.bytes || 0);
- return la.localeCompare(lb); // 'az' default
- });
-
- // Nothing at all in the library (manifest empty / not uploaded yet).
- if (state.all.length === 0) {
- show(els.loading, false);
- show(els.grid, false);
- show(els.emptySearch, false);
- show(els.error, false);
- show(els.empty, true);
- if (els.count) els.count.textContent = '';
- return;
- }
+ const list = visibleCharacters(state.all, { query: state.query, sort: state.sort });
+ const panel = viewState({ loaded: true, failed: false, total: state.all.length, visible: list.length });
- // A search that matches nothing.
- if (list.length === 0) {
- show(els.loading, false);
- show(els.grid, false);
- show(els.empty, false);
- show(els.error, false);
- show(els.emptySearch, true);
- if (els.count) els.count.textContent = '0 characters';
+ if (panel !== 'grid') {
+ showOnly(panel);
+ if (els.count) els.count.textContent = panel === 'empty-search' ? '0 characters' : '';
return;
}
@@ -210,20 +211,12 @@ function applyView() {
cancelReveal();
els.grid.replaceChildren(frag);
- show(els.loading, false);
- show(els.empty, false);
- show(els.emptySearch, false);
- show(els.error, false);
- show(els.grid, true);
+ showOnly('grid');
if (els.count) els.count.textContent = `${list.length} of ${state.all.length}`;
}
async function load() {
- show(els.loading, true);
- show(els.grid, false);
- show(els.empty, false);
- show(els.emptySearch, false);
- show(els.error, false);
+ showOnly('loading');
try {
const res = await fetch('/api/avatars/library');
@@ -240,11 +233,7 @@ async function load() {
}
applyView();
} catch (err) {
- show(els.loading, false);
- show(els.grid, false);
- show(els.empty, false);
- show(els.emptySearch, false);
- show(els.error, true);
+ showOnly('error');
if (els.errorMsg) {
// The catalog pass lands after /api/locale resolves and would otherwise
// revert this concrete reason back to the generic placeholder shipped in
diff --git a/src/converter.css b/src/converter.css
index cc83a660e..cfa5329b4 100644
--- a/src/converter.css
+++ b/src/converter.css
@@ -172,6 +172,22 @@
}
}
+/* Below ~360px the asset button leaves too little room beside the number, and a
+ converted amount the reader cannot finish is a broken result. Stack it so the
+ figure gets the full row width. */
+@media (max-width: 22.5rem) {
+ .cvt-row {
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 0.5rem;
+ }
+ .cvt-amount,
+ .cvt-result {
+ width: 100%;
+ flex: 0 0 auto;
+ }
+}
+
/* Inline validation for the amount field. */
.cvt-hint {
margin: 0.5rem 0 0;
@@ -422,6 +438,11 @@
.cvt-picker {
position: fixed;
z-index: 60;
+ display: flex;
+ flex-direction: column;
+ /* Set per-open by positionPicker() from the space left under (or over) the
+ anchor, so the list scrolls inside the popover instead of off-screen. */
+ max-height: var(--cvt-pick-max, 26rem);
width: min(22rem, calc(100vw - 2rem));
background: var(--cv-surface);
border: 1px solid var(--cv-border);
@@ -448,6 +469,7 @@
.cvt-pick-search {
position: relative;
+ flex: 0 0 auto;
padding: 0.625rem;
border-bottom: 1px solid var(--cv-border);
}
@@ -485,7 +507,8 @@
}
.cvt-pick-list {
- max-height: 20rem;
+ flex: 1 1 auto;
+ min-height: 0;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
padding: 0.375rem;
diff --git a/src/converter.js b/src/converter.js
index 2a455310b..67943e663 100644
--- a/src/converter.js
+++ b/src/converter.js
@@ -639,6 +639,9 @@ function onPickerKey(e) {
}
const PICKER_GUTTER = 8;
+const PICKER_OFFSET = 6;
+// Below this the popover is too short to browse, so it flips above the anchor.
+const PICKER_MIN_HEIGHT = 220;
function positionPicker(anchor) {
// Fixed position (viewport coords) so the offset parent is unambiguous: the
@@ -652,9 +655,25 @@ function positionPicker(anchor) {
const width = el.offsetWidth || el.getBoundingClientRect().width;
const maxLeft = Math.max(PICKER_GUTTER, window.innerWidth - width - PICKER_GUTTER);
const left = Math.min(Math.max(PICKER_GUTTER, rect.right - width), maxLeft);
- el.style.top = `${rect.bottom + 6}px`;
el.style.left = `${left}px`;
el.style.right = 'auto';
+
+ // The "to" button sits low in the card, so on a phone there is often no room
+ // under it. Flip above the anchor when that side has more space, and cap the
+ // height either way so the list scrolls inside the popover instead of
+ // running off the bottom of the screen.
+ const below = window.innerHeight - rect.bottom - PICKER_OFFSET - PICKER_GUTTER;
+ const above = rect.top - PICKER_OFFSET - PICKER_GUTTER;
+ const flip = below < PICKER_MIN_HEIGHT && above > below;
+ const available = Math.max(PICKER_MIN_HEIGHT, flip ? above : below);
+ el.style.setProperty('--cvt-pick-max', `${available}px`);
+ if (flip) {
+ el.style.top = 'auto';
+ el.style.bottom = `${window.innerHeight - rect.top + PICKER_OFFSET}px`;
+ } else {
+ el.style.bottom = 'auto';
+ el.style.top = `${rect.bottom + PICKER_OFFSET}px`;
+ }
}
function openPicker(side, anchor) {
diff --git a/src/shared/character-library-view.js b/src/shared/character-library-view.js
new file mode 100644
index 000000000..2005dd7f7
--- /dev/null
+++ b/src/shared/character-library-view.js
@@ -0,0 +1,85 @@
+// Pure view logic for /character-library.
+//
+// The page module (src/character-library.js) owns the DOM; everything here is a
+// function of the manifest rows that GET /api/avatars/library returns, so the
+// search, the sort and the three deep links a card offers can be tested without
+// a browser. Rows look like:
+//
+// { name: 'aj', label: 'Aj', url: '/r2-proxy/.../aj.glb',
+// thumb: '/r2-proxy/.../aj.png', bytes: 5918024, source: 'mixamo' }
+
+/** Display name for a row: the curated label, else the manifest key. */
+export function characterName(a) {
+ return (a?.label || a?.name || '').trim();
+}
+
+/** "34.3 MB" / "812 KB", or an empty string when the manifest omits the size. */
+export function formatBytes(n) {
+ if (!n) return '';
+ const mb = n / 1024 / 1024;
+ return mb >= 1 ? `${mb.toFixed(1)} MB` : `${Math.round(n / 1024)} KB`;
+}
+
+/**
+ * The line under a card's name. A row with no `bytes` used to render as
+ * "Mixamo · " with a separator dangling off the end; the separator now only
+ * appears when there is a size to separate it from.
+ */
+export function cardMeta(a) {
+ const source = a?.source === 'mixamo' || !a?.source ? 'Mixamo' : String(a.source);
+ const size = formatBytes(a?.bytes);
+ return size ? `${source} · ${size}` : source;
+}
+
+/**
+ * The three viewers that accept a raw model URL. Returns null when the row
+ * carries no GLB, which is the caller's signal to render no action at all
+ * rather than a link to nowhere.
+ */
+export function viewerLinks(a) {
+ const glb = a?.url || '';
+ if (!glb) return null;
+ const model = encodeURIComponent(glb);
+ return {
+ preview: `/app#model=${model}`,
+ use: `/studio?model=${model}`,
+ animate: `/pose?src=${model}&title=${encodeURIComponent(characterName(a))}`,
+ };
+}
+
+/** Case-insensitive substring match on the display name. */
+export function filterCharacters(list, query) {
+ const q = String(query || '').trim().toLowerCase();
+ if (!q) return [...(list || [])];
+ return (list || []).filter((a) => characterName(a).toLowerCase().includes(q));
+}
+
+export const SORTS = ['az', 'za', 'largest', 'smallest'];
+
+/** Sort a copy of `list`. An unknown mode sorts A to Z, matching the select's default. */
+export function sortCharacters(list, mode) {
+ const out = [...(list || [])];
+ const byName = (a, b) => characterName(a).toLowerCase().localeCompare(characterName(b).toLowerCase());
+ if (mode === 'za') return out.sort((a, b) => -byName(a, b));
+ if (mode === 'largest') return out.sort((a, b) => (b?.bytes || 0) - (a?.bytes || 0));
+ if (mode === 'smallest') return out.sort((a, b) => (a?.bytes || 0) - (b?.bytes || 0));
+ return out.sort(byName);
+}
+
+/** The rows a given search + sort should render, in render order. */
+export function visibleCharacters(list, { query = '', sort = 'az' } = {}) {
+ return sortCharacters(filterCharacters(list, query), sort);
+}
+
+/**
+ * Which of the page's five states the current data implies. Kept here so the
+ * page cannot show "no matches" for an empty library, or an empty library
+ * message for a search that simply missed.
+ */
+export function viewState({ loaded, failed, total, visible }) {
+ if (failed) return 'error';
+ if (!loaded) return 'loading';
+ if (!total) return 'empty';
+ if (!visible) return 'empty-search';
+ return 'grid';
+}
diff --git a/tests/character-library-view.test.js b/tests/character-library-view.test.js
new file mode 100644
index 000000000..34b7100e2
--- /dev/null
+++ b/tests/character-library-view.test.js
@@ -0,0 +1,190 @@
+import { describe, it, expect } from 'vitest';
+import {
+ SORTS,
+ cardMeta,
+ characterName,
+ filterCharacters,
+ formatBytes,
+ sortCharacters,
+ viewState,
+ viewerLinks,
+ visibleCharacters,
+} from '../src/shared/character-library-view.js';
+
+// Rows shaped like a real GET /api/avatars/library payload.
+const AJ = {
+ name: 'aj',
+ label: 'Aj',
+ url: '/r2-proxy/avatars/mixamo/glb/aj.glb',
+ thumb: '/r2-proxy/avatars/mixamo/thumbs/aj.png',
+ bytes: 5918024,
+ source: 'mixamo',
+};
+const ABE = { name: 'abe', label: 'Abe', url: '/r2-proxy/avatars/mixamo/glb/abe.glb', bytes: 35947032, source: 'mixamo' };
+const ALIEN = { name: 'alien-soldier', label: 'Alien Soldier', url: '/r2-proxy/avatars/mixamo/glb/alien-soldier.glb', bytes: 4101348, source: 'mixamo' };
+const LIBRARY = [AJ, ABE, ALIEN];
+
+describe('character name', () => {
+ it('prefers the curated label over the manifest key', () => {
+ expect(characterName(AJ)).toBe('Aj');
+ });
+
+ it('falls back to the manifest key when a row carries no label', () => {
+ expect(characterName({ name: 'x-bot' })).toBe('x-bot');
+ });
+
+ it('is empty rather than "undefined" for a row with neither', () => {
+ expect(characterName({})).toBe('');
+ expect(characterName(null)).toBe('');
+ });
+});
+
+describe('size formatting', () => {
+ it('renders megabytes to one decimal above 1 MB', () => {
+ expect(formatBytes(35947032)).toBe('34.3 MB');
+ expect(formatBytes(5918024)).toBe('5.6 MB');
+ });
+
+ it('renders whole kilobytes below 1 MB', () => {
+ expect(formatBytes(831488)).toBe('812 KB');
+ });
+
+ it('says nothing when the manifest omits the size', () => {
+ expect(formatBytes(0)).toBe('');
+ expect(formatBytes(undefined)).toBe('');
+ });
+});
+
+describe('card meta line', () => {
+ it('pairs the source with the size', () => {
+ expect(cardMeta(AJ)).toBe('Mixamo · 5.6 MB');
+ });
+
+ // The separator used to render unconditionally, so a row with no size showed
+ // "Mixamo · " with the bullet dangling off the end of the line.
+ it('drops the separator when there is no size to separate', () => {
+ expect(cardMeta({ name: 'aj', source: 'mixamo' })).toBe('Mixamo');
+ });
+
+ it('names a non-Mixamo source rather than mislabelling it', () => {
+ expect(cardMeta({ name: 'k', source: 'avaturn', bytes: 2097152 })).toBe('avaturn · 2.0 MB');
+ });
+});
+
+describe('viewer deep links', () => {
+ it('points the three actions at the viewers that take a raw model URL', () => {
+ const links = viewerLinks(AJ);
+ expect(links.preview).toBe('/app#model=%2Fr2-proxy%2Favatars%2Fmixamo%2Fglb%2Faj.glb');
+ expect(links.use).toBe('/studio?model=%2Fr2-proxy%2Favatars%2Fmixamo%2Fglb%2Faj.glb');
+ expect(links.animate).toBe('/pose?src=%2Fr2-proxy%2Favatars%2Fmixamo%2Fglb%2Faj.glb&title=Aj');
+ });
+
+ it('encodes a name with a space so the Animation Studio title survives', () => {
+ expect(viewerLinks(ALIEN).animate).toContain('title=Alien%20Soldier');
+ });
+
+ // A row with no GLB must render no action at all: an href="#" is a dead
+ // control, and every one of these links needs a model to open.
+ it('offers nothing for a row that carries no model', () => {
+ expect(viewerLinks({ name: 'ghost' })).toBeNull();
+ expect(viewerLinks({ name: 'ghost', url: '' })).toBeNull();
+ });
+});
+
+describe('search', () => {
+ it('matches case-insensitively on the display name', () => {
+ expect(filterCharacters(LIBRARY, 'alien').map(characterName)).toEqual(['Alien Soldier']);
+ expect(filterCharacters(LIBRARY, 'ALIEN').map(characterName)).toEqual(['Alien Soldier']);
+ });
+
+ it('matches inside the name, not only at the start', () => {
+ expect(filterCharacters(LIBRARY, 'soldier').map(characterName)).toEqual(['Alien Soldier']);
+ });
+
+ it('returns the whole library for an empty or whitespace query', () => {
+ expect(filterCharacters(LIBRARY, '')).toHaveLength(3);
+ expect(filterCharacters(LIBRARY, ' ')).toHaveLength(3);
+ });
+
+ it('returns nothing for a query that matches nothing', () => {
+ expect(filterCharacters(LIBRARY, 'zzzz')).toEqual([]);
+ });
+
+ it('never mutates the library it was handed', () => {
+ const before = [...LIBRARY];
+ filterCharacters(LIBRARY, 'a');
+ expect(LIBRARY).toEqual(before);
+ });
+});
+
+describe('sort', () => {
+ it('sorts A to Z by default and for an unknown mode', () => {
+ expect(sortCharacters(LIBRARY, 'az').map(characterName)).toEqual(['Abe', 'Aj', 'Alien Soldier']);
+ expect(sortCharacters(LIBRARY, 'nonsense').map(characterName)).toEqual(['Abe', 'Aj', 'Alien Soldier']);
+ });
+
+ it('sorts Z to A', () => {
+ expect(sortCharacters(LIBRARY, 'za').map(characterName)).toEqual(['Alien Soldier', 'Aj', 'Abe']);
+ });
+
+ it('sorts by file size in both directions', () => {
+ expect(sortCharacters(LIBRARY, 'largest').map(characterName)).toEqual(['Abe', 'Aj', 'Alien Soldier']);
+ expect(sortCharacters(LIBRARY, 'smallest').map(characterName)).toEqual(['Alien Soldier', 'Aj', 'Abe']);
+ });
+
+ it('sorts a sizeless row to the light end rather than dropping it', () => {
+ const withUnknown = [...LIBRARY, { name: 'mystery', label: 'Mystery' }];
+ expect(sortCharacters(withUnknown, 'smallest').map(characterName)[0]).toBe('Mystery');
+ expect(sortCharacters(withUnknown, 'largest')).toHaveLength(4);
+ });
+
+ it('leaves the source array untouched', () => {
+ const before = [...LIBRARY];
+ sortCharacters(LIBRARY, 'za');
+ expect(LIBRARY).toEqual(before);
+ });
+
+ it('covers every mode the sort select offers', () => {
+ for (const mode of SORTS) expect(sortCharacters(LIBRARY, mode)).toHaveLength(3);
+ });
+});
+
+describe('search and sort together', () => {
+ it('filters first, then orders what survived', () => {
+ expect(visibleCharacters(LIBRARY, { query: 'a', sort: 'smallest' }).map(characterName)).toEqual([
+ 'Alien Soldier',
+ 'Aj',
+ 'Abe',
+ ]);
+ });
+
+ it('defaults to the whole library, A to Z', () => {
+ expect(visibleCharacters(LIBRARY).map(characterName)).toEqual(['Abe', 'Aj', 'Alien Soldier']);
+ });
+
+ it('survives a manifest that has not arrived yet', () => {
+ expect(visibleCharacters(undefined, { query: 'a' })).toEqual([]);
+ });
+});
+
+describe('which panel the page shows', () => {
+ it('shows the skeleton until the manifest lands', () => {
+ expect(viewState({ loaded: false, failed: false, total: 0, visible: 0 })).toBe('loading');
+ });
+
+ it('shows the error state when the fetch failed, whatever else is true', () => {
+ expect(viewState({ loaded: true, failed: true, total: 3, visible: 3 })).toBe('error');
+ expect(viewState({ loaded: false, failed: true, total: 0, visible: 0 })).toBe('error');
+ });
+
+ // The two empties are different messages: one says the library is being
+ // staged, the other offers to clear the search.
+ it('tells an empty library apart from a search that missed', () => {
+ expect(viewState({ loaded: true, failed: false, total: 0, visible: 0 })).toBe('empty');
+ expect(viewState({ loaded: true, failed: false, total: 3, visible: 0 })).toBe('empty-search');
+ });
+
+ it('shows the grid when there is something to render', () => {
+ expect(viewState({ loaded: true, failed: false, total: 3, visible: 1 })).toBe('grid');
+ });
+});