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.

fix(creations,converter): land the gallery, compare and scene-compose work from this worktree

nirholas416bdc622d69
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 23fe430e5..f86b1752c 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -122,7 +122,7 @@ bottom.
| Animation gallery | [pages/animations.html](pages/animations.html) + [src/animations-gallery.js](src/animations-gallery.js) | Live at `/animations` | 2,100+ clips with poster thumbnails ([scripts/build-animation-thumbnails.mjs](scripts/build-animation-thumbnails.mjs)), derived categories ([src/animation-categories.js](src/animation-categories.js)), shared live-preview engine ([src/animations-live-preview.js](src/animations-live-preview.js)) · see [docs/animations.md](docs/animations.md) |
| Gesture vocabulary | [pages/gestures.html](pages/gestures.html) + [src/gestures-page.js](src/gestures-page.js), slots [src/runtime/animation-slots.js](src/runtime/animation-slots.js) | Live at `/gestures` | The 19 gesture slots an agent plays, each previewed on a live avatar, with the skill hints that trigger it and a builder that saves a per-slot clip override straight onto an agent (`meta.edits.animations`). Hint table is generated from the shipped skill definitions by [scripts/build-agent-hints.mjs](scripts/build-agent-hints.mjs), so attribution cannot go stale · see [docs/animations.md](docs/animations.md) |
| Choreographer | [pages/choreograph.html](pages/choreograph.html) + [src/choreograph-page.js](src/choreograph-page.js), engine [src/runtime/choreography.js](src/runtime/choreography.js) | Live at `/choreograph` | Timeline for composing gesture slots into named, timed routines, previewed on the shared live-preview engine with crossfades and a scrubbable playhead. One dependency-free module defines the routine format, the URL wire format and the timing engine; the studio, `PUT /api/agents/:id/animations` (stored at `meta.choreographies`), the public manifest and `AgentAvatar.playChoreography` all import it, and `<agent-3d>.playRoutine('welcome')` performs one from any embed. Also published as `@three-ws/avatar/runtime/choreography.js` · see [docs/choreography.md](docs/choreography.md) |
-| Character Library | [pages/character-library.html](pages/character-library.html) + [src/character-library.js](src/character-library.js) → `/character-library`, API [api/avatars/library.js](api/avatars/library.js) | Live at `/character-library` | 106 professionally rigged Mixamo characters (skinned GLB + thumbnails on R2, `avatars/mixamo/`), each drives the full animation library. Pipeline: [scripts/fetch-mixamo-avatars.mjs](scripts/fetch-mixamo-avatars.mjs) → [scripts/convert-mixamo-avatars.mjs](scripts/convert-mixamo-avatars.mjs) → [scripts/fetch-mixamo-avatar-thumbnails.mjs](scripts/fetch-mixamo-avatar-thumbnails.mjs) → [scripts/build-mixamo-avatar-library.mjs](scripts/build-mixamo-avatar-library.mjs) publishes `avatars/library/manifest.json`. Cards deep-link into the 3D viewer (`/app#model=`), Widget Studio (`/studio?model=`), and Animation Studio (`/pose?src=`). Mirrors the animation-library R2-manifest pattern (no DB). See [public/avatars/mixamo/README.md](public/avatars/mixamo/README.md) |
+| Character Library | [pages/character-library.html](pages/character-library.html) + [src/character-library.js](src/character-library.js) → `/character-library`, API [api/avatars/library.js](api/avatars/library.js) | Live at `/character-library` | Professionally rigged Mixamo characters (skinned GLB + thumbnails on R2, `avatars/mixamo/`), each drives the full animation library. The live count comes from the R2 manifest and renders in the hero; no page copy hard-codes it. Pipeline: [scripts/fetch-mixamo-avatars.mjs](scripts/fetch-mixamo-avatars.mjs) → [scripts/convert-mixamo-avatars.mjs](scripts/convert-mixamo-avatars.mjs) → [scripts/fetch-mixamo-avatar-thumbnails.mjs](scripts/fetch-mixamo-avatar-thumbnails.mjs) → [scripts/build-mixamo-avatar-library.mjs](scripts/build-mixamo-avatar-library.mjs) publishes `avatars/library/manifest.json`. Cards deep-link into the 3D viewer (`/app#model=`), Widget Studio (`/studio?model=`), and Animation Studio (`/pose?src=`). Mirrors the animation-library R2-manifest pattern (no DB). See [public/avatars/mixamo/README.md](public/avatars/mixamo/README.md) |
| Object Library | [pages/objects.html](pages/objects.html) + [src/objects-library.js](src/objects-library.js) → `/objects`, API [api/objects/library.js](api/objects/library.js) | Live at `/objects` | Hundreds of CC0 (public-domain) 3D props from Poly Haven (packed to GLB on R2, `objects/polyhaven/`). Pipeline: [scripts/fetch-polyhaven-objects.mjs](scripts/fetch-polyhaven-objects.mjs) (glTF→GLB via @gltf-transform) → [scripts/render-glb-thumbnails.mjs](scripts/render-glb-thumbnails.mjs) → [scripts/build-object-library.mjs](scripts/build-object-library.mjs) publishes `objects/library/manifest.json`. Same R2-manifest pattern as the Character/animation libraries (no DB). Cards preview in the 3D viewer (`/app#model=`), place into AR Studio (`/ar/studio?src=`), and download the GLB directly (CC0). AR Studio's tray also has an Objects tab over the same manifest. |
| Agent-Forged Gallery | [pages/forged.html](pages/forged.html) + [src/forged-gallery.js](src/forged-gallery.js) → `/forged`, API [api/forged.js](api/forged.js), writer [api/_lib/x402/pipelines/forge-content.js](api/_lib/x402/pipelines/forge-content.js) | Live at `/forged` | 3D props BOUGHT by the autonomous x402 agents with real USDC: the hourly forge-content pipeline pays `/api/x402/forge` (draft tier), the generated GLB lands in `forge_autonomous_props` with payment provenance (payer wallet, price, Solana settlement signature), and `/forged` renders each prop with its on-chain receipt linked to Solscan. Honest feed: no synthetic entries; before the first paid generation the page shows its designed empty state. Category chips (crate/barrel/furniture/terrain), prompt search, newest/priciest/most-novel sorts. |
| Motion Swap (avatar body-swap in video) | [pages/motion-swap.html](pages/motion-swap.html) `→ /motion-swap` + [src/motion-swap.js](src/motion-swap.js), API [api/motion-swap.js](api/motion-swap.js), worker [workers/model-video2motion/](workers/model-video2motion) | Live | Upload a video of one person, get it back with a 3D avatar performing their motion. The worker (CPU Cloud Run, MediaPipe pose + hands + multiclass person segmentation, all Apache-2.0) tracks 33 body world landmarks plus 21 per hand each frame, solves them onto the canonical Wolf3D skeleton, body and all 30 finger bones, with an in-house bend-plane IK solver ([pose_solver.py](workers/model-video2motion/pose_solver.py), pure NumPy, unit-tested), and emits a standard `AnimationClip.toJSON()` + person-mask video + per-frame screen anchors. The browser composites in one WebGL scene: footage on a shader quad with the subject pixelated under the mask, avatar retargeted via [src/animation-retarget.js](src/animation-retarget.js) and pinned to the subject's anchor each frame, MediaRecorder export with original audio. Provider mode `video2motion` (`GCP_VIDEO2MOTION_URL`) in [api/_providers/gcp.js](api/_providers/gcp.js). Docs: [docs/motion-swap.md](docs/motion-swap.md). Tests: [test_pose_solver.py](workers/model-video2motion/test_pose_solver.py) (solver) and [test_service.py](workers/model-video2motion/test_service.py) (HTTP contract, ffmpeg normalize/mask encode, SSRF guard, live MediaPipe pass). |
diff --git a/pages/club.html b/pages/club.html
index da76bcbf4..4991dd564 100644
--- a/pages/club.html
+++ b/pages/club.html
@@ -855,9 +855,20 @@
pointer-events: none;
opacity: 0;
transform: translateY(-10px);
- transition: opacity 0.6s ease, transform 0.6s ease;
+ /* visibility, not just opacity: this pill holds a <select> and a
+ Browse button, and a transparent control is still a tab stop. Off
+ the walk-in, a keyboard user would otherwise tab into an agent
+ picker they cannot see. Flipped after the fade so it still plays. */
+ visibility: hidden;
+ transition: opacity 0.6s ease, transform 0.6s ease, visibility 0s linear 0.6s;
+ }
+ .club-agent-switch.is-visible {
+ opacity: 1;
+ transform: translateY(0);
+ pointer-events: auto;
+ visibility: visible;
+ transition-delay: 0s;
}
- .club-agent-switch.is-visible { opacity: 1; transform: translateY(0); pointer-events: auto; }
.club-agent-label {
font: 600 11px/1 'Inter', system-ui, sans-serif;
letter-spacing: 0.08em;
@@ -1002,13 +1013,19 @@
cursor: pointer;
pointer-events: none;
opacity: 0;
- transition: opacity 0.25s ease, transform 0.25s ease;
+ /* Same reason as the agent pill above: an invisible <button> is still
+ a tab stop, so "Enter the club" must leave the tab order until the
+ walk-in actually puts you at the door. */
+ visibility: hidden;
+ transition: opacity 0.25s ease, transform 0.25s ease, visibility 0s linear 0.25s;
}
.club-door-prompt.is-visible {
opacity: 1;
pointer-events: auto;
+ visibility: visible;
transform: translate(-50%, -50%) scale(1);
animation: clubPromptBob 1.8s ease-in-out infinite;
+ transition-delay: 0s;
}
.club-door-prompt:hover { border-color: #ff3bd6; box-shadow: 0 0 44px -4px rgba(255, 59, 214, 0.9); }
.club-door-prompt:focus-visible { outline: 2px solid #fff; outline-offset: 3px; }
diff --git a/pages/coins.html b/pages/coins.html
index 1445fd148..c526077ff 100644
--- a/pages/coins.html
+++ b/pages/coins.html
@@ -18,18 +18,18 @@
</script>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title data-i18n="coins.meta_title">Coins — live prices &amp; market caps · three.ws</title>
+ <title data-i18n="coins.meta_title">Coins: Live Prices &amp; Market Caps · three.ws</title>
<meta
name="description"
- content="Live cryptocurrency market data — prices, trends, and a global overview for the top digital assets, with rich detail pages for every coin."
+ content="Live global crypto market data: total market cap, BTC and ETH dominance, Fear &amp; Greed, and the top coins with prices, 24h and 7d moves, and 7d sparklines. Every coin opens a detail page with charts, market stats, and news."
data-i18n-attr="content:coins.meta_description"/>
<meta property="og:type" content="website" />
<meta property="og:site_name" content="three.ws" />
<meta property="og:url" content="https://three.ws/coins" />
- <meta property="og:title" content="Coins — live prices &amp; market caps · three.ws" data-i18n-attr="content:coins.meta_og_title"/>
+ <meta property="og:title" content="Coins: Live Prices &amp; Market Caps · three.ws" data-i18n-attr="content:coins.meta_og_title"/>
<meta
property="og:description"
- content="Live cryptocurrency market data — prices, trends, and a global overview for the top digital assets."
+ content="Live global crypto market data: total market cap, dominance, Fear &amp; Greed, and the top coins with prices, 24h and 7d moves, and 7d sparklines."
data-i18n-attr="content:coins.meta_og_description"/>
<meta
property="og:image"
@@ -42,7 +42,7 @@
<meta name="twitter:title" content="Coins · three.ws" data-i18n-attr="content:coins.meta_twitter_title"/>
<meta
name="twitter:description"
- content="Live cryptocurrency market data — prices, trends, and a global overview for the top digital assets."
+ content="Live global crypto market data: total market cap, dominance, Fear &amp; Greed, and the top coins with prices, 24h and 7d moves, and 7d sparklines."
data-i18n-attr="content:coins.meta_twitter_description"/>
<meta
name="twitter:image"
@@ -61,14 +61,14 @@
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1" />
<meta property="og:locale" content="en_US" />
- <meta property="og:image:alt" content="Markets — Live Crypto Prices — three.ws" />
+ <meta property="og:image:alt" content="Coins: live prices and market caps on three.ws" />
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@graph": [
{
"@type": "WebPage",
- "name": "Markets — Live Crypto Prices",
+ "name": "Coins: Live Prices & Market Caps",
"description": "Live global cryptocurrency market data: total market cap, dominance, Fear & Greed, and the top coins with prices, 24h/7d moves, and 7d sparklines. Every coin links to a rich /coin/:id detail page with an interactive chart, market stats, related news, and official links.",
"url": "https://three.ws/coins",
"isPartOf": {
@@ -76,7 +76,7 @@
"name": "three.ws",
"url": "https://three.ws"
},
- "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&amp;t=Markets+%E2%80%94+Live+Crypto+Prices&amp;d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin+li&amp;p=%2Fcoins"
+ "primaryImageOfPage": "https://three.ws/api/page-og?s=crypto&t=Coins%3A+Live+Prices+%26+Market+Caps&d=Live+global+cryptocurrency+market+data%3A+total+market+cap%2C+dominance%2C+Fear+%26+Greed%2C+and+the+top+coins+with+prices%2C+24h%2F7d+moves%2C+and+7d+sparklines.+Every+coin&p=%2Fcoins"
}
]
}
@@ -89,7 +89,7 @@
<main class="cv-container">
<h1 class="cv-h1" data-i18n="coins.coins">Coins</h1>
<p class="cv-sub" data-i18n="coins.real_time_cryptocurrency_market_data_prices">
- Real-time cryptocurrency market data — prices, trends, and global overview for
+ Real-time cryptocurrency market data: prices, trends, and a global overview for
hundreds of digital assets.
</p>
@@ -145,6 +145,7 @@
autocomplete="off"
spellcheck="false"
role="combobox"
+ aria-autocomplete="list"
aria-expanded="false"
aria-controls="cv-search-pop"
aria-label="Search coins by name or symbol"
diff --git a/pages/creations.html b/pages/creations.html
index 50c2e938b..0096ab238 100644
--- a/pages/creations.html
+++ b/pages/creations.html
@@ -89,6 +89,7 @@
<div class="cr-search-row">
<label class="cr-search" for="cr-q">
<svg viewBox="0 0 20 20" width="16" height="16" aria-hidden="true"><path fill="none" stroke="currentColor" stroke-width="1.6" d="M13.6 13.6 18 18M9 15.5a6.5 6.5 0 1 1 0-13 6.5 6.5 0 0 1 0 13Z"/></svg>
+ <span class="cr-sr-only" data-i18n="creations.search_creations">Search creations</span>
<input type="search" id="cr-q" placeholder="Search prompts — “dragon”, “sneaker”, “low-poly car”…" autocomplete="off" maxlength="120" />
</label>
<select id="cr-category" class="cr-select" aria-label="Filter by category">
@@ -103,9 +104,9 @@
</select>
</div>
<div class="cr-sort-row" role="tablist" aria-label="Sort">
- <button type="button" class="cr-sort-btn active" data-sort="recent" role="tab" aria-selected="true" data-i18n="creations.new">New</button>
- <button type="button" class="cr-sort-btn" data-sort="remixed" role="tab" aria-selected="false" data-i18n="creations.most_remixed">Most remixed</button>
- <button type="button" class="cr-sort-btn" data-sort="royalty" role="tab" aria-selected="false" data-i18n="creations.highest_royalty">Highest royalty</button>
+ <button type="button" class="cr-sort-btn active" data-sort="recent" role="tab" aria-selected="true" aria-controls="cr-feed" data-i18n="creations.new">New</button>
+ <button type="button" class="cr-sort-btn" data-sort="remixed" role="tab" aria-selected="false" aria-controls="cr-feed" tabindex="-1" data-i18n="creations.most_remixed">Most remixed</button>
+ <button type="button" class="cr-sort-btn" data-sort="royalty" role="tab" aria-selected="false" aria-controls="cr-feed" tabindex="-1" data-i18n="creations.highest_royalty">Highest royalty</button>
</div>
</section>
@@ -114,11 +115,11 @@
<span id="cr-count" class="cr-count" aria-live="polite"></span>
</section>
- <section id="cr-feed" class="cr-grid" aria-label="3D creations" aria-busy="true"></section>
+ <section id="cr-feed" class="cr-grid" role="tabpanel" aria-label="3D creations" aria-busy="true"></section>
<div id="cr-footer-state" class="cr-footer-state"></div>
- <section class="cr-card cr-lineage-panel is-hidden" id="cr-lineage-panel" aria-labelledby="cr-lineage-title">
+ <section class="cr-lineage-panel is-hidden" id="cr-lineage-panel" aria-labelledby="cr-lineage-title">
<div class="cr-lineage-head">
<h2 class="cr-section-h" id="cr-lineage-title" data-i18n="creations.remix_lineage">Remix lineage</h2>
<button type="button" class="cr-icon-btn" id="cr-lineage-close" aria-label="Close lineage view" data-i18n-attr="aria-label:creations.close_lineage_view_arialabel">✕</button>
diff --git a/src/clash.css b/src/clash.css
index cc0c4743e..ac421ec00 100644
--- a/src/clash.css
+++ b/src/clash.css
@@ -147,14 +147,24 @@
}
.cl-round-stat-timer dd { color: var(--warn); }
+/* The three tabs measure ~304px, so on a 320px screen (288px of content width
+ inside the shell) the trailing "Communities" tab used to run off the right
+ edge and get clipped, with no page scroll to reach it. Wrapping keeps the
+ whole group reachable; the pill radius still reads correctly on two rows. */
.cl-tabs {
display: inline-flex;
+ flex-wrap: wrap;
+ justify-content: center;
+ max-width: 100%;
gap: 4px;
padding: 4px;
border: 1px solid var(--stroke);
- border-radius: var(--radius-pill);
+ border-radius: var(--radius-lg);
background: var(--surface-1);
}
+@media (min-width: 480px) {
+ .cl-tabs { flex-wrap: nowrap; border-radius: var(--radius-pill); }
+}
.cl-tab {
appearance: none;
border: 0;
@@ -165,8 +175,12 @@
border-radius: var(--radius-pill);
cursor: pointer;
text-decoration: none;
+ white-space: nowrap;
transition: color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard);
}
+@media (max-width: 479px) {
+ .cl-tab { padding: 9px 12px; }
+}
.cl-tab:hover { color: var(--ink-bright); }
.cl-tab.active { background: var(--surface-3); color: var(--ink-bright); }
.cl-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
diff --git a/src/coin-pages.css b/src/coin-pages.css
index 695b01195..bba3f1c37 100644
--- a/src/coin-pages.css
+++ b/src/coin-pages.css
@@ -996,7 +996,7 @@ html.cv-page,
}
.cv-load-err {
margin-top: 0.625rem;
- color: var(--cv-down);
+ color: var(--cv-red);
}
/* An in-prose control that acts on this page (retry, clear a filter) is a button,
diff --git a/src/coins-index.js b/src/coins-index.js
index 452d6b341..564e61265 100644
--- a/src/coins-index.js
+++ b/src/coins-index.js
@@ -420,7 +420,7 @@ function renderLiqOffline() {
const el = $('cv-liq');
if (!el) return;
el.innerHTML =
- '<p class="cv-liq-offline" role="status"><span class="dot" aria-hidden="true"></span>Liquidation feed offline — showing the rest of the markets page as usual.</p>';
+ '<p class="cv-liq-offline" role="status"><span class="dot" aria-hidden="true"></span>Liquidation feed offline. The rest of the markets page is live as usual.</p>';
}
function renderLiqPopulated(data) {
@@ -475,7 +475,7 @@ function renderLiqPopulated(data) {
: `<span class="cv-liq-item">${inner}</span>`;
})
.join('')
- : '<span class="cv-liq-item" style="color:var(--cv-text-3)">No liquidations in the last 4h — quiet market.</span>';
+ : '<span class="cv-liq-item" style="color:var(--cv-text-3)">No liquidations in the last 4h. Quiet market.</span>';
el.innerHTML = `
<span class="cv-liq-badge ${badgeCls}">${esc(badge)}</span>
diff --git a/src/collection.js b/src/collection.js
index d5b88712b..0ed9e533b 100644
--- a/src/collection.js
+++ b/src/collection.js
@@ -177,36 +177,50 @@ function emptyState(panel) {
</div>`;
}
+function els() {
+ return {
+ authWall: document.getElementById('col-auth-wall'),
+ errorEl: document.getElementById('col-error'),
+ colMain: document.getElementById('col-main'),
+ colStats: document.getElementById('col-stats'),
+ skillsGrid: document.getElementById('skills-grid'),
+ subsGrid: document.getElementById('subs-grid'),
+ };
+}
+
// Render a retryable load error into the shared error element and clear the
// loading skeletons so they never linger. Wires a Retry button to re-run load().
-function renderLoadError(errorEl, skillsGrid, subsGrid, detail) {
+function renderLoadError(detail) {
+ const { errorEl, colMain, colStats, skillsGrid, subsGrid } = els();
errorEl.innerHTML = '';
const msg = document.createElement('span');
msg.textContent = detail
- ? `Couldn't load your collection — ${detail}.`
+ ? `Couldn't load your collection: ${detail}.`
: 'Failed to load your collection. Please try again.';
const retry = document.createElement('button');
retry.type = 'button';
retry.className = 'col-retry-btn';
retry.textContent = 'Retry';
- retry.style.marginLeft = '10px';
retry.addEventListener('click', () => { load(); });
errorEl.append(msg, retry);
errorEl.hidden = false;
skillsGrid.innerHTML = '';
subsGrid.innerHTML = '';
+ // Nothing loaded, so the tabs and the stats bar would be empty chrome around
+ // the error. Collapse them and let the alert own the page.
+ colMain.hidden = true;
+ colStats.hidden = true;
}
async function load() {
- const authWall = document.getElementById('col-auth-wall');
- const errorEl = document.getElementById('col-error');
- const colMain = document.getElementById('col-main');
- const colStats = document.getElementById('col-stats');
- const skillsGrid = document.getElementById('skills-grid');
- const subsGrid = document.getElementById('subs-grid');
-
- // Show skeleton while loading
+ const { authWall, errorEl, colMain, colStats, skillsGrid, subsGrid } = els();
+
+ // Loading state: the tabs and the skeleton grid are visible from the first
+ // frame. Keeping col-main hidden until the fetch resolved meant the skeletons
+ // rendered into a hidden container and the loading state was unreachable.
errorEl.hidden = true;
+ authWall.hidden = true;
+ colMain.hidden = false;
skillsGrid.innerHTML = skeletonGrid(6);
subsGrid.innerHTML = skeletonGrid(3);
@@ -220,19 +234,22 @@ async function load() {
// Network-level failure (offline, DNS, aborted): without this the awaited
// Promise.all rejects and the skeletons render forever. Surface a retryable
// error instead.
- renderLoadError(errorEl, skillsGrid, subsGrid, err?.message);
+ renderLoadError(err?.message);
return;
}
if (skillsRes.status === 401 || subsRes.status === 401) {
authWall.hidden = false;
+ colMain.hidden = true;
+ colStats.hidden = true;
skillsGrid.innerHTML = '';
subsGrid.innerHTML = '';
return;
}
if (!skillsRes.ok || !subsRes.ok) {
- renderLoadError(errorEl, skillsGrid, subsGrid);
+ const bad = !skillsRes.ok ? skillsRes : subsRes;
+ renderLoadError(`the server returned ${bad.status}`);
return;
}
@@ -241,12 +258,12 @@ async function load() {
({ data: skillsData } = await skillsRes.json());
({ subscriptions: subsData } = await subsRes.json());
} catch (err) {
- renderLoadError(errorEl, skillsGrid, subsGrid, err?.message);
+ renderLoadError(err?.message);
return;
}
- const purchases = skillsData?.purchases ?? [];
- const subs = subsData ?? [];
+ const purchases = Array.isArray(skillsData?.purchases) ? skillsData.purchases : [];
+ const subs = Array.isArray(subsData) ? subsData : [];
const nftCount = purchases.filter(p => p.skill_nft_mint).length;
const now = Date.now();
const activeSubs = subs.filter(s =>
@@ -273,20 +290,52 @@ async function load() {
? subs.map(subCard).join('')
: emptyState('subscriptions');
- // Update tab labels with counts
- const tabs = document.querySelectorAll('.col-tab');
- tabs[0].textContent = `Skills (${purchases.length})`;
- tabs[1].textContent = `Subscriptions (${subs.length})`;
+ // Counts live in their own span so the runtime i18n pass, which rewrites the
+ // sibling [data-i18n] label's textContent whenever the catalog lands, cannot
+ // race the count away.
+ setTabCount('skills', purchases.length);
+ setTabCount('subscriptions', subs.length);
+}
+
+function setTabCount(panel, n) {
+ const el = document.querySelector(`.col-tab[data-panel="${panel}"] .col-tab-count`);
+ if (el) el.textContent = `(${n})`;
+}
+
+// Tab switching: a WAI-ARIA tablist with roving tabindex, so Arrow/Home/End move
+// between tabs and Tab itself lands on the selected panel.
+const tabs = [...document.querySelectorAll('.col-tab')];
+
+function selectTab(tab, { focus = false } = {}) {
+ for (const t of tabs) {
+ const on = t === tab;
+ t.classList.toggle('active', on);
+ t.setAttribute('aria-selected', String(on));
+ t.tabIndex = on ? 0 : -1;
+ const panel = document.getElementById(`panel-${t.dataset.panel}`);
+ if (!panel) continue;
+ panel.classList.toggle('active', on);
+ panel.hidden = !on;
+ }
+ if (focus) tab.focus();
}
-// Tab switching
-document.querySelectorAll('.col-tab').forEach(tab => {
- tab.addEventListener('click', () => {
- document.querySelectorAll('.col-tab').forEach(t => { t.classList.remove('active'); t.setAttribute('aria-selected', 'false'); });
- document.querySelectorAll('.col-panel').forEach(p => p.classList.remove('active'));
- tab.classList.add('active');
- tab.setAttribute('aria-selected', 'true');
- document.getElementById(`panel-${tab.dataset.panel}`).classList.add('active');
+tabs.forEach((tab, i) => {
+ tab.addEventListener('click', () => selectTab(tab));
+ tab.addEventListener('keydown', (e) => {
+ const step = e.key === 'ArrowRight' ? 1 : e.key === 'ArrowLeft' ? -1 : 0;
+ if (step) {
+ e.preventDefault();
+ selectTab(tabs[(i + step + tabs.length) % tabs.length], { focus: true });
+ return;
+ }
+ if (e.key === 'Home') {
+ e.preventDefault();
+ selectTab(tabs[0], { focus: true });
+ } else if (e.key === 'End') {
+ e.preventDefault();
+ selectTab(tabs[tabs.length - 1], { focus: true });
+ }
});
});
diff --git a/src/communities.js b/src/communities.js
index 395ce2033..58ec886b3 100644
--- a/src/communities.js
+++ b/src/communities.js
@@ -20,11 +20,43 @@ const $ = (id) => document.getElementById(id);
const nameInput = $('name-input');
const avatarRow = $('avatar-row');
const avatarUrlInput = $('avatar-url-input');
+const avatarUrlError = $('avatar-url-error');
const coinGrid = $('coin-grid');
const searchInput = $('coin-search');
const mintInput = $('mint-input');
const mintBtn = $('mint-enter');
const mintError = $('mint-error');
+const titleEl = document.querySelector('title');
+
+// ── i18n ownership ─────────────────────────────────────────────────────────
+// Several nodes here carry a data-i18n key (so the pre-render placeholder is
+// translated) but hold live state once this script runs: the document title,
+// the coin-profile failure message, the graduation label. The i18n catalog pass
+// lands after /api/locale resolves, which is routinely *after* the first render,
+// and it would revert those nodes to their declared copy. `data-i18n-owned="1"`
+// is that runtime's documented opt-out. Releasing an element hands it back and
+// restores the copy the catalog would have written, so a non-English visitor
+// keeps a localized page once the live state is gone.
+const i18nDefaults = new WeakMap();
+
+function claimI18n(el, text) {
+ if (!el) return;
+ if (!i18nDefaults.has(el)) i18nDefaults.set(el, el.textContent);
+ el.setAttribute('data-i18n-owned', '1');
+ el.textContent = text;
+}
+
+function releaseI18n(el) {
+ if (!el) return;
+ el.removeAttribute('data-i18n-owned');
+ const key = el.getAttribute('data-i18n');
+ const translated = key ? window.threewsI18n?.t?.(key) : '';
+ const restored = translated && translated !== key ? translated : i18nDefaults.get(el);
+ if (restored != null) el.textContent = restored;
+}
+
+const setPageTitle = (text) => claimI18n(titleEl, text);
+const releasePageTitle = () => releaseI18n(titleEl);
// Selected avatar: { kind: 'default'|'id'|'url', value, label, thumb }
let selectedAvatar = { kind: 'default', value: DEFAULT_AVATAR_URL, label: 'Default', thumb: '' };
@@ -58,7 +90,11 @@ function avatarChip({ kind, value, label, thumb, id }) {
selectedAvatar = { kind, value, label, thumb };
try { localStorage.setItem(AVATAR_CHOICE_KEY, JSON.stringify(selectedAvatar)); } catch {}
markSelectedAvatar();
- if (kind !== 'url' && avatarUrlInput) avatarUrlInput.value = '';
+ if (kind !== 'url' && avatarUrlInput) {
+ avatarUrlInput.value = '';
+ avatarUrlInput.classList.remove('is-error');
+ setAvatarUrlMessage('');
+ }
});
return chip;
}
@@ -116,12 +152,29 @@ async function initAvatars() {
}
// Paste a direct GLB / VRM / Ready Player Me URL.
+function setAvatarUrlMessage(text, ok = false) {
+ if (!avatarUrlError) return;
+ avatarUrlError.textContent = text;
+ avatarUrlError.classList.toggle('is-ok', ok && !!text);
+}
+
if (avatarUrlInput) {
const apply = () => {
const url = avatarUrlInput.value.trim();
- if (!url) return;
- if (!/^https?:\/\//i.test(url)) { avatarUrlInput.classList.add('is-error'); return; }
+ if (!url) {
+ avatarUrlInput.classList.remove('is-error');
+ setAvatarUrlMessage('');
+ return;
+ }
+ // A silent red border tells the visitor nothing. Say what is wrong and what
+ // a working value looks like.
+ if (!/^https?:\/\//i.test(url)) {
+ avatarUrlInput.classList.add('is-error');
+ setAvatarUrlMessage('Enter a full https:// link to a .glb or .gltf file.');
+ return;
+ }
avatarUrlInput.classList.remove('is-error');
+ setAvatarUrlMessage('Custom avatar selected.', true);
selectedAvatar = { kind: 'url', value: url, label: 'Custom', thumb: '' };
try { localStorage.setItem(AVATAR_CHOICE_KEY, JSON.stringify(selectedAvatar)); } catch {}
// Reflect the choice: clear chip highlight (none of the chips own a URL).
@@ -129,6 +182,12 @@ if (avatarUrlInput) {
};
avatarUrlInput.addEventListener('change', apply);
avatarUrlInput.addEventListener('blur', apply);
+ // Clear a stale complaint as soon as the visitor starts fixing the value.
+ avatarUrlInput.addEventListener('input', () => {
+ if (!avatarUrlInput.classList.contains('is-error')) return;
+ avatarUrlInput.classList.remove('is-error');
+ setAvatarUrlMessage('');
+ });
}
// ── Hand-off into the world ────────────────────────────────────────────────
@@ -190,6 +249,7 @@ function coinCard(coin) {
function renderCoins(coins) {
coinGrid.innerHTML = '';
+ coinGrid.setAttribute('aria-busy', 'false');
const usable = (coins || []).filter((c) => c && c.mint && MINT_RE.test(c.mint));
if (!usable.length) {
coinGrid.innerHTML = `<div class="coin-empty">No coins matched. Try a different search, or paste a mint address below.</div>`;
@@ -202,6 +262,7 @@ function renderCoins(coins) {
function renderSkeleton(n = 12) {
coinGrid.innerHTML = '';
+ coinGrid.setAttribute('aria-busy', 'true');
for (let i = 0; i < n; i++) {
const sk = document.createElement('div');
sk.className = 'coin-card is-skeleton';
@@ -211,6 +272,7 @@ function renderSkeleton(n = 12) {
}
function renderCoinError() {
+ coinGrid.setAttribute('aria-busy', 'false');
coinGrid.innerHTML = `
<div class="coin-empty">
<p>Couldn't reach the pump.fun feed.</p>
@@ -304,6 +366,8 @@ function routeView() {
loadCoinProfile(m[1]);
} else {
_coinProfileMint = null;
+ // Back to the browse view: the coin's title no longer describes the page.
+ releasePageTitle();
}
}
window.addEventListener('popstate', routeView);
@@ -368,15 +432,15 @@ async function loadCoinProfile(mint) {
if (loadFailed) {
// Couldn't reach the feed — distinguish from a genuine 404 and let the
// user retry the same mint without re-navigating.
- $('coin-profile-empty-msg').textContent = 'Couldn’t load this coin right now.';
- document.title = 'Couldn’t load coin · three.ws';
+ claimI18n($('coin-profile-empty-msg'), 'Couldn’t load this coin right now.');
+ setPageTitle('Couldn’t load coin · three.ws');
if (retryBtn) {
retryBtn.hidden = false;
retryBtn.onclick = () => loadCoinProfile(mint);
}
} else {
- $('coin-profile-empty-msg').textContent = 'That coin couldn’t be found on pump.fun.';
- document.title = 'Coin not found · three.ws';
+ releaseI18n($('coin-profile-empty-msg'));
+ setPageTitle('Coin not found · three.ws');
if (retryBtn) retryBtn.hidden = true;
}
return;
@@ -446,10 +510,14 @@ function renderCoinProfile(coin) {
if (navigator.share) { try { await navigator.share({ title, text, url }); return; } catch {} }
try {
await navigator.clipboard.writeText(url);
- const orig = shareBtn.textContent;
- shareBtn.textContent = 'Link copied ✓';
- setTimeout(() => { shareBtn.textContent = orig; }, 1500);
- } catch {}
+ claimI18n(shareBtn, 'Link copied ✓');
+ setTimeout(() => releaseI18n(shareBtn), 1500);
+ } catch {
+ // Clipboard denied (permission or an insecure origin): the address bar
+ // already holds the shareable URL, so say that instead of failing mute.
+ claimI18n(shareBtn, 'Copy the page URL');
+ setTimeout(() => releaseI18n(shareBtn), 2500);
+ }
};
// Social links when pump.fun provides them.
@@ -464,7 +532,7 @@ function renderCoinProfile(coin) {
$('coin-profile-skeleton').hidden = true;
$('coin-profile-body').hidden = false;
- document.title = `$${symbol || name} · Coin Communities · three.ws`;
+ setPageTitle(`$${symbol || name} · Coin Communities · three.ws`);
}
function statHtml(label, value, up = false, id = '') {
@@ -497,7 +565,8 @@ async function loadCoinMarket(mint) {
$('cp-grad-ring').style.setProperty('--pct', `${pct.toFixed(0)}%`);
$('cp-grad-pct').textContent = g.isGraduated ? '✓' : `${pct.toFixed(0)}%`;
const lbl = gradWrap.querySelector('.cp-grad-label');
- if (lbl) lbl.textContent = g.isGraduated ? 'graduated' : 'to graduation';
+ if (g.isGraduated) claimI18n(lbl, 'graduated');
+ else releaseI18n(lbl);
}
} catch (err) {
log.warn('[communities] coin market', err?.message ?? err);
diff --git a/src/compare.js b/src/compare.js
index bd05af345..e1da2d669 100644
--- a/src/compare.js
+++ b/src/compare.js
@@ -28,8 +28,12 @@ async function getJson(url) {
return res.json();
}
-// state.coins: [{ id, color, detail, series }]
-const state = { coins: [], days: 30, loadingChart: false };
+// state.coins: [{ id, color, detail, series, status, seriesError }]
+// status: 'loading' while /api/coin/detail is in flight, 'ready' once it lands,
+// 'missing' when the id does not exist (404), 'failed' for anything else. Every
+// non-ready status is surfaced in the UI; none of them is allowed to leave a
+// skeleton on screen forever.
+const state = { coins: [], days: 30, loadingChart: false, booting: true };
const RANGES = [
{ label: '7D', days: 7 },
@@ -64,24 +68,35 @@ function nextColor() {
// ── Add / remove ──────────────────────────────────────────────────────────────
+async function loadDetail(entry) {
+ entry.status = 'loading';
+ try {
+ const { coin } = await getJson(`/api/coin/detail?id=${encodeURIComponent(entry.id)}`);
+ entry.detail = coin;
+ entry.status = 'ready';
+ } catch (err) {
+ entry.detail = null;
+ entry.status = err.status === 404 ? 'missing' : 'failed';
+ }
+}
+
+/** Returns why the add was refused, or 'added' once the coin has been fetched. */
async function addCoin(id) {
id = id.toLowerCase();
- if (state.coins.length >= MAX_COINS) return;
- if (state.coins.find((c) => c.id === id)) return;
- const entry = { id, color: nextColor(), detail: null, series: null, error: false };
+ if (state.coins.length >= MAX_COINS) return 'full';
+ if (state.coins.find((c) => c.id === id)) return 'duplicate';
+ const entry = { id, color: nextColor(), detail: null, series: null, status: 'loading' };
state.coins.push(entry);
renderChips();
+ renderTable();
+ renderChart();
syncUrl();
- try {
- const { coin } = await getJson(`/api/coin/detail?id=${encodeURIComponent(id)}`);
- entry.detail = coin;
- } catch {
- entry.error = true;
- }
+ await loadDetail(entry);
renderChips();
renderTable();
await loadSeries(entry);
renderChart();
+ return entry.status === 'ready' ? 'added' : entry.status;
}
function removeCoin(id) {
@@ -92,8 +107,38 @@ function removeCoin(id) {
syncUrl();
}
+/** Re-fetch every coin whose detail request failed on a transport error. */
+async function retryFailed() {
+ const failed = state.coins.filter((c) => c.status === 'failed');
+ if (!failed.length) return;
+ for (const c of failed) c.status = 'loading';
+ renderChips();
+ renderTable();
+ await Promise.all(failed.map(loadDetail));
+ renderChips();
+ renderTable();
+ await Promise.all(failed.map(loadSeries));
+ renderChart();
+}
+
+function dropUnresolved(status) {
+ const keep = state.coins.filter((c) => c.status !== status);
+ if (keep.length === state.coins.length) return;
+ state.coins = keep;
+ renderChips();
+ renderTable();
+ renderChart();
+ syncUrl();
+}
+
// ── Chips ─────────────────────────────────────────────────────────────────────
+const CHIP_NOTE = {
+ loading: 'Loading',
+ missing: 'Not found',
+ failed: 'Failed to load',
+};
+
function renderChips() {
const el = $('cmp-chips');
el.innerHTML = state.coins
@@ -103,10 +148,13 @@ function renderChips() {
const img = d?.image
? `<img loading="lazy" decoding="async" src="${esc(d.image)}" alt="" width="18" height="18" data-no-dark-filter />`
: `<span class="dot" style="background:${c.color}"></span>`;
- return `<span class="cmp-chip" style="border-color:${c.color}55">
+ const note = CHIP_NOTE[c.status];
+ const state_ = c.status && c.status !== 'ready' ? ` data-state="${c.status}"` : '';
+ return `<span class="cmp-chip" role="listitem"${state_} style="border-color:${c.color}55">
<span class="dot" style="background:${c.color}"></span>
${img}
<span>${name}${d?.symbol ? ` <span style="color:var(--cv-text-3)">${esc(d.symbol)}</span>` : ''}</span>
+ ${note ? `<span class="note">${note}</span>` : ''}
<button type="button" data-remove="${esc(c.id)}" aria-label="Remove ${name}">×</button>
</span>`;
})
@@ -114,6 +162,23 @@ function renderChips() {
el.querySelectorAll('button[data-remove]').forEach((b) =>
b.addEventListener('click', () => removeCoin(b.dataset.remove)),
);
+ syncPicker();
+}
+
+/** The picker has to say why it is closed once four coins are on screen. */
+function syncPicker() {
+ const input = $('cmp-search-input');
+ const hint = $('cmp-limit-hint');
+ const share = $('cmp-share');
+ const full = state.coins.length >= MAX_COINS;
+ if (input) {
+ input.disabled = full;
+ input.placeholder = full
+ ? 'Four coins is the maximum'
+ : `Add a coin to compare (up to ${MAX_COINS})…`;
+ }
+ if (hint) hint.hidden = !full;
+ if (share) share.disabled = !state.coins.length;
}
// ── Overlay chart ─────────────────────────────────────────────────────────────
@@ -124,6 +189,11 @@ const PAD = { top: 16, right: 56, bottom: 26, left: 16 };
async function loadSeries(entry) {
entry.series = null;
+ entry.seriesError = false;
+ if (entry.status === 'missing') {
+ entry.series = [];
+ return;
+ }
try {
const { data } = await getJson(
`/api/coin/ohlc?id=${encodeURIComponent(entry.id)}&days=${state.days}`,
@@ -137,6 +207,7 @@ async function loadSeries(entry) {
: [];
} catch {
entry.series = [];
+ entry.seriesError = true;
}
}
@@ -182,17 +253,34 @@ function renderChart() {
`<button type="button" class="cv-range-btn" data-days="${r.days}" aria-pressed="${r.days === state.days}">${r.label}</button>`,
).join('');
+ const pending =
+ state.loadingChart ||
+ state.coins.some((c) => c.status === 'loading' || (c.series === null && c.status !== 'missing'));
+
let body;
if (!state.coins.length) {
- body = '<div class="cv-chart-state">Add a coin above to start comparing.</div>';
- } else if (state.loadingChart) {
+ body = state.booting
+ ? '<div class="cv-chart-state"><span class="cv-spinner" aria-hidden="true"></span>Loading comparison…</div>'
+ : '<div class="cv-chart-state">Add a coin with the search box to start comparing.</div>';
+ } else if (pending) {
body =
'<div class="cv-chart-state"><span class="cv-spinner" aria-hidden="true"></span>Loading performance…</div>';
} else {
const g = chartGeometry();
if (!g) {
- body =
- '<div class="cv-chart-state">Performance data unavailable for the current selection.</div>';
+ // Every coin came back without a usable series. Say which failure it was
+ // and give the user the one control that can fix it.
+ const transport = state.coins.some((c) => c.seriesError || c.status === 'failed');
+ body = `<div class="cv-chart-state col" role="alert">
+ <p>${
+ transport
+ ? 'Performance data could not be loaded. The market data service did not respond.'
+ : 'No performance history is published for this selection over the last ' +
+ state.days +
+ ' days.'
+ }</p>
+ <button type="button" class="cv-linkbtn" id="cmp-chart-retry">${transport ? 'Retry' : 'Reload'}</button>
+ </div>`;
} else {
const h = CH - PAD.top - PAD.bottom;
const steps = 4;
@@ -233,12 +321,16 @@ function renderChart() {
}
}
+ // A coin the overlay could not draw still owns a legend slot, labelled so the
+ // missing line reads as a known gap rather than a rendering bug.
const legend = state.coins.length
? `<div class="cmp-legend">${state.coins
- .map(
- (c) =>
- `<span class="li"><span class="dot" style="background:${c.color}"></span>${esc(c.detail?.symbol || c.id)}</span>`,
- )
+ .map((c) => {
+ const drawn = !pending && c.series && c.series.length >= 2;
+ return `<span class="li${drawn ? '' : ' na'}"><span class="dot" style="background:${c.color}"></span>${esc(c.detail?.symbol || c.id)}${
+ pending || drawn ? '' : ' <span class="tag">no data</span>'
+ }</span>`;
+ })
.join('')}</div>`
: '';
@@ -260,6 +352,7 @@ function renderChart() {
reloadAllSeries();
});
});
+ el.querySelector('#cmp-chart-retry')?.addEventListener('click', () => reloadAllSeries());
wireChartPointer();
}
@@ -301,7 +394,9 @@ function wireChartPointer() {
.join('');
tip.hidden = false;
tip.innerHTML = `<p class="d" style="margin:0 0 0.25rem">${esc(formatChartTick(t, state.days))}</p>${rows}`;
- tip.style.left = `${(x / CW) * 100}%`;
+ // Clamped so the tooltip never hangs off the panel and drags the page into
+ // a horizontal scroll on a narrow viewport.
+ tip.style.left = `${Math.max(14, Math.min(86, (x / CW) * 100))}%`;
}
function hide() {
cross.setAttribute('hidden', '');
@@ -345,6 +440,42 @@ const ROWS = [
},
];
+function listIds(coins) {
+ return coins.map((c) => `<strong>${esc(c.detail?.name || c.id)}</strong>`).join(', ');
+}
+
+/** Anything the selection asked for and the API could not give back. */
+function issuesHtml() {
+ const missing = state.coins.filter((c) => c.status === 'missing');
+ const failed = state.coins.filter((c) => c.status === 'failed');
+ if (!missing.length && !failed.length) return '';
+ const lines = [];
+ if (failed.length)
+ lines.push(
+ `<p>Could not load ${listIds(failed)}. The market data service did not respond.</p>`,
+ );
+ if (missing.length)
+ lines.push(
+ `<p>No coin matches ${listIds(missing)}. Use the search box to pick one that exists.</p>`,
+ );
+ const acts = [
+ failed.length
+ ? '<button type="button" class="cv-linkbtn" data-retry-failed>Retry</button>'
+ : '',
+ missing.length
+ ? `<button type="button" class="cv-linkbtn" data-drop-missing>Remove ${missing.length > 1 ? 'them' : 'it'}</button>`
+ : '',
+ ].join('');
+ return `<div class="cmp-issues" role="alert">${lines.join('')}<div class="acts">${acts}</div></div>`;
+}
+
+function wireIssueActions(el) {
+ el.querySelector('[data-retry-failed]')?.addEventListener('click', retryFailed);
+ el.querySelector('[data-drop-missing]')?.addEventListener('click', () =>
+ dropUnresolved('missing'),
+ );
+}
+
function renderTable() {
const el = $('cmp-table');
const ready = state.coins.filter((c) => c.detail);
@@ -352,15 +483,20 @@ function renderTable() {
el.innerHTML = '';
return;
}
+ const issues = issuesHtml();
if (!ready.length) {
- el.innerHTML = '<div class="cv-skel" style="height:16rem"></div>';
+ // Never leave the skeleton up once every request has settled: a permanent
+ // shimmer reads as a hung page, not as a failure the user can act on.
+ const stillLoading = state.coins.some((c) => c.status === 'loading');
+ el.innerHTML = issues + (stillLoading ? '<div class="cv-skel" style="height:16rem"></div>' : '');
+ wireIssueActions(el);
return;
}
const head = ready
.map(
(c) =>
- `<th><a class="coin" href="/coin/${encodeURIComponent(c.id)}" style="text-decoration:none;color:inherit">
+ `<th scope="col"><a class="coin" href="/coin/${encodeURIComponent(c.id)}" style="text-decoration:none;color:inherit">
${c.detail.image ? `<img loading="lazy" decoding="async" src="${esc(c.detail.image)}" alt="" data-no-dark-filter />` : ''}
<span style="color:${c.color}">${esc(c.detail.symbol || c.detail.name)}</span>
</a></th>`,
@@ -387,16 +523,19 @@ function renderTable() {
return `<td class="${cls.join(' ')}">${esc(row.fmt(v))}</td>`;
})
.join('');
- return `<tr><td>${esc(row.label)}</td>${cells}</tr>`;
+ return `<tr><th scope="row">${esc(row.label)}</th>${cells}</tr>`;
}).join('');
el.innerHTML = `
+ ${issues}
<div class="cmp-table-wrap">
<table class="cmp-table">
- <thead><tr><th></th>${head}</tr></thead>
+ <caption class="cv-sr-only">Key market statistics for the selected coins, best value in each row highlighted.</caption>
+ <thead><tr><th scope="col"><span class="cv-sr-only">Metric</span></th>${head}</tr></thead>
<tbody>${body}</tbody>
</table>
</div>`;
+ wireIssueActions(el);
}
// ── Search type-ahead (mirrors the /coins picker) ─────────────────────────────
diff --git a/src/converter.css b/src/converter.css
index adde2f768..0d015ba9b 100644
--- a/src/converter.css
+++ b/src/converter.css
@@ -43,6 +43,20 @@
outline: 2px solid var(--cv-accent);
outline-offset: 2px;
}
+.cvt-preset.is-active {
+ color: var(--cv-accent);
+ border-color: color-mix(in srgb, var(--cv-accent) 55%, transparent);
+ background: color-mix(in srgb, var(--cv-accent) 12%, transparent);
+}
+.cvt-preset[disabled] {
+ cursor: default;
+ opacity: 0.45;
+}
+.cvt-preset[disabled]:hover {
+ background: var(--cv-surface-2);
+ color: var(--cv-text-2);
+ border-color: var(--cv-border);
+}
/* ── Widget shell ────────────────────────────────────────────────────────── */
@@ -63,7 +77,13 @@
}
}
+/*
+ * min-width:0 is load-bearing: as a grid item .cvt-side defaults to
+ * min-width:auto, which floors it at the amount input's intrinsic width and
+ * pushed the asset buttons off-screen at 320px.
+ */
.cvt-side {
+ min-width: 0;
background: var(--cv-surface-2);
border: 1px solid var(--cv-border);
border-radius: var(--cv-radius-lg);
@@ -90,9 +110,10 @@
gap: 0.75rem;
}
-/* Amount input — big, mono, borderless (the side card is the frame). */
+/* Amount input: big, mono, borderless (the side card is the frame). */
.cvt-amount {
- flex: 1 1 auto;
+ flex: 1 1 0;
+ width: 0;
min-width: 0;
appearance: none;
border: 0;
@@ -112,9 +133,11 @@
color: var(--cv-text-3);
}
-/* Result — same visual weight as the input, read-only. */
+/* Result: same visual weight as the input, read-only. */
.cvt-result {
- flex: 1 1 auto;
+ display: block;
+ flex: 1 1 0;
+ width: 0;
min-width: 0;
color: var(--cv-text);
font-family: var(--cv-font-mono);
@@ -130,6 +153,32 @@
color: var(--cv-text-3);
}
+/* Small phones: shrink the display type and side padding so the amount and the
+ asset button both stay legible on one row instead of ellipsing. */
+@media (max-width: 24.9375rem) {
+ .cvt-side {
+ padding: 0.875rem;
+ }
+ .cvt-amount,
+ .cvt-result {
+ font-size: 1.375rem;
+ }
+ .cvt-asset {
+ padding: 0.3125rem 0.5rem 0.3125rem 0.375rem;
+ gap: 0.3125rem;
+ }
+ .cvt-asset-code {
+ font-size: 0.875rem;
+ }
+}
+
+/* Inline validation for the amount field. */
+.cvt-hint {
+ margin: 0.5rem 0 0;
+ font-size: 0.8125rem;
+ color: var(--cv-warn, #f59e0b);
+}
+
.cvt-subline {
margin: 0.5rem 0 0;
font-size: 0.8125rem;
@@ -274,9 +323,73 @@
color: var(--cv-text-3);
}
+/* ── Footer: freshness stamp + share ─────────────────────────────────────── */
+
+.cvt-foot {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ justify-content: center;
+ gap: 0.5rem 0.875rem;
+ margin-top: 0.25rem;
+}
.cvt-card .cv-updated {
text-align: center;
- margin-top: 0.25rem;
+ margin: 0;
+}
+
+.cvt-copy {
+ appearance: none;
+ cursor: pointer;
+ display: inline-flex;
+ align-items: center;
+ gap: 0.375rem;
+ font: inherit;
+ font-size: 0.8125rem;
+ font-weight: 500;
+ color: var(--cv-text-2);
+ background: var(--cv-surface-2);
+ border: 1px solid var(--cv-border);
+ border-radius: 999px;
+ padding: 0.3125rem 0.75rem;
+ transition:
+ background 0.15s,
+ color 0.15s,
+ border-color 0.15s;
+}
+.cvt-copy:hover {
+ color: var(--cv-text);
+ background: var(--cv-surface-3);
+ border-color: var(--cv-border-hover);
+}
+.cvt-copy:active {
+ transform: translateY(1px);
+}
+.cvt-copy:focus-visible {
+ outline: 2px solid var(--cv-accent);
+ outline-offset: 2px;
+}
+.cvt-copy.is-copied {
+ color: var(--cv-accent);
+ border-color: color-mix(in srgb, var(--cv-accent) 55%, transparent);
+ background: color-mix(in srgb, var(--cv-accent) 12%, transparent);
+}
+.cvt-copy svg {
+ flex: 0 0 auto;
+}
+
+/* Screen-reader-only announcement region for the copy result. */
+.cvt-sr-status {
+ position: absolute;
+ width: 1px;
+ height: 1px;
+ margin: -1px;
+ padding: 0;
+ overflow: hidden;
+ clip: rect(0 0 0 0);
+ clip-path: inset(50%);
+ white-space: nowrap;
+ border: 0;
}
.cvt-retry {
@@ -403,10 +516,16 @@
transition: background 0.12s;
}
.cvt-pick-item:hover,
-.cvt-pick-item:focus-visible {
+.cvt-pick-item:focus-visible,
+.cvt-pick-item.is-active {
background: var(--cv-surface-2);
outline: none;
}
+/* Keyboard highlight is stronger than hover: the search box keeps DOM focus, so
+ this ring is the only cue for where Enter would land. */
+.cvt-pick-item.is-active {
+ box-shadow: inset 0 0 0 1px color-mix(in srgb, var(--cv-accent) 55%, transparent);
+}
.cvt-pick-item img {
width: 22px;
height: 22px;
diff --git a/src/converter.js b/src/converter.js
index dc9e595fe..f631545f1 100644
--- a/src/converter.js
+++ b/src/converter.js
@@ -1,70 +1,39 @@
-// /converter — crypto ⇄ crypto ⇄ fiat converter, part of the /coins "Markets"
-// surface. Reuses the shared /api/coin proxies:
-// · /api/coin/rates → curated fiat currencies (units per 1 BTC)
-// · /api/coin/markets?q=<text> → coin search type-ahead (same UX as /coins)
-// · /api/coin/detail?id=<id> → a coin's live USD price (market.price)
+// /converter - crypto and fiat converter, part of the /coins "Markets" surface.
+// Reuses the shared /api/coin proxies:
+// · /api/coin/rates -> curated fiat currencies (units per 1 BTC)
+// · /api/coin/markets?q=<text> -> coin search type-ahead (same UX as /coins)
+// · /api/coin/detail?id=<id> -> a coin's live USD price (market.price)
//
-// Conversion is anchored in USD. Every asset knows its USD value:
-// · crypto: priceUSD = market.price (USD per 1 coin)
-// · fiat: fiatPerUsd(code) = fiat.per_btc / usd.per_btc (units per 1 USD)
-// From any FROM asset we compute the USD value of `amount`, then express that
-// value in the TO asset — which makes all four directions fall out of one
-// formula: crypto→crypto, crypto→fiat, fiat→crypto, fiat→fiat.
+// The conversion math, formatting, and shareable-URL codec live in
+// src/shared/converter-state.js; this module is the DOM layer on top of them.
+// Every view is addressable: /converter?from=ethereum&to=EUR&amount=3 restores
+// both sides and the amount, and the URL rewrites itself as the user edits so
+// the address bar (and the Copy link button) always hold the current result.
import { formatPrice, escapeHtml as esc } from './shared/coin-format.js';
+import {
+ EMPTY,
+ assetCode,
+ buildConverterQuery,
+ convert as convertAmount,
+ formatInAsset,
+ parseAmount,
+ parseConverterQuery,
+ resolveAssetRef,
+} from './shared/converter-state.js';
const $ = (id) => document.getElementById(id);
async function getJson(url) {
const res = await fetch(url, { headers: { accept: 'application/json' } });
if (!res.ok) {
- const err = new Error(`fetch ${url} → ${res.status}`);
+ const err = new Error(`fetch ${url} -> ${res.status}`);
err.status = res.status;
throw err;
}
return res.json();
}
-// ── Formatting ────────────────────────────────────────────────────────────────
-
-// Fiat amount with the currency's own unit symbol + thousands separators.
-// Alphabetic units ("Fr.", "R$", "kr") get a space; glyphs ("$", "€", "₹") hug.
-function formatFiatAmount(n, unit) {
- if (n == null || !Number.isFinite(n)) return '—';
- const sign = n < 0 ? '-' : '';
- const abs = Math.abs(n);
- let body;
- if (abs !== 0 && abs < 0.01) body = abs.toPrecision(4);
- else body = abs.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
- const u = unit || '';
- const sep = /[A-Za-z.]$/.test(u) ? ' ' : '';
- return `${sign}${u}${sep}${body}`;
-}
-
-// Crypto amount: full precision for whole coins, significant figures for the
-// deep-decimal results a fiat→BTC conversion produces (e.g. 0.00001587 BTC).
-function formatCryptoAmount(n) {
- if (n == null || !Number.isFinite(n)) return '—';
- if (n === 0) return '0';
- const abs = Math.abs(n);
- if (abs >= 1) return n.toLocaleString('en-US', { maximumFractionDigits: 8 });
- const s = n.toPrecision(6);
- const expanded = s.includes('e') ? Number(s).toFixed(18) : s;
- return expanded.replace(/(\.\d*?)0+$/, '$1').replace(/\.$/, '');
-}
-
-// Format `n` in whatever `asset` is — used for the result field and rate line.
-function formatInAsset(n, asset) {
- if (!asset) return '—';
- return asset.kind === 'fiat' ? formatFiatAmount(n, asset.unit) : formatCryptoAmount(n);
-}
-
-// Short code shown on the asset button and rate line.
-function assetCode(asset) {
- if (!asset) return '';
- return asset.kind === 'fiat' ? asset.code : asset.symbol;
-}
-
// ── State ─────────────────────────────────────────────────────────────────────
// rates: { byCode: Map<CODE, {code,name,unit,per_btc}>, usdPerBtc, list:[], updated_at }
@@ -75,50 +44,91 @@ const state = {
from: null,
to: null,
amount: 1,
+ amountText: '1',
loading: true,
error: null,
pending: { from: false, to: false },
};
const DEFAULT_CRYPTO = 'bitcoin';
+const DEFAULT_FIAT = 'USD';
-// ── Conversion math (USD-anchored) ────────────────────────────────────────────
+const usdPerBtc = () => state.rates?.usdPerBtc ?? NaN;
+const convert = (amount, from, to) => convertAmount(amount, from, to, usdPerBtc());
-function fiatPerUsd(fiat) {
- // units of `fiat` per 1 BTC ÷ USD per 1 BTC = units of `fiat` per 1 USD.
- return fiat.per_btc / state.rates.usdPerBtc;
+// ── Shareable URL ─────────────────────────────────────────────────────────────
+
+// Every state change rewrites the query in place. replaceState (not pushState)
+// keeps the back button pointing at wherever the visitor came from instead of
+// burying it under one entry per keystroke.
+function syncUrl() {
+ if (state.loading || state.error) return;
+ const query = buildConverterQuery(state);
+ const next = `${window.location.pathname}${query}`;
+ if (next === `${window.location.pathname}${window.location.search}`) return;
+ window.history.replaceState(null, '', next);
+ const copy = $('cvt-copy');
+ if (copy) resetCopyButton(copy);
}
-// USD value of `amount` units of `asset`.
-function toUsd(amount, asset) {
- if (!asset || !Number.isFinite(amount)) return null;
- if (asset.kind === 'crypto') {
- if (!Number.isFinite(asset.priceUSD)) return null;
- return amount * asset.priceUSD;
- }
- // fiat: amount fiat-units ÷ (fiat-units per USD) = USD.
- const perUsd = fiatPerUsd(asset);
- if (!Number.isFinite(perUsd) || perUsd <= 0) return null;
- return amount / perUsd;
+function shareUrl() {
+ return `${window.location.origin}${window.location.pathname}${buildConverterQuery(state)}`;
}
-// Express a USD value in `asset`.
-function fromUsd(valueUsd, asset) {
- if (!asset || !Number.isFinite(valueUsd)) return null;
- if (asset.kind === 'crypto') {
- if (!Number.isFinite(asset.priceUSD) || asset.priceUSD <= 0) return null;
- return valueUsd / asset.priceUSD;
- }
- const perUsd = fiatPerUsd(asset);
- if (!Number.isFinite(perUsd)) return null;
- return valueUsd * perUsd;
+const COPY_ICON =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="9" y="9" width="13" height="13" rx="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>';
+const CHECK_ICON =
+ '<svg viewBox="0 0 24 24" width="15" height="15" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><polyline points="20 6 9 17 4 12"/></svg>';
+
+function resetCopyButton(btn) {
+ btn.classList.remove('is-copied');
+ btn.innerHTML = `${COPY_ICON}<span>Copy link</span>`;
}
-// Convert `amount` of FROM into TO. Null if either leg lacks a price.
-function convert(amount, from, to) {
- const usd = toUsd(amount, from);
- if (usd == null) return null;
- return fromUsd(usd, to);
+// Clipboard API first; on a browser or context that refuses it, fall back to a
+// scratch textarea so the button still works instead of silently doing nothing.
+async function writeClipboard(text) {
+ if (navigator.clipboard?.writeText) {
+ try {
+ await navigator.clipboard.writeText(text);
+ return true;
+ } catch {
+ // Permission denied or an insecure context: try the fallback below.
+ }
+ }
+ const ta = document.createElement('textarea');
+ ta.value = text;
+ ta.setAttribute('readonly', '');
+ ta.style.cssText = 'position:fixed;top:0;left:-9999px;opacity:0';
+ document.body.appendChild(ta);
+ ta.select();
+ let ok = false;
+ try {
+ ok = document.execCommand('copy');
+ } catch {
+ ok = false;
+ }
+ ta.remove();
+ return ok;
+}
+
+let copyTimer = null;
+async function onCopyLink() {
+ const btn = $('cvt-copy');
+ if (!btn) return;
+ const ok = await writeClipboard(shareUrl());
+ clearTimeout(copyTimer);
+ btn.classList.add('is-copied');
+ btn.innerHTML = ok
+ ? `${CHECK_ICON}<span>Link copied</span>`
+ : `${COPY_ICON}<span>Press Ctrl+C</span>`;
+ const status = $('cvt-copy-status');
+ if (status) {
+ status.textContent = ok
+ ? `Link copied: ${shareUrl()}`
+ : 'Copy blocked by the browser. The link is in the address bar.';
+ }
+ copyTimer = setTimeout(() => resetCopyButton(btn), 2200);
}
// ── Rendering ─────────────────────────────────────────────────────────────────
@@ -143,6 +153,15 @@ function assetButtonInner(asset, side) {
return `<span class="cvt-asset-glyph fiat">${esc(glyph)}</span><span class="cvt-asset-code">${esc(asset.code)}</span>${CHEVRON}`;
}
+// Accessible name for the asset button, so a screen reader hears the currency
+// rather than just "button".
+function assetButtonLabel(asset, side) {
+ const what = side === 'from' ? 'Convert from' : 'Convert to';
+ if (state.pending[side]) return `${what}: loading`;
+ if (!asset) return `${what}: choose a currency`;
+ return `${what}: ${asset.name || assetCode(asset)}. Change currency`;
+}
+
function assetSubline(asset) {
if (!asset) return '';
if (asset.kind === 'crypto') {
@@ -160,7 +179,7 @@ function renderRate() {
}
const one = convert(1, state.from, state.to);
if (one == null) {
- el.innerHTML = `<span class="dim">Live rate unavailable for this pair.</span>`;
+ el.innerHTML = `<span class="dim">Live rate unavailable for this pair. Pick another currency or try again shortly.</span>`;
return;
}
el.innerHTML = `1 ${esc(assetCode(state.from))} = <strong>${esc(formatInAsset(one, state.to))}</strong> ${esc(assetCode(state.to))}`;
@@ -169,33 +188,55 @@ function renderRate() {
function renderResult() {
const el = $('cvt-result');
if (!el) return;
- const amt = state.amount;
- if (!Number.isFinite(amt)) {
- el.innerHTML = '<span class="cvt-result-empty">—</span>';
- return;
- }
- const out = convert(amt, state.from, state.to);
+ const out = Number.isFinite(state.amount)
+ ? convert(state.amount, state.from, state.to)
+ : null;
if (out == null) {
- el.innerHTML = '<span class="cvt-result-empty">—</span>';
+ el.innerHTML = `<span class="cvt-result-empty">${EMPTY}</span>`;
return;
}
el.textContent = formatInAsset(out, state.to);
}
+// A typed value the converter cannot use gets an explanation instead of a bare
+// placeholder, so the user knows the page is not broken.
+function renderAmountHint() {
+ const el = $('cvt-amount-hint');
+ if (!el) return;
+ const raw = state.amountText.trim();
+ if (!raw) {
+ el.textContent = 'Enter an amount to convert.';
+ el.hidden = false;
+ return;
+ }
+ if (!Number.isFinite(state.amount)) {
+ el.textContent = 'Enter a positive number, digits only.';
+ el.hidden = false;
+ return;
+ }
+ el.hidden = true;
+ el.textContent = '';
+}
+
function renderUpdated() {
const el = $('cvt-updated');
if (!el || !state.rates) return;
const d = new Date(state.rates.updated_at);
+ if (Number.isNaN(d.getTime())) {
+ el.textContent = 'Live market prices';
+ return;
+ }
el.textContent = `Rates updated ${d.toLocaleTimeString('en-US', { hour: '2-digit', minute: '2-digit' })} · live market prices`;
}
function renderCard() {
const app = $('cvt-app');
+ renderPresets();
if (state.error) {
app.innerHTML = `
<div class="cvt-card cv-card">
<div class="cv-empty">
- <p style="margin:0 0 0.75rem">We couldn't load live rates just now.</p>
+ <p style="margin:0 0 0.75rem">We couldn't load live rates just now. Check your connection, then retry.</p>
<button type="button" class="cvt-retry" id="cvt-retry">Try again</button>
</div>
</div>`;
@@ -214,7 +255,7 @@ function renderCard() {
app.innerHTML = `
<div class="cvt-card cv-card">
<div class="cvt-side" data-side="from">
- <span class="cvt-label">Amount</span>
+ <label class="cvt-label" for="cvt-amount">Amount</label>
<div class="cvt-row">
<input
class="cvt-amount"
@@ -223,27 +264,29 @@ function renderCard() {
inputmode="decimal"
autocomplete="off"
spellcheck="false"
- aria-label="Amount to convert"
- value="${esc(state.amount != null && Number.isFinite(state.amount) ? String(state.amount) : '')}"
+ size="1"
+ aria-describedby="cvt-amount-hint"
+ value="${esc(state.amountText)}"
/>
- <button type="button" class="cvt-asset" id="cvt-from-btn" aria-haspopup="listbox" aria-expanded="false">
+ <button type="button" class="cvt-asset" id="cvt-from-btn" aria-haspopup="dialog" aria-expanded="false" aria-label="${esc(assetButtonLabel(state.from, 'from'))}">
${assetButtonInner(state.from, 'from')}
</button>
</div>
+ <p class="cvt-hint" id="cvt-amount-hint" hidden></p>
<p class="cvt-subline" id="cvt-from-sub">${assetSubline(state.from)}</p>
</div>
<div class="cvt-swap-wrap">
- <button type="button" class="cvt-swap" id="cvt-swap" aria-label="Swap currencies" title="Swap">
+ <button type="button" class="cvt-swap" id="cvt-swap" aria-label="Swap the two currencies" title="Swap">
${SWAP_ICON}
</button>
</div>
<div class="cvt-side" data-side="to">
- <span class="cvt-label">Converted to</span>
+ <span class="cvt-label" id="cvt-to-label">Converted to</span>
<div class="cvt-row">
- <div class="cvt-result" id="cvt-result" aria-live="polite"></div>
- <button type="button" class="cvt-asset" id="cvt-to-btn" aria-haspopup="listbox" aria-expanded="false">
+ <output class="cvt-result" id="cvt-result" for="cvt-amount" aria-live="polite" aria-labelledby="cvt-to-label"></output>
+ <button type="button" class="cvt-asset" id="cvt-to-btn" aria-haspopup="dialog" aria-expanded="false" aria-label="${esc(assetButtonLabel(state.to, 'to'))}">
${assetButtonInner(state.to, 'to')}
</button>
</div>
@@ -251,59 +294,70 @@ function renderCard() {
</div>
<p class="cvt-rate" id="cvt-rate"></p>
- <p class="cv-updated" id="cvt-updated"></p>
+ <div class="cvt-foot">
+ <p class="cv-updated" id="cvt-updated"></p>
+ <button type="button" class="cvt-copy" id="cvt-copy">${COPY_ICON}<span>Copy link</span></button>
+ </div>
+ <p class="cvt-sr-status" id="cvt-copy-status" role="status" aria-live="polite"></p>
</div>`;
wireCard();
renderResult();
renderRate();
+ renderAmountHint();
renderUpdated();
}
-// Refresh just the dynamic bits without tearing down the input (keeps focus /
+// Refresh just the dynamic bits without tearing down the input (keeps focus and
// caret while typing). Falls back to a full re-render if the card isn't mounted.
function refresh() {
if (!$('cvt-result')) {
renderCard();
return;
}
- const fb = $('cvt-from-btn');
- const tb = $('cvt-to-btn');
- if (fb) fb.innerHTML = assetButtonInner(state.from, 'from');
- if (tb) tb.innerHTML = assetButtonInner(state.to, 'to');
- const fs = $('cvt-from-sub');
- const ts = $('cvt-to-sub');
- if (fs) fs.innerHTML = assetSubline(state.from);
- if (ts) ts.innerHTML = assetSubline(state.to);
+ for (const side of ['from', 'to']) {
+ const btn = $(`cvt-${side}-btn`);
+ if (btn) {
+ btn.innerHTML = assetButtonInner(state[side], side);
+ btn.setAttribute('aria-label', assetButtonLabel(state[side], side));
+ }
+ const sub = $(`cvt-${side}-sub`);
+ if (sub) sub.innerHTML = assetSubline(state[side]);
+ }
renderResult();
renderRate();
+ renderAmountHint();
renderUpdated();
+ renderPresets();
+ syncUrl();
}
function wireCard() {
const input = $('cvt-amount');
let debounce = null;
input?.addEventListener('input', () => {
- const raw = input.value.replace(/,/g, '').trim();
+ state.amountText = input.value;
clearTimeout(debounce);
debounce = setTimeout(() => {
- const n = raw === '' ? NaN : Number(raw);
- state.amount = Number.isFinite(n) && n >= 0 ? n : NaN;
+ state.amount = parseAmount(input.value);
renderResult();
+ renderAmountHint();
+ renderPresets();
+ syncUrl();
}, 120);
});
// Select-all on focus so a tap-and-type replaces the value cleanly.
input?.addEventListener('focus', () => input.select());
$('cvt-swap')?.addEventListener('click', swap);
- $('cvt-from-btn')?.addEventListener('click', (e) => {
- e.stopPropagation();
- openPicker('from', e.currentTarget);
- });
- $('cvt-to-btn')?.addEventListener('click', (e) => {
- e.stopPropagation();
- openPicker('to', e.currentTarget);
- });
+ $('cvt-copy')?.addEventListener('click', onCopyLink);
+ for (const side of ['from', 'to']) {
+ $(`cvt-${side}-btn`)?.addEventListener('click', (e) => {
+ e.stopPropagation();
+ if (picker.open && picker.side === side) closePicker();
+ else openPicker(side, e.currentTarget);
+ });
+ }
}
function swap() {
@@ -316,12 +370,12 @@ function swap() {
// ── Asset resolution ──────────────────────────────────────────────────────────
function fiatAsset(code) {
- const f = state.rates?.byCode.get(code.toUpperCase());
+ const f = state.rates?.byCode.get(String(code).toUpperCase());
if (!f) return null;
return { kind: 'fiat', code: f.code, name: f.name, unit: f.unit, per_btc: f.per_btc };
}
-// Fetch a coin's live USD price and metadata → a crypto asset.
+// Fetch a coin's live USD price and metadata -> a crypto asset.
async function cryptoAsset(id, seed = {}) {
const { coin } = await getJson(`/api/coin/detail?id=${encodeURIComponent(id)}`);
const price = coin?.market?.price;
@@ -337,7 +391,7 @@ async function cryptoAsset(id, seed = {}) {
// Load a crypto into `side`, showing a spinner on that side while the price
// request is in flight. Seed carries the search-result metadata so the button
-// shows the symbol/icon immediately.
+// shows the symbol and icon immediately.
async function selectCrypto(side, id, seed = {}) {
state.pending[side] = true;
// Optimistic placeholder so the button updates instantly.
@@ -353,8 +407,8 @@ async function selectCrypto(side, id, seed = {}) {
try {
state[side] = await cryptoAsset(id, seed);
} catch {
- // Keep the placeholder but mark price missing — the rate line shows the
- // "unavailable" copy rather than a wrong number.
+ // Keep the placeholder but leave the price missing: the rate line shows
+ // the "unavailable" copy rather than a wrong number.
state[side] = { ...state[side], priceUSD: NaN };
}
state.pending[side] = false;
@@ -368,9 +422,19 @@ function selectFiat(side, code) {
refresh();
}
+// Load whichever kind of asset a URL ref or preset names.
+function selectRef(side, ref, seed = {}) {
+ if (!ref) return null;
+ if (ref.kind === 'fiat') {
+ selectFiat(side, ref.code);
+ return null;
+ }
+ return selectCrypto(side, ref.id, seed);
+}
+
// ── Asset picker (fiat + crypto search) ───────────────────────────────────────
-const picker = { open: false, side: null, anchor: null, timer: null };
+const picker = { open: false, side: null, anchor: null, timer: null, active: -1 };
function currencyGlyph(f) {
return f.unit || f.code.slice(0, 1);
@@ -385,14 +449,14 @@ function pickerFiatRows(query) {
const items = rows
.map(
(f) => `
- <button type="button" class="cvt-pick-item" role="option" data-kind="fiat" data-code="${esc(f.code)}">
+ <button type="button" class="cvt-pick-item" role="option" aria-selected="false" data-kind="fiat" data-code="${esc(f.code)}">
<span class="cvt-pick-glyph fiat">${esc(currencyGlyph(f))}</span>
<span class="cvt-pick-name">${esc(f.name)}</span>
<span class="cvt-pick-code">${esc(f.code)}</span>
</button>`,
)
.join('');
- return `<div class="cvt-pick-group"><p class="cvt-pick-head">Fiat currencies</p>${items}</div>`;
+ return `<div class="cvt-pick-group" role="group" aria-label="Fiat currencies"><p class="cvt-pick-head">Fiat currencies</p>${items}</div>`;
}
function pickerCryptoRows(coins) {
@@ -400,7 +464,7 @@ function pickerCryptoRows(coins) {
const items = coins
.map(
(c) => `
- <button type="button" class="cvt-pick-item" role="option" data-kind="crypto" data-id="${esc(c.id)}" data-symbol="${esc(c.symbol)}" data-name="${esc(c.name)}" data-thumb="${esc(c.thumb || '')}">
+ <button type="button" class="cvt-pick-item" role="option" aria-selected="false" data-kind="crypto" data-id="${esc(c.id)}" data-symbol="${esc(c.symbol)}" data-name="${esc(c.name)}" data-thumb="${esc(c.thumb || '')}">
${c.thumb ? `<img loading="lazy" decoding="async" src="${esc(c.thumb)}" alt="" width="22" height="22" data-no-dark-filter />` : `<span class="cvt-pick-glyph">${esc((c.symbol || '?').slice(0, 1))}</span>`}
<span class="cvt-pick-name">${esc(c.name)}</span>
<span class="cvt-pick-code">${esc(c.symbol)}</span>
@@ -408,11 +472,12 @@ function pickerCryptoRows(coins) {
</button>`,
)
.join('');
- return `<div class="cvt-pick-group"><p class="cvt-pick-head">Cryptocurrencies</p>${items}</div>`;
+ return `<div class="cvt-pick-group" role="group" aria-label="Cryptocurrencies"><p class="cvt-pick-head">Cryptocurrencies</p>${items}</div>`;
}
-function renderPicker({ query = '', coins = null, loading = false } = {}) {
- const el = $('cvt-picker');
+// One builder for the results body, used by both the full popover render and
+// the list-only refresh, so the two can never drift apart.
+function pickerBody({ query = '', coins = null, loading = false } = {}) {
const fiatRows = pickerFiatRows(query);
let cryptoSection;
if (loading) {
@@ -424,19 +489,24 @@ function renderPicker({ query = '', coins = null, loading = false } = {}) {
: `<div class="cvt-pick-note">No coins match “${esc(query)}”.</div>`;
} else {
cryptoSection =
- '<div class="cvt-pick-note">Type to search 10,000+ coins by name or symbol.</div>';
+ '<div class="cvt-pick-note">Type to search thousands of coins by name or symbol.</div>';
+ }
+ if (!fiatRows && coins && !coins.length) {
+ return `<div class="cvt-pick-note">Nothing matches “${esc(query)}”. Try a ticker such as BTC, or a name such as Euro.</div>`;
}
- const body =
- !fiatRows && coins && !coins.length
- ? `<div class="cvt-pick-note">Nothing matches “${esc(query)}”.</div>`
- : `${fiatRows}${cryptoSection}`;
+ return `${fiatRows}${cryptoSection}`;
+}
+function renderPicker({ query = '', coins = null, loading = false } = {}) {
+ const el = $('cvt-picker');
el.innerHTML = `
<div class="cvt-pick-search">
<svg class="mag" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
- <input type="text" id="cvt-pick-input" placeholder="Search currency or coin" autocomplete="off" spellcheck="false" aria-label="Search for a currency or coin" value="${esc(query)}" />
+ <input type="text" id="cvt-pick-input" placeholder="Search currency or coin" autocomplete="off" spellcheck="false"
+ role="combobox" aria-expanded="true" aria-controls="cvt-pick-list" aria-autocomplete="list"
+ aria-label="Search for a currency or coin" value="${esc(query)}" />
</div>
- <div class="cvt-pick-list" id="cvt-pick-list" role="listbox">${body}</div>`;
+ <div class="cvt-pick-list" id="cvt-pick-list" role="listbox" aria-label="Currencies and coins">${pickerBody({ query, coins, loading })}</div>`;
const input = $('cvt-pick-input');
input.focus();
@@ -445,10 +515,44 @@ function renderPicker({ query = '', coins = null, loading = false } = {}) {
wirePickerItems();
}
+// Re-render the list only (not the whole popover) so the search input keeps
+// focus and caret while results stream in.
+function renderPickerPreserveFocus(opts) {
+ const list = $('cvt-pick-list');
+ if (!list) return renderPicker(opts);
+ list.innerHTML = pickerBody(opts);
+ wirePickerItems();
+}
+
+function pickerItems() {
+ return [...($('cvt-pick-list')?.querySelectorAll('.cvt-pick-item') || [])];
+}
+
function wirePickerItems() {
- $('cvt-pick-list')
- ?.querySelectorAll('.cvt-pick-item')
- .forEach((btn) => btn.addEventListener('click', () => choosePickItem(btn)));
+ picker.active = -1;
+ pickerItems().forEach((btn, i) => {
+ btn.id = `cvt-pick-opt-${i}`;
+ btn.addEventListener('click', () => choosePickItem(btn));
+ btn.addEventListener('mousemove', () => setActiveItem(i, { scroll: false }));
+ });
+ $('cvt-pick-input')?.removeAttribute('aria-activedescendant');
+}
+
+// Roving highlight driven from the search box: the input keeps DOM focus (so
+// typing never breaks) and aria-activedescendant points at the current option.
+function setActiveItem(index, { scroll = true } = {}) {
+ const items = pickerItems();
+ if (!items.length) return;
+ const next = ((index % items.length) + items.length) % items.length;
+ items.forEach((el, i) => {
+ const on = i === next;
+ el.classList.toggle('is-active', on);
+ el.setAttribute('aria-selected', on ? 'true' : 'false');
+ });
+ picker.active = next;
+ const el = items[next];
+ if (scroll) el.scrollIntoView({ block: 'nearest' });
+ $('cvt-pick-input')?.setAttribute('aria-activedescendant', el.id);
}
function choosePickItem(btn) {
@@ -463,6 +567,7 @@ function choosePickItem(btn) {
});
}
closePicker();
+ $(`cvt-${side}-btn`)?.focus();
}
function onPickerInput(e) {
@@ -472,14 +577,14 @@ function onPickerInput(e) {
renderPickerPreserveFocus({ query: '' });
return;
}
- // Show fiat matches + a loading state immediately, then fill crypto results.
+ // Show fiat matches plus a loading state immediately, then fill in crypto.
renderPickerPreserveFocus({ query: q, loading: true });
picker.timer = setTimeout(async () => {
try {
const { coins } = await getJson(`/api/coin/markets?q=${encodeURIComponent(q)}`);
// Guard against a stale response after the input changed again.
if ($('cvt-pick-input')?.value.trim() === q) {
- renderPickerPreserveFocus({ query: q, coins });
+ renderPickerPreserveFocus({ query: q, coins: coins || [] });
}
} catch {
if ($('cvt-pick-input')?.value.trim() === q) {
@@ -489,42 +594,47 @@ function onPickerInput(e) {
}, 250);
}
-// Re-render the list only (not the whole popover) so the search input keeps
-// focus and caret while results stream in.
-function renderPickerPreserveFocus(opts) {
- const list = $('cvt-pick-list');
- if (!list) return renderPicker(opts);
- const { query = '', coins = null, loading = false } = opts;
- const fiatRows = pickerFiatRows(query);
- let cryptoSection;
- if (loading) {
- cryptoSection =
- '<div class="cvt-pick-note"><span class="cv-spinner" aria-hidden="true"></span>Searching coins…</div>';
- } else if (coins) {
- cryptoSection = coins.length
- ? pickerCryptoRows(coins)
- : `<div class="cvt-pick-note">No coins match “${esc(query)}”.</div>`;
- } else {
- cryptoSection =
- '<div class="cvt-pick-note">Type to search 10,000+ coins by name or symbol.</div>';
- }
- list.innerHTML =
- !fiatRows && coins && !coins.length
- ? `<div class="cvt-pick-note">Nothing matches “${esc(query)}”.</div>`
- : `${fiatRows}${cryptoSection}`;
- wirePickerItems();
-}
-
function onPickerKey(e) {
if (e.key === 'Escape') {
e.preventDefault();
+ const anchor = picker.anchor;
closePicker();
- picker.anchor?.focus();
+ anchor?.focus();
+ return;
+ }
+ if (e.key === 'ArrowDown') {
+ e.preventDefault();
+ setActiveItem(picker.active + 1);
+ return;
+ }
+ if (e.key === 'ArrowUp') {
+ e.preventDefault();
+ setActiveItem(picker.active <= 0 ? pickerItems().length - 1 : picker.active - 1);
+ return;
}
+ if (e.key === 'Home') {
+ e.preventDefault();
+ setActiveItem(0);
+ return;
+ }
+ if (e.key === 'End') {
+ e.preventDefault();
+ setActiveItem(pickerItems().length - 1);
+ return;
+ }
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ const items = pickerItems();
+ const target = items[picker.active >= 0 ? picker.active : 0];
+ if (target) choosePickItem(target);
+ return;
+ }
+ // Tab out of the popover closes it rather than leaving an orphan overlay.
+ if (e.key === 'Tab') closePicker();
}
function positionPicker(anchor) {
- // Fixed position (viewport coords) so the offset parent is unambiguous — the
+ // Fixed position (viewport coords) so the offset parent is unambiguous: the
// popover is a sibling of the card, not a child. Right-aligned under the
// button and clamped to an 8px viewport gutter on both edges.
const el = $('cvt-picker');
@@ -548,6 +658,7 @@ function openPicker(side, anchor) {
function closePicker() {
if (!picker.open) return;
+ clearTimeout(picker.timer);
picker.open = false;
picker.anchor?.setAttribute('aria-expanded', 'false');
const el = $('cvt-picker');
@@ -555,6 +666,7 @@ function closePicker() {
el.innerHTML = '';
picker.side = null;
picker.anchor = null;
+ picker.active = -1;
}
document.addEventListener('click', (e) => {
@@ -565,7 +677,7 @@ document.addEventListener('click', (e) => {
window.addEventListener('resize', () => {
if (picker.open && picker.anchor) positionPicker(picker.anchor);
});
-// A fixed popover doesn't follow page scroll — keep it pinned to its anchor.
+// A fixed popover doesn't follow page scroll: keep it pinned to its anchor.
window.addEventListener(
'scroll',
() => {
@@ -578,101 +690,126 @@ window.addEventListener(
const PRESETS = [
{
- label: 'BTC → USD',
+ label: 'BTC to USD',
from: { kind: 'crypto', id: 'bitcoin', symbol: 'BTC' },
to: { kind: 'fiat', code: 'USD' },
},
{
- label: 'ETH → USD',
+ label: 'ETH to USD',
from: { kind: 'crypto', id: 'ethereum', symbol: 'ETH' },
to: { kind: 'fiat', code: 'USD' },
},
{
- label: 'SOL → USD',
+ label: 'SOL to USD',
from: { kind: 'crypto', id: 'solana', symbol: 'SOL' },
to: { kind: 'fiat', code: 'USD' },
},
{
- label: 'USD → BTC',
+ label: 'USD to BTC',
from: { kind: 'fiat', code: 'USD' },
to: { kind: 'crypto', id: 'bitcoin', symbol: 'BTC' },
},
];
+// A preset reads as pressed only when it fully describes the current view:
+// both sides and the amount it would apply.
+function presetIsActive(p) {
+ const sideMatches = (ref, asset) => {
+ if (!asset) return false;
+ return ref.kind === 'fiat' ? asset.code === ref.code : asset.id === ref.id;
+ };
+ return (
+ state.amount === 1 && sideMatches(p.from, state.from) && sideMatches(p.to, state.to)
+ );
+}
+
function renderPresets() {
const el = $('cvt-presets');
- el.innerHTML = PRESETS.map(
- (p, i) =>
- `<button type="button" class="cvt-preset" data-preset="${i}">${esc(p.label)}</button>`,
- ).join('');
+ if (!el) return;
+ // Disabled until rates land, so a preset is never a button that does nothing.
+ const ready = Boolean(state.rates);
+ const html = PRESETS.map((p, i) => {
+ const on = ready && presetIsActive(p);
+ return `<button type="button" class="cvt-preset${on ? ' is-active' : ''}" data-preset="${i}" aria-pressed="${on}"${ready ? '' : ' disabled'}>${esc(p.label)}</button>`;
+ }).join('');
+ if (el.innerHTML === html) return;
+ el.innerHTML = html;
el.querySelectorAll('[data-preset]').forEach((btn) =>
btn.addEventListener('click', () => applyPreset(PRESETS[Number(btn.dataset.preset)])),
);
}
-async function applyPreset(p) {
+function applyPreset(p) {
if (!state.rates) return;
closePicker();
state.amount = 1;
+ state.amountText = '1';
const input = $('cvt-amount');
if (input) input.value = '1';
// Set both sides. Fiat resolves instantly; crypto resolves via detail fetch.
- if (p.from.kind === 'fiat') selectFiat('from', p.from.code);
- else selectCrypto('from', p.from.id, { symbol: p.from.symbol });
- if (p.to.kind === 'fiat') selectFiat('to', p.to.code);
- else selectCrypto('to', p.to.id, { symbol: p.to.symbol });
+ selectRef('from', p.from, { symbol: p.from.symbol });
+ selectRef('to', p.to, { symbol: p.to.symbol });
}
// ── Boot ──────────────────────────────────────────────────────────────────────
+// Turn the current query string into the two asset refs and the amount, falling
+// back to the default BTC to USD view for anything the URL doesn't name.
+function viewFromUrl() {
+ const q = parseConverterQuery(window.location.search);
+ const byCode = state.rates?.byCode;
+ return {
+ from: resolveAssetRef(q.from, byCode) || { kind: 'crypto', id: DEFAULT_CRYPTO },
+ to: resolveAssetRef(q.to, byCode) || { kind: 'fiat', code: DEFAULT_FIAT },
+ amount: Number.isFinite(q.amount) ? q.amount : 1,
+ };
+}
+
+async function applyView(view) {
+ state.amount = view.amount;
+ state.amountText = String(view.amount);
+ const input = $('cvt-amount');
+ if (input) input.value = state.amountText;
+ await Promise.all([selectRef('from', view.from), selectRef('to', view.to)].filter(Boolean));
+}
+
async function boot() {
state.loading = true;
state.error = null;
renderCard();
- // Rates + the default coin's price, in parallel — the page needs both to show
- // its default BTC → USD conversion.
- const [ratesRes, btcRes] = await Promise.allSettled([
- getJson('/api/coin/rates'),
- cryptoAsset(DEFAULT_CRYPTO, { symbol: 'BTC', name: 'Bitcoin' }),
- ]);
-
- if (ratesRes.status !== 'fulfilled') {
+ let rates;
+ try {
+ rates = await getJson('/api/coin/rates');
+ } catch {
state.loading = false;
state.error = 'rates';
renderCard();
return;
}
- const { fiats, updated_at } = ratesRes.value;
+ const fiats = Array.isArray(rates?.fiats) ? rates.fiats : [];
const byCode = new Map(fiats.map((f) => [f.code, f]));
const usd = byCode.get('USD');
- if (!usd) {
+ if (!usd || !Number.isFinite(usd.per_btc)) {
state.loading = false;
state.error = 'rates';
renderCard();
return;
}
- state.rates = { byCode, list: fiats, usdPerBtc: usd.per_btc, updated_at };
-
- // Default matchup: 1 BTC → USD. If the coin price failed, still show the
- // widget (the rate line degrades gracefully) so the page is never a dead end.
- state.from =
- btcRes.status === 'fulfilled'
- ? btcRes.value
- : {
- kind: 'crypto',
- id: DEFAULT_CRYPTO,
- symbol: 'BTC',
- name: 'Bitcoin',
- image: null,
- priceUSD: NaN,
- };
- state.to = fiatAsset('USD');
- state.amount = 1;
+ state.rates = { byCode, list: fiats, usdPerBtc: usd.per_btc, updated_at: rates.updated_at };
state.loading = false;
- renderCard();
+
+ // applyView mounts the card through refresh() with an optimistic placeholder
+ // on each side, so the widget is on screen before the coin price lands.
+ await applyView(viewFromUrl());
+ syncUrl();
}
-renderPresets();
+// Back/forward past the entry the page was opened on: re-apply that view.
+window.addEventListener('popstate', () => {
+ if (!state.rates) return;
+ applyView(viewFromUrl());
+});
+
boot();
diff --git a/src/create-prompt.js b/src/create-prompt.js
index 8a11226fd..3b11be475 100644
--- a/src/create-prompt.js
+++ b/src/create-prompt.js
@@ -45,9 +45,17 @@ let _submitting = false;
let _startedAt = 0;
let _elapsedTimer = 0;
let _aborter = /** @type {AbortController | null} */ (null);
-let _cancelled = false;
let _stallNoted = false;
+// Monotonic build token. Every start() claims the next one; cancelling or
+// returning to compose burns the current token. A run whose token is no longer
+// current is "stale" and must not touch the UI: without this, cancelling a
+// build and immediately starting another let the abandoned poll loop wake from
+// its sleep, keep polling the old job, and drop the OLD avatar onto the done
+// screen while the NEW build was still running.
+let _runId = 0;
+const isStale = (run) => run !== _runId;
+
function showStep(step) {
for (const el of document.querySelectorAll('.step')) {
el.classList.toggle('active', el.getAttribute('data-step') === step);
@@ -130,8 +138,8 @@ async function start() {
return;
}
+ const run = ++_runId;
_submitting = true;
- _cancelled = false;
_stallNoted = false;
_aborter = new AbortController();
generateBtn.disabled = true;
diff --git a/src/creations.css b/src/creations.css
index 1f577966e..ff318bc9b 100644
--- a/src/creations.css
+++ b/src/creations.css
@@ -8,6 +8,9 @@
.cr-shell { max-width: 1200px; margin: 0 auto; padding: var(--space-xl, 40px) var(--space-md, 16px) var(--space-2xl, 64px); }
+/* Labels that name a control for assistive tech without adding visible chrome. */
+.cr-sr-only { position: absolute; width: 1px; height: 1px; margin: -1px; padding: 0; overflow: hidden; clip: rect(0 0 0 0); clip-path: inset(50%); white-space: nowrap; border: 0; }
+
/* Hero */
.cr-hero { text-align: center; margin-bottom: var(--space-xl, 40px); }
.cr-kicker { display: inline-flex; align-items: center; gap: 8px; font-size: var(--text-2xs, .68rem); letter-spacing: .14em; text-transform: uppercase; color: var(--ink-dim, #888); margin: 0 0 var(--space-sm, 12px); }
diff --git a/src/creations.js b/src/creations.js
index 8013defbb..8813b1999 100644
--- a/src/creations.js
+++ b/src/creations.js
@@ -68,11 +68,14 @@ function truncate(s, n) {
// ── card rendering ───────────────────────────────────────────────────────────
-function thumbHTML(glbUrl, alt) {
+function thumbHTML(glbUrl, alt, posterUrl) {
if (!glbUrl) return `<div class="cr-card-noglb" aria-hidden="true">3D</div>`;
+ // The feed ships a rendered still alongside every GLB, so paint that first
+ // and let the interactive mesh swap in once it has streamed.
+ const poster = posterUrl ? ` poster="${esc(posterUrl)}"` : '';
return `<model-viewer
src="${esc(glbUrl)}"
- alt="${esc(alt)}"
+ alt="${esc(alt)}"${poster}
class="cr-card-mv"
reveal="auto"
loading="lazy"
@@ -100,21 +103,21 @@ function cardHTML(item) {
<article class="cr-card" data-id="${esc(item.id)}">
<div class="cr-card-thumb">
${item.isDerived ? '<span class="cr-card-derived" title="This is itself a remix">remix</span>' : ''}
- ${thumbHTML(item.glbUrl, promptText)}
+ ${thumbHTML(item.glbUrl, promptText, item.previewImageUrl)}
</div>
<div class="cr-card-body">
<p class="cr-card-prompt" title="${esc(item.prompt || '')}">${esc(promptText)}</p>
<div class="cr-card-meta">${categoryChip}${royaltyChip}${remixChip}</div>
<div class="cr-card-actions">
<a class="cr-card-btn" href="/m/${esc(item.id)}" title="Open the model page: stats, comments, likes">Details</a>
- <a class="cr-card-btn" href="${esc(item.viewerUrl)}" target="_blank" rel="noopener noreferrer">View</a>
- <button class="cr-card-btn" type="button" data-lineage="${esc(item.id)}">Lineage</button>
+ ${item.viewerUrl ? `<a class="cr-card-btn" href="${esc(item.viewerUrl)}" target="_blank" rel="noopener noreferrer">View</a>` : ''}
+ <button class="cr-card-btn" type="button" data-lineage="${esc(item.id)}" aria-controls="cr-lineage-panel">Lineage</button>
${item.prompt ? `<button class="cr-card-btn" type="button" data-copy-prompt="${esc(item.id)}" title="Copy the prompt that generated this model">Copy prompt</button>` : ''}
<button class="cr-card-btn cr-card-btn--remix" type="button" data-remix-open="${esc(item.id)}">Remix — $0.25</button>
<span class="cr-time">${esc(timeAgo(item.createdAt))}</span>
</div>
<div class="cr-remix-inline" data-remix-inline="${esc(item.id)}">
- <input type="text" class="cr-remix-input" placeholder='Describe the change, e.g. "make it metallic"' maxlength="500" />
+ <input type="text" class="cr-remix-input" aria-label="Describe the change this remix should make" placeholder='Describe the change, e.g. "make it metallic"' maxlength="500" />
<button class="cr-card-btn cr-card-btn--remix" type="button" data-remix-pay="${esc(item.id)}">Pay &amp; remix</button>
<div class="cr-remix-status" role="status" aria-live="polite"></div>
</div>
@@ -440,7 +443,7 @@ function trendingRowHTML(item, i) {
<li>
<a class="cr-lb-row" href="${esc(item.viewerUrl)}" target="_blank" rel="noopener noreferrer">
<span class="cr-lb-rank">${i + 1}</span>
- <span class="cr-lb-thumb">${thumbHTML(item.glbUrl, item.prompt || 'creation')}</span>
+ <span class="cr-lb-thumb">${thumbHTML(item.glbUrl, item.prompt || 'creation', item.previewImageUrl)}</span>
<span class="cr-lb-body">
<span class="cr-lb-title">${esc(truncate(item.prompt || 'A 3D creation', 48))}</span>
<span class="cr-lb-meta">${esc(item.category || 'other')}${item.remixable ? '' : ' · no longer remixable'}</span>
diff --git a/src/scene-compose.js b/src/scene-compose.js
index cbb3e02ef..17fb5fffe 100644
--- a/src/scene-compose.js
+++ b/src/scene-compose.js
@@ -42,6 +42,8 @@ const loadingMsg = $('lmsg');
const avatarPrompt = $('ap');
const canvasHint = $('ch');
const objectList = $('ol');
+const scenePanel = $('po');
+const sceneScrim = $('poscrim');
const inspectorEl = $('ins');
const saveStatus = $('ss');
const statTris = $('s-tri');
@@ -62,6 +64,7 @@ const btnShot = $('btn-screenshot');
const btnExport = $('btn-export');
const btnSaveOutfit = $('btn-save-outfit');
const btnHelp = $('btn-help');
+const btnPanel = $('btn-panel');
const helpPanel = $('hp');
const helpClose = $('hp-close');
@@ -72,12 +75,14 @@ const forgeFill = $('fprf');
const forgeMsg = $('fprm');
const forgeErr = $('fe');
const creationsList = $('gl');
+const creationsHead = $('glh');
const dropZone = $('dz');
const glbFileInput = $('gfi');
const intentChips = $('intent-chips');
const suggestPills = $('sps');
const avatarUrlInput = $('av-url');
+const avatarPromptErr = $('ape');
const btnLoadUrl = $('btn-load-url');
const btnBrowseAv = $('btn-browse-av');
const btnSkip = $('btn-skip');
@@ -257,10 +262,23 @@ const FORGE_TIMEOUT = 12 * 60 * 1000;
// ── Undo / Redo ───────────────────────────────────────────────────────────────
const hist = { stack: [], cursor: -1 };
+/**
+ * A command leaves the stack in one of two ways, and each frees a different
+ * side's GPU resources, without this the removed meshes stayed resident for
+ * the life of the tab, because nothing could safely dispose them while undo
+ * could still bring them back.
+ *
+ * abandon(), the command sat after the cursor (it had been undone) and a new
+ * command truncated the redo branch. Its *undone* state is now
+ * permanent, so whatever the redo would have re-added is garbage.
+ * forget(), the command fell off the 50-deep tail. Its *applied* state is
+ * now permanent, so whatever the undo would have restored is
+ * garbage.
+ */
function pushHistory(cmd) {
- hist.stack.splice(hist.cursor + 1);
+ for (const dropped of hist.stack.splice(hist.cursor + 1)) dropped.abandon?.();
hist.stack.push(cmd);
- if (hist.stack.length > 50) hist.stack.shift();
+ if (hist.stack.length > 50) hist.stack.shift().forget?.();
else hist.cursor++;
syncUndoUI();
}
@@ -406,6 +424,8 @@ function addToScene(group, name, glbUrl, role = 'item', pushUndo = true) {
pushHistory({
execute: () => { scene.add(group); sceneObjects.set(id, sceneObjects.get(id) || { group, name, glbUrl, visible: true, boneAttached: false, boneName: null, role }); renderHierarchy(); },
undo: () => { if (selectedId === id) deselect(); scene.remove(group); sceneObjects.delete(id); renderHierarchy(); },
+ // Abandoned after an undo: the object is out of the scene for good.
+ abandon: () => { if (!sceneObjects.has(id)) disposeObject(group); },
});
}
renderHierarchy();
@@ -416,18 +436,36 @@ function addToScene(group, name, glbUrl, role = 'item', pushUndo = true) {
function removeObject(id) {
const obj = sceneObjects.get(id);
if (!obj) return;
- if (obj.boneAttached && obj.boneName) {
- const be = avatarBones.find((b) => b.name === obj.boneName);
+ // Remember the bone so undo can put the item back ON the bone. Restoring it
+ // to the scene root instead left the row tagged with a bone it was no longer
+ // parented to, and the inspector offering "Detach" on a detached item.
+ const restoreBone = obj.boneAttached ? obj.boneName : null;
+ if (restoreBone) {
+ const be = avatarBones.find((b) => b.name === restoreBone);
if (be) scene.attach(obj.group);
}
if (selectedId === id) deselect();
scene.remove(obj.group);
const snapshot = { ...obj };
sceneObjects.delete(id);
- if (id === avatarId) { avatarId = null; avatarBones = []; if (mixer) { mixer.stopAllAction(); mixer = null; } }
+ if (id === avatarId) {
+ // Anything parented to this avatar's bones would vanish with it, so hand
+ // those items back to the scene root before the skeleton goes away.
+ sceneObjects.forEach((o, oid) => { if (o.boneAttached) detachFromBone(oid, false); });
+ avatarId = null; avatarBones = [];
+ if (mixer) { mixer.stopAllAction(); mixer = null; }
+ }
+ const reattach = () => {
+ const be = restoreBone ? avatarBones.find((b) => b.name === restoreBone) : null;
+ if (be) { scene.remove(snapshot.group); be.bone.add(snapshot.group); }
+ else if (restoreBone) { snapshot.boneAttached = false; snapshot.boneName = null; }
+ };
pushHistory({
execute: () => { scene.remove(snapshot.group); sceneObjects.delete(id); renderHierarchy(); },
- undo: () => { scene.add(snapshot.group); sceneObjects.set(id, snapshot); renderHierarchy(); },
+ undo: () => { scene.add(snapshot.group); reattach(); sceneObjects.set(id, snapshot); renderHierarchy(); },
+ // Fell off the tail: the removal can no longer be undone, so free the GPU
+ // buffers this object still holds.
+ forget: () => { if (!sceneObjects.has(id)) disposeObject(snapshot.group); },
});
renderHierarchy();
}
@@ -483,8 +521,10 @@ canvasEl.addEventListener('pointerdown', (e) => {
function setMode(mode) {
xformMode = mode;
transform.setMode(mode);
- [btnTrans, btnRot, btnScale].forEach((b) => b.classList.remove('active'));
- ({ translate: btnTrans, rotate: btnRot, scale: btnScale })[mode]?.classList.add('active');
+ const byMode = { translate: btnTrans, rotate: btnRot, scale: btnScale };
+ [btnTrans, btnRot, btnScale].forEach((b) => { b.classList.remove('active'); b.setAttribute('aria-pressed', 'false'); });
+ byMode[mode]?.classList.add('active');
+ byMode[mode]?.setAttribute('aria-pressed', 'true');
}
btnTrans.addEventListener('click', () => setMode('translate'));
@@ -502,6 +542,7 @@ btnSpace.addEventListener('click', toggleSpace);
function toggleSnap() {
snapEnabled = !snapEnabled;
btnSnap.classList.toggle('active', snapEnabled);
+ btnSnap.setAttribute('aria-pressed', String(snapEnabled));
toast(`Snap ${snapEnabled ? 'on (0.25 units)' : 'off'}`);
}
btnSnap.addEventListener('click', toggleSnap);
@@ -526,21 +567,34 @@ const CAM_PRESETS = {
iso: { pos: [3.5, 3.5, 3.5], target: [0, 0.8, 0] },
};
+function openCamMenu() {
+ camMenu.hidden = false;
+ btnCam.setAttribute('aria-expanded', 'true');
+ camMenu.querySelector('.cmi')?.focus();
+}
+
+function closeCamMenu(restoreFocus = true) {
+ if (camMenu.hidden) return;
+ camMenu.hidden = true;
+ btnCam.setAttribute('aria-expanded', 'false');
+ if (restoreFocus) btnCam.focus();
+}
+
function applyCameraPreset(name) {
const p = CAM_PRESETS[name];
if (!p) return;
camera.position.set(...p.pos);
orbit.target.set(...p.target);
orbit.update();
- camMenu.hidden = true;
+ closeCamMenu(false);
}
-btnCam.addEventListener('click', (e) => { e.stopPropagation(); camMenu.hidden = !camMenu.hidden; });
+btnCam.addEventListener('click', (e) => { e.stopPropagation(); if (camMenu.hidden) openCamMenu(); else closeCamMenu(false); });
camMenu.querySelectorAll('.cmi').forEach((item) => {
item.addEventListener('click', () => applyCameraPreset(item.dataset.cam));
});
document.addEventListener('click', (e) => {
- if (!btnCam.contains(e.target) && !camMenu.contains(e.target)) camMenu.hidden = true;
+ if (!btnCam.contains(e.target) && !camMenu.contains(e.target)) closeCamMenu(false);
});
// ── Frame camera on selected (F key) ─────────────────────────────────────────
@@ -589,6 +643,16 @@ document.addEventListener('keydown', (e) => {
if (ctrl && e.key === 'g') { e.preventDefault(); toggleSnap(); return; }
if (ctrl && e.key === 'p') { e.preventDefault(); takeScreenshot(); return; }
if (ctrl && e.key === 'd') { e.preventDefault(); duplicateSelected(); return; }
+ // Escape has to work from inside a text field too, or the avatar picker and
+ // the shortcuts panel become untrappable once focus lands in one of them.
+ if (e.key === 'Escape') {
+ if (!camMenu.hidden) { closeCamMenu(); return; }
+ if (!avatarModal.hidden) { closeAvatarModal(); return; }
+ if (!helpPanel.hidden) { closeDialog(helpPanel); return; }
+ if (scenePanel.classList.contains('open')) { setScenePanel(false); return; }
+ if (!inp) deselect();
+ return;
+ }
if (inp) return;
@@ -597,19 +661,63 @@ document.addEventListener('keydown', (e) => {
if (e.key === 'r' || e.key === 'R') setMode('scale');
if (e.key === 'f' || e.key === 'F') frameObject(selectedId);
if (e.key === 'x' || e.key === 'X') toggleSpace();
- if (e.key === 'Escape') { deselect(); camMenu.hidden = true; helpPanel.hidden = true; avatarModal.hidden = true; }
if (e.key === 'Delete' || e.key === 'Backspace') { if (selectedId !== null) removeObject(selectedId); }
- if (e.key === '?') { helpPanel.hidden = !helpPanel.hidden; }
+ if (e.key === '?') { if (helpPanel.hidden) openDialog(helpPanel, helpClose); else closeDialog(helpPanel); }
// Numpad camera presets (Blender-style)
if (e.code === 'Numpad1' && !e.ctrlKey) applyCameraPreset('front');
if (e.code === 'Numpad3' && !e.ctrlKey) applyCameraPreset('left');
if (e.code === 'Numpad7' && !e.ctrlKey) applyCameraPreset('top');
});
+// ── Dialogs (help + avatar picker) ────────────────────────────────────────────
+// Focus moves into the dialog on open and returns to the trigger on close, and
+// Tab is trapped inside it, without that a keyboard user tabs behind the
+// backdrop into a viewport they cannot see.
+const FOCUSABLE = 'a[href],button:not([disabled]),input,select,textarea,[tabindex]:not([tabindex="-1"])';
+let dialogReturnFocus = null;
+
+function openDialog(el, initial) {
+ dialogReturnFocus = document.activeElement;
+ el.hidden = false;
+ (initial || el.querySelector(FOCUSABLE))?.focus();
+}
+
+function closeDialog(el) {
+ if (el.hidden) return;
+ el.hidden = true;
+ if (dialogReturnFocus?.isConnected) dialogReturnFocus.focus();
+ dialogReturnFocus = null;
+}
+
+function openDialogs() {
+ return [helpPanel, avatarModal].filter((d) => !d.hidden);
+}
+
+document.addEventListener('keydown', (e) => {
+ if (e.key !== 'Tab') return;
+ const dlg = openDialogs()[0];
+ if (!dlg) return;
+ const items = [...dlg.querySelectorAll(FOCUSABLE)].filter((el) => el.offsetParent !== null);
+ if (!items.length) return;
+ const first = items[0], last = items[items.length - 1];
+ if (e.shiftKey && document.activeElement === first) { e.preventDefault(); last.focus(); }
+ else if (!e.shiftKey && document.activeElement === last) { e.preventDefault(); first.focus(); }
+}, true);
+
// ── Help panel ────────────────────────────────────────────────────────────────
-btnHelp.addEventListener('click', () => { helpPanel.hidden = !helpPanel.hidden; });
-helpClose.addEventListener('click', () => { helpPanel.hidden = true; });
-helpPanel.addEventListener('click', (e) => { if (e.target === helpPanel) helpPanel.hidden = true; });
+btnHelp.addEventListener('click', () => { if (helpPanel.hidden) openDialog(helpPanel, helpClose); else closeDialog(helpPanel); });
+helpClose.addEventListener('click', () => closeDialog(helpPanel));
+helpPanel.addEventListener('click', (e) => { if (e.target === helpPanel) closeDialog(helpPanel); });
+
+// ── Scene panel drawer (narrow viewports) ─────────────────────────────────────
+function setScenePanel(open) {
+ scenePanel.classList.toggle('open', open);
+ sceneScrim.classList.toggle('open', open);
+ btnPanel.setAttribute('aria-expanded', String(open));
+ btnPanel.classList.toggle('active', open);
+}
+btnPanel.addEventListener('click', () => setScenePanel(!scenePanel.classList.contains('open')));
+sceneScrim.addEventListener('click', () => setScenePanel(false));
// ── Hierarchy rendering ───────────────────────────────────────────────────────
function roleIcon(role) {
@@ -637,49 +745,61 @@ function renderHierarchy() {
row.className = 'or' + (id === selectedId ? ' sel' : '');
row.dataset.id = id;
+ const pick = document.createElement('button');
+ pick.type = 'button';
+ pick.className = 'ob';
+ pick.setAttribute('aria-pressed', String(id === selectedId));
+
const icon = document.createElement('span');
icon.className = 'oi';
+ icon.setAttribute('aria-hidden', 'true');
icon.textContent = roleIcon(obj.role);
- row.appendChild(icon);
+ pick.appendChild(icon);
const name = document.createElement('span');
name.className = 'on';
name.textContent = obj.name;
- row.appendChild(name);
+ pick.appendChild(name);
if (obj.boneAttached) {
const tag = document.createElement('span');
tag.className = 'ot b';
tag.textContent = cleanBoneName(obj.boneName).split(' ').pop();
- row.appendChild(tag);
+ pick.appendChild(tag);
} else if (obj.role !== 'item' && obj.role !== 'other') {
const tag = document.createElement('span');
tag.className = 'ot';
tag.textContent = obj.role;
- row.appendChild(tag);
+ pick.appendChild(tag);
}
+ pick.addEventListener('click', () => select(id));
+ // Double-click to rename
+ pick.addEventListener('dblclick', (ev) => { ev.preventDefault(); startRename(id, name); });
+ row.appendChild(pick);
+
const actions = document.createElement('div');
actions.className = 'oa';
const visBtn = document.createElement('button');
+ visBtn.type = 'button';
visBtn.className = 'oab';
visBtn.title = obj.visible ? 'Hide' : 'Show';
+ visBtn.setAttribute('aria-label', `${obj.visible ? 'Hide' : 'Show'} ${obj.name}`);
visBtn.textContent = obj.visible ? '●' : '○';
visBtn.addEventListener('click', (ev) => { ev.stopPropagation(); toggleVis(id); });
actions.appendChild(visBtn);
const delBtn = document.createElement('button');
+ delBtn.type = 'button';
delBtn.className = 'oab d';
delBtn.title = 'Remove';
+ delBtn.setAttribute('aria-label', `Remove ${obj.name}`);
delBtn.textContent = '×';
delBtn.addEventListener('click', (ev) => { ev.stopPropagation(); removeObject(id); });
actions.appendChild(delBtn);
row.appendChild(actions);
- row.addEventListener('click', () => select(id));
- // Double-click to rename
- row.addEventListener('dblclick', (ev) => { ev.preventDefault(); startRename(id, row, name); });
objectList.appendChild(row);
}
@@ -691,23 +811,22 @@ function renderHierarchy() {
}
}
-function startRename(id, row, nameEl) {
+function startRename(id, nameEl) {
const obj = sceneObjects.get(id);
if (!obj) return;
const input = document.createElement('input');
input.className = 'oni';
input.value = obj.name;
+ input.setAttribute('aria-label', 'Object name');
nameEl.replaceWith(input);
input.focus();
input.select();
+ let done = false;
const commit = () => {
- const newName = input.value.trim() || obj.name;
- obj.name = newName;
- const span = document.createElement('span');
- span.className = 'on';
- span.textContent = newName;
- input.replaceWith(span);
- span.addEventListener('dblclick', (ev) => { ev.preventDefault(); startRename(id, row, span); });
+ if (done) return;
+ done = true;
+ obj.name = input.value.trim() || obj.name;
+ renderHierarchy();
};
input.addEventListener('blur', commit);
input.addEventListener('keydown', (e) => {