/* Card Grader — UI */
const state = { settings: {}, modelGuide: {}, history: [] };
const $ = (sel) => document.querySelector(sel);
function esc(text) {
return String(text === null || text === undefined ? '' : text)
.replace(/&/g, '&').replace(//g, '>')
.replace(/"/g, '"');
}
/* ------------------------------------------------------------------ api */
// The path this app is mounted under (e.g. "/cards"), or "" at the domain
// root — set server-side via a data attribute since a script has no other
// reliable way to know where it was served from.
const APP_BASE = document.documentElement.dataset.base || '';
async function api(path, options = {}) {
const response = await fetch(APP_BASE + path, {
headers: { 'Content-Type': 'application/json' },
...options,
body: options.body ? JSON.stringify(options.body) : undefined,
});
const text = await response.text();
let data = null;
try { data = text ? JSON.parse(text) : null; } catch (_) { data = null; }
if (!response.ok) {
throw new Error((data && data.error) || `Request failed (${response.status})`);
}
return data;
}
function banner(message, isError = false) {
const node = $('#banner');
if (!message) { node.hidden = true; return; }
node.className = isError ? 'banner err' : 'banner';
node.textContent = message;
node.hidden = false;
if (!isError) setTimeout(() => { node.hidden = true; }, 3200);
}
/* ------------------------------------------------------------- file read */
//
// Read straight to a data URL at pick time, and only clear the input once
// the bytes are safely in hand. Holding File objects and reading them later
// looks equivalent and isn't: clearing input.value (which is what lets you
// re-pick the same file) can detach the underlying blob in some browsers, so
// a read attempted afterward fails with no useful reason. Reading now
// sidesteps that, and the data URL doubles as the preview source.
function bytesToBase64(bytes) {
// Chunked: fromCharCode.apply on a multi-megabyte array blows the stack.
let binary = '';
const chunk = 0x8000;
for (let i = 0; i < bytes.length; i += chunk) {
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunk));
}
return btoa(binary);
}
async function readOneImage(file) {
// Two independent read paths, because they fail independently. FileReader
// is the older API and is the one that trips over files a phone exposes
// through a cloud provider or a scoped-storage URI; file.arrayBuffer() is
// the modern path and frequently succeeds where it doesn't. Trying both
// turns a hard failure into a retry, and if both fail the real
// DOMException name gets reported rather than a guess at the cause.
const errors = [];
try {
const buffer = await file.arrayBuffer();
if (buffer && buffer.byteLength) {
const type = file.type || 'image/jpeg';
return `data:${type};base64,${bytesToBase64(new Uint8Array(buffer))}`;
}
errors.push('arrayBuffer returned nothing');
} catch (err) {
errors.push(`arrayBuffer: ${err && err.name ? err.name : err}`);
}
try {
return await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(String(reader.result));
reader.onerror = () => reject(reader.error || new Error('unknown'));
reader.readAsDataURL(file);
});
} catch (err) {
errors.push(`FileReader: ${err && err.name ? err.name : err}`);
}
const detail = errors.join('; ');
const hint = /NotReadable|NotFound/i.test(detail)
? ' The file may be stored in the cloud rather than on the device — open it once in your photo app so it downloads, then try again.'
: ' Try saving a copy of it first, then pick the copy.';
throw new Error(`Could not read "${file.name || 'that file'}" (${detail}).${hint}`);
}
async function readPickedImages(input, limit) {
const picked = Array.from(input.files || []).slice(0, Math.max(0, limit));
const out = [];
for (const file of picked) {
out.push({ name: file.name || 'upload', dataUrl: await readOneImage(file) });
}
input.value = '';
return out;
}
function pickedToPayload(items) {
return items.map((i) => ({ filename: i.name, image_base64: i.dataUrl.split(',')[1] }));
}
/* --------------------------------------------------------------- grading */
const SEVERITY_PILL = {
none: 'pill-grade', minor: 'pill-marginal', moderate: 'pill-marginal',
major: 'pill-critical', cannot_assess: 'pill-raw',
};
const SEVERITY_LABEL = {
none: 'clean', minor: 'minor', moderate: 'moderate', major: 'major',
cannot_assess: "can't tell from photo",
};
const gradeState = { files: [], result: null, busy: false };
function renderGradeBlock(g, opts = {}) {
if (!g) return '';
const m = g.edge_measurements || null;
let measuredLine = '';
if (m && m.reliable === false) {
measuredLine = `not measurable — ${m.reason || "this card's finish"}`;
} else if (m && m.edges) {
measuredLine = ['top', 'right', 'bottom', 'left']
.filter((s) => m.edges[s])
.map((s) => `${s} ${m.edges[s].percent.toFixed(0)}%`).join(' · ');
}
const cm = g.centering_measurement || null;
const centeringLine = cm
? `measured — left/right ${cm.horizontal_label} · top/bottom ${cm.vertical_label}` : '';
// Only worth surfacing when it's away from noise — most cards sit within
// a percent or two of standard and repeating that number on every card
// would just be clutter, not information. Shown against its best-matching
// standard; which standard is actually relevant is a judgment call the
// model made with the photo in hand, not something this line re-derives.
const am = g.aspect_measurement || null;
const bestDev = am && am.against_standards && am.best_match
? am.against_standards[am.best_match].deviation_percent : null;
const aspectLine = (bestDev !== null && bestDev >= 3)
? `ratio ${bestDev}% off standard (${am.best_match}) — ` +
`verify this isn't just a rotated photo before reading it as trimming` : '';
const rows = ['centering', 'corners', 'edges', 'surface'].map((key) => {
const cat = (g.categories || {})[key] || {};
const sev = cat.severity || 'cannot_assess';
let extra = '';
if (key === 'edges' && measuredLine) {
extra = `
measured whitening — ${esc(measuredLine)}
`;
} else if (key === 'centering' && centeringLine) {
extra = `
${esc(centeringLine)}
`;
} else if (key === 'corners' && aspectLine) {
extra = `
${esc(aspectLine)}
`;
}
return `
${key}
${esc(SEVERITY_LABEL[sev])}
${esc(cat.observation || '')}${extra}
`;
}).join('');
return `
A photo can't show surface scratches, print lines, or light edge wear the
way a grader's raking light does — and a seller's listing photo is often lit to hide them.
Treat this as a rough screen, not a prediction of what it comes back as.
Stored only in this browser and sent with your own grading
requests — never saved on the server. Get one at console.anthropic.com.
${s.server_key_configured
? 'This server already has a key set up, so you can leave this blank and use that instead — but then the owner pays for your grades.'
: 'This server has no key of its own, so you need one here to grade anything.'}
Server settings${locked ? ' locked' : ''}
${locked ? `
This server is shared, so its settings are read-only.
Use your own key above.
` : `
Never sent back to the browser once saved. Leave blank to keep
the current one.
Sonnet 5 is the default for a tested reason — run head-to-head
against Haiku on the same cards, Haiku misread a PSA centering tolerance and landed
three grades off. Drop to Haiku only if cost matters more than accuracy to you.
`}
`;
$('#settings-modal').hidden = false;
$('#modal-scrim').hidden = false;
}
/* A personal key lives in localStorage, never on the server — that's what
lets someone use a shared instance without spending the owner's credits. */
function myApiKey() {
try { return localStorage.getItem('cardgrader_api_key') || ''; } catch (_) { return ''; }
}
function setMyApiKey(value) {
try {
if (value) localStorage.setItem('cardgrader_api_key', value);
else localStorage.removeItem('cardgrader_api_key');
} catch (_) { /* private browsing — the field just won't persist */ }
}
function closeSettings() {
$('#settings-modal').hidden = true;
$('#modal-scrim').hidden = true;
}
async function saveSettings() {
setMyApiKey($('#set-my-key').value.trim());
// Only push server settings when this instance allows it, and only send a
// key when one was actually typed — an empty box means "leave it alone",
// not "erase it".
const serverKeyField = $('#set-api-key');
if (serverKeyField) {
const payload = { vision_model: $('#set-model').value };
const typed = serverKeyField.value.trim();
if (typed) payload.anthropic_api_key = typed;
state.settings = await api('/api/settings', { method: 'POST', body: payload });
}
closeSettings();
updateModelCostHint();
banner('Settings saved.');
}
function updateModelCostHint() {
const info = state.modelGuide[state.settings.vision_model];
$('#model-cost-hint').textContent = info ? `~$${info.per_grade.toFixed(3)} per grade (${info.label})` : '';
}
$('#btn-settings').addEventListener('click', () => openSettings().catch((err) => banner(err.message, true)));
$('#settings-modal').addEventListener('click', (e) => {
if (e.target.closest('#settings-close')) return closeSettings();
if (e.target.closest('#settings-save')) saveSettings().catch((err) => banner(err.message, true));
});
$('#modal-scrim').addEventListener('click', closeSettings);
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') { closeSettings(); closeEntryModal(); }
});
/* ---------------------------------------------------------------- load */
async function load() {
state.settings = await api('/api/settings');
try { state.modelGuide = await api('/api/vision-models'); } catch (_) { state.modelGuide = {}; }
updateModelCostHint();
await loadHistory();
if (!state.settings.server_key_configured && !myApiKey()) {
banner('Add your Anthropic API key in Settings before grading a card.');
}
}
load().catch((err) => banner(`Could not load: ${err.message}`, true));
/* ------------------------------------------------------------------ pwa */
//
// Service workers only run in a secure context: https, or localhost. Over a
// plain LAN address (http://192.168.x.x) registration silently fails and the
// app stays a normal web page — which is exactly why the README pushes you
// through a tunnel rather than just handing friends your LAN IP.
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker.register(APP_BASE + '/sw.js').catch(() => {
/* Not fatal — the app works fine uninstalled. */
});
});
}
// Android/Chrome fires this instead of showing its own prompt, so the offer
// has to be surfaced deliberately. iOS never fires it: Safari has no
// programmatic install, only the manual Share > Add to Home Screen, so the
// hint below covers that case instead of pretending a button exists.
let deferredInstall = null;
window.addEventListener('beforeinstallprompt', (e) => {
e.preventDefault();
deferredInstall = e;
const btn = $('#btn-install');
if (btn) btn.hidden = false;
});
document.addEventListener('click', async (e) => {
if (!e.target.closest('#btn-install')) return;
if (!deferredInstall) {
banner("No install prompt available — try Chrome's own menu (⋮ → Install app) instead.", true);
return;
}
try {
await deferredInstall.prompt();
const choice = await deferredInstall.userChoice;
if (choice.outcome !== 'accepted') banner(`Install ${choice.outcome}.`);
} catch (err) {
banner(`Install failed: ${err.message}`, true);
} finally {
deferredInstall = null;
$('#btn-install').hidden = true;
}
});