Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="utf-8">
- <title>Observation Practice</title>
- <style>
- :root { color-scheme: light; }
- body { font-family: system-ui, -apple-system, "Segoe UI", sans-serif; margin: 0; padding: 16px; background: #f4f4f5; color: #18181b; }
- h1 { margin: 0 0 12px 0; font-size: 20px; }
- .tabs { display: flex; gap: 4px; margin-bottom: 16px; border-bottom: 1px solid #e4e4e7; }
- .tab { padding: 8px 16px; font-size: 14px; background: none; border: none; border-bottom: 2px solid transparent; cursor: pointer; color: #71717a; font-family: inherit; margin-bottom: -1px; }
- .tab:hover { color: #18181b; }
- .tab.active { color: #18181b; border-bottom-color: #3b82f6; font-weight: 500; }
- .controls { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
- .controls label { font-size: 14px; display: inline-flex; align-items: center; gap: 4px; }
- select, input, button { padding: 6px 10px; font-size: 14px; border-radius: 6px; border: 1px solid #d4d4d8; background: white; font-family: inherit; }
- input[type=number] { width: 60px; }
- button { cursor: pointer; }
- button:hover:not(:disabled) { background: #f4f4f5; }
- button:disabled { opacity: 0.5; cursor: not-allowed; }
- button.primary { background: #3b82f6; color: white; border-color: #3b82f6; }
- button.primary:hover:not(:disabled) { background: #2563eb; }
- button.danger { color: #b91c1c; border-color: #fecaca; }
- button.danger:hover:not(:disabled) { background: #fef2f2; }
- .canvases { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; }
- .panel { background: white; border-radius: 8px; padding: 12px; }
- .panel h3 { margin: 0 0 8px 0; font-size: 12px; color: #71717a; text-transform: uppercase; letter-spacing: 0.5px; font-weight: 600; }
- canvas { display: block; border: 1px solid #e4e4e7; border-radius: 4px; background: white; touch-action: none; max-width: 100%; }
- canvas.editable { cursor: crosshair; }
- .tool-row { margin-top: 8px; display: flex; gap: 6px; flex-wrap: wrap; }
- .tool-row button.active { background: #18181b; color: white; border-color: #18181b; }
- .hint { font-size: 12px; color: #71717a; margin-top: 6px; min-height: 16px; }
- .score { margin-top: 16px; background: white; border-radius: 8px; padding: 16px; }
- .score-overall { font-size: 28px; font-weight: 600; }
- .score-overall .label { font-size: 14px; color: #71717a; font-weight: 400; margin-right: 8px; }
- .score-detail { margin-top: 12px; font-size: 13px; }
- .score-detail table { border-collapse: collapse; width: 100%; }
- .score-detail th, .score-detail td { text-align: left; padding: 6px 10px; border-bottom: 1px solid #f4f4f5; }
- .score-detail th { color: #71717a; font-weight: 500; font-size: 12px; text-transform: uppercase; letter-spacing: 0.3px; }
- .score-detail .sub td { padding-left: 28px; font-size: 12px; color: #71717a; }
- .pct { font-variant-numeric: tabular-nums; }
- .good { color: #15803d; }
- .ok { color: #a16207; }
- .bad { color: #b91c1c; }
- .records-toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; }
- .records-toolbar .spacer { flex: 1; }
- .records-toolbar .count { font-size: 13px; color: #71717a; }
- .records-list { background: white; border-radius: 8px; overflow: hidden; }
- .records-list table { border-collapse: collapse; width: 100%; font-size: 14px; }
- .records-list th, .records-list td { padding: 10px 12px; text-align: left; border-bottom: 1px solid #f4f4f5; }
- .records-list th { color: #71717a; font-weight: 500; font-size: 12px; text-transform: uppercase; letter-spacing: 0.3px; background: #fafafa; }
- .records-list tbody tr { cursor: pointer; }
- .records-list tbody tr:hover { background: #f4f4f5; }
- .records-list .actions { text-align: right; }
- .records-list .actions button { padding: 4px 10px; font-size: 12px; }
- .records-empty { padding: 40px; text-align: center; color: #71717a; background: white; border-radius: 8px; }
- .record-detail-toolbar { display: flex; gap: 8px; align-items: center; margin-bottom: 12px; flex-wrap: wrap; background: white; border-radius: 8px; padding: 10px 14px; }
- .record-detail-toolbar .meta { flex: 1; font-size: 14px; }
- .record-detail-toolbar .meta b { font-weight: 600; }
- .record-detail-toolbar .nav-info { font-size: 12px; color: #71717a; }
- .kbd { display: inline-block; padding: 1px 5px; font-size: 11px; font-family: ui-monospace, monospace; background: #f4f4f5; border: 1px solid #e4e4e7; border-radius: 3px; color: #52525b; }
- [hidden] { display: none !important; }
- </style>
- </head>
- <body>
- <h1>Observation Practice</h1>
- <div class="tabs">
- <button class="tab active" data-tab="practice">Practice</button>
- <button class="tab" data-tab="records">Records <span id="tab-records-count" class="count"></span></button>
- </div>
- <!-- Practice view -->
- <div id="view-practice">
- <div class="controls">
- <label>Mode:
- <select id="mode">
- <option value="dots">Dots</option>
- <option value="lines">Lines</option>
- <option value="polygon">Polygon</option>
- <option value="mixed">Mixed</option>
- </select>
- </label>
- <label>Count: <input id="count" type="number" min="1" max="12" value="3"></label>
- <button class="primary" id="generate">New Puzzle</button>
- <button id="check">Check Accuracy</button>
- <button id="clear">Clear Drawing</button>
- <button id="reveal" disabled>Toggle Overlay</button>
- </div>
- <div class="canvases">
- <div class="panel">
- <h3>Reference</h3>
- <canvas id="ref" width="500" height="500"></canvas>
- </div>
- <div class="panel">
- <h3>Your Drawing</h3>
- <canvas id="user" class="editable" width="500" height="500"></canvas>
- <div class="tool-row" id="tool-row">
- <button data-tool="dot" class="active">Dot</button>
- <button data-tool="line">Line</button>
- <button data-tool="polygon">Polygon</button>
- <button data-action="finishPoly">Finish Polygon</button>
- <button data-action="undo">Undo</button>
- </div>
- <div class="hint" id="hint">Click to place a dot.</div>
- </div>
- </div>
- <div class="score" id="score" hidden>
- <div class="score-overall"><span class="label">Overall</span><span id="overall"></span></div>
- <div class="score-detail" id="detail"></div>
- </div>
- </div>
- <!-- Records view -->
- <div id="view-records" hidden>
- <!-- list mode -->
- <div id="records-list-mode">
- <div class="records-toolbar">
- <button id="export-records">Export</button>
- <button id="import-records">Import</button>
- <input type="file" id="import-file" accept="application/json,.json" hidden>
- <button class="danger" id="clear-all-records">Clear All</button>
- <span class="spacer"></span>
- <span class="count" id="records-count"></span>
- </div>
- <div id="records-list-container"></div>
- </div>
- <!-- detail mode -->
- <div id="records-detail-mode" hidden>
- <div class="record-detail-toolbar">
- <button id="record-back">← Back</button>
- <button id="record-prev">‹ Prev</button>
- <button id="record-next">Next ›</button>
- <div class="meta" id="record-meta"></div>
- <span class="nav-info">Use <span class="kbd">←</span> <span class="kbd">→</span></span>
- <button class="danger" id="record-delete">Delete</button>
- </div>
- <div class="canvases">
- <div class="panel">
- <h3>Reference</h3>
- <canvas id="record-ref" width="500" height="500"></canvas>
- </div>
- <div class="panel">
- <h3>Your Drawing</h3>
- <canvas id="record-user" width="500" height="500"></canvas>
- </div>
- </div>
- <div class="score">
- <div class="score-overall"><span class="label">Overall</span><span id="record-overall"></span></div>
- <div class="score-detail" id="record-detail"></div>
- </div>
- </div>
- </div>
- <script>
- (() => {
- const W = 500, H = 500, PAD = 40;
- const STORAGE_KEY = 'copy-practice-records-v1';
- // ---------- geometry helpers ----------
- const rand = (a, b) => Math.random() * (b - a) + a;
- const randPoint = () => ({ x: rand(PAD, W - PAD), y: rand(PAD, H - PAD) });
- const dist = (a, b) => Math.hypot(a.x - b.x, a.y - b.y);
- const lineLen = l => Math.hypot(l.x2 - l.x1, l.y2 - l.y1);
- const lineAngleDeg = l => Math.atan2(l.y2 - l.y1, l.x2 - l.x1) * 180 / Math.PI;
- function angleDiffUndirected(a, b) {
- let d = ((a - b) % 180 + 180) % 180;
- if (d > 90) d = 180 - d;
- return d;
- }
- const pctFromDist = (d, tol = 100) => Math.max(0, 100 * (1 - d / tol));
- const pctFromAngle = (deg, tol = 45) => Math.max(0, 100 * (1 - Math.abs(deg) / tol));
- const pctFromLen = (refL, userL) => Math.max(0, 100 * (1 - Math.abs(refL - userL) / Math.max(refL, 1)));
- function bestEndpointMatch(ref, user) {
- const a = (dist({ x: ref.x1, y: ref.y1 }, { x: user.x1, y: user.y1 }) +
- dist({ x: ref.x2, y: ref.y2 }, { x: user.x2, y: user.y2 })) / 2;
- const b = (dist({ x: ref.x1, y: ref.y1 }, { x: user.x2, y: user.y2 }) +
- dist({ x: ref.x2, y: ref.y2 }, { x: user.x1, y: user.y1 })) / 2;
- return Math.min(a, b);
- }
- // ---------- generation ----------
- function genDot() { return { type: 'dot', ...randPoint() }; }
- function genLine() {
- let p1 = randPoint(), p2 = randPoint();
- while (dist(p1, p2) < 80) p2 = randPoint();
- return { type: 'line', x1: p1.x, y1: p1.y, x2: p2.x, y2: p2.y };
- }
- function genPolygon(n, cx, cy, baseR) {
- n = Math.max(3, n);
- cx = cx ?? W / 2 + rand(-40, 40);
- cy = cy ?? H / 2 + rand(-40, 40);
- baseR = baseR ?? rand(110, 180);
- const angles = [];
- for (let i = 0; i < n; i++) angles.push(rand(0, 2 * Math.PI));
- angles.sort((a, b) => a - b);
- for (let i = 1; i < n; i++) {
- if (angles[i] - angles[i - 1] < 0.3) angles[i] = angles[i - 1] + 0.3;
- }
- const points = angles.map(a => ({
- x: cx + baseR * rand(0.7, 1.1) * Math.cos(a),
- y: cy + baseR * rand(0.7, 1.1) * Math.sin(a),
- }));
- return { type: 'polygon', points };
- }
- function generateShapes(mode, count) {
- const out = [];
- if (mode === 'dots') {
- for (let i = 0; i < count; i++) out.push(genDot());
- } else if (mode === 'lines') {
- for (let i = 0; i < count; i++) out.push(genLine());
- } else if (mode === 'polygon') {
- out.push(genPolygon(count));
- } else {
- const types = ['dot', 'line', 'polygon'];
- for (let i = 0; i < count; i++) {
- const t = types[Math.floor(Math.random() * types.length)];
- if (t === 'dot') out.push(genDot());
- else if (t === 'line') out.push(genLine());
- else {
- const cx = rand(PAD + 70, W - PAD - 70);
- const cy = rand(PAD + 70, H - PAD - 70);
- out.push(genPolygon(3 + Math.floor(Math.random() * 3), cx, cy, rand(50, 100)));
- }
- }
- }
- return out;
- }
- // ---------- drawing ----------
- function drawShapes(ctx, shapes, opts = {}) {
- ctx.save();
- ctx.lineWidth = opts.lineWidth ?? 2;
- ctx.strokeStyle = opts.color ?? '#18181b';
- ctx.fillStyle = opts.color ?? '#18181b';
- for (const s of shapes) {
- if (s.type === 'dot') {
- ctx.beginPath();
- ctx.arc(s.x, s.y, 5, 0, Math.PI * 2);
- ctx.fill();
- } else if (s.type === 'line') {
- ctx.beginPath();
- ctx.moveTo(s.x1, s.y1); ctx.lineTo(s.x2, s.y2);
- ctx.stroke();
- ctx.beginPath(); ctx.arc(s.x1, s.y1, 3, 0, Math.PI * 2); ctx.fill();
- ctx.beginPath(); ctx.arc(s.x2, s.y2, 3, 0, Math.PI * 2); ctx.fill();
- } else if (s.type === 'polygon') {
- if (!s.points || s.points.length < 2) continue;
- ctx.beginPath();
- ctx.moveTo(s.points[0].x, s.points[0].y);
- for (let i = 1; i < s.points.length; i++) ctx.lineTo(s.points[i].x, s.points[i].y);
- ctx.closePath();
- ctx.stroke();
- for (const p of s.points) {
- ctx.beginPath(); ctx.arc(p.x, p.y, 3, 0, Math.PI * 2); ctx.fill();
- }
- }
- }
- ctx.restore();
- }
- // ---------- scoring ----------
- function scoreDot(ref, user) {
- const d = dist(ref, user);
- return { distance: d, accuracy: pctFromDist(d) };
- }
- function scoreLine(ref, user) {
- const endpointDist = bestEndpointMatch(ref, user);
- const positionPct = pctFromDist(endpointDist);
- const angleDiff = angleDiffUndirected(lineAngleDeg(ref), lineAngleDeg(user));
- const anglePct = pctFromAngle(angleDiff, 45);
- const lenPct = pctFromLen(lineLen(ref), lineLen(user));
- const overall = (positionPct + anglePct + lenPct) / 3;
- return { positionPct, anglePct, lenPct, angleDiff, endpointDist, overall };
- }
- function scorePolygon(ref, user) {
- const refPts = ref.points;
- const userPts = user.points;
- let best = null;
- if (refPts.length === userPts.length) {
- const n = refPts.length;
- for (const dir of [1, -1]) {
- for (let off = 0; off < n; off++) {
- const reordered = [];
- for (let i = 0; i < n; i++) {
- const idx = dir === 1 ? (off + i) % n : (((off - i) % n) + n) % n;
- reordered.push(userPts[idx]);
- }
- let total = 0;
- for (let i = 0; i < n; i++) total += dist(refPts[i], reordered[i]);
- if (!best || total < best.total) best = { total, points: reordered };
- }
- }
- } else {
- best = { points: userPts.slice(0, refPts.length), total: 0 };
- }
- const n = Math.min(refPts.length, best.points.length);
- const vertices = [];
- for (let i = 0; i < n; i++) {
- const d = dist(refPts[i], best.points[i]);
- vertices.push({ ref: refPts[i], user: best.points[i], distance: d, accuracy: pctFromDist(d) });
- }
- const edges = [];
- for (let i = 0; i < n; i++) {
- const j = (i + 1) % n;
- const refE = { x1: refPts[i].x, y1: refPts[i].y, x2: refPts[j].x, y2: refPts[j].y };
- const userE = { x1: best.points[i].x, y1: best.points[i].y, x2: best.points[j].x, y2: best.points[j].y };
- const angleDiff = angleDiffUndirected(lineAngleDeg(refE), lineAngleDeg(userE));
- edges.push({ angleDiff, anglePct: pctFromAngle(angleDiff, 45), lenPct: pctFromLen(lineLen(refE), lineLen(userE)) });
- }
- const avg = arr => arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0;
- const vertexAvg = avg(vertices.map(v => v.accuracy));
- const angleAvg = avg(edges.map(e => e.anglePct));
- const lenAvg = avg(edges.map(e => e.lenPct));
- let overall = (vertexAvg + angleAvg + lenAvg) / 3;
- let countNote = null;
- if (refPts.length !== userPts.length) {
- const penalty = Math.abs(refPts.length - userPts.length) * 15;
- overall = Math.max(0, overall - penalty);
- countNote = `${userPts.length} of ${refPts.length} vertices (−${penalty}% penalty)`;
- }
- return { vertices, edges, vertexAvg, angleAvg, lenAvg, overall, countNote };
- }
- function matchAndScore(refShapes, userShapes) {
- const refByType = { dot: [], line: [], polygon: [] };
- const userByType = { dot: [], line: [], polygon: [] };
- refShapes.forEach(s => refByType[s.type].push(s));
- userShapes.forEach(s => userByType[s.type].push(s));
- const dots = [];
- const usedD = new Set();
- for (const r of refByType.dot) {
- let bi = -1, bd = Infinity;
- for (let i = 0; i < userByType.dot.length; i++) {
- if (usedD.has(i)) continue;
- const d = dist(r, userByType.dot[i]);
- if (d < bd) { bd = d; bi = i; }
- }
- if (bi >= 0) { usedD.add(bi); dots.push({ ref: r, user: userByType.dot[bi], ...scoreDot(r, userByType.dot[bi]) }); }
- else dots.push({ ref: r, user: null, accuracy: 0, distance: null });
- }
- const lines = [];
- const usedL = new Set();
- for (const r of refByType.line) {
- let bi = -1, bd = Infinity;
- for (let i = 0; i < userByType.line.length; i++) {
- if (usedL.has(i)) continue;
- const d = bestEndpointMatch(r, userByType.line[i]);
- if (d < bd) { bd = d; bi = i; }
- }
- if (bi >= 0) { usedL.add(bi); lines.push({ ref: r, user: userByType.line[bi], ...scoreLine(r, userByType.line[bi]) }); }
- else lines.push({ ref: r, user: null, overall: 0, positionPct: 0, anglePct: 0, lenPct: 0, angleDiff: null });
- }
- const polys = [];
- const usedP = new Set();
- for (const r of refByType.polygon) {
- let bi = -1, bs = -1;
- for (let i = 0; i < userByType.polygon.length; i++) {
- if (usedP.has(i)) continue;
- const sc = scorePolygon(r, userByType.polygon[i]);
- if (sc.overall > bs) { bs = sc.overall; bi = i; }
- }
- if (bi >= 0) { usedP.add(bi); polys.push({ ref: r, user: userByType.polygon[bi], ...scorePolygon(r, userByType.polygon[bi]) }); }
- else polys.push({ ref: r, user: null, overall: 0, vertexAvg: 0, angleAvg: 0, lenAvg: 0, edges: [] });
- }
- const extras = (userByType.dot.length - usedD.size) +
- (userByType.line.length - usedL.size) +
- (userByType.polygon.length - usedP.size);
- return { dots, lines, polys, extras };
- }
- function overallScore(r) {
- const arr = [...r.dots.map(d => d.accuracy), ...r.lines.map(l => l.overall), ...r.polys.map(p => p.overall)];
- return arr.length ? arr.reduce((a, b) => a + b, 0) / arr.length : 0;
- }
- function pctClass(p) { return p >= 85 ? 'good' : p >= 60 ? 'ok' : 'bad'; }
- function fmtPct(p) { return `<span class="pct ${pctClass(p)}">${p.toFixed(1)}%</span>`; }
- function buildScoreHTML(r) {
- let html = '<table><thead><tr><th>Shape</th><th>Position</th><th>Angle</th><th>Length</th><th>Score</th></tr></thead><tbody>';
- let n = 0;
- for (const d of r.dots) {
- n++;
- const pos = d.user ? `${fmtPct(d.accuracy)} <span style="color:#71717a">(${d.distance.toFixed(1)} px off)</span>` : '<span class="bad">missing</span>';
- html += `<tr><td>Dot ${n}</td><td>${pos}</td><td>—</td><td>—</td><td>${fmtPct(d.accuracy)}</td></tr>`;
- }
- for (const l of r.lines) {
- n++;
- if (!l.user) { html += `<tr><td>Line ${n}</td><td colspan="3"><span class="bad">missing</span></td><td>${fmtPct(0)}</td></tr>`; continue; }
- const angCell = `${fmtPct(l.anglePct)} <span style="color:#71717a">(${l.angleDiff.toFixed(1)}° off)</span>`;
- html += `<tr><td>Line ${n}</td><td>${fmtPct(l.positionPct)}</td><td>${angCell}</td><td>${fmtPct(l.lenPct)}</td><td>${fmtPct(l.overall)}</td></tr>`;
- }
- for (const p of r.polys) {
- n++;
- if (!p.user) { html += `<tr><td>Polygon ${n}</td><td colspan="3"><span class="bad">missing</span></td><td>${fmtPct(0)}</td></tr>`; continue; }
- const note = p.countNote ? ` <span style="color:#a16207">(${p.countNote})</span>` : '';
- html += `<tr><td>Polygon ${n}${note}</td><td>${fmtPct(p.vertexAvg)}</td><td>${fmtPct(p.angleAvg)}</td><td>${fmtPct(p.lenAvg)}</td><td>${fmtPct(p.overall)}</td></tr>`;
- for (let i = 0; i < p.edges.length; i++) {
- const e = p.edges[i];
- html += `<tr class="sub"><td>↳ edge ${i + 1}</td><td>—</td><td>${fmtPct(e.anglePct)} <span style="color:#a1a1aa">(${e.angleDiff.toFixed(1)}° off)</span></td><td>${fmtPct(e.lenPct)}</td><td>—</td></tr>`;
- }
- }
- if (r.extras > 0) {
- html += `<tr><td colspan="5" style="color:#a16207;font-size:12px;">${r.extras} extra shape${r.extras > 1 ? 's' : ''} you drew didn't match a reference (not counted).</td></tr>`;
- }
- html += '</tbody></table>';
- return html;
- }
- function renderScoreInto(scoreEl, overallEl, detailEl, scoring) {
- overallEl.innerHTML = fmtPct(overallScore(scoring));
- detailEl.innerHTML = buildScoreHTML(scoring);
- scoreEl.hidden = false;
- }
- // ============================================================
- // PRACTICE VIEW
- // ============================================================
- const refCanvas = document.getElementById('ref');
- const userCanvas = document.getElementById('user');
- const rctx = refCanvas.getContext('2d');
- const uctx = userCanvas.getContext('2d');
- let referenceShapes = [];
- let userShapes = [];
- let currentTool = 'dot';
- let pendingLine = null;
- let pendingPoly = null;
- let showOverlay = false;
- let savedThisPuzzle = false;
- function renderRef() {
- rctx.clearRect(0, 0, W, H);
- drawShapes(rctx, referenceShapes);
- }
- function renderUser() {
- uctx.clearRect(0, 0, W, H);
- if (showOverlay) drawShapes(uctx, referenceShapes, { color: '#cbd5e1', lineWidth: 1 });
- drawShapes(uctx, userShapes, { color: '#2563eb' });
- if (pendingLine) {
- uctx.fillStyle = '#2563eb';
- uctx.beginPath(); uctx.arc(pendingLine.x, pendingLine.y, 4, 0, Math.PI * 2); uctx.fill();
- }
- if (pendingPoly && pendingPoly.points.length > 0) {
- uctx.strokeStyle = '#2563eb';
- uctx.fillStyle = '#2563eb';
- uctx.lineWidth = 2;
- if (pendingPoly.points.length >= 2) {
- uctx.beginPath();
- uctx.moveTo(pendingPoly.points[0].x, pendingPoly.points[0].y);
- for (let i = 1; i < pendingPoly.points.length; i++) uctx.lineTo(pendingPoly.points[i].x, pendingPoly.points[i].y);
- uctx.stroke();
- }
- for (const p of pendingPoly.points) {
- uctx.beginPath(); uctx.arc(p.x, p.y, 3, 0, Math.PI * 2); uctx.fill();
- }
- }
- }
- function getPos(e, canvas) {
- const r = canvas.getBoundingClientRect();
- const sx = canvas.width / r.width, sy = canvas.height / r.height;
- return { x: (e.clientX - r.left) * sx, y: (e.clientY - r.top) * sy };
- }
- userCanvas.addEventListener('click', e => {
- const p = getPos(e, userCanvas);
- if (currentTool === 'dot') {
- userShapes.push({ type: 'dot', x: p.x, y: p.y });
- } else if (currentTool === 'line') {
- if (!pendingLine) pendingLine = p;
- else {
- userShapes.push({ type: 'line', x1: pendingLine.x, y1: pendingLine.y, x2: p.x, y2: p.y });
- pendingLine = null;
- }
- } else if (currentTool === 'polygon') {
- if (!pendingPoly) pendingPoly = { points: [] };
- pendingPoly.points.push(p);
- }
- renderUser();
- });
- function setTool(tool) {
- currentTool = tool;
- pendingLine = null;
- document.querySelectorAll('#tool-row button[data-tool]').forEach(b => {
- b.classList.toggle('active', b.dataset.tool === tool);
- });
- updateHint();
- }
- function commitPolygon() {
- if (pendingPoly && pendingPoly.points.length >= 3) {
- userShapes.push({ type: 'polygon', points: pendingPoly.points });
- }
- pendingPoly = null;
- }
- function updateHint() {
- const hints = {
- dot: 'Click to place a dot.',
- line: 'Click for line start, click again for line end.',
- polygon: 'Click to add vertices. Click "Finish Polygon" when done (min 3).',
- };
- document.getElementById('hint').textContent = hints[currentTool];
- }
- document.getElementById('tool-row').addEventListener('click', e => {
- const tool = e.target.dataset.tool;
- const action = e.target.dataset.action;
- if (tool) { commitPolygon(); setTool(tool); renderUser(); }
- else if (action === 'finishPoly') { commitPolygon(); renderUser(); }
- else if (action === 'undo') {
- if (pendingPoly && pendingPoly.points.length > 0) {
- pendingPoly.points.pop();
- if (pendingPoly.points.length === 0) pendingPoly = null;
- } else if (pendingLine) pendingLine = null;
- else if (userShapes.length > 0) userShapes.pop();
- renderUser();
- }
- });
- function newPuzzle() {
- const mode = document.getElementById('mode').value;
- const count = Math.max(1, parseInt(document.getElementById('count').value) || 1);
- referenceShapes = generateShapes(mode, count);
- userShapes = [];
- pendingLine = null;
- pendingPoly = null;
- showOverlay = false;
- savedThisPuzzle = false;
- document.getElementById('reveal').disabled = true;
- document.getElementById('score').hidden = true;
- renderRef();
- renderUser();
- }
- const revealBtn = document.getElementById('reveal');
- document.getElementById('generate').addEventListener('click', newPuzzle);
- document.getElementById('check').addEventListener('click', () => {
- commitPolygon();
- showOverlay = true;
- revealBtn.disabled = false;
- renderUser();
- const scoring = matchAndScore(referenceShapes, userShapes);
- renderScoreInto(document.getElementById('score'), document.getElementById('overall'), document.getElementById('detail'), scoring);
- if (!savedThisPuzzle) {
- saveRecord({
- id: Date.now() + '-' + Math.random().toString(36).slice(2, 8),
- ts: Date.now(),
- mode: document.getElementById('mode').value,
- count: parseInt(document.getElementById('count').value) || 1,
- reference: referenceShapes,
- user: userShapes,
- overall: overallScore(scoring),
- });
- savedThisPuzzle = true;
- refreshRecordsCount();
- }
- });
- document.getElementById('clear').addEventListener('click', () => {
- userShapes = [];
- pendingLine = null;
- pendingPoly = null;
- showOverlay = false;
- revealBtn.disabled = true;
- document.getElementById('score').hidden = true;
- renderUser();
- });
- revealBtn.addEventListener('click', () => { showOverlay = !showOverlay; renderUser(); });
- document.getElementById('mode').addEventListener('change', e => {
- const map = { dots: 'dot', lines: 'line', polygon: 'polygon', mixed: 'dot' };
- setTool(map[e.target.value]);
- });
- // ============================================================
- // RECORDS STORAGE
- // ============================================================
- function loadRecords() {
- try {
- const raw = localStorage.getItem(STORAGE_KEY);
- if (!raw) return [];
- const arr = JSON.parse(raw);
- return Array.isArray(arr) ? arr : [];
- } catch { return []; }
- }
- function persistRecords(records) {
- localStorage.setItem(STORAGE_KEY, JSON.stringify(records));
- }
- function saveRecord(record) {
- const records = loadRecords();
- records.push(record);
- persistRecords(records);
- }
- function deleteRecord(id) {
- const records = loadRecords().filter(r => r.id !== id);
- persistRecords(records);
- }
- function refreshRecordsCount() {
- const n = loadRecords().length;
- document.getElementById('tab-records-count').textContent = n ? `(${n})` : '';
- }
- // ============================================================
- // RECORDS VIEW
- // ============================================================
- const recordRefCanvas = document.getElementById('record-ref');
- const recordUserCanvas = document.getElementById('record-user');
- const rrctx = recordRefCanvas.getContext('2d');
- const ructx = recordUserCanvas.getContext('2d');
- let viewingRecordIndex = -1;
- let cachedSorted = []; // newest first
- function getSortedRecords() {
- return loadRecords().slice().sort((a, b) => b.ts - a.ts);
- }
- function modeLabel(mode, count) {
- const m = { dots: 'Dots', lines: 'Lines', polygon: 'Polygon', mixed: 'Mixed' }[mode] || mode;
- return `${m} (${count})`;
- }
- function fmtDate(ts) {
- const d = new Date(ts);
- return d.toLocaleString();
- }
- function renderRecordsList() {
- cachedSorted = getSortedRecords();
- const container = document.getElementById('records-list-container');
- document.getElementById('records-count').textContent = `${cachedSorted.length} record${cachedSorted.length === 1 ? '' : 's'}`;
- if (cachedSorted.length === 0) {
- container.innerHTML = '<div class="records-empty">No records yet. Complete a puzzle and click "Check Accuracy" to record it.</div>';
- return;
- }
- let html = '<div class="records-list"><table><thead><tr><th>#</th><th>Date</th><th>Mode</th><th>Score</th><th></th></tr></thead><tbody>';
- cachedSorted.forEach((r, i) => {
- html += `<tr data-id="${r.id}"><td>${i + 1}</td><td>${fmtDate(r.ts)}</td><td>${modeLabel(r.mode, r.count)}</td><td>${fmtPct(r.overall)}</td><td class="actions"><button class="danger" data-delete="${r.id}">Delete</button></td></tr>`;
- });
- html += '</tbody></table></div>';
- container.innerHTML = html;
- }
- function showList() {
- document.getElementById('records-list-mode').hidden = false;
- document.getElementById('records-detail-mode').hidden = true;
- viewingRecordIndex = -1;
- renderRecordsList();
- }
- function showDetail(index) {
- cachedSorted = getSortedRecords();
- if (cachedSorted.length === 0) { showList(); return; }
- viewingRecordIndex = Math.max(0, Math.min(index, cachedSorted.length - 1));
- document.getElementById('records-list-mode').hidden = true;
- document.getElementById('records-detail-mode').hidden = false;
- renderDetail();
- }
- function renderDetail() {
- const r = cachedSorted[viewingRecordIndex];
- if (!r) { showList(); return; }
- rrctx.clearRect(0, 0, W, H);
- ructx.clearRect(0, 0, W, H);
- drawShapes(rrctx, r.reference || []);
- drawShapes(ructx, r.reference || [], { color: '#cbd5e1', lineWidth: 1 });
- drawShapes(ructx, r.user || [], { color: '#2563eb' });
- document.getElementById('record-meta').innerHTML =
- `<b>${fmtDate(r.ts)}</b> · ${modeLabel(r.mode, r.count)} · Score ${fmtPct(r.overall)}` +
- ` <span style="color:#71717a">(${viewingRecordIndex + 1} of ${cachedSorted.length})</span>`;
- const scoring = matchAndScore(r.reference || [], r.user || []);
- renderScoreInto(
- document.querySelector('#view-records .score'),
- document.getElementById('record-overall'),
- document.getElementById('record-detail'),
- scoring
- );
- document.getElementById('record-prev').disabled = viewingRecordIndex <= 0;
- document.getElementById('record-next').disabled = viewingRecordIndex >= cachedSorted.length - 1;
- }
- document.getElementById('records-list-container').addEventListener('click', e => {
- const delId = e.target.dataset.delete;
- if (delId) {
- e.stopPropagation();
- deleteRecord(delId);
- refreshRecordsCount();
- renderRecordsList();
- return;
- }
- const row = e.target.closest('tr[data-id]');
- if (row) {
- const id = row.dataset.id;
- const idx = cachedSorted.findIndex(r => r.id === id);
- if (idx >= 0) showDetail(idx);
- }
- });
- document.getElementById('record-back').addEventListener('click', showList);
- document.getElementById('record-prev').addEventListener('click', () => { if (viewingRecordIndex > 0) showDetail(viewingRecordIndex - 1); });
- document.getElementById('record-next').addEventListener('click', () => { if (viewingRecordIndex < cachedSorted.length - 1) showDetail(viewingRecordIndex + 1); });
- document.getElementById('record-delete').addEventListener('click', () => {
- const r = cachedSorted[viewingRecordIndex];
- if (!r) return;
- deleteRecord(r.id);
- refreshRecordsCount();
- cachedSorted = getSortedRecords();
- if (cachedSorted.length === 0) showList();
- else showDetail(Math.min(viewingRecordIndex, cachedSorted.length - 1));
- });
- // keyboard nav (only when in records detail view)
- document.addEventListener('keydown', e => {
- if (document.getElementById('view-records').hidden) return;
- if (document.getElementById('records-detail-mode').hidden) return;
- if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA') return;
- if (e.key === 'ArrowLeft') {
- if (viewingRecordIndex > 0) { showDetail(viewingRecordIndex - 1); e.preventDefault(); }
- } else if (e.key === 'ArrowRight') {
- if (viewingRecordIndex < cachedSorted.length - 1) { showDetail(viewingRecordIndex + 1); e.preventDefault(); }
- } else if (e.key === 'Escape') {
- showList();
- }
- });
- // export / import / clear all
- document.getElementById('export-records').addEventListener('click', () => {
- const records = loadRecords();
- if (records.length === 0) { alert('No records to export.'); return; }
- const blob = new Blob([JSON.stringify({ version: 1, records }, null, 2)], { type: 'application/json' });
- const url = URL.createObjectURL(blob);
- const a = document.createElement('a');
- const ts = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
- a.href = url;
- a.download = `copy-practice-records-${ts}.json`;
- document.body.appendChild(a);
- a.click();
- document.body.removeChild(a);
- URL.revokeObjectURL(url);
- });
- const importInput = document.getElementById('import-file');
- document.getElementById('import-records').addEventListener('click', () => importInput.click());
- importInput.addEventListener('change', () => {
- const file = importInput.files[0];
- if (!file) return;
- const reader = new FileReader();
- reader.onload = () => {
- try {
- const data = JSON.parse(reader.result);
- const incoming = Array.isArray(data) ? data : (data.records || []);
- if (!Array.isArray(incoming)) throw new Error('invalid file');
- const existing = loadRecords();
- const existingIds = new Set(existing.map(r => r.id));
- let added = 0;
- for (const r of incoming) {
- if (r && r.id && r.reference && r.user && !existingIds.has(r.id)) {
- existing.push(r);
- existingIds.add(r.id);
- added++;
- }
- }
- persistRecords(existing);
- refreshRecordsCount();
- renderRecordsList();
- alert(`Imported ${added} record${added === 1 ? '' : 's'}. ${incoming.length - added} skipped (duplicates or invalid).`);
- } catch (err) {
- alert('Import failed: ' + err.message);
- } finally {
- importInput.value = '';
- }
- };
- reader.readAsText(file);
- });
- document.getElementById('clear-all-records').addEventListener('click', () => {
- if (loadRecords().length === 0) return;
- if (!confirm('Delete ALL records? This cannot be undone.')) return;
- persistRecords([]);
- refreshRecordsCount();
- renderRecordsList();
- });
- // ============================================================
- // TABS
- // ============================================================
- document.querySelectorAll('.tab').forEach(tab => {
- tab.addEventListener('click', () => {
- const target = tab.dataset.tab;
- document.querySelectorAll('.tab').forEach(t => t.classList.toggle('active', t === tab));
- document.getElementById('view-practice').hidden = target !== 'practice';
- document.getElementById('view-records').hidden = target !== 'records';
- if (target === 'records') showList();
- });
- });
- // ---------- init ----------
- updateHint();
- newPuzzle();
- refreshRecordsCount();
- })();
- </script>
- </body>
- </html>
Advertisement