diff --git a/.github/workflows/web.yml b/.github/workflows/web.yml index 071e1aa..be44ef6 100644 --- a/.github/workflows/web.yml +++ b/.github/workflows/web.yml @@ -32,6 +32,7 @@ jobs: # Safari on iPhone runs WebKit; the Chrome acceptance above does not see its layout. # Uses the build from test:browser. - run: npx playwright install --with-deps webkit + - run: node scripts/quality.acceptance.mjs - run: node scripts/webkit-layout.mjs # The reference views (web/DESIGN.md, "Rebuild") for review on every PR. - uses: actions/upload-artifact@v7.0.2 @@ -89,3 +90,6 @@ jobs: env: BASE_URL: https://proofofwork.fyi EXPECT_POSTHOG: '1' + - run: node scripts/quality.acceptance.mjs + env: + BASE_URL: https://proofofwork.fyi diff --git a/web/DESIGN.md b/web/DESIGN.md index 41c3f4f..b1d39dc 100644 --- a/web/DESIGN.md +++ b/web/DESIGN.md @@ -377,6 +377,9 @@ decision, 2026-10-27): "Mining" between races, "Re-mine block #K" during a repair. Nothing else: not "Start demo", not during a race or a repeating run, not while typing, with Cmd/Ctrl/Alt, on key repeat or under an open dialog. + Settings lets the learner disable this single-letter shortcut, including its + announcement, for speech input or assistive technology. The choice stays in this + browser; the mining button remains available. - **Miner details** (Mirko, 2026-11-03, replaces the miner editor): a click on a miner's name opens a **popover** under its lane, between races and during one: its **share** of the racing miners' hashpower as a slider from 5 to 90 %, which is its chance to find the next block; the @@ -597,6 +600,16 @@ Rules for every workbench component (`src/components/workbench/`): ## Guards +- Labs and the leaderboard view load on demand; the workbench starts without their + code or styles. `check:bundle` follows the build manifest's static imports and caps + initial gzip transfer at 255 KiB JavaScript and 25 KiB CSS. +- `test:quality` checks WCAG A/AA axe rules in both themes at 360 px and desktop, + plus the skip link, dialog focus return and shortcut preference. The skip link + focuses the current view without changing experiments. Explaining bubbles remain + hoverable; Escape dismisses chain explanations while preserving keyboard position. +- Accent labels use dark ink on the brighter dark-theme blue; muted text remains + readable on all panel surfaces. The light theme uses white labels on darker blue. + - `src/__tests__/designTokens.test.js` fails on any color literal (hex, `rgb()`, `hsl()`) outside `src/styles/tokens.css`. - The browser acceptance (`npm run test:browser`) writes the reference views diff --git a/web/package-lock.json b/web/package-lock.json index 35aec50..2f4ca30 100644 --- a/web/package-lock.json +++ b/web/package-lock.json @@ -22,6 +22,7 @@ "@types/react": "^19.2.5", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^5.1.1", + "axe-core": "4.14.0", "eslint": "^9.39.1", "eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-refresh": "^0.4.24", @@ -2942,6 +2943,16 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/axe-core": { + "version": "4.14.0", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.14.0.tgz", + "integrity": "sha512-9WTZxEjsZ7b13TH8JPmbV2z8CHbl80/2hm3XPEG4JgNdQLK81IBRXmSxHfMAOkSqQeRxT/0dwNDz2GOm3zzpcQ==", + "dev": true, + "license": "MPL-2.0", + "engines": { + "node": ">=4" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", diff --git a/web/package.json b/web/package.json index 3d5ca2f..f096c04 100644 --- a/web/package.json +++ b/web/package.json @@ -9,7 +9,9 @@ "lint": "eslint .", "preview": "vite preview", "test": "vitest run", - "check": "npm run lint && npm test && npm run build", + "check": "npm run lint && npm test && npm run build && npm run check:bundle", + "check:bundle": "node scripts/check-bundle.mjs", + "test:quality": "npm run build && node scripts/quality.acceptance.mjs", "deploy:check": "npm run build && wrangler deploy --env production --dry-run", "deploy": "npm run build && wrangler deploy --env \"\"", "deploy:production": "npm run build && wrangler deploy --env production", @@ -31,6 +33,7 @@ "@types/react": "^19.2.5", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^5.1.1", + "axe-core": "4.14.0", "eslint": "^9.39.1", "eslint-plugin-react-hooks": "^7.0.1", "eslint-plugin-react-refresh": "^0.4.24", diff --git a/web/scripts/check-bundle.mjs b/web/scripts/check-bundle.mjs new file mode 100644 index 0000000..402addc --- /dev/null +++ b/web/scripts/check-bundle.mjs @@ -0,0 +1,32 @@ +import assert from 'node:assert/strict'; +import { readFile } from 'node:fs/promises'; +import { gzipSync } from 'node:zlib'; +import { resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const dist = resolve(process.argv[2] || fileURLToPath(new URL('../dist', import.meta.url))); +const manifest = JSON.parse(await readFile(`${dist}/.vite/manifest.json`, 'utf8')); +const entries = Object.keys(manifest).filter(key => manifest[key].isEntry); +assert.ok(entries.length, 'Build manifest has no entry'); +const files = new Set(); +const visited = new Set(); +function collect(key) { + if (visited.has(key)) return; + visited.add(key); + const chunk = manifest[key]; + assert.ok(chunk, `Missing static dependency ${key}`); + files.add(chunk.file); + for (const css of chunk.css || []) files.add(css); + for (const dependency of chunk.imports || []) collect(dependency); +} +entries.forEach(collect); +const sizes = { js: 0, css: 0 }; +for (const file of files) { + const kind = file.endsWith('.js') ? 'js' : file.endsWith('.css') ? 'css' : null; + if (kind) sizes[kind] += gzipSync(await readFile(resolve(dist, file))).length; +} +// e009022 eagerly shipped 265,995 bytes JS and 26,504 bytes CSS (gzip). +// Keep room above the split build while preventing a return to that payload. +assert.ok(sizes.js <= 255 * 1024, `Initial JavaScript ${sizes.js} exceeds 255 KiB gzip`); +assert.ok(sizes.css <= 25 * 1024, `Initial CSS ${sizes.css} exceeds 25 KiB gzip`); +console.log(JSON.stringify({ initialGzipBytes: sizes, files: [...files] })); diff --git a/web/scripts/quality.acceptance.mjs b/web/scripts/quality.acceptance.mjs new file mode 100644 index 0000000..79cd2b9 --- /dev/null +++ b/web/scripts/quality.acceptance.mjs @@ -0,0 +1,96 @@ +import assert from 'node:assert/strict'; +import { chromium } from 'playwright'; +import { createRequire } from 'node:module'; +import { spawn } from 'node:child_process'; +import { stripVTControlCharacters } from 'node:util'; +import { fileURLToPath } from 'node:url'; + +const require = createRequire(import.meta.url); +const base = process.env.BASE_URL || 'http://127.0.0.1:4187'; +const root = fileURLToPath(new URL('..', import.meta.url)); +let server, browser; +try { + if (!process.env.BASE_URL) { + server = spawn(process.execPath, [fileURLToPath(new URL('../node_modules/vite/bin/vite.js', import.meta.url)), 'preview', '--host', '127.0.0.1', '--port', '4187', '--strictPort'], { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] }); + let log = ''; + server.stdout.on('data', data => { log += data; }); + server.stderr.on('data', data => { log += data; }); + let ready = false; + for (let i = 0; i < 100; i++) { + if (server.exitCode !== null) throw new Error(`Preview exited: ${log}`); + try { if (stripVTControlCharacters(log).includes(base) && (await fetch(base)).ok) { ready = true; break; } } catch { /* Startup only. */ } + await new Promise(resolve => setTimeout(resolve, 100)); + } + assert.ok(ready, `Preview did not start: ${log}`); + } + browser = await chromium.launch({ channel: 'chrome', headless: true }); + for (const width of [360, 1512]) { + const context = await browser.newContext({ viewport: { width, height: 860 }, reducedMotion: 'reduce' }); + await context.route(/^https:\/\/(eu\.i\.posthog\.com|api\.proofofwork\.fyi)\//, route => route.abort('connectionrefused')); + const page = await context.newPage(); + const errors = []; + page.on('pageerror', error => errors.push(error.message)); + const audit = async label => { + await page.addScriptTag({ path: require.resolve('axe-core/axe.min.js') }); + const violations = await page.evaluate(async () => (await globalThis.axe.run(document, { + runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa', 'wcag21aa', 'wcag22aa'] } + })).violations.map(v => ({ id: v.id, targets: v.nodes.map(node => node.target) }))); + assert.deepEqual(violations, [], `${label} ${width}px`); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), `${label}: horizontal overflow`); + }; + for (const route of ['', '#/hash-lab', '#/chain-lab']) { + await page.goto(`${base}/${route}`); + await page.getByRole('main').waitFor(); + if (route) await page.getByRole('button', { name: 'Back to simulator', exact: true }).waitFor(); + const view = await page.getByRole('main').getAttribute('aria-label'); + await page.getByRole('link', { name: 'Skip to content', exact: true }).focus(); + await page.keyboard.press('Enter'); + assert.equal(await page.evaluate(() => document.activeElement.id), 'workbench'); + assert.equal(await page.getByRole('main').getAttribute('aria-label'), view); + for (const theme of ['dark', 'light']) { + await page.evaluate(theme => document.documentElement.setAttribute('data-theme', theme), theme); + await audit(`${route || 'workbench'} ${theme}`); + } + if (!route) { + const newTransaction = page.getByRole('button', { name: 'New transaction', exact: true }); + await newTransaction.click(); + await page.getByRole('button', { name: 'Cancel', exact: true }).focus(); + await page.keyboard.press('Enter'); + assert.equal(await newTransaction.evaluate(element => element === document.activeElement), true); + const miner = page.getByRole('button', { name: 'Hal: hashpower, attempts and name', exact: true }); + await miner.click(); + await page.getByRole('group', { name: 'Miner Hal', exact: true }).getByRole('button', { name: 'Done', exact: true }).click(); + assert.equal(await miner.evaluate(element => element === document.activeElement), true); + if (width >= 1024) { + const face = page.locator('.chain-band-tile-face').first(); + await page.keyboard.press('Tab'); + await face.focus(); + const explanation = page.getByRole('group', { name: 'Full hash of block 0', exact: true }); + assert.equal(await explanation.isVisible(), true); + await page.keyboard.press('Escape'); + assert.equal(await explanation.isVisible(), false); + assert.equal(await face.evaluate(element => element === document.activeElement), true); + } + } + } + await page.goto(`${base}/`); + await page.getByRole('button', { name: width < 768 ? 'Menu' : 'More', exact: true }).click(); + await page.getByRole('button', { name: 'Reset', exact: true }).hover(); + await page.getByRole('tooltip').waitFor(); + await page.getByRole('button', { name: 'Settings', exact: true }).click(); + await page.getByRole('dialog', { name: 'Settings', exact: true }).waitFor(); + for (const theme of ['dark', 'light']) { + await page.evaluate(theme => document.documentElement.setAttribute('data-theme', theme), theme); + await audit(`Settings ${theme}`); + } + const shortcut = page.getByRole('checkbox', { name: 'Enable M to mine or re-mine a block', exact: true }); + await shortcut.uncheck(); + await page.keyboard.press('Escape'); + assert.equal(await page.evaluate(() => document.activeElement.getAttribute('aria-label')), width < 768 ? 'Menu' : 'More'); + await page.reload(); + assert.equal(await page.evaluate(() => localStorage.getItem('proofofwork-mining-shortcut')), '0'); + assert.deepEqual(errors, []); + await context.close(); + } + console.log('Quality: WCAG A/AA axe checks in both themes, 360px/desktop, skip link, dialog focus return and shortcut preference passed'); +} finally { await browser?.close(); server?.kill(); } diff --git a/web/src/App.jsx b/web/src/App.jsx index 9e3607b..c0c76fc 100644 --- a/web/src/App.jsx +++ b/web/src/App.jsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'; +import { lazy, Suspense, useCallback, useEffect, useRef, useState, useSyncExternalStore } from 'react'; import { useBlockchain } from './hooks/useBlockchain'; import { useMinerIdentity } from './hooks/useMinerIdentity'; import { playMiningSuccessSound, playRecordSound, unlockMiningAudio } from './lib/sound'; @@ -15,9 +15,6 @@ import { LowerDifficultyDialog } from './components/workbench/LowerDifficultyDia import { Workbench } from './components/workbench/Workbench'; import { MissionRail } from './components/workbench/MissionRail'; import { MissionIntro } from './components/workbench/MissionIntro'; -import { HashLab } from './components/HashLab'; -import { ChainLab } from './components/ChainLab'; -import { PoolPanel } from './components/PoolPanel'; import { minerProfileHash, POOL_HASH } from './lib/poolApi'; import { BlockDetailsModal } from './components/BlockDetailsModal'; import { ParticipantDetailsModal } from './components/ParticipantDetailsModal'; @@ -29,6 +26,11 @@ import './index.css'; import { adjustedDifficulty, averagePace, checkWindowStart, isCheckHeight } from './lib/difficulty'; import { DEFAULT_FEE_RATE } from './lib/blockchain'; +// Free play starts on the workbench; other experiments load when opened. +const HashLab = lazy(() => import('./components/HashLab').then(module => ({ default: module.HashLab }))); +const ChainLab = lazy(() => import('./components/ChainLab').then(module => ({ default: module.ChainLab }))); +const PoolPanel = lazy(() => import('./components/PoolPanel').then(module => ({ default: module.PoolPanel }))); + const INITIAL_CONFIG = { name: 'powfyicoin', miningDifficulty: 4, blockReward: 3.125, halvingEvent: 21, participants: ['Alice', 'Bob', 'Chris', 'Hal', 'Dorian', 'Laszlo'], miners: ['Hal', 'Dorian', 'Laszlo'] @@ -447,7 +449,7 @@ function App() { return (
- Skip to workbench + { event.preventDefault(); document.getElementById('workbench')?.focus(); }}>Skip to content setShowSettings(true)} compact={compact} saveState={sim.saveState} /> @@ -457,7 +459,7 @@ function App() {
-
+
{showIntro && } @@ -471,6 +473,7 @@ function App() { onDifficulty={onDifficulty} onBack={onBack} onCreateTransaction={onCreateTransaction} onCreateWallet={createWallet} onCreateMiner={createMiner} onRenameMiner={onRenameMiner} onShare={setMinerShare} onOpenMiner={openMiner} onSlowMotion={setSlowMotion} onOpenWallet={setWalletDetails} onOpenDetails={setDetails} onOpenTransaction={setPendingTx} onOpenBlockTx={(transaction, blockIndex) => setBlockTx({ transaction, blockIndex })} onOpenChainLab={() => navigate('chain-lab')} error={error} />} + Loading {VIEW_LABELS[view]}…

}> {view === 'hash-lab' &&
navigate('workbench')} @@ -483,6 +486,7 @@ function App() { {view === 'pool' &&
navigate('workbench')} profile={profile} onOpenProfile={openProfile} onCloseProfile={closeProfile} />
} +
{winner &&
} diff --git a/web/src/__tests__/AppMissions.test.jsx b/web/src/__tests__/AppMissions.test.jsx index 04166ac..e9eb361 100644 --- a/web/src/__tests__/AppMissions.test.jsx +++ b/web/src/__tests__/AppMissions.test.jsx @@ -55,12 +55,12 @@ describe('optional missions in App', () => { expect(collapsed()).toBe(true); }); - it('remembers dismissal, while the page and free labs stay usable', () => { + it('remembers dismissal, while the page and free labs stay usable', async () => { render(); fireEvent.click(screen.getByRole('button', { name: "Don't show again" })); expect(intro()).toBeNull(); fireEvent.click(screen.getByRole('button', { name: 'Hash lab', exact: true })); - expect(screen.getByText('Free hash lab')).toBeTruthy(); + expect(await screen.findByText('Free hash lab')).toBeTruthy(); expect(screen.getByText('No coach')).toBeTruthy(); fireEvent.click(screen.getByRole('button', { name: 'Complete manual proof' })); expect(JSON.parse(localStorage.getItem(STORAGE_KEY)).completed).toEqual([]); diff --git a/web/src/__tests__/ChainBand.test.jsx b/web/src/__tests__/ChainBand.test.jsx index 5aa0527..f41b9ee 100644 --- a/web/src/__tests__/ChainBand.test.jsx +++ b/web/src/__tests__/ChainBand.test.jsx @@ -256,13 +256,26 @@ describe('ChainBand health line', () => { }); describe('ChainBand full-hash tooltip', () => { + it('dismisses a full-hash group and a link explanation with Escape without losing position', () => { + renderBand(); + const face = tile(2); + act(() => face.focus()); + fireEvent.keyDown(face, { key: 'Escape' }); + expect(face.closest('.chain-band-tile').classList.contains('is-tip-dismissed')).toBe(true); + expect(document.activeElement).toBe(face); + const link = document.querySelector('.chain-band-link'); + act(() => link.focus()); + fireEvent.keyDown(link, { key: 'Escape' }); + expect(link.classList.contains('is-tip-dismissed')).toBe(true); + expect(link.getAttribute('role')).toBe('group'); + }); it('copies the full hash without selecting the block', async () => { const writeText = vi.fn(() => Promise.resolve()); vi.stubGlobal('navigator', { ...navigator, clipboard: { writeText } }); const { onSelect } = renderBand(); const copy = screen.getByRole('button', { name: 'Copy full hash of block 2' }); - expect(copy.closest('[role="tooltip"]').textContent).toContain('Starts with 00 · prev = hash of #1'); - expect(tile(2).getAttribute('aria-describedby')).toBe(copy.closest('[role="tooltip"]').id); + expect(copy.closest('[role="group"]').textContent).toContain('Starts with 00 · prev = hash of #1'); + expect(tile(2).getAttribute('aria-describedby')).toBe(copy.closest('[role="group"]').id); await act(async () => { fireEvent.click(copy); }); expect(writeText).toHaveBeenCalledWith(hashOf(2)); expect(copy.textContent).toBe('Copied'); @@ -274,7 +287,7 @@ describe('ChainBand full-hash tooltip', () => { vi.stubGlobal('navigator', { ...navigator, clipboard: { writeText } }); renderBand({ views: makeViews(5, TAMPERED) }); const copy = screen.getByRole('button', { name: 'Copy full hash of block 2' }); - const tip = copy.closest('[role="tooltip"]'); + const tip = copy.closest('[role="group"]'); expect(tip.textContent).toContain('Now'); expect(tip.textContent).toContain('As mined'); expect(tip.textContent).toContain('Your edit: tx 1: 1.5 → 2'); @@ -318,13 +331,23 @@ describe('ChainBand scrolling row', () => { expect(items).toHaveLength(13); expect(items.slice(0, 12).map(item => item.querySelector('.chain-band-tile > .chain-band-num').textContent)) .toEqual(Array.from({ length: 12 }, (_, i) => `#${i}`)); - expect(items.at(-1).querySelector('[role="group"]').getAttribute('aria-label')).toMatch(/^Candidate block 12/); + expect(items.at(-1).querySelector('.chain-band-cand[role="group"]').getAttribute('aria-label')).toMatch(/^Candidate block 12/); expect(items.every(item => ![...item.classList].some(cls => cls.startsWith('is-hidden')))).toBe(true); expect(container.querySelector('.chain-band').className).not.toMatch(/has-earlier/); expect(container.querySelectorAll('.chain-band-scroll')).toHaveLength(1); }); describe('following the newest block', () => { + it('scrolls instantly when reduced motion is requested', () => { + const original = globalThis.matchMedia; + globalThis.matchMedia = () => ({ matches: true, addEventListener() {}, removeEventListener() {} }); + try { + const { rerender } = render(); + scrollTo.mockClear(); + rerender(); + expect(scrollTo).toHaveBeenCalledWith({ left: expect.any(Number), behavior: 'auto' }); + } finally { globalThis.matchMedia = original; } + }); let scrollTo; beforeEach(() => { scrollTo = vi.fn(); diff --git a/web/src/__tests__/HashLabComparison.test.jsx b/web/src/__tests__/HashLabComparison.test.jsx index 58bb3e2..6833897 100644 --- a/web/src/__tests__/HashLabComparison.test.jsx +++ b/web/src/__tests__/HashLabComparison.test.jsx @@ -73,6 +73,7 @@ describe('measured work-lesson comparison', () => { localStorage.setItem('proofofwork-rail-collapsed', '0'); history.replaceState(null, '', '/#/hash-lab'); render(); + await act(async () => { await vi.dynamicImportSettled(); await vi.advanceTimersByTimeAsync(0); }); expect(screen.getByRole('heading', { name: 'Same message. A stricter target.' })).toBeTruthy(); await find(1); const first = row('One zero').textContent; diff --git a/web/src/__tests__/HintLayer.test.jsx b/web/src/__tests__/HintLayer.test.jsx index 2daa5d3..82804eb 100644 --- a/web/src/__tests__/HintLayer.test.jsx +++ b/web/src/__tests__/HintLayer.test.jsx @@ -76,6 +76,29 @@ describe('HintLayer', () => { }); describe('hints catalog', () => { + it('keeps a menu hint when the pointer returns to its control during the crossing delay', () => { + render(
); + fireEvent.pointerOver(backHal(), { pointerType: 'mouse' }); + act(() => vi.advanceTimersByTime(400)); + const bubble = screen.getByRole('tooltip'); + fireEvent.pointerOut(backHal(), { pointerType: 'mouse', relatedTarget: document.body }); + act(() => vi.advanceTimersByTime(100)); + fireEvent.pointerOver(backHal(), { pointerType: 'mouse', relatedTarget: document.body }); + act(() => vi.advanceTimersByTime(250)); + expect(screen.getByRole('tooltip')).toBe(bubble); + }); + it('lets the pointer cross into the explaining bubble and dismisses it with Escape', () => { + render(); + fireEvent.pointerOver(backHal(), { pointerType: 'mouse' }); + act(() => vi.advanceTimersByTime(400)); + const bubble = screen.getByRole('tooltip'); + fireEvent.pointerOut(backHal(), { pointerType: 'mouse', relatedTarget: bubble }); + fireEvent.pointerOver(bubble, { pointerType: 'mouse', relatedTarget: backHal() }); + act(() => vi.advanceTimersByTime(500)); + expect(screen.getByRole('tooltip')).toBe(bubble); + fireEvent.keyDown(document, { key: 'Escape' }); + expect(screen.queryByRole('tooltip')).toBeNull(); + }); it('throws on an unknown key, so a typo fails its component test', () => { expect(() => hint('no.such-hint')).toThrow(/Unknown hint/); }); diff --git a/web/src/__tests__/MempoolCard.test.jsx b/web/src/__tests__/MempoolCard.test.jsx index 3293095..394b423 100644 --- a/web/src/__tests__/MempoolCard.test.jsx +++ b/web/src/__tests__/MempoolCard.test.jsx @@ -11,6 +11,15 @@ const card = () => screen.getByRole('region', { name: 'Mempool' }); const newTx = () => screen.getByRole('button', { name: 'New transaction' }); describe('MempoolCard', () => { + it('returns keyboard focus to New transaction after cancelling its inline form', () => { + render(); + newTx().focus(); + fireEvent.click(newTx()); + const cancel = screen.getByRole('button', { name: 'Cancel' }); + cancel.focus(); + fireEvent.click(cancel); + expect(document.activeElement).toBe(newTx()); + }); it('idle: pending pill, rows, coinbase line and a glowing New transaction', () => { render(); const text = card().textContent; diff --git a/web/src/__tests__/NextBlockCard.test.jsx b/web/src/__tests__/NextBlockCard.test.jsx index b6d9a6f..5dccead 100644 --- a/web/src/__tests__/NextBlockCard.test.jsx +++ b/web/src/__tests__/NextBlockCard.test.jsx @@ -423,6 +423,19 @@ describe('NextBlockCard miner popover', () => { }); describe('NextBlockCard M key', () => { + it('can disable single-letter mining shortcuts while retaining the button', () => { + localStorage.setItem('proofofwork-mining-shortcut', '0'); + try { + const onMine = vi.fn(); + render(); + const button = screen.getByRole('button', { name: 'Mining' }); + expect(button.hasAttribute('aria-keyshortcuts')).toBe(false); + fireEvent.keyDown(document.body, { key: 'm' }); + expect(onMine).not.toHaveBeenCalled(); + fireEvent.click(button); + expect(onMine).toHaveBeenCalledTimes(1); + } finally { localStorage.removeItem('proofofwork-mining-shortcut'); } + }); const pressM = (target = document.body, options = {}) => fireEvent.keyDown(target, { key: 'm', ...options }); it('mines between races, like the button that announces it', () => { const onMine = vi.fn(); diff --git a/web/src/__tests__/RecordCelebration.test.jsx b/web/src/__tests__/RecordCelebration.test.jsx index def5f9a..fabd8a2 100644 --- a/web/src/__tests__/RecordCelebration.test.jsx +++ b/web/src/__tests__/RecordCelebration.test.jsx @@ -9,6 +9,24 @@ beforeEach(() => { vi.useFakeTimers(); }); afterEach(() => { cleanup(); vi.useRealTimers(); }); describe('RecordCelebration', () => { + it('keeps the focused action while the pointer leaves, and keeps hover when focus leaves', () => { + const onClose = vi.fn(); + render(); + const card = screen.getByRole('status'); + const action = screen.getByRole('button', { name: 'Leaderboard' }); + fireEvent.pointerEnter(card); + act(() => action.focus()); + fireEvent.pointerLeave(card); + act(() => vi.advanceTimersByTime(2000)); + expect(onClose).not.toHaveBeenCalled(); + fireEvent.pointerEnter(card); + act(() => action.blur()); + act(() => vi.advanceTimersByTime(2000)); + expect(onClose).not.toHaveBeenCalled(); + fireEvent.pointerLeave(card); + act(() => vi.advanceTimersByTime(1000)); + expect(onClose).toHaveBeenCalledTimes(1); + }); it('renders nothing without a record', () => { const { container } = render( {}} />); expect(container.innerHTML).toBe(''); diff --git a/web/src/__tests__/WorkbenchFeeMarket.test.jsx b/web/src/__tests__/WorkbenchFeeMarket.test.jsx index 4b98717..f1e64e9 100644 --- a/web/src/__tests__/WorkbenchFeeMarket.test.jsx +++ b/web/src/__tests__/WorkbenchFeeMarket.test.jsx @@ -42,6 +42,19 @@ function view(chain, isMining = false) { const props = { coinName: 'FixtureCoin', targetSeconds: 10, selectedIndex: null, remining: null }; describe('workbench fee-market counts', () => { + it('describes only the visible activity tail, and reuses it during mining progress', () => { + const chain = createBlockchain({ participants: ['Miner Fixture'], miners: ['Miner Fixture'], miningDifficulty: 1 }); + for (let i = 0; i < 40; i++) mine(chain); + const sim = view(chain); + const original = sim.describeTx; + sim.describeTx = vi.fn(original); + const { rerender } = render(); + // The selected genesis is separate; Activity needs at most its 12 visible payments. + expect(sim.describeTx.mock.calls.filter(([tx]) => tx !== chain.blockArray[0].transactions[0]).length).toBeLessThanOrEqual(12); + sim.describeTx.mockClear(); + rerender(); + expect(sim.describeTx.mock.calls.filter(([tx]) => tx !== chain.blockArray[0].transactions[0])).toHaveLength(0); + }); it('shows five candidate payments before and during mining, with eight still pending', () => { const chain = fundedBatch(); const { rerender } = render(); diff --git a/web/src/components/HintLayer.css b/web/src/components/HintLayer.css index c1d2b93..e4e3c00 100644 --- a/web/src/components/HintLayer.css +++ b/web/src/components/HintLayer.css @@ -6,17 +6,23 @@ border-radius: var(--r-md); border: 1px solid var(--line-3); background: var(--overlay); color: var(--text-2); box-shadow: 0 18px 40px -10px var(--shadow); font: 13px/19px var(--ui); text-align: left; white-space: normal; overflow: visible; - pointer-events: none; + pointer-events: auto; animation: hint-layer-in 120ms ease-out; } .hint-layer-title { display: block; margin-bottom: 2px; color: var(--text); font-weight: 600; } .hint-layer-text { display: block; } +/* Keep the 10px crossing between the control and its bubble hoverable. */ +.hint-layer::after { content: ""; position: absolute; left: 0; right: 0; height: 10px; } +.hint-layer[data-side="below"]::after { top: -10px; } +.hint-layer[data-side="above"]::after { bottom: -10px; } +.hint-layer[data-side="left"]::after { top: 0; left: auto; right: -10px; width: 10px; height: 100%; } .hint-layer::before { content: ""; position: absolute; left: calc(var(--hint-arrow, 50%) - 5px); width: 10px; height: 10px; transform: rotate(45deg); background: var(--overlay); } .hint-layer[data-side="below"]::before { top: -6px; border-left: 1px solid var(--line-3); border-top: 1px solid var(--line-3); } .hint-layer[data-side="above"]::before { bottom: -6px; border-right: 1px solid var(--line-3); border-bottom: 1px solid var(--line-3); } +.hint-layer[data-side="left"]::before { left: auto; right: -6px; top: 12px; border-right: 1px solid var(--line-3); border-top: 1px solid var(--line-3); } @keyframes hint-layer-in { from { opacity: 0; } to { opacity: 1; } } @media (prefers-reduced-motion: reduce) { .hint-layer { animation: none; } } diff --git a/web/src/components/HintLayer.jsx b/web/src/components/HintLayer.jsx index f9eeb55..d5f4803 100644 --- a/web/src/components/HintLayer.jsx +++ b/web/src/components/HintLayer.jsx @@ -90,16 +90,27 @@ export function HintLayer() { }; const onPointerOver = event => { if (event.pointerType === 'touch') return; + if (bubbleRef.current?.contains(event.target)) { clearTimeout(s.timer); s.timer = null; return; } const target = targetOf(event.target); - if (!target || target === s.target || target === s.suppressed) return; + if (target && target === s.target) { clearTimeout(s.timer); s.timer = null; return; } + if (!target || target === s.suppressed) return; schedule(target); }; const onPointerOut = event => { if (event.pointerType === 'touch') return; + const bubble = bubbleRef.current; + if (bubble?.contains(event.relatedTarget)) return; + if (bubble?.contains(event.target)) { + if (!s.target?.contains(event.relatedTarget)) hide(); + return; + } const from = targetOf(event.target); if (!from || from.contains(event.relatedTarget)) return; if (from === s.suppressed) s.suppressed = null; - if (from === s.target || !s.target) hide(); + if (from === s.target || !s.target) { + if (from.closest('.top-bar-menu')) { clearTimeout(s.timer); s.timer = setTimeout(hide, 200); } + else hide(); + } }; const onFocusIn = event => { const target = targetOf(event.target); @@ -171,13 +182,28 @@ export function HintLayer() { const viewW = document.documentElement.clientWidth || window.innerWidth; const viewH = window.innerHeight; const below = rect.bottom + GAP + height <= viewH - EDGE || rect.top - GAP - height < EDGE; - const top = below ? rect.bottom + GAP : rect.top - GAP - height; + let top = below ? rect.bottom + GAP : rect.top - GAP - height; const center = rect.left + rect.width / 2; - const left = Math.max(EDGE, Math.min(center - width / 2, viewW - EDGE - width)); + let left = Math.max(EDGE, Math.min(center - width / 2, viewW - EDGE - width)); + let side = below ? 'below' : 'above'; + // A menu explanation must leave the other actions clickable. On narrow + // screens it sits below the menu; on a desktop it sits beside it. + const menu = shown.target.closest('.top-bar-menu')?.getBoundingClientRect(); + if (menu) { + if (menu.left - GAP - width >= EDGE) { + left = menu.left - GAP - width; + top = Math.max(EDGE, Math.min(rect.top, viewH - EDGE - height)); + side = 'left'; + } else { + const underMenu = menu.bottom + GAP + height <= viewH - EDGE; + top = underMenu ? menu.bottom + GAP : Math.max(EDGE, menu.top - GAP - height); + side = underMenu ? 'below' : 'above'; + } + } bubble.style.top = `${Math.round(top)}px`; bubble.style.left = `${Math.round(left)}px`; bubble.style.setProperty('--hint-arrow', `${Math.round(Math.max(12, Math.min(center - left, width - 12)))}px`); - bubble.dataset.side = below ? 'below' : 'above'; + bubble.dataset.side = side; }, [shown]); // Every way out of explain mode starts with a tap (which closes the bubble) or Escape. diff --git a/web/src/components/workbench/ChainBand.css b/web/src/components/workbench/ChainBand.css index 936ad6a..d1e819e 100644 --- a/web/src/components/workbench/ChainBand.css +++ b/web/src/components/workbench/ChainBand.css @@ -286,6 +286,7 @@ .chain-band-tip.is-end { left: auto; right: -12px; } .chain-band-tip.is-end::before { left: auto; right: 40px; } .chain-band-tile:hover .chain-band-tip, .chain-band-tile-face:focus-visible ~ .chain-band-tip, .chain-band-tip:focus-within { display: block; } +.chain-band-tile.is-tip-dismissed .chain-band-tip, .chain-band-link.is-tip-dismissed .chain-band-ltip { display: none; } .chain-band-tile:hover, .chain-band-tile:has(.chain-band-tile-face:focus-visible), .chain-band-tile:has(.chain-band-tip:focus-within) { z-index: 31; } .chain-band-tip-head { display: flex; align-items: center; gap: var(--s-3); margin-bottom: 6px; diff --git a/web/src/components/workbench/ChainBand.jsx b/web/src/components/workbench/ChainBand.jsx index 0504fa8..73f84ec 100644 --- a/web/src/components/workbench/ChainBand.jsx +++ b/web/src/components/workbench/ChainBand.jsx @@ -187,6 +187,8 @@ function FullHash({ hash, miss = 0 }) { function Tile({ view, views, newest, selected, pinned, repairPosition, shade, onSelect, tipEnd, events, pace }) { const tipId = useId(); + const [dismissed, setDismissed] = useState(false); + const face = useRef(null); const state = stateOf(view); const mismatch = view.status === 'hash-mismatch'; const classes = ['chain-band-tile', newest && 'is-newest', selected && (pinned ? 'is-selected' : 'is-current'), @@ -196,12 +198,14 @@ function Tile({ view, views, newest, selected, pinned, repairPosition, shade, on const shownHash = mismatch ? view.computedHash : view.storedHash; const miss = mismatch ? view.difficulty : 0; return ( -
+
setDismissed(false)} onFocusCapture={() => setDismissed(false)} + onKeyDown={event => { if (event.key === 'Escape') { event.stopPropagation(); face.current?.focus(); setDismissed(true); } }}> {repairPosition ? ( ) : null} - {state !== 'broken' && } -