diff --git a/README.md b/README.md index a98bb48..9d5e62f 100644 --- a/README.md +++ b/README.md @@ -118,33 +118,53 @@ A few things to ask once it is connected: - **33 components.** Load balancers, caches, databases, queues and workers, plus CDNs, rate limiters, circuit breakers, read replicas, shards, autoscalers, stream brokers, WebSocket gateways, serverless functions, bulkheads and more. -- **23 worked examples.** Sixteen teaching scenarios that each isolate one failure mode, and seven +- **24 worked examples.** Seventeen teaching scenarios that each isolate one failure mode, and seven reconstructions of real architectures. - **A real discrete-event engine.** Finite server slots, gamma-distributed service times and measured percentiles, with no formula standing in for the simulation. -- **Chaos controls.** Crash a node, slow it down, force an error rate, or cut a single link, then - watch the failure travel. -- **Deterministic runs.** The same seed and topology replay identically, every time. +- **Faults.** Crash a node, restart it, crash one instance, slow it, stall it or make it glitch. + Cut a connection, drop packets on it, deliver requests twice or lose the answers coming back. + Every fault can be undone, and Reset plays them again at the same moments. +- **Can you break it?** Say what has to hold, and a search throws faults at the design until it + fails, then shrinks the break to the fewest faults that still cause it. Watch it as a replay or + send it as a link. +- **Correctness checks.** Beyond up and fast: was a payment charged twice, was a saved write lost, + did a client read its own write? Follow the first request that broke the rule, step by step. +- **18 challenges.** Designs that fail as they start, a check that plays three fixed runs of + traffic, slot budgets, and a workspace of their own, so your design stays untouched. +- **Six real incidents.** Published outages rebuilt small, each with its source. Watch one happen, + then fix it. +- **A learning path.** Every example, challenge and outage in 48 steps, with a task card on each + example, a first-visit tour, Find the problem and What just happened. +- **Traffic shapes.** Steady, ramp, spike, daily cycle, bursty and thundering herd, with an uneven + key spread for hot shards, and load shown as a multiple of where the design started. +- **Live diagram.** Requests move along the connections coloured by how they ended, with retries, + losses and full waiting lines marked, and each client's own p99 and failure rate. +- **Deterministic runs.** The same seed and topology replay identically, every time, and a replay + link plays the exact run for someone else. - **Explanations built in.** Every metric and unit has a plain-language definition one hover away. - **Share links and design files.** Send a design as an encrypted link, or save it as a `.breakscale` file that opens on the website and in VS Code. +- **Made to use quickly.** A Ctrl+K command palette, context menus, copy and paste, speed control, + a pinned run to compare against, and a presenting mode for teaching a room. - **Private by design.** No account, and your designs never leave your machine unless you share them. The website counts page views with Vercel's cookie-free analytics; the extension and the MCP server have no analytics at all. ## Examples -| Example | What it teaches | -| ------------------- | ---------------------------------------------------------------- | -| Single Server | Latency climbs sharply as the database fills up | -| Load Balanced | Three servers share the load, but all still talk to one database | -| Cache Aside | Lower the hit rate and the database takes the whole load | -| Async Workers | The backlog grows when workers fall behind, and drains after | -| Retry Storm | Retries multiply the load that caused them | -| Rate Limited API | Serves slightly less, but what it serves stays fast | -| Circuit Breaker | Break the dependency, watch the circuit trip, then recover | -| Sharded Database | One shard melts while the average still looks healthy | -| Autoscaling Service | Requests fail in the gap while new servers boot | +| Example | What it teaches | +| --------------------- | ---------------------------------------------------------------- | +| Single Server | Latency climbs sharply as the database fills up | +| Load Balanced | Three servers share the load, but all still talk to one database | +| Cache Aside | Lower the hit rate and the database takes the whole load | +| Async Workers | The backlog grows when workers fall behind, and drains after | +| Retry Storm | Retries multiply the load that caused them | +| Rate Limited API | Serves slightly less, but what it serves stays fast | +| Circuit Breaker | Break the dependency, watch the circuit trip, then recover | +| Sharded Database | One shard melts while the average still looks healthy | +| Autoscaling Service | Requests fail in the gap while new servers boot | +| Checkout and payments | A retry after a slow answer charges some customers twice | Plus **Netflix**, **Spotify**, **Discord**, **Uber**, **Twitter/X**, **Stripe** and **WhatsApp**, reconstructed from published engineering material. Each one says what it models and what it @@ -157,7 +177,8 @@ the topology, and a handful of details are what make its results worth trusting. **Finite server slots.** A component's `capacity` is how many requests it can work on at once, and `instances` is how many copies of it are running. Anything beyond `instances × capacity` waits in a -real FIFO queue, and anything beyond the queue limit is shed. +real FIFO queue, and anything beyond the queue limit is shed. A service, worker or lambda holds its +slot while it waits on the parts it calls, so a slow database fills the servers in front of it too. **Service time variance.** Service time is a mean plus a coefficient of variation, sampled from a gamma distribution. Variance is what pulls tail latency away from the average, so it is modelled @@ -212,6 +233,20 @@ for (let i = 0; i < 600; i += 1) engine.advance(1000 / 60); console.log(engine.snapshot().system); ``` +The search behind Can you break it? runs from a script too. `verify` takes a design and a goal and +returns the smallest set of faults it found that breaks the goal, with a replay of the run: + +```ts +import { verify } from './src/sim/verify'; +import { PRESETS } from './src/sim/presets'; + +const design = PRESETS.find((p) => p.id === 'checkout')!.topology; +const v = verify(design, { metric: 'doubleCharges', max: 0 }, { chargeable: ['pay'] }); +if (v.status === 'broken') console.log(v.schedule, v.measured.actual); +``` + +The [docs](https://docs.breakscale.tech) cover every goal and option. + ## Contributing - Found a bug, or a number that looks wrong? [Open an issue](https://github.com/workersio/breakscale/issues). diff --git a/mcp/src/breakIt.test.ts b/mcp/src/breakIt.test.ts index 7f050f0..a5af8c9 100644 --- a/mcp/src/breakIt.test.ts +++ b/mcp/src/breakIt.test.ts @@ -7,7 +7,7 @@ import { measureSeed, } from '../../src/sim/breakit'; import { Engine } from '../../src/sim/engine'; -import { PRESETS } from '../../src/sim/presets'; +import { PRESETS, defaultConfig } from '../../src/sim/presets'; import type { Topology } from '../../src/sim/types'; import { HOSTED_BREAK, LOCAL_BREAK, breakDesign } from './breakIt'; import type { BreakLimits, BreakRequest } from './breakIt'; @@ -166,3 +166,103 @@ describe('break_it', () => { expect(out.text).toMatch(/^Stopped after \d+ schedules? without an answer/); }); }); + +describe('break_it: correctness', () => { + const checkout = (): Topology => ({ + nodes: [ + { + id: 'client', + kind: 'client', + label: 'Client', + x: 0, + y: 0, + config: { ...defaultConfig('client'), rps: 100 }, + }, + { + id: 'checkout', + kind: 'service', + label: 'Checkout', + x: 0, + y: 0, + config: { + ...defaultConfig('service'), + capacity: 64, + serviceMs: 5, + timeoutMs: 300, + retries: 2, + }, + }, + { + id: 'pay', + kind: 'service', + label: 'Payment Provider', + x: 0, + y: 0, + config: { + ...defaultConfig('service'), + capacity: 64, + serviceMs: 100, + serviceCv: 0.3, + }, + }, + ], + edges: [ + { id: 'a', from: 'client', to: 'checkout', weight: 1 }, + { id: 'b', from: 'checkout', to: 'pay', weight: 1 }, + ], + }); + + it('names the request charged twice and tells its story', async () => { + const text = await said(checkout(), { + goal: { metric: 'doubleCharges', max: 0 }, + chargeable: ['pay'], + }); + expect(text).toContain('Broke it with one fault'); + expect(text).toMatch( + /Request \d+ was charged twice at Payment Provider \(id 'pay'\)/, + ); + expect(text).toMatch(/What happened to request \d+, on the replay's clock:/); + expect(text).toMatch( + /\d+\.\d\ds Payment Provider \(id 'pay'\) charges the card again\. \(charged again\)/, + ); + }, 60_000); + + it('asks for the paying part when nothing is marked', async () => { + const out = await breakDesign( + checkout(), + { goal: { metric: 'doubleCharges', max: 0 } }, + LOCAL_BREAK, + APP, + ); + expect(out.ok).toBe(false); + if (!out.ok) expect(out.errors.join(' ')).toContain('Pass chargeable'); + }); + it('says a hold comes from nothing retrying when nothing does', async () => { + const t = checkout(); + const noRetry = { + ...t, + nodes: t.nodes.map((n) => + n.id === 'checkout' ? { ...n, config: { ...n.config, retries: 0 } } : n, + ), + }; + const text = await said(noRetry, { + goal: { metric: 'doubleCharges', max: 0 }, + chargeable: ['pay'], + budget: 5, + kinds: ['crash', 'crash-instance', 'slow', 'errors', 'cut'], + }); + expect(text).toContain('Held.'); + expect(text).toContain( + "Nothing on the way to Payment Provider (id 'pay') sends a call again", + ); + }, 60_000); + + it('names the stale read and tags it in the story', async () => { + const text = await said(preset('read-replicas'), { + goal: { metric: 'staleReads', max: 0 }, + }); + expect(text).toContain('It already misses the goal with no faults'); + expect(text).toMatch(/Request \d+ read a record at /); + expect(text).toContain('(stale)'); + }, 60_000); +}); diff --git a/mcp/src/breakIt.ts b/mcp/src/breakIt.ts index e2f80c2..a2e98a9 100644 --- a/mcp/src/breakIt.ts +++ b/mcp/src/breakIt.ts @@ -1,15 +1,23 @@ import { ShareLinkTooLargeError, buildShareUrl } from '../../src/share'; import type { AttackKind } from '../../src/sim/breakit'; -import { verifySteps } from '../../src/sim/verify'; +import { isCorrectnessGoal } from '../../src/sim/challenge'; +import type { Violation } from '../../src/sim/oplog'; +import { followRequest, verifySteps } from '../../src/sim/verify'; import type { Verdict, VerifyGoal, VerifyOptions } from '../../src/sim/verify'; import type { FailureReason, Topology } from '../../src/sim/types'; import { baselineSentence, + checkedLine, + clock, closestLine, effectSentence, + evidenceSentence, goalLine, + nothingRetriesLine, scheduleSentence, singlePointLines, + timelineWords, + TRUNCATED_LINE, triedLine, } from '../../src/components/breakCopy'; import type { Names } from '../../src/components/breakCopy'; @@ -67,6 +75,7 @@ export interface BreakRequest { budget?: number; seed?: number; includeSinglePoints?: boolean; + chargeable?: string[]; } export type BreakOutcome = @@ -102,6 +111,31 @@ function failures(byReason: Partial>): string | nu ); } +/** A story line's tag, after the line. */ +const TAG = { 'charged-again': 'charged again', lost: 'lost', stale: 'stale' } as const; + +/** Most lines of a request's story one answer carries. */ +const STORY_LINES = 24; + +/** + * The earliest violation of a correctness goal, and the request's story + * from the replay, a line per step. + */ +function evidence(v: Violation, replay: Topology, names: Names): string[] { + const tl = followRequest(replay, v.rid); + const lines = ['', evidenceSentence(v, names)]; + if (tl === null) return lines; + const story = timelineWords(tl, names, v).map( + (l) => `${clock(l.t)} ${l.text}${l.tag === null ? '' : ` (${TAG[l.tag]})`}`, + ); + lines.push(`What happened to request ${v.rid}, on the replay's clock:`); + lines.push(...story.slice(0, STORY_LINES)); + if (story.length > STORY_LINES) { + lines.push(`And ${story.length - STORY_LINES} more steps.`); + } + return lines; +} + /** Search the design for a schedule of faults that misses the goal, and say what happened. */ export async function breakDesign( design: Topology, @@ -132,6 +166,7 @@ export async function breakDesign( ...(req.includeSinglePoints !== undefined ? { includeSinglePoints: req.includeSinglePoints } : {}), + ...(req.chargeable !== undefined ? { chargeable: req.chargeable } : {}), }; const it = verifySteps(design, goal, opts); @@ -168,6 +203,10 @@ export async function breakDesign( ); const why = failures(m.failuresByReason); if (why) lines.push(why); + if (m.truncated === true) lines.push(TRUNCATED_LINE); + if (verdict.first !== undefined && verdict.replay !== undefined) { + lines.push(...evidence(verdict.first, verdict.replay, names)); + } break; } case 'held': { @@ -199,6 +238,14 @@ export async function breakDesign( `That was the whole budget. Up to ${limits.maxBudget} schedules can be tried.`, ); } + if (verdict.nothingRetries === true) { + const charged = design.nodes + .filter((n) => n.config.chargeable === 1 || req.chargeable?.includes(n.id)) + .map((n) => n.id); + lines.push(nothingRetriesLine(charged, names)); + } + if (verdict.checked !== undefined) lines.push(checkedLine(goal, verdict.checked)); + if (verdict.truncated === true) lines.push(TRUNCATED_LINE); const c = verdict.closest; // closestLine's "yet" is for the panel's live progress; this answer is final. lines.push( @@ -226,6 +273,9 @@ export async function breakDesign( ? 'No smaller schedule breaks it.' : 'A smaller schedule might still break it.'), ); + if (verdict.first !== undefined) { + lines.push(...evidence(verdict.first, verdict.replay, names)); + } try { lines.push( '', @@ -245,7 +295,11 @@ export async function breakDesign( const points = singlePointLines(verdict.singlePoints, names); if (points.length > 0) { lines.push('', 'Single points of failure:', ...points); - if (!req.includeSinglePoints && verdict.status !== 'alreadyBroken') { + if ( + !req.includeSinglePoints && + verdict.status !== 'alreadyBroken' && + !isCorrectnessGoal(verdict.goal) + ) { lines.push( 'Losing one of these breaks any goal, so the search never crashed, failed or cut them whole. It could still slow them and take down single machines. includeSinglePoints true crashes and cuts them too.', ); diff --git a/mcp/src/design.test.ts b/mcp/src/design.test.ts index 7be43c2..5357714 100644 --- a/mcp/src/design.test.ts +++ b/mcp/src/design.test.ts @@ -142,7 +142,7 @@ describe('buildTopology', () => { expect(r.errors).toEqual([ "faults[0] names node 'cache', but there is no such node.", 'faults[1] has atMs -5; use a time in milliseconds, 0 or more.', - 'faults[2] has kind "boom"; use crash, slow, errors, partition, crash-instance.', + 'faults[2] has kind "boom"; use crash, slow, errors, partition, crash-instance, restart, pause.', "faults[3] names edge 'users->db', but there is no such edge.", ]); expect(buildTopology({ ...chain, faults: 'crash it' }).ok).toBe(false); diff --git a/mcp/src/readme.ts b/mcp/src/readme.ts index d8477ad..d1e3a77 100644 --- a/mcp/src/readme.ts +++ b/mcp/src/readme.ts @@ -219,13 +219,26 @@ is simulated time in milliseconds from the start of the run. takes a node down. Other kinds: \`slow\` with \`"opts": { "factor": 3 }\` (three times slower), \`errors\` with \`"opts": { "rate": 0.2 }\` (20% of requests fail), \`partition\` (its outgoing edges stop carrying - requests), and \`crash-instance\` (one of its \`instances\` dies and the + requests), \`crash-instance\` (one of its \`instances\` dies and the rest keep serving, which is how scaling out survives losing a machine - and scaling up does not). + and scaling up does not), and \`restart\` with + \`"opts": { "downMs": 2000 }\` (down like a crash, then back by itself + 2 seconds later), and \`pause\` with \`"opts": { "pauseMs": 2000 }\` + (it stops for 2 seconds and then carries on: nothing fails or is lost, + its work finishes late, and callers whose timeouts fire meanwhile may + send the request again). - \`{ "atMs": 20000, "action": "clear", "nodeId": "db" }\` heals it. - \`{ "atMs": 5000, "action": "cut", "edgeId": "api->db" }\` cuts one edge and \`restore\` reconnects it. An edge's id is \`from->to\` unless you gave it one. +- \`{ "atMs": 5000, "action": "duplicate", "edgeId": "api->pay", "rate": 0.05 }\` + makes an edge deliver 5% of the requests that cross it twice, and + \`undup\` stops it. The second copy does the work again at the far end, + and nobody hears its answer. +- \`{ "atMs": 5000, "action": "cut-replies", "edgeId": "api->pay" }\` makes + an edge lose every answer coming back across it, and \`restore-replies\` + lets them through again. Requests still cross and do their work; the + caller waits until its own timeout, or for good without one. \`seed\` (a whole number, default 1) picks the random draws. The same design, seed and faults always give the same numbers. @@ -237,6 +250,35 @@ It tries crashes, slowdowns, errors and cut edges, makes the schedule that breaks it as small as it can, and returns a link that replays the run. It only slows a part every request passes through, since losing one breaks any goal; \`includeSinglePoints: true\` crashes and cuts those too. +For the three goals below it crashes and cuts them anyway, since an +outage alone cannot break those. + +Three goals are about the data rather than speed, and a run where nothing +gets through does not break them: + +- \`{ "metric": "doubleCharges", "max": 0 }\` with \`"chargeable": ["pay"]\`: + every payment is charged at most once. A caller that times out and + retries while the first try is still running is the usual way to break + it, and an edge delivering a request twice is another. For this goal + the search also tries \`duplicate\` and \`cut-replies\` on each edge + and \`pause\` on each part. Setting \`idempotencyKeys: 1\` on the + paying part fixes all of them. +- \`{ "metric": "lostAckedWrites", "max": 0 }\`: no write the client was + told was saved is lost. Two parts say saved before it is safe: a + write-behind cache, and a \`db\` or \`replica\` with \`flushEveryMs\` + above 0, which answers before the write is on disk and has it there + that many ms later. A crash or restart of the whole store loses the + writes still in memory. The design needs one of them. A job a queue + accepted and then lost is counted by \`lostJobs\` instead. +- \`{ "metric": "staleReads", "max": 0 }\`: read your writes. Once a client + is told a write was saved, its later reads of that record show it. A + replica set with replication lag, or a search index with a refresh + delay, breaks it, usually with no faults at all. \`freshReads: 1\` on + a replica set fixes it: a read of a key the replicas are still behind + on goes to the primary, and takes one of its write slots. + +For these the answer names the first request that broke the rule and +tells its story: each call, timeout, retry and charge, with its time. ## Saving to a file diff --git a/mcp/src/server.ts b/mcp/src/server.ts index 2d628fd..10f3f8b 100644 --- a/mcp/src/server.ts +++ b/mcp/src/server.ts @@ -180,8 +180,9 @@ export function createServer({ description: 'Searches for a schedule of faults (crashes, slowdowns, errors, cut edges) that makes a design miss a goal, then makes the schedule as small as it can. ' + 'Returns the verdict in words and, when it breaks, a breakscale.tech link that replays the run. ' + + 'For the correctness goals, doubleCharges, lostAckedWrites and staleReads, it also names the first request that broke the rule and tells its story step by step. ' + `Deterministic: the same design, goal and options always give the same answer. Tries at most ${breakLimits.maxBudget} schedules from its budget per call, then plays a few more to make a break smaller. ` + - 'By default it never crashes, fails or cuts a single point of failure whole; includeSinglePoints turns that on. ' + + 'By default it never crashes, fails or cuts a single point of failure whole, except for the correctness goals, which an outage cannot break; includeSinglePoints turns that on. ' + 'Takes the same design as create_view, plus the goal.', inputSchema: z.object({ ...design, @@ -189,17 +190,21 @@ export function createServer({ // in words, where an enum would answer with a JSON path. goal: z .object({ - metric: z.string().describe(`One of ${VERIFY_METRICS.join(', ')}`), + metric: z + .string() + .describe( + `One of ${VERIFY_METRICS.join(', ')}. doubleCharges counts payments charged more than once, such as a retry after a timeout where both tries charge; it needs chargeable. lostAckedWrites counts writes the client was told were saved that never reached storage; it needs a write-behind cache, or a db or replica set with flushEveryMs above 0. staleReads counts reads that missed a write the same client was told was saved; it needs a replica set or a search index`, + ), max: z .number() .describe( - 'No more than this: percent for errorRate (1 means 1%), ms for p99 and p95, a count for lostWrites and lostJobs', + 'No more than this: percent for errorRate (1 means 1%), ms for p99 and p95, a count for lostWrites, lostJobs, doubleCharges, lostAckedWrites and staleReads', ), route: z .string() .optional() .describe( - "A client's id, to hold the goal for that client's requests only. Not for lostWrites or lostJobs", + "A client's id, to hold the goal for that client's requests only. Not for lostWrites, lostJobs, doubleCharges, lostAckedWrites or staleReads", ), }) .describe('What has to hold'), @@ -229,6 +234,12 @@ export function createServer({ .describe( 'Also crash, fail and cut the parts every request passes through. Default false: those break any goal', ), + chargeable: z + .array(z.string()) + .optional() + .describe( + 'For doubleCharges: ids of the parts where every finished call charges money, such as a payment provider', + ), }), annotations: { title: 'Try to break a design', readOnlyHint: true }, }, diff --git a/src/App.challenge.test.tsx b/src/App.challenge.test.tsx index 42b41ee..f70bc3d 100644 --- a/src/App.challenge.test.tsx +++ b/src/App.challenge.test.tsx @@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { act } from 'react'; import { createRoot, type Root } from 'react-dom/client'; import App from './App'; +import { PHONE_QUERY } from './phoneQuery'; import { CHALLENGES_KEY } from './challengeWorkspace'; import { saveDesign } from './savedDesigns'; import { buildDesignFile } from './designFile'; @@ -196,6 +197,20 @@ describe('starting a challenge', () => { expect(document.activeElement).toBe(panel()?.querySelector('h2')); }); + it('says why F does nothing, instead of doing nothing', () => { + mount(); + startChallenge(hold.name); + act(() => { + document.body.dispatchEvent( + new KeyboardEvent('keydown', { key: 'f', bubbles: true }), + ); + }); + expect(document.querySelector('.app-toast')?.textContent).toBe( + 'Can you break it? is off during a challenge.', + ); + expect(document.querySelector('.chal.brk')).toBeNull(); + }); + it('holds the load still, and hides the suggested fix', () => { mount(); startChallenge(hold.name); @@ -414,18 +429,20 @@ describe('across a reload', () => { expect(canvasIds()).toEqual(['mine-client', 'mine-svc']); }); - it('opens a brief from a challenge link, and takes the link off the URL', () => { + it('opens a brief from a challenge link, which stays on the URL while it is open', () => { window.history.replaceState(null, '', '/?challenge=keep-it-warm'); mount(); expect(panel()?.textContent).toContain(challengeById('keep-it-warm')!.name); advance(10); - expect(window.location.search).toBe(''); + expect(window.location.search).toBe('?challenge=keep-it-warm'); // Boot moved the reader out of their own design, so it says so. expect(document.querySelector('.app-toast')?.textContent).toBe( 'Your design is set aside. It comes back when you leave.', ); press(must('Back to my design')); expect(canvasIds()).toEqual(['mine-client', 'mine-svc']); + // Left, the address no longer names it, so a reload does not reopen it. + expect(window.location.search).toBe(''); }); it('lets a share link open over a brief without touching the reader design', async () => { @@ -512,7 +529,10 @@ describe('the check', () => { startChallenge(hold.name); expect(document.querySelector('.chal-chip')?.textContent).toBe('Not checked yet'); settleCheck(); - expect(document.querySelector('.chal-chip')?.textContent).toBe('Not yet'); + // The design is still the one the brief starts from, so its miss is + // the problem as set, not a failed attempt. + expect(document.querySelector('.chal-chip')?.textContent).toBe('As it starts'); + expect(document.querySelector('.chal-verdict')?.className).toContain('is-base'); expect(panel()?.textContent).not.toContain(hold.lesson); press(must('Details')); expect(byName('Watch run 1')).not.toBeNull(); @@ -538,9 +558,14 @@ describe('the check', () => { set.call(input, String(start + 4)); input.dispatchEvent(new Event('input', { bubbles: true })); }); + // Folded beside the inspector while the reader works. + expect(document.querySelector('.chal-body')?.hidden).toBe(true); settleCheck(); expect(document.querySelector('.chal-chip')?.textContent).toBe('Passed'); expect(panel()?.textContent).toContain(hold.lesson); + // The inspector is open beside the brief, and the pass still opens it. + expect(document.querySelector('.ins')).not.toBeNull(); + expect(document.querySelector('.chal-body')?.hidden).toBe(false); expect(storedChallenges().progress[hold.id]?.version).toBe(hold.version); // Watching the run keeps the pass: the design is the same one. @@ -556,4 +581,45 @@ describe('the check', () => { openMenu('Challenges'); expect(must(hold.name).textContent).toContain('Passed'); }); + + it('on a phone, takes the inspector sheet down so the pass can be seen', () => { + vi.stubGlobal( + 'matchMedia', + (query: string) => + ({ + matches: query === PHONE_QUERY, + media: query, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + }) as unknown as MediaQueryList, + ); + mount(); + startChallenge(hold.name); + press(document.querySelector('[data-hit="node"][data-kind="db"]')!); + const inspecting = () => + document.querySelector('.app-body')?.classList.contains('has-inspector'); + expect(inspecting()).toBe(true); + const label = [...document.querySelectorAll('.ins label')].find( + (l) => l.textContent?.trim() === 'Slots per instance', + ); + const input = document.getElementById( + label!.getAttribute('for')!, + ) as HTMLInputElement; + act(() => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call( + input, + String(Number(input.value) + 4), + ); + input.dispatchEvent(new Event('input', { bubbles: true })); + }); + settleCheck(); + expect(document.querySelector('.chal-chip')?.textContent).toBe('Passed'); + expect(inspecting()).toBe(false); + expect(document.querySelector('.chal-body')?.hidden).toBe(false); + // The part is still selected; tapping it brings its settings back. + press(document.querySelector('[data-hit="node"][data-kind="db"]')!); + expect(inspecting()).toBe(true); + }); }); diff --git a/src/App.contextMenu.test.tsx b/src/App.contextMenu.test.tsx new file mode 100644 index 0000000..c04b4bd --- /dev/null +++ b/src/App.contextMenu.test.tsx @@ -0,0 +1,405 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import App from './App'; +import { makeNode } from './sim/presets'; +import type { Topology } from './sim/types'; +import { LONG_PRESS_MS } from './components/pointerInput'; + +/** + * The canvas context menu, end to end: right-click and a held finger open + * it, a moved press or a second finger does not, and its rows go through + * the same paths as the keys (one undo step each, fresh ids on paste). + */ + +class FakePointerEvent extends MouseEvent { + pointerId: number; + pointerType: string; + isPrimary: boolean; + constructor( + type: string, + init: MouseEventInit & { pointerId?: number; pointerType?: string } = {}, + ) { + super(type, init); + this.pointerId = init.pointerId ?? 1; + this.pointerType = init.pointerType ?? 'mouse'; + this.isPrimary = true; + } +} + +const SESSION_KEY = 'breakscale.session.v1'; + +function ownDesign(): Topology { + const client = { ...makeNode('client', 0, 0), id: 'mine-client', label: 'My client' }; + const svc = { ...makeNode('service', 240, 0), id: 'mine-svc', label: 'My service' }; + const db = { ...makeNode('db', 480, 0), id: 'mine-db', label: 'My db' }; + return { + nodes: [client, svc, db], + edges: [ + { id: 'mine-client->mine-svc', from: client.id, to: svc.id, weight: 1 }, + { id: 'mine-svc->mine-db', from: svc.id, to: db.id, weight: 1 }, + ], + }; +} + +let container: HTMLDivElement; +let root: Root; + +function mount(): void { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + act(() => root.render()); +} + +type At = { x: number; y: number }; +const ptr = ( + type: string, + el: Element, + at: At, + extra: { pointerId?: number; pointerType?: string; buttons?: number } = {}, +) => + act(() => { + el.dispatchEvent( + new FakePointerEvent(type, { + bubbles: true, + cancelable: true, + button: 0, + buttons: type === 'pointerup' ? 0 : 1, + clientX: at.x, + clientY: at.y, + pointerType: 'mouse', + ...extra, + }), + ); + }); + +function click(el: Element): void { + const at = { x: 5, y: 5 }; + ptr('pointerdown', el, at); + ptr('pointerup', el, at); + act(() => { + el.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); + }); +} + +function rightClick(el: Element, at: At = { x: 40, y: 40 }): void { + act(() => { + el.dispatchEvent( + new MouseEvent('contextmenu', { + bubbles: true, + cancelable: true, + button: 2, + clientX: at.x, + clientY: at.y, + }), + ); + }); +} + +const wait = (ms: number) => act(() => vi.advanceTimersByTime(ms)); + +/** A finger resting on `el` for the long-press delay, then lifting. */ +function hold(el: Element, at: At = { x: 60, y: 60 }, lift = true): void { + ptr('pointerdown', el, at, { pointerType: 'touch' }); + wait(LONG_PRESS_MS + 10); + if (lift) ptr('pointerup', el, at, { pointerType: 'touch' }); +} + +function key(k: string, init: KeyboardEventInit = {}): void { + const target = document.activeElement ?? document.body; + act(() => { + target.dispatchEvent( + new KeyboardEvent('keydown', { + key: k, + bubbles: true, + cancelable: true, + ...init, + }), + ); + }); +} + +const node = (id: string) => + document.querySelector(`.cv-node[data-id="${id}"]`)!; +const nodes = () => [...document.querySelectorAll('.cv-node')]; +const edgeHit = (id: string) => + document.querySelector(`[data-hit="edge"][data-id="${id}"]`)!; +const surface = () => document.querySelector('.cv-surface')!; +const menu = () => document.querySelector('.cm'); +const rows = () => + [...(menu()?.querySelectorAll('[role="menuitem"]') ?? [])].map( + (b) => b.querySelector('.mn-label')?.textContent, + ); +function row(label: string): HTMLButtonElement { + const el = [ + ...(menu()?.querySelectorAll('[role="menuitem"]') ?? []), + ].find((b) => b.querySelector('.mn-label')?.textContent === label); + if (!el) throw new Error(`no row ${label}; rows are ${rows().join(', ')}`); + return el; +} +const toast = () => document.querySelector('.app-toast')?.firstChild?.textContent; +const undo = () => key('z', { ctrlKey: true, code: 'KeyZ' } as KeyboardEventInit); + +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = + true; + vi.useFakeTimers(); + vi.stubGlobal('PointerEvent', FakePointerEvent); + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.reject(new Error('offline'))), + ); + localStorage.clear(); + window.history.replaceState(null, '', '/'); + localStorage.setItem( + SESSION_KEY, + JSON.stringify({ topology: ownDesign(), rps: 50, presetId: null }), + ); +}); + +afterEach(() => { + act(() => root.unmount()); + container.remove(); + document.body.innerHTML = ''; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe('opening the menu', () => { + it('opens on a right-click, named for the part', () => { + mount(); + rightClick(node('mine-svc')); + expect(menu()).not.toBeNull(); + expect(menu()?.getAttribute('data-chrome')).not.toBeNull(); + expect(menu()?.getAttribute('aria-label')).toBe('My service'); + expect(rows()[0]).toBe('Inspect'); + expect(rows().some((r) => r?.startsWith('Crash'))).toBe(true); + // The right-click selected nothing, so no inspector opened under it. + expect(node('mine-svc').classList.contains('is-selected')).toBe(false); + }); + + it('opens on a held finger, and the lift does not select', () => { + mount(); + hold(node('mine-db')); + expect(menu()?.getAttribute('aria-label')).toBe('My db'); + expect(node('mine-db').classList.contains('is-selected')).toBe(false); + expect(menu()).not.toBeNull(); + }); + + it('does not open for a short tap, which still selects', () => { + mount(); + const at = { x: 60, y: 60 }; + ptr('pointerdown', node('mine-db'), at, { pointerType: 'touch' }); + wait(200); + ptr('pointerup', node('mine-db'), at, { pointerType: 'touch' }); + wait(LONG_PRESS_MS); + expect(menu()).toBeNull(); + expect(node('mine-db').classList.contains('is-selected')).toBe(true); + }); + + it('does not open when the finger moves first: that is a drag', () => { + mount(); + const before = node('mine-db').getAttribute('transform'); + ptr('pointerdown', node('mine-db'), { x: 60, y: 60 }, { pointerType: 'touch' }); + // A three-event flick: down, one big move, up, well inside the delay. + ptr('pointermove', node('mine-db'), { x: 160, y: 140 }, { pointerType: 'touch' }); + ptr('pointerup', node('mine-db'), { x: 160, y: 140 }, { pointerType: 'touch' }); + wait(LONG_PRESS_MS + 10); + expect(menu()).toBeNull(); + expect(node('mine-db').getAttribute('transform')).not.toBe(before); + }); + + it('does not open for two fingers: that is a pan or a pinch', () => { + mount(); + const s = surface(); + ptr('pointerdown', s, { x: 50, y: 50 }, { pointerType: 'touch', pointerId: 1 }); + wait(100); + ptr('pointerdown', s, { x: 150, y: 50 }, { pointerType: 'touch', pointerId: 2 }); + wait(LONG_PRESS_MS + 10); + expect(menu()).toBeNull(); + }); + + it('drags on from a hold, closing the menu', () => { + mount(); + const before = node('mine-db').getAttribute('transform'); + hold(node('mine-db'), { x: 60, y: 60 }, false); + expect(menu()).not.toBeNull(); + ptr('pointermove', node('mine-db'), { x: 140, y: 120 }, { pointerType: 'touch' }); + expect(menu()).toBeNull(); + ptr('pointerup', node('mine-db'), { x: 140, y: 120 }, { pointerType: 'touch' }); + expect(node('mine-db').getAttribute('transform')).not.toBe(before); + }); + + it('ignores the lift of the finger that opened it, landing on a row', () => { + mount(); + hold(node('mine-db')); + // Chrome sends the lift's click to the row now under the finger, with no + // press on the menu before it. + act(() => { + row('Delete').dispatchEvent( + new MouseEvent('click', { bubbles: true, cancelable: true, detail: 1 }), + ); + }); + expect(menu()).not.toBeNull(); + expect(node('mine-db')).not.toBeNull(); + }); + + it('opens from Shift+F10 and the menu key, which a Mac sends no contextmenu for', () => { + mount(); + act(() => node('mine-svc').focus()); + key('F10', { shiftKey: true }); + expect(menu()?.getAttribute('data-via')).toBe('keyboard'); + expect(document.activeElement?.textContent).toBe('Inspect'); + // Where the browser does follow with its own event, it is the same menu. + const first = menu(); + rightClick(node('mine-svc'), { x: 0, y: 0 }); + expect(menu()).toBe(first); + key('Escape'); + expect(document.activeElement).toBe(node('mine-svc')); + key('ContextMenu'); + expect(menu()).not.toBeNull(); + }); + + it('does not open twice when Android also sends its own contextmenu', () => { + mount(); + hold(node('mine-db'), { x: 60, y: 60 }, false); + const first = menu(); + rightClick(node('mine-db'), { x: 60, y: 60 }); + expect(menu()).toBe(first); + }); + + it('closes on Escape without clearing the selection, and hands focus back', () => { + mount(); + click(node('mine-svc')); + act(() => node('mine-svc').focus()); + // The menu key: no pointer, so it opens under the focused part. + rightClick(node('mine-svc'), { x: 0, y: 0 }); + expect(menu()?.getAttribute('data-via')).toBe('keyboard'); + expect(document.activeElement?.textContent).toBe('Inspect'); + key('ArrowDown'); + expect(document.activeElement?.textContent).toContain('Duplicate'); + key('End'); + expect(document.activeElement?.textContent).toBe('Delete'); + key('Escape'); + expect(menu()).toBeNull(); + expect(node('mine-svc').classList.contains('is-selected')).toBe(true); + expect(document.activeElement).toBe(node('mine-svc')); + }); +}); + +describe('what the rows do', () => { + it('duplicates as one undo step, with a fresh id and the same settings', () => { + mount(); + rightClick(node('mine-db')); + click(row('Duplicate')); + expect(menu()).toBeNull(); + expect(nodes()).toHaveLength(4); + const copy = nodes().find((n) => !n.dataset.id?.startsWith('mine-')); + expect(copy?.dataset.id).toMatch(/^db-\d+$/); + undo(); + expect(nodes()).toHaveLength(3); + }); + + it('copies on touch and pastes where the canvas was held', () => { + mount(); + hold(node('mine-svc')); + click(row('Copy')); + expect(toast()).toBe('Copied My service. Ctrl+V pastes at the pointer.'); + hold(surface(), { x: 300, y: 300 }); + expect(menu()?.getAttribute('aria-label')).toBe('Canvas'); + expect(rows()).toContain('Paste here'); + click(row('Paste here')); + // The paste reads the in-app copy, so no promise is left to settle. + expect(nodes()).toHaveLength(4); + const ids = nodes().map((n) => n.dataset.id); + expect(new Set(ids).size).toBe(4); + undo(); + expect(nodes()).toHaveLength(3); + }); + + it('copies a part with its connection to another copied part', () => { + mount(); + // Shift-click builds a two-part selection. + click(node('mine-svc')); + act(() => { + const at = { bubbles: true, cancelable: true, clientX: 5, clientY: 5 }; + node('mine-db').dispatchEvent( + new FakePointerEvent('pointerdown', { ...at, buttons: 1, shiftKey: true }), + ); + node('mine-db').dispatchEvent( + new FakePointerEvent('pointerup', { ...at, buttons: 0, shiftKey: true }), + ); + }); + rightClick(node('mine-db')); + expect(menu()?.getAttribute('aria-label')).toBe('2 components'); + click(row('Copy all 2')); + rightClick(surface(), { x: 400, y: 400 }); + click(row('Paste here')); + expect(nodes()).toHaveLength(5); + // Two old connections plus the copied one between the copies. + expect(document.querySelectorAll('[data-hit="edge"]')).toHaveLength(3); + }); + + it('crashes and fixes through the menu', () => { + mount(); + rightClick(node('mine-db')); + click(row('Crash')); + rightClick(node('mine-db')); + expect(rows()).toContain('Fix'); + expect(rows()).not.toContain('Crash'); + click(row('Fix')); + rightClick(node('mine-db')); + expect(rows()).toContain('Crash'); + }); + + it('cuts and restores a connection, and deletes it', () => { + mount(); + rightClick(edgeHit('mine-svc->mine-db')); + expect(menu()?.getAttribute('aria-label')).toBe('My service to My db'); + click(row('Cut connection')); + rightClick(edgeHit('mine-svc->mine-db')); + click(row('Restore connection')); + rightClick(edgeHit('mine-svc->mine-db')); + expect(rows()).toContain('Add 10% packet loss'); + click(row('Delete connection')); + expect(document.querySelector('[data-id="mine-svc->mine-db"]')).toBeNull(); + undo(); + expect(edgeHit('mine-svc->mine-db')).not.toBeNull(); + }); + + it('arms a link from Connect to, finished by a tap on the target', () => { + mount(); + hold(node('mine-client')); + click(row('Connect to…')); + expect(document.querySelector('.cv-hint')?.textContent).toBe( + 'Click a component to connect · Esc to cancel', + ); + click(node('mine-db')); + expect(edgeHit('mine-client->mine-db')).not.toBeNull(); + }); + + it('deletes with an undo in the toast', () => { + mount(); + rightClick(node('mine-db')); + click(row('Delete')); + expect(document.querySelector('.cv-node[data-id="mine-db"]')).toBeNull(); + expect(toast()).toBe('Deleted My db'); + }); +}); + +describe('duplicate and copy in the inspector', () => { + it('sit beside Delete and act on the selection', () => { + mount(); + click(node('mine-db')); + const foot = document.querySelector('.ins-foot')!; + const labels = [...foot.querySelectorAll('button')].map((b) => b.textContent); + expect(labels).toEqual(['Duplicate', 'Copy', 'Delete component']); + click(foot.querySelectorAll('button')[0]!); + expect(nodes()).toHaveLength(4); + click(document.querySelector('.ins-foot')!.querySelectorAll('button')[1]!); + expect(toast()).toMatch(/^Copied /); + }); +}); diff --git a/src/App.css b/src/App.css index a1a15a5..785098f 100644 --- a/src/App.css +++ b/src/App.css @@ -20,6 +20,8 @@ /* dvh keeps things reachable on mobile browsers whose toolbars collapse. */ height: 100dvh; overflow: hidden; + /* Not a scroll box either; see .app-body. */ + overflow: clip; background: var(--bg); } @@ -109,21 +111,31 @@ color: var(--text); } -/* With a star count, the button is no longer a pure icon square: it grows - into a pill just wide enough for the mark and the digits, per this app's - own rule that every number renders in the mono stack with tabular - figures. Width is the only thing that changes, so neighbouring buttons in - the bar never shift. */ -.app-source-link.has-stars { - width: auto; +/* A pill wide enough for the mark, a star and four digits ("1.2k" is the + widest formatStars returns below a million), whether or not the count has + arrived. The count is fetched after first paint, and a button that grew + when it landed pushed the load island narrower and slid Pause, Step and + Reset sideways under the reader's pointer. Reserved, the count fades into + room that was already there. 4ch of the mono stack, because that is the + face the digits are drawn in. Doubled to outrank .btn-icon's square. */ +.app-source-link.btn-icon { + width: calc( + var(--sp-2) + 16px + var(--sp-1) + 16px + 4px + 4ch + var(--sp-3) + 2 * var(--bw) + ); padding: 0 var(--sp-3) 0 var(--sp-2); gap: var(--sp-1); + font-family: var(--mono); + font-size: var(--fs-sm); } .app-source-stars { display: inline-flex; align-items: center; gap: 4px; + /* Right-aligned in a fixed slot, so the count-up from 0 never moves the + mark beside it. */ + justify-content: flex-end; + min-width: calc(16px + 4px + 4ch); height: 16px; /* matches the GitHub mark's box exactly, so the two sit on one line */ font-family: var(--mono); font-variant-numeric: tabular-nums; @@ -136,6 +148,12 @@ animation: app-stars-in var(--dur-slow) var(--ease-out); } +/* The word, in the text face: it is a name, not a figure. */ +.app-source-name { + font-family: var(--sans); + font-weight: var(--fw-med); +} + /* Positioning context for the glyph and its rays, sized to the GitHub mark's own 16px box so the two sit on one line: a visibly smaller glyph is what read as misaligned earlier even though both boxes were already @@ -261,9 +279,7 @@ gap: var(--sp-1); width: 56px; margin: 0; - font-size: var(--fs-label); - letter-spacing: var(--tr-label); - text-transform: uppercase; + font-size: var(--fs-sm); color: var(--text-faint); } @@ -345,12 +361,13 @@ /* On a phone the star count gives up its room to that label. */ @media (max-width: 639px) { - .app-source-stars { + .app-source-stars, + .app-source-name { display: none; } /* Back to the plain .btn-icon square. */ - .app-source-link.has-stars { + .app-source-link.btn-icon { width: 36px; padding: 0; } @@ -485,6 +502,11 @@ display: flex; min-height: 0; overflow: hidden; + /* clip, not just hidden: hidden still leaves a scroll box that focus(), + scrollIntoView and an iPad keyboard can scroll, and each did, by 13px, + sliding every panel under the bar until reload. Same fix as html and + body in index.css. */ + overflow: clip; /* Where the floating bar ends, plus a gap: its 12px offset, its 56px height, and 12px below it. Everything that must clear the bar reads this @@ -722,6 +744,20 @@ bottom: calc(var(--strip-shown) + var(--sp-3) * 2); } +/* The traffic key sits one row above the ledger and follows it. Not on a + phone, where the panels are sheets and the key keeps its own corner. */ +@media (min-width: 721px) and (min-height: 501px), + (min-width: 721px) and (pointer: fine), + (min-width: 721px) and (pointer: none) { + .app-body.has-library .cv-key { + left: calc(var(--rail-w) + var(--sp-3) * 2); + } + + .app-body.has-metrics .cv-key { + bottom: calc(var(--strip-shown) + var(--sp-3) * 2 + var(--key-lift)); + } +} + /* The format bar rides the same lift, one row higher so it clears the ledger and the zoom cluster it shares the foot of the canvas with. */ .app-body.has-metrics .cv-format { @@ -740,7 +776,8 @@ } .cv-ledger, -.cv-zoom { +.cv-zoom, +.cv-key { transition: left var(--dur-base) var(--ease), right var(--dur-base) var(--ease), @@ -794,7 +831,9 @@ /* The bar floats over the top of the canvas on a desktop, as opaque as any panel, and a tall diagram fitted to the full height had its top row under it. A phone's header is not over the canvas, so it needs nothing here. */ -@media (min-width: 721px) { +@media (min-width: 721px) and (min-height: 501px), + (min-width: 721px) and (pointer: fine), + (min-width: 721px) and (pointer: none) { .stage-safe { top: var(--bar-clear); } @@ -1011,6 +1050,58 @@ } } +/* -------------------------------------------------------------------------- + The compact bar: two rows of islands. + + Below the width where the three islands fit side by side, the load + island takes a row of its own under the other two, the same shape as the + phone header. Whether they fit is MEASURED (useBarFit.ts sets data-fit), + not read off a breakpoint: the old 1000px rule assumed the row held down + to about 840px, and in fact the transport was drawn under the menu island + from about 1180px down, where it could be seen and not pressed. + + On its own row the slider gets the width the row has: it is the control + the reader drags, and on a tablet it is dragged with a finger. + -------------------------------------------------------------------------- */ + +@media (min-width: 721px) and (min-height: 501px), + (min-width: 721px) and (pointer: fine), + (min-width: 721px) and (pointer: none) { + .app-bar[data-fit='compact'] { + flex-wrap: wrap; + row-gap: var(--sp-2); + } + + .app-bar[data-fit='compact'] .app-island-load { + order: 3; + flex: 1 1 100%; + max-width: none; + } + + .app-bar[data-fit='compact'] .traffic-load { + max-width: none; + } + + /* Moves into the menu, as it does on a phone. */ + .app-bar[data-fit='compact'] .app-source-link { + display: none; + } +} + +/* A phone on its side is about 390px tall, and two rows of 56px islands + inside the bar's padding took 158px of it. The padding goes and the + identity row comes down to its buttons' height, which gives back about + 40px of diagram. */ +@media (min-width: 721px) and (max-height: 500px) { + .app-bar[data-fit='compact'] { + padding-block: 0; + } + + .app-bar[data-fit='compact'] .app-island:not(.app-island-load) { + min-height: 48px; + } +} + /* -------------------------------------------------------------------------- Short windows. @@ -1049,43 +1140,100 @@ /* -------------------------------------------------------------------------- Undo / redo receipt. - Bottom center, floating over the stage: the top bar is where the ACTION - lives, but the change it reverted happened on the canvas, so the receipt - appears near the work. Plain panel surface and a hairline, no translucency. - z-index above the stage chrome (5) and below the tooltip layer (400): a - receipt must never cover an explanation the student asked for. + Bottom center of the UNCOVERED canvas, just above the zoom row: the top + bar is where the ACTION lives, but the change it reverted happened on the + canvas, so the receipt appears near the work. The dock spans the same + width the .stage-safe sentinel does, from the same has-* classes, so the + receipt is never under a rail or over the stats row, the charts toggle + or an open brief. Plain panel surface and a hairline, no translucency. + z-index above the panels (10) and briefs (20) and below the tooltip + layer (400): a receipt must never cover an explanation the student asked + for. Motion: entrance only, 160ms, opacity plus a few px of rise; the exit is an unmount because a receipt that lingers while fading invites reading it twice. Under prefers-reduced-motion it simply appears. -------------------------------------------------------------------------- */ -.app-toast { - position: fixed; - bottom: var(--sp-5); - left: 50%; - transform: translateX(-50%); +.app-toast-dock { + /* The zoom cluster's height (Canvas.css), the row this clears. */ + --toast-row-h: calc(32px + var(--sp-1) * 2 + 2px); + + position: absolute; + left: 0; + right: 0; + bottom: calc(var(--sp-3) + var(--toast-row-h) + var(--sp-2)); z-index: 300; + display: flex; + flex-direction: column; + align-items: center; + gap: var(--sp-2); + padding-inline: var(--sp-3); + /* Only the toasts take a press; the gap around them is still canvas. */ + pointer-events: none; +} + +/* The desktop's panels float beside the canvas. A phone's are sheets, and + App.phone.css places the dock for those. */ +@media (min-width: 721px) and (min-height: 501px), + (min-width: 721px) and (pointer: fine), + (min-width: 721px) and (pointer: none) { + .app-body.has-library .app-toast-dock { + left: calc(var(--rail-w) + var(--sp-3)); + } + + .app-body.has-inspector .app-toast-dock { + right: calc(var(--ins-w) + var(--sp-3)); + } + + .app-body.has-challenge:not(.has-inspector) .app-toast-dock { + right: calc(var(--chal-w) + var(--sp-3) * 2); + } + + .app-body.has-challenge.has-inspector .app-toast-dock { + right: calc(var(--ins-w) + var(--chal-w) + var(--sp-3) * 3); + } + + .app-body.has-metrics .app-toast-dock { + bottom: calc( + var(--strip-shown) + var(--sp-3) * 2 + var(--toast-row-h) + var(--sp-2) + ); + } +} + +.app-toast { + display: flex; + align-items: center; + gap: var(--sp-3); + max-width: 100%; padding: var(--sp-2) var(--sp-4); border: var(--bw) solid var(--border-strong); - border-radius: var(--r-btn); + border-radius: var(--r-md); background: var(--surface); color: var(--text); font-size: var(--fs-sm); font-weight: var(--fw-med); line-height: var(--lh-label); box-shadow: var(--shadow-sm); - animation: app-toast-in 160ms var(--ease-out); + pointer-events: auto; + animation: app-toast-in var(--dur-base) var(--ease-out); +} + +/* The toast's one action, such as Undo after a delete. It trims the toast's + own padding so the button does not make the toast taller. */ +.app-toast:has(.app-toast-action) { + padding-block: var(--sp-1); + padding-right: var(--sp-1); } @keyframes app-toast-in { from { opacity: 0; - transform: translateX(-50%) translateY(4px); + transform: translateY(4px); } to { opacity: 1; - transform: translateX(-50%) translateY(0); + transform: translateY(0); } } @@ -1108,6 +1256,36 @@ } } +/* "Skip to diagram". Out of sight until Tab reaches it, then over the + bar's top left corner, where focus would otherwise land next. */ +.app-skip { + position: absolute; + top: var(--sp-3); + left: var(--sp-3); + z-index: 500; + padding: var(--sp-2) var(--sp-4); + border: var(--bw) solid var(--border-strong); + border-radius: var(--r-md); + background: var(--surface); + color: var(--text); + font-size: var(--fs-sm); + font-weight: var(--fw-med); + text-decoration: none; + box-shadow: var(--shadow-sm); + transform: translateY(calc(-100% - var(--sp-5))); +} + +.app-skip:focus { + transform: none; +} + +/* The diagram itself takes focus from the skip link on an empty canvas. + Its ring is drawn inside it, since outside is under the panels. */ +.stage-canvas:focus-visible { + outline-offset: -2px; + border-radius: 0; +} + /* The file picker behind the Open button. Not display:none, because a hidden input in some browsers stops accepting a programmatic click; taken out of the layout and out of the tab order instead, since the @@ -1170,7 +1348,7 @@ neutralised here, because a sheet is not something to sit beside. -------------------------------------------------------------------------- */ -@media (max-width: 720px) { +@media (max-width: 720px), (pointer: coarse) and (max-height: 500px) { /* ------------------------------------------------------------------ A phone is a different application shape, not a narrow desktop. @@ -1452,7 +1630,7 @@ display: none; } -@media (max-width: 720px) { +@media (max-width: 720px), (pointer: coarse) and (max-height: 500px) { .app-tabbar { position: fixed; bottom: 0; @@ -1529,7 +1707,7 @@ display: none; } -@media (max-width: 720px) { +@media (max-width: 720px), (pointer: coarse) and (max-height: 500px) { /* Dims the canvas and catches the tap that closes the sheet. Below the slot (z-index 10) and above everything else on the stage. */ .app-scrim { @@ -1556,7 +1734,7 @@ align-items: center; justify-content: center; height: 44px; - padding: 20px 0; + padding: var(--sp-5) 0; /* The browser must not claim the vertical drag for scrolling, or the sheet never sees the move events it needs to follow the finger. */ touch-action: none; @@ -1566,7 +1744,7 @@ .app-grabber-bar { width: 36px; height: 4px; - border-radius: 2px; + border-radius: var(--r-mark); background: var(--border-strong); } @@ -1625,3 +1803,54 @@ opacity: 0; } } + +/* -------------------------------------------------------------------------- + The ledger never runs under the zoom cluster. + + Both sit on the canvas's bottom edge, the ledger from the left and the + zoom from the right, and with the inspector open there was no longer room + for both: at 1024 the two overlapped by 34px. The ledger is capped at the + room between its corner and the zoom's, and the facts that do not fit + drop whole from the end (the clock first, then the connections) instead + of being cut mid-word; useLedgerFit.ts counts them. --zoom-w is the cluster's measured width plus a little: + 169px with a mouse, 205px with 44px touch buttons. + -------------------------------------------------------------------------- */ +@media (min-width: 721px) and (min-height: 501px), + (min-width: 721px) and (pointer: fine), + (min-width: 721px) and (pointer: none) { + .app-body { + --ledger-left: calc(var(--sp-3) * 2 + 32px); + --zoom-right: var(--sp-3); + --zoom-w: 176px; + } + + .app-body.has-library { + --ledger-left: calc(var(--rail-w) + var(--sp-3) * 3 + 32px); + } + + .app-body.has-inspector { + --zoom-right: calc(var(--ins-w) + var(--sp-3) * 2); + } + + .app-body .cv-ledger { + max-width: calc( + 100% - var(--ledger-left) - var(--zoom-right) - var(--zoom-w) - var(--sp-3) + ); + overflow: hidden; + white-space: nowrap; + } + + /* data-drop is set by useLedgerFit: how many facts, from the end, do not + fit. */ + .cv-ledger[data-drop='1'] > :nth-last-child(-n + 1), + .cv-ledger[data-drop='2'] > :nth-last-child(-n + 2), + .cv-ledger[data-drop='3'] > :nth-last-child(-n + 3) { + display: none; + } +} + +@media (min-width: 721px) and (pointer: coarse) { + .app-body { + --zoom-w: 212px; + } +} diff --git a/src/App.emptyStates.test.tsx b/src/App.emptyStates.test.tsx index 4ec241d..0c914ce 100644 --- a/src/App.emptyStates.test.tsx +++ b/src/App.emptyStates.test.tsx @@ -109,7 +109,7 @@ describe('an empty canvas', () => { expect(c?.closest('.cv-surface')).toBeNull(); const labels = [...(c?.querySelectorAll('button') ?? [])].map((b) => b.textContent); expect(labels).toEqual([ - 'Start with one server', + 'Start with one service', 'Browse examples', 'Try a challenge', ]); @@ -117,7 +117,7 @@ describe('an empty canvas', () => { it('starts with one server as one undoable step', () => { mount(); - press(must('Start with one server')); + press(must('Start with one service')); const simple = PRESETS.find((p) => p.id === 'single-server')!; expect(nodeIds()).toEqual(simple.topology.nodes.map((n) => n.id)); expect(card()).toBeNull(); diff --git a/src/App.history.test.ts b/src/App.history.test.ts index ce20e73..f46235e 100644 --- a/src/App.history.test.ts +++ b/src/App.history.test.ts @@ -241,6 +241,19 @@ describe('SessionHistory', () => { expect(h.oldestLabel).toBe('add'); }); + it('names a new last entry on every commit, even with the stack full', () => { + // The delete toast's Undo checks this; depth stops moving at the limit. + const h = new SessionHistory(); + const t0 = makeTopology(); + for (let i = 0; i < HISTORY_LIMIT + 10; i++) h.commit('add', snap(t0)); + h.commit('delete', snap(t0)); + const deleted = h.lastEntry; + expect(deleted?.label).toBe('delete'); + h.commit('move', snap(t0)); + expect(h.undoDepth).toBe(HISTORY_LIMIT); + expect(h.lastEntry).not.toBe(deleted); + }); + it('skips no-op entries instead of burning an undo press', () => { const h = new SessionHistory(); const t0 = makeTopology(); diff --git a/src/App.incidents.test.tsx b/src/App.incidents.test.tsx index 7043a88..3d69b4d 100644 --- a/src/App.incidents.test.tsx +++ b/src/App.incidents.test.tsx @@ -83,13 +83,23 @@ function must(name: string): HTMLElement { } const panel = () => document.querySelector('section.chal'); -const caption = () => document.querySelector('.inc-caption')?.textContent ?? null; +/** The caption as read: its time, then its words. */ +const caption = () => { + const el = document.querySelector('.inc-caption'); + if (!el) return null; + const at = el.querySelector('.inc-caption-at')?.textContent; + const text = el.querySelector('.inc-caption-text')?.textContent; + return at && text ? `${at}: ${text}` : el.textContent; +}; const canvasIds = () => [...document.querySelectorAll('[data-hit="node"]')].map((n) => n.getAttribute('data-id'), ); const s3 = incidentById('incident-s3-2017')!; +const coinbase = incidentById('incident-coinbase-2026')!; +const coinbase21 = incidentById('incident-coinbase-2021')!; +const discord = incidentById('incident-discord-2023')!; function openIncident(): void { press(must('Menu')); @@ -136,11 +146,33 @@ describe('a real incident', () => { const link = p?.querySelector('.inc-source a'); expect(link?.href).toBe(s3.source.url); expect(link?.textContent).toBe(s3.source.title); - // Opening it changes nothing on the canvas. - expect(canvasIds()).toEqual(['mine-client', 'mine-svc']); expect(document.activeElement).toBe(p?.querySelector('h2')); }); + it('puts its scene on the canvas, paused at the start, as one undo step', () => { + mount(); + openIncident(); + expect(canvasIds()).toEqual(s3.scene.nodes.map((n) => n.id)); + expect(document.querySelector('.app-toast')?.textContent).toBe( + `Opened ${s3.name}. Undo brings your design back.`, + ); + // Paused: nothing has happened yet, so there is no caption to show. + advance(3000); + expect(caption()).toBeNull(); + expect(must('Watch it happen')).not.toBeNull(); + press(must('Undo')); + expect(canvasIds()).toEqual(['mine-client', 'mine-svc']); + }); + + it('gives the run back its play state when closed without watching', () => { + mount(); + expect(must('Pause')).not.toBeNull(); + openIncident(); + expect(must('Play')).not.toBeNull(); + press(must('Close')); + expect(must('Pause')).not.toBeNull(); + }); + it('plays the scene with captions, and one undo puts the design back', () => { mount(); openIncident(); @@ -151,6 +183,7 @@ describe('a real incident', () => { advance(21_000); expect(caption()).toBe(`20s: ${s3.captions[1]!.text}`); + // Watching the scene opening installed is not a second step to undo. press(must('Undo')); expect(canvasIds()).toEqual(['mine-client', 'mine-svc']); // Not the scene any more, so no caption. @@ -169,6 +202,41 @@ describe('a real incident', () => { expect(canvasIds()).toEqual(['mine-client', 'mine-svc']); }); + it('reads the first check of Fix it as the problem, before the outage', () => { + mount(); + openIncident(); + press(must('Fix it')); + for (let i = 0; i < 80; i++) { + advance(250); + if (document.querySelector('.chal-verdict:not(.is-pending)')) break; + } + const verdict = document.querySelector('.chal-verdict'); + expect(verdict?.className).toContain('is-base'); + expect(verdict?.className).not.toContain('is-danger'); + expect(verdict?.textContent).toMatch( + /^As it starts\. When S3, one region, goes down at 20s, \d+(\.\d+)?% of requests from /, + ); + // The live run has not reached the outage yet, and says how long it has. + // It is running: opening paused the scene for Watch, not for the brief. + advance(2000); + const left = /^Outage in (\d+)s$/.exec( + document.querySelector('.chal-countdown')?.textContent ?? '', + ); + expect(left).not.toBeNull(); + expect(Number(left![1])).toBeLessThan(20); + expect(panel()?.textContent).toContain('In the 3 test runs (15s to 60s)'); + }); + + it("sets aside the reader's own design, not the scene, after watching it", () => { + mount(); + openIncident(); + press(must('Watch it happen')); + advance(1000); + press(must('Fix it')); + press(must('Back to my design')); + expect(canvasIds()).toEqual(['mine-client', 'mine-svc']); + }); + it('announces the first caption from a live region that was already there', () => { mount(); openIncident(); @@ -202,11 +270,43 @@ describe('finding the incidents in the examples dialog', () => { press(must('Menu')); press(must('Examples')); search('incident'); - expect(incidentNames()).toHaveLength(3); + expect(incidentNames()).toHaveLength(6); search('2017'); expect(incidentNames()).toEqual([s3.name]); }); + it('finds the Coinbase outage by the company, and opens its brief', () => { + mount(); + press(must('Menu')); + press(must('Examples')); + search('coinbase'); + expect(incidentNames()).toEqual([coinbase.name, coinbase21.name]); + press(must(coinbase.name)); + advance(400); + expect(panel()?.textContent).toContain(coinbase.simNote); + press(must('Fix it')); + expect(panel()?.textContent).toContain(coinbase.brief.brief); + expect(canvasIds()).toEqual(coinbase.scene.nodes.map((n) => n.id)); + }); + + it.each([ + ['discord', () => discord], + ['memcached', () => coinbase21], + ])('finds %s and opens its brief on its own scene', (q, which) => { + const i = which(); + mount(); + press(must('Menu')); + press(must('Examples')); + search(q); + expect(incidentNames()).toEqual([i.name]); + press(must(i.name)); + advance(400); + expect(panel()?.textContent).toContain(i.simNote); + press(must('Fix it')); + expect(panel()?.textContent).toContain(i.brief.brief); + expect(canvasIds()).toEqual(i.scene.nodes.map((n) => n.id)); + }); + it('jumps from the header to the first incident, clearing a search', () => { mount(); press(must('Menu')); @@ -214,7 +314,7 @@ describe('finding the incidents in the examples dialog', () => { search('cache'); Element.prototype.scrollIntoView ??= () => {}; press(must('Incidents')); - expect(incidentNames()).toHaveLength(3); + expect(incidentNames()).toHaveLength(6); expect(document.activeElement?.querySelector('.ex-item-name')?.textContent).toBe( incidentNames()[0], ); diff --git a/src/App.keyboard.test.tsx b/src/App.keyboard.test.tsx new file mode 100644 index 0000000..983680c --- /dev/null +++ b/src/App.keyboard.test.tsx @@ -0,0 +1,322 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import App from './App'; +import { makeNode } from './sim/presets'; +import type { Topology } from './sim/types'; +import { ONE_RAIL_QUERY } from './oneRail'; + +/** + * The keyboard and overlay pass: the skip link, the tab order, the rail as + * one tab stop, F6, keyboard connect, the delete toast and its Undo, and one + * rail at a time on a tablet held upright. + */ + +class FakePointerEvent extends MouseEvent { + pointerId: number; + pointerType: string; + isPrimary: boolean; + constructor( + type: string, + init: MouseEventInit & { pointerId?: number; pointerType?: string } = {}, + ) { + super(type, init); + this.pointerId = init.pointerId ?? 1; + this.pointerType = init.pointerType ?? 'mouse'; + this.isPrimary = true; + } +} + +const SESSION_KEY = 'breakscale.session.v1'; + +function ownDesign(): Topology { + const client = { ...makeNode('client', 0, 0), id: 'mine-client', label: 'My client' }; + const svc = { ...makeNode('service', 240, 0), id: 'mine-svc', label: 'My service' }; + const db = { ...makeNode('db', 480, 0), id: 'mine-db', label: 'My db' }; + const cache = { ...makeNode('cache', 480, 200), id: 'mine-cache', label: 'My cache' }; + return { + nodes: [client, svc, db, cache], + edges: [{ id: 'mine-client->mine-svc', from: client.id, to: svc.id, weight: 1 }], + }; +} + +let container: HTMLDivElement; +let root: Root; + +function mount(): void { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + act(() => root.render()); +} + +function press(el: Element): void { + const at = { bubbles: true, cancelable: true, button: 0, clientX: 5, clientY: 5 }; + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerdown', { ...at, buttons: 1 })); + el.dispatchEvent(new MouseEvent('mousedown', { ...at, buttons: 1 })); + }); + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('mouseup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('click', { ...at, buttons: 0 })); + }); +} + +/** A key press on whatever has focus, the way the browser sends it. */ +function key(k: string, init: KeyboardEventInit = {}): void { + const target = document.activeElement ?? document.body; + act(() => { + target.dispatchEvent( + new KeyboardEvent('keydown', { + key: k, + bubbles: true, + cancelable: true, + ...init, + }), + ); + }); +} + +const node = (id: string) => + document.querySelector(`.cv-node[data-id="${id}"]`)!; +const edge = (id: string) => + document.querySelector(`[data-hit="edge"][data-id="${id}"]`); +const body = () => document.querySelector('.app-body')!.classList; + +/** Everything Tab stops on, in page order. */ +function tabStops(): HTMLElement[] { + return [ + ...document.querySelectorAll( + 'a[href], button:not([disabled]), input:not([disabled]), select, textarea, [tabindex]', + ), + ].filter((el) => el.tabIndex >= 0 && !el.closest('[aria-hidden="true"]')); +} + +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = + true; + vi.useFakeTimers(); + vi.stubGlobal('PointerEvent', FakePointerEvent); + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.reject(new Error('offline'))), + ); + localStorage.clear(); + window.history.replaceState(null, '', '/'); + localStorage.setItem( + SESSION_KEY, + JSON.stringify({ topology: ownDesign(), rps: 50, presetId: null }), + ); +}); + +afterEach(() => { + act(() => root.unmount()); + container.remove(); + document.body.innerHTML = ''; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe('getting to the diagram from the keyboard', () => { + it('starts with a skip link that puts focus on the diagram', () => { + mount(); + const stops = tabStops(); + expect(stops[0]?.textContent).toBe('Skip to diagram'); + press(stops[0]!); + expect(document.activeElement?.classList.contains('cv-node')).toBe(true); + }); + + it('reaches the diagram before the rails, and the rail is one stop', () => { + mount(); + const stops = tabStops(); + const firstNode = stops.findIndex((el) => el.classList.contains('cv-node')); + const firstRow = stops.findIndex((el) => el.classList.contains('pal-row')); + expect(firstNode).toBeGreaterThan(0); + expect(firstRow).toBeGreaterThan(firstNode); + expect(stops.filter((el) => el.closest('.pal-rows'))).toHaveLength(1); + }); + + it('moves through the rail with the arrows and explains a row on ?', () => { + mount(); + const rows = [...document.querySelectorAll('.pal-row')]; + act(() => rows[0]!.focus()); + key('ArrowDown'); + expect(document.activeElement).toBe(rows[1]); + expect(rows[1]!.tabIndex).toBe(0); + expect(rows[0]!.tabIndex).toBe(-1); + key('End'); + expect(document.activeElement).toBe(rows[rows.length - 1]); + key('Home'); + expect(document.activeElement).toBe(rows[0]); + // Focus alone opens the row's card, and the row is described by it. + const card = document.querySelector('.pal-card'); + expect(card?.textContent).toContain('Example:'); + expect(rows[0]!.getAttribute('aria-describedby')).toBeTruthy(); + key('?'); + expect(document.activeElement?.textContent).toBe('Learn more'); + expect(card?.contains(document.activeElement)).toBe(true); + // The row's own explanation, not the glossary panel. + expect(document.querySelector('[role="dialog"][aria-label="Glossary"]')).toBeNull(); + // Escape shuts the card and goes back to the row; a second is harmless. + key('Escape'); + expect(document.activeElement).toBe(rows[0]); + expect(document.querySelector('.pal-card')).toBeNull(); + key('Escape'); + expect(document.activeElement).toBe(rows[0]); + key('?'); + key('ArrowDown'); + expect(document.activeElement).toBe(rows[1]); + }); + + it('steps between regions with F6 and back with Shift+F6', () => { + mount(); + key('F6'); + expect(document.activeElement?.closest('.app-bar')).not.toBeNull(); + key('F6'); + expect(document.activeElement?.classList.contains('cv-node')).toBe(true); + key('F6'); + expect(document.activeElement?.closest('.app-slot-left')).not.toBeNull(); + key('F6', { shiftKey: true }); + expect(document.activeElement?.classList.contains('cv-node')).toBe(true); + }); +}); + +describe('connecting from the keyboard', () => { + it('makes one edge to the picked part, as one undo step', () => { + mount(); + press(node('mine-svc')); + key('l'); + const hint = () => document.querySelector('.cv-hint')?.textContent; + // Downstream first: the nearest part to the right. + expect(hint()).toBe( + 'Connect My service to My db. Arrows pick, Enter connects, Esc cancels.', + ); + expect(document.activeElement).toBe(node('mine-db')); + key('ArrowDown'); + expect(hint()).toContain('to My cache'); + // An arrow picks; it does not move the focused part. + const t = node('mine-cache').getAttribute('transform'); + key('ArrowUp'); + expect(node('mine-cache').getAttribute('transform')).toBe(t); + expect(hint()).toContain('to My db'); + key('Enter'); + expect(edge('mine-svc->mine-db')).not.toBeNull(); + expect(document.querySelectorAll('[data-hit="edge"]')).toHaveLength(2); + expect(document.querySelector('.cv-hint')).toBeNull(); + expect(document.activeElement).toBe(node('mine-svc')); + key('z', { ctrlKey: true, code: 'KeyZ' } as KeyboardEventInit); + expect(edge('mine-svc->mine-db')).toBeNull(); + expect(edge('mine-client->mine-svc')).not.toBeNull(); + }); + + it('offers only parts it can link to, and Escape keeps the selection', () => { + mount(); + press(node('mine-client')); + key('L'); + // Already linked to My service, so the first offer skips it. + expect(document.querySelector('.cv-hint')?.textContent).not.toContain( + 'to My service', + ); + key('Escape'); + expect(document.querySelector('.cv-hint')).toBeNull(); + expect(node('mine-client').classList.contains('is-selected')).toBe(true); + expect(document.querySelectorAll('[data-hit="edge"]')).toHaveLength(1); + }); + + it('needs exactly one part selected', () => { + mount(); + key('l'); + expect(document.querySelector('.cv-hint')).toBeNull(); + }); +}); + +describe('deleting a part', () => { + it('sits at the end of the inspector and offers an undo', () => { + mount(); + press(node('mine-db')); + const scroll = document.querySelector('.ins-scroll')!; + const del = [...document.querySelectorAll('button')].find( + (b) => b.textContent === 'Delete component', + )!; + // Inside the scrolling content, after everything else in it. + expect(scroll.contains(del)).toBe(true); + expect(scroll.lastElementChild?.contains(del)).toBe(true); + press(del); + expect(document.querySelector('.cv-node[data-id="mine-db"]')).toBeNull(); + const toast = document.querySelector('.app-toast')!; + expect(toast.closest('.app-body')).not.toBeNull(); + expect(toast.firstChild?.textContent).toBe('Deleted My db'); + press(toast.querySelector('button')!); + expect(document.querySelector('.cv-node[data-id="mine-db"]')).not.toBeNull(); + }); + + it('Undo in the toast does nothing once something else was done', () => { + mount(); + press(node('mine-db')); + key('Delete'); + const undo = document.querySelector('.app-toast button')!; + expect(undo.textContent).toBe('Undo'); + press(node('mine-cache')); + key('Delete'); + // The second toast replaced the first; its Undo takes back the cache. + press(document.querySelector('.app-toast button')!); + expect(document.querySelector('.cv-node[data-id="mine-cache"]')).not.toBeNull(); + expect(document.querySelector('.cv-node[data-id="mine-db"]')).toBeNull(); + }); +}); + +describe('one rail at a time on a tablet held upright', () => { + beforeEach(() => { + vi.stubGlobal( + 'matchMedia', + (query: string) => + ({ + matches: query === ONE_RAIL_QUERY, + media: query, + addEventListener: () => {}, + removeEventListener: () => {}, + addListener: () => {}, + removeListener: () => {}, + }) as unknown as MediaQueryList, + ); + }); + + it('starts with the components rail closed, and opening one closes the other', () => { + mount(); + expect(body().contains('has-library')).toBe(false); + const toggle = () => + document.querySelector('.stage-toggle-library')!; + press(toggle()); + expect(body().contains('has-library')).toBe(true); + press(node('mine-svc')); + expect(body().contains('has-inspector')).toBe(true); + expect(body().contains('has-library')).toBe(false); + press(toggle()); + expect(body().contains('has-library')).toBe(true); + expect(body().contains('has-inspector')).toBe(false); + }); + + it('keeps the rail open for a part added from it', () => { + mount(); + press(document.querySelector('.stage-toggle-library')!); + const row = document.querySelector( + '.pal-row[data-row="cache"]', + )!; + press(row); + expect(document.querySelectorAll('.cv-node')).toHaveLength(5); + expect(body().contains('has-library')).toBe(true); + expect(body().contains('has-inspector')).toBe(false); + }); + + it('does not save the folded rail as the reader choice', () => { + mount(); + expect(body().contains('has-library')).toBe(false); + const saved = JSON.parse(localStorage.getItem('breakscale.layout.v1') ?? '{}') as { + library?: boolean; + }; + expect(saved.library).not.toBe(false); + }); +}); diff --git a/src/App.loadMultiple.test.tsx b/src/App.loadMultiple.test.tsx new file mode 100644 index 0000000..ab91878 --- /dev/null +++ b/src/App.loadMultiple.test.tsx @@ -0,0 +1,130 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import App from './App'; +import { makeNode } from './sim/presets'; + +/** + * The header's 1x through the whole app: a design built on an empty canvas + * gets one from its first client, and a canvas cleared and rebuilt is not + * measured against the design that was there before. + */ + +class FakePointerEvent extends MouseEvent { + pointerId: number; + pointerType: string; + isPrimary: boolean; + constructor( + type: string, + init: MouseEventInit & { pointerId?: number; pointerType?: string } = {}, + ) { + super(type, init); + this.pointerId = init.pointerId ?? 1; + this.pointerType = init.pointerType ?? 'mouse'; + this.isPrimary = true; + } +} + +const SESSION_KEY = 'breakscale.session.v1'; + +let container: HTMLDivElement; +let root: Root; + +function mount(): void { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + act(() => root.render()); +} + +function press(el: Element): void { + const at = { bubbles: true, cancelable: true, button: 0, clientX: 5, clientY: 5 }; + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerdown', { ...at, buttons: 1 })); + el.dispatchEvent(new MouseEvent('mousedown', { ...at, buttons: 1 })); + }); + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('mouseup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('click', { ...at, buttons: 0 })); + }); +} + +/** Add one component from the palette, the way a click on its row does. */ +function add(kind: string): void { + const row = document.querySelector(`.pal-row[data-kind="${kind}"]`); + if (!row) throw new Error(`no palette row for ${kind}`); + press(row); +} + +/** Drag the load slider to a position: press, the value moves, release. */ +function drag(to: number): void { + const slider = document.querySelector('.traffic-load-track input')!; + const at = { bubbles: true, cancelable: true, button: 0 }; + act(() => { + slider.dispatchEvent(new FakePointerEvent('pointerdown', { ...at, buttons: 1 })); + const set = Object.getOwnPropertyDescriptor( + HTMLInputElement.prototype, + 'value', + )!.set!; + set.call(slider, String(to)); + slider.dispatchEvent(new Event('input', { bubbles: true })); + slider.dispatchEvent(new Event('change', { bubbles: true })); + slider.dispatchEvent(new FakePointerEvent('pointerup', { ...at, buttons: 0 })); + }); +} + +const chip = () => document.querySelector('.traffic-multiple'); + +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = + true; + vi.useFakeTimers(); + vi.stubGlobal('PointerEvent', FakePointerEvent); + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.reject(new Error('offline'))), + ); + localStorage.clear(); + window.history.replaceState(null, '', '/'); +}); + +afterEach(() => { + act(() => root.unmount()); + container.remove(); + document.body.innerHTML = ''; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +function session(nodes: unknown[], rps: number): void { + localStorage.setItem( + SESSION_KEY, + JSON.stringify({ topology: { nodes, edges: [] }, rps, presetId: null }), + ); +} + +describe('the load multiple', () => { + it('appears for a design built on an empty canvas', () => { + session([], 0); + mount(); + add('client'); + expect(chip()?.textContent).toBe('1.0x'); + const slider = document.querySelector( + '.traffic-load-track input', + )!; + drag(Number(slider.value) + 40); + expect(chip()?.textContent).not.toBe('1.0x'); + expect(chip()?.getAttribute('aria-label')).toMatch(/where 1x is 50\/s$/); + }); + + it('starts again from the first client after the old ones are gone', () => { + // A 1x of 400 left over from a design whose clients were all deleted. + session([{ ...makeNode('service', 0, 0, 'Service'), id: 'svc' }], 400); + mount(); + add('client'); + expect(chip()?.textContent).toBe('1.0x'); + }); +}); diff --git a/src/App.palette.test.tsx b/src/App.palette.test.tsx new file mode 100644 index 0000000..08519f7 --- /dev/null +++ b/src/App.palette.test.tsx @@ -0,0 +1,307 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import App from './App'; +import { makeNode } from './sim/presets'; +import type { Topology } from './sim/types'; + +/** + * The command palette and presenting mode, through the shell: the chord, + * the menu row, typing, the arrows, Enter and Escape; then P and the three + * fault keys. + */ + +class FakePointerEvent extends MouseEvent { + pointerId: number; + pointerType: string; + isPrimary: boolean; + constructor( + type: string, + init: MouseEventInit & { pointerId?: number; pointerType?: string } = {}, + ) { + super(type, init); + this.pointerId = init.pointerId ?? 1; + this.pointerType = init.pointerType ?? 'mouse'; + this.isPrimary = true; + } +} + +const SESSION_KEY = 'breakscale.session.v1'; + +function ownDesign(): Topology { + const client = { ...makeNode('client', 0, 0), id: 'mine-client', label: 'My client' }; + const svc = { ...makeNode('service', 240, 0), id: 'mine-svc', label: 'My service' }; + return { + nodes: [client, svc], + edges: [{ id: 'mine-client->mine-svc', from: client.id, to: svc.id, weight: 1 }], + }; +} + +let container: HTMLDivElement; +let root: Root; + +function mount(): void { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + act(() => root.render()); +} + +/** A press the way a mouse makes one, ending in the click. */ +function press(el: Element): void { + const at = { bubbles: true, cancelable: true, button: 0, clientX: 5, clientY: 5 }; + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerdown', { ...at, buttons: 1 })); + el.dispatchEvent(new MouseEvent('mousedown', { ...at, buttons: 1 })); + }); + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('mouseup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('click', { ...at, buttons: 0 })); + }); +} + +/** A key on whatever has focus, bubbling to the window like a real one. */ +function key(k: string, init: KeyboardEventInit = {}): void { + const target = document.activeElement ?? document.body; + act(() => { + target.dispatchEvent( + new KeyboardEvent('keydown', { + key: k, + bubbles: true, + cancelable: true, + ...init, + }), + ); + }); +} + +/** Typing into the focused box the way React hears it. */ +function type(text: string): void { + const input = document.activeElement as HTMLInputElement; + const setter = Object.getOwnPropertyDescriptor( + HTMLInputElement.prototype, + 'value', + )?.set; + act(() => { + setter?.call(input, text); + input.dispatchEvent(new Event('input', { bubbles: true })); + }); +} + +const dialog = () => + document.querySelector('[role="dialog"][aria-label="Search actions"]'); +const combobox = () => document.querySelector('.cp-input'); +const nodeLabels = () => + Array.from(document.querySelectorAll('[data-hit="node"]')).map((n) => + n.getAttribute('data-id'), + ); + +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = + true; + vi.useFakeTimers(); + vi.stubGlobal('PointerEvent', FakePointerEvent); + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.reject(new Error('offline'))), + ); + localStorage.clear(); + window.history.replaceState(null, '', '/'); + localStorage.setItem( + SESSION_KEY, + JSON.stringify({ topology: ownDesign(), rps: 50, presetId: null }), + ); +}); + +afterEach(() => { + act(() => root.unmount()); + container.remove(); + document.body.innerHTML = ''; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe('command palette', () => { + it('Ctrl+K opens it with focus in the box; typing "netf" and Enter opens Netflix', () => { + mount(); + const opener = document.querySelector('.app-menu-btn'); + opener?.focus(); + key('k', { code: 'KeyK', ctrlKey: true }); + expect(dialog()).not.toBeNull(); + expect(document.activeElement).toBe(combobox()); + + type('netf'); + const first = document.querySelector('.cp-row'); + expect(first?.textContent).toContain('Netflix'); + expect(combobox()?.getAttribute('aria-activedescendant')).toBe(first?.id); + + key('Enter'); + act(() => { + vi.advanceTimersByTime(400); + }); + expect(dialog()).toBeNull(); + expect(nodeLabels()).not.toContain('mine-client'); + expect(nodeLabels().length).toBeGreaterThan(10); + // Focus goes back where it was. + expect(document.activeElement).toBe(opener); + }); + + it('the arrows move the active row and wrap; Escape closes without running', () => { + mount(); + key('k', { code: 'KeyK', metaKey: true }); + const rows = () => Array.from(document.querySelectorAll('.cp-row')); + const active = () => combobox()?.getAttribute('aria-activedescendant'); + expect(active()).toBe(rows()[0]?.id); + key('ArrowDown'); + expect(active()).toBe(rows()[1]?.id); + expect(rows()[1]?.getAttribute('aria-selected')).toBe('true'); + key('ArrowUp'); + key('ArrowUp'); + expect(active()).toBe(rows().at(-1)?.id); + key('Escape'); + act(() => { + vi.advanceTimersByTime(400); + }); + expect(dialog()).toBeNull(); + expect(nodeLabels()).toContain('mine-client'); + }); + + it('is the first row of the menu, and a recent command comes first next time', () => { + mount(); + press(document.querySelector('.app-menu-btn')!); + const first = document.querySelector('.mn-item'); + expect(first?.textContent).toContain('Search actions'); + press(first!); + expect(dialog()).not.toBeNull(); + type('reset the run'); + key('Enter'); + act(() => { + vi.advanceTimersByTime(400); + }); + key('k', { code: 'KeyK', ctrlKey: true }); + expect(document.querySelector('.cp-row')?.textContent).toContain('Reset the run'); + }); + + it('a row that cannot run says why and does nothing on Enter', () => { + mount(); + key('k', { code: 'KeyK', ctrlKey: true }); + type('fit the diagram'); + const row = document.querySelector('.cp-row'); + expect(row?.getAttribute('aria-disabled')).toBeNull(); + type('pin this run'); + // Nothing has been measured with the fake clock still at zero. + const pin = document.querySelector('.cp-row'); + expect(pin?.getAttribute('aria-disabled')).toBe('true'); + expect(pin?.querySelector('.cp-why')?.textContent).toMatch(/^Nothing measured yet/); + key('Enter'); + expect(dialog()).not.toBeNull(); + }); + + it('crashing a part from it selects that part and records the fault', () => { + mount(); + key('k', { code: 'KeyK', ctrlKey: true }); + type('crash my serv'); + expect(document.querySelector('.cp-row')?.textContent).toContain( + 'Crash My service', + ); + key('Enter'); + act(() => { + vi.advanceTimersByTime(400); + }); + const svc = document.querySelector('[data-hit="node"][data-id="mine-svc"]'); + expect(svc?.classList.contains('is-faulted')).toBe(true); + expect(svc?.classList.contains('is-selected')).toBe(true); + }); +}); + +describe('presenting', () => { + const app = () => document.querySelector('.app'); + + it('Shift+P turns it on and off, closing the side panels only while it is on', () => { + mount(); + expect(app()?.classList.contains('is-presenting')).toBe(false); + // A bare P is not the shortcut: it was too easy to press by accident. + key('p'); + expect(app()?.classList.contains('is-presenting')).toBe(false); + const railWas = document + .querySelector('.app-body') + ?.classList.contains('has-library'); + key('P', { shiftKey: true }); + expect(app()?.classList.contains('is-presenting')).toBe(true); + expect(document.querySelector('.app-body')?.classList.contains('has-library')).toBe( + false, + ); + expect(document.querySelector('.pb-hint')?.textContent).toBe( + 'Click a part or Tab to one. X crashes it, W slows it, R fixes it.', + ); + press(document.querySelector('.pb-exit button:last-child')!); + expect(app()?.classList.contains('is-presenting')).toBe(false); + expect(document.querySelector('.app-body')?.classList.contains('has-library')).toBe( + railWas, + ); + }); + + it('X, W and R break and fix the focused part, and say why when they cannot', () => { + mount(); + key('P', { shiftKey: true }); + const svc = document.querySelector( + '[data-hit="node"][data-id="mine-svc"]', + ); + act(() => svc?.focus()); + const state = () => document.querySelector('.pb-state')?.textContent; + expect(document.querySelector('.pb-label')?.textContent).toBe('My service'); + expect(state()).toBe('Running'); + + key('x'); + expect(state()).toBe('Crashed'); + key('x'); + expect(document.querySelector('.app-toast')?.textContent).toBe( + 'My service is already crashed. R fixes it.', + ); + key('r'); + expect(state()).toBe('Running'); + key('w'); + expect(state()).toBe('Slowed 5×'); + // The inspector stays shut the whole time. + expect( + document.querySelector('.app-body')?.classList.contains('has-inspector'), + ).toBe(false); + }); + + it('X does nothing outside presenting, and the keys wait while a dialog is open', () => { + mount(); + const svc = document.querySelector( + '[data-hit="node"][data-id="mine-svc"]', + ); + act(() => svc?.focus()); + key('x'); + expect(svc?.classList.contains('is-faulted')).toBe(false); + key('P', { shiftKey: true }); + key('k', { code: 'KeyK', ctrlKey: true }); + // Typed into the palette's box, so it is text, not a crash. + key('x'); + expect( + document + .querySelector('[data-hit="node"][data-id="mine-svc"]') + ?.classList.contains('is-faulted'), + ).toBe(false); + }); + + it('is in the menu and in the palette', () => { + mount(); + press(document.querySelector('.app-menu-btn')!); + const row = Array.from(document.querySelectorAll('.mn-item')).find((b) => + b.textContent?.includes('Start presenting'), + ); + expect(row).toBeDefined(); + press(row!); + expect(app()?.classList.contains('is-presenting')).toBe(true); + key('k', { code: 'KeyK', ctrlKey: true }); + type('stop pres'); + key('Enter'); + expect(app()?.classList.contains('is-presenting')).toBe(false); + }); +}); diff --git a/src/App.phone.css b/src/App.phone.css new file mode 100644 index 0000000..4a36a62 --- /dev/null +++ b/src/App.phone.css @@ -0,0 +1,235 @@ +/* ========================================================================== + The phone layout's room for the diagram. + + Loaded after App.css, whose phone block builds the header, the tab bar and + the sheets. This file decides how much of the canvas those leave, which + is what the camera frames and pans into (the .stage-safe sentinel), and + how the same layout lies down when the phone does. + ========================================================================== */ + +@media (max-width: 720px), (pointer: coarse) and (max-height: 500px) { + /* The desktop insets the sentinel by a rail's width. A sheet is not + beside the canvas, so those insets do not apply here. */ + .app-body.has-library .stage-canvas > .stage-safe, + .app-body.has-inspector .stage-canvas > .stage-safe { + left: 0; + right: 0; + } + + /* The inspector stops at a fixed height instead of growing to most of + the screen, so the diagram it is about keeps the strip above it. At + 62% it covered every part of a three-box design at 390x844; at 45% the + strip is about 300px, and the selected part is panned into it (see + reveal.ts). The sheet's own list scrolls. */ + .app-body { + --ins-sheet-h: 45dvh; + } + + .app-slot-right { + height: var(--ins-sheet-h); + } + + .app-body.has-inspector .stage-canvas > .stage-safe { + bottom: calc(var(--ins-sheet-h) + env(safe-area-inset-bottom, 0px)); + } + + /* Toasts drop from under the header, a row down so they clear "Find the + problem" (a 44px button at the canvas's top left). At the foot of the + screen they sat on the tab bar and on whichever sheet was open; the + header is the one edge nothing slides over. */ + .app-toast-dock { + position: fixed; + top: calc(var(--bar-clear) + var(--sp-3) + 44px + var(--sp-2)); + bottom: auto; + } +} + +/* -------------------------------------------------------------------------- + A phone on its side. + + About 390px tall. The portrait header (two rows) and a bottom sheet left + a strip of diagram under 100px, so here the header is one row and the + sheets come in from the sides, the way the desktop rails do, leaving the + diagram its full height beside them. + -------------------------------------------------------------------------- */ + +/* One row from 760px. Narrower, as on a 667px phone, a slider beside + everything else in the row was under 70px wide, too short to set a load + with, so the load control keeps a row of its own there. */ +@media (pointer: coarse) and (max-height: 500px) and (min-width: 760px) { + .app-bar { + flex-wrap: nowrap; + align-items: center; + } + + /* The wordmark goes; undo and redo stay at the start of the row. */ + .app-brand, + .app-saved { + display: none; + } + + .app-island-brand { + flex: none; + padding-right: 0; + } + + .app-history { + margin-left: 0; + } + + .app-island-load { + order: 2; + flex: 1 1 auto; + min-width: 0; + border-top: 0; + padding-block: var(--sp-1); + } + + .app-island-menu { + order: 3; + flex: none; + } + + /* The short word, as in portrait (see .app-break-short in App.css). A + 932px phone is wide enough for the long label by the desktop rule, and + the long label ran into Reset. */ + .app-break-long { + display: none; + } + + .app-break-short { + display: inline; + } +} + +@media (pointer: coarse) and (max-height: 500px) { + /* The load control is one line. The load and p99 each stack the figure + over its caption, as on a desktop, so both stay named in the width of + the figure and the slider keeps the rest. */ + .traffic { + flex-wrap: nowrap; + } + + .traffic-load-track { + flex: 1 1 auto; + order: 0; + } + + .traffic-headline { + order: 0; + margin-left: 0; + } + + .traffic-load-readout, + .traffic-metric { + flex-direction: column; + align-items: flex-start; + gap: 0; + } + + /* The menu stops above the tab bar, which would otherwise cover its + last rows. */ + .app-bar .mn { + max-height: calc( + 100dvh - var(--bar-clear, 72px) - var(--tabbar-h) - + env(safe-area-inset-bottom, 0px) + ); + } + + /* --- Sheets at the sides --------------------------------------- */ + + .app-body { + --side-sheet-w: 45vw; + } + + .app-slot-left, + .app-slot-right { + top: var(--bar-clear); + bottom: calc(var(--tabbar-h) + env(safe-area-inset-bottom, 0px)); + width: var(--side-sheet-w); + height: auto; + max-height: none; + border-bottom: var(--bw) solid var(--border); + } + + .app-slot-left { + right: auto; + border-left: 0; + border-radius: 0 var(--r-lg) var(--r-lg) 0; + } + + .app-slot-right { + left: auto; + border-right: 0; + border-radius: var(--r-lg) 0 0 var(--r-lg); + } + + /* The desktop rails' slides (App.css), since these come in from the same + edges. */ + .app-slot-left.is-entering { + animation-name: app-slot-in-left; + } + + .app-slot-left.is-closing { + animation-name: app-slot-out-left; + } + + .app-slot-right.is-entering { + animation-name: app-slot-in-right; + } + + .app-slot-right.is-closing { + animation-name: app-slot-out-right; + } + + /* A brief, an incident or "Can you break it?" takes the same side. As a + bottom sheet it held half of a 257px canvas, and the diagram it is + about had the other 120px. Folded, it is its heading only. */ + .app-body .chal { + top: var(--bar-clear); + bottom: calc(var(--tabbar-h) + env(safe-area-inset-bottom, 0px)); + left: auto; + right: 0; + width: var(--side-sheet-w); + max-height: none; + border-bottom: var(--bw) solid var(--border); + border-right: 0; + border-radius: var(--r-lg) 0 0 var(--r-lg); + } + + .app-body .chal.is-collapsed { + bottom: auto; + border-radius: 0 0 0 var(--r-lg); + } + + .app-body.has-challenge .stage-canvas > .stage-safe { + right: var(--side-sheet-w); + bottom: 0; + } + + /* The diagram keeps the side the inspector leaves, at full height. */ + .app-body.has-inspector .stage-canvas > .stage-safe { + right: var(--side-sheet-w); + bottom: 0; + } + + /* A toast keeps to the same side, off the sheets. */ + .app-body.has-library .app-toast-dock { + left: var(--side-sheet-w); + } + + .app-body.has-inspector .app-toast-dock, + .app-body.has-challenge .app-toast-dock { + right: var(--side-sheet-w); + } +} + +/* The traffic key's corner is under a docked brief, incident or task card + or the tour on a phone. It steps aside while one is open rather than sit beneath it. */ +@media (max-width: 720px), (pointer: coarse) and (max-height: 500px) { + .app-body.has-challenge .cv-key, + .app-body.has-task .cv-key, + .app:has(.tour-card) .cv-key { + display: none; + } +} diff --git a/src/App.present.css b/src/App.present.css new file mode 100644 index 0000000..fbbeb7b --- /dev/null +++ b/src/App.present.css @@ -0,0 +1,192 @@ +/* ========================================================================== + Presenting mode (present.ts): the canvas and the live numbers, sized for a + projector. One block, keyed on .app.is-presenting, so the normal layout is + untouched while the mode is off. + + What goes: the wordmark and its row (undo, redo, saved), GitHub, Share, + Can you break it?, the menu, the side panels' toggles and the components + count. The panels themselves are closed by the shell, so the safe-area + sentinel and every fit see the freed width. What stays: the load slider, + p99, goodput, errors, dropped and the transport, at --present-scale. + ========================================================================== */ + +.app.is-presenting { + --present-scale: 1.5; +} + +.app.is-presenting .app-island-brand, +.app.is-presenting .app-island-menu, +.app.is-presenting .stage-toggle-library, +.app.is-presenting .stage-toggle-inspector, +.app.is-presenting .cv-ledger, +.app.is-presenting .cv-hint-idle { + display: none; +} + +/* The load island is the whole bar now, so it may use all of it, and the + slider with it: the room should see the load being dragged. */ +.app.is-presenting .app-island-load { + max-width: none; +} + +.app.is-presenting .traffic-load { + max-width: 720px; +} + +/* The bar's figures, on the desktop layout only: a phone's header already + fills its width, and growing it only took rows from the diagram. The + hero keeps its place as the largest thing on screen; the secondary + readouts and their labels grow with it so the back row can read which + number is which. The p99 column is a fixed width at the normal size + (Inspector.css) so the slider does not jump as the figure changes, and + is scaled with it. */ +@media (min-width: 721px) and (min-height: 501px), + (min-width: 721px) and (pointer: fine), + (min-width: 721px) and (pointer: none) { + .app.is-presenting .traffic .num-hero { + font-size: calc(var(--fs-hero) * var(--present-scale)); + } + + .app.is-presenting .traffic .num-md, + .app.is-presenting .traffic .num-lg { + font-size: calc(var(--fs-num) * var(--present-scale)); + } + + .app.is-presenting .traffic .label { + font-size: calc(var(--fs-label) * var(--present-scale)); + } + + .app.is-presenting .traffic-headline > .traffic-metric:first-child { + width: calc(98px * var(--present-scale)); + } +} + +/* The presenting bar (PresentBar.css) takes the foot of the canvas, so the + safe area every fit frames into stops above it. --pb-h is the bar's own + measured height; it wraps to two or three rows on a narrow screen. */ +.app.is-presenting .stage-safe { + bottom: calc(var(--pb-h, 56px) + var(--sp-3) * 2); +} + +.app.is-presenting .app-body.has-metrics .stage-safe { + bottom: calc(var(--strip-shown) + var(--pb-h, 56px) + var(--sp-3) * 3); +} + +/* The traffic key sits in the canvas's bottom corner, which is the bar's + row now; it lifts clear of the bar as the safe area does. */ +.app.is-presenting .cv-key { + bottom: calc(var(--pb-h, 56px) + var(--sp-3) * 2); +} + +.app.is-presenting .app-body.has-metrics .cv-key { + bottom: calc(var(--strip-shown) + var(--pb-h, 56px) + var(--sp-3) * 3); +} + +/* Phones. The tab bar goes: two of its three tabs open panels this mode + keeps shut. */ +@media (max-width: 720px), (pointer: coarse) and (max-height: 500px) { + .app.is-presenting { + --tabbar-h: 0px; + } + + .app.is-presenting .app-tabbar { + display: none; + } + + .app.is-presenting .stage-canvas > .stage-safe { + bottom: calc(var(--pb-h, 56px) + var(--sp-2) * 2); + } + + /* A brief, an incident or a task card docks on the tab bar, which this + mode takes away; they sit on the presenting bar instead of under it. */ + .app.is-presenting .app-body .chal, + .app.is-presenting .app-body .task { + bottom: calc( + var(--pb-h, 56px) + var(--sp-2) * 2 + env(safe-area-inset-bottom, 0px) + ); + } + + /* "What just happened" sits at the canvas's foot on a phone, which is + this bar's place now; it moves up by the bar's height. */ + .app.is-presenting .app-body .wh { + bottom: calc(var(--pb-h, 56px) + var(--sp-2) * 2); + } +} + +/* The zoom group's "Zoom to 70%" note is advice for the person building, + not the room watching. */ +.app.is-presenting .cv-zoom-note { + display: none; +} + +/* Toasts and "What just happened" sit one row above the canvas's foot, + a row sized for the zoom group. While presenting that row is this bar, + which is taller and wider, so they clear its measured height instead. */ +@media (min-width: 721px) and (min-height: 501px), + (min-width: 721px) and (pointer: fine), + (min-width: 721px) and (pointer: none) { + .app.is-presenting .app-toast-dock { + --toast-row-h: var(--pb-h, 56px); + } + + .app.is-presenting .wh { + --wh-zoom-h: var(--pb-h, 56px); + } +} + +/* When the larger figures no longer fit one row (useBarFit measures it, as + it does for the normal bar), the figures and the transport keep the top + row and the load slider takes the full row under them. */ +@media (min-width: 721px) and (min-height: 501px), + (min-width: 721px) and (pointer: fine), + (min-width: 721px) and (pointer: none) { + .app.is-presenting .app-bar[data-fit='compact'] .traffic { + flex-wrap: wrap; + row-gap: var(--sp-2); + } + + .app.is-presenting .app-bar[data-fit='compact'] .traffic-load { + order: 1; + flex: 1 1 100%; + max-width: none; + } + + .app.is-presenting .app-bar[data-fit='compact'] .traffic-spacer { + display: none; + } + + .app.is-presenting .app-bar[data-fit='compact'] .traffic-headline { + margin-right: auto; + } + + /* The normal bar drops goodput, errors and dropped below 860px of + control (Inspector.css), to keep the slider. Here the slider has its + own row, so they stay: they are half of what a class is shown. */ + .app.is-presenting .app-bar[data-fit='compact'] .traffic-metric-group { + display: flex; + } +} + +/* A phone on its side shows a brief as a side sheet, and folded it is its + heading only, at the top. */ +@media (pointer: coarse) and (max-height: 500px) { + .app.is-presenting .app-body .chal.is-collapsed { + bottom: auto; + } +} + +/* A phone held upright frames the diagram above a docked brief, incident or + task card, and in this mode those sit on the bar, so the frame stops above + both. */ +@media (max-width: 720px) and (orientation: portrait) { + .app.is-presenting .app-body.has-challenge .stage-canvas > .stage-safe { + bottom: calc( + var(--chal-sheet-h, var(--chal-fold-h)) + var(--pb-h, 56px) + var(--sp-2) * 2 + + env(safe-area-inset-bottom, 0px) + ); + } + + .app.is-presenting .app-body.has-task .stage-canvas > .stage-safe { + bottom: calc(var(--task-phone-h) + var(--pb-h, 56px) + var(--sp-2) * 3); + } +} diff --git a/src/App.runMenu.test.tsx b/src/App.runMenu.test.tsx new file mode 100644 index 0000000..f7ce9c4 --- /dev/null +++ b/src/App.runMenu.test.tsx @@ -0,0 +1,145 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import App from './App'; +import { makeNode } from './sim/presets'; +import type { Topology } from './sim/types'; + +/** + * Pause, Step and Reset from the menu. A touch screen has no Space or S key, + * and on a narrow bar the menu is the place every layout can always reach. + */ + +class FakePointerEvent extends MouseEvent { + pointerId: number; + pointerType: string; + isPrimary: boolean; + constructor( + type: string, + init: MouseEventInit & { pointerId?: number; pointerType?: string } = {}, + ) { + super(type, init); + this.pointerId = init.pointerId ?? 1; + this.pointerType = init.pointerType ?? 'mouse'; + this.isPrimary = true; + } +} + +const SESSION_KEY = 'breakscale.session.v1'; + +function ownDesign(): Topology { + const client = { ...makeNode('client', 0, 0), id: 'mine-client', label: 'My client' }; + const svc = { ...makeNode('service', 240, 0), id: 'mine-svc', label: 'My service' }; + return { + nodes: [client, svc], + edges: [{ id: 'mine-client->mine-svc', from: client.id, to: svc.id, weight: 1 }], + }; +} + +let container: HTMLDivElement; +let root: Root; + +function mount(): void { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + act(() => root.render()); +} + +/** A press the way a finger or a mouse makes one, ending in the click. */ +function press(el: Element): void { + const at = { bubbles: true, cancelable: true, button: 0, clientX: 5, clientY: 5 }; + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerdown', { ...at, buttons: 1 })); + el.dispatchEvent(new MouseEvent('mousedown', { ...at, buttons: 1 })); + }); + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('mouseup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('click', { ...at, buttons: 0 })); + }); +} + +function openMenu(): HTMLButtonElement[] { + press(document.querySelector('[aria-label="Menu"]')!); + return [...document.querySelectorAll('.mn-item')]; +} + +function item(label: string): HTMLButtonElement { + const el = openMenu().find( + (b) => b.querySelector('.mn-label')?.textContent === label, + ); + if (!el) throw new Error(`no menu item ${label}`); + return el; +} + +const toggle = () => + document.querySelector('.transport-toggle')!.getAttribute('aria-label'); +const clock = () => document.querySelector('.cv-ledger-time')?.textContent; + +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = + true; + vi.useFakeTimers(); + vi.stubGlobal('PointerEvent', FakePointerEvent); + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.reject(new Error('offline'))), + ); + localStorage.clear(); + window.history.replaceState(null, '', '/'); + localStorage.setItem( + SESSION_KEY, + JSON.stringify({ topology: ownDesign(), rps: 50, presetId: null }), + ); +}); + +afterEach(() => { + act(() => root.unmount()); + container.remove(); + document.body.innerHTML = ''; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe('the run controls in the menu', () => { + it('come first after Search actions, with their keys, and a rule after them', () => { + mount(); + const rows = openMenu().map((b) => b.textContent); + expect(rows.slice(0, 4)).toEqual([ + 'Search actionsCtrl+K', + 'PauseSpace', + 'StepS', + 'Reset', + ]); + const seps = Array.from(document.querySelectorAll('.mn [role="separator"]')); + expect(seps.map((s) => s.previousElementSibling?.textContent).slice(0, 2)).toEqual([ + 'Search actionsCtrl+K', + 'Reset', + ]); + }); + + it('pause and play the run', () => { + mount(); + expect(toggle()).toBe('Pause'); + press(item('Pause')); + expect(toggle()).toBe('Play'); + press(item('Play')); + expect(toggle()).toBe('Pause'); + }); + + it('step one tick from a stopped clock, and reset it to zero', () => { + mount(); + press(item('Pause')); + expect(clock()).toBe('0.0s'); + press(item('Step')); + expect(clock()).toBe('0.1s'); + expect(toggle()).toBe('Play'); + press(item('Step')); + expect(clock()).toBe('0.2s'); + press(item('Reset')); + expect(clock()).toBe('0.0s'); + }); +}); diff --git a/src/App.speed.test.tsx b/src/App.speed.test.tsx new file mode 100644 index 0000000..2582ebe --- /dev/null +++ b/src/App.speed.test.tsx @@ -0,0 +1,153 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import App from './App'; +import { makeNode } from './sim/presets'; +import type { Topology } from './sim/types'; + +/** + * Play speed from the bar and from [ and ]. The engine only ever sees + * advance(dt) in frame-sized steps (speed.test.ts); this is the shell. + */ + +class FakePointerEvent extends MouseEvent { + pointerId: number; + pointerType: string; + isPrimary: boolean; + constructor( + type: string, + init: MouseEventInit & { pointerId?: number; pointerType?: string } = {}, + ) { + super(type, init); + this.pointerId = init.pointerId ?? 1; + this.pointerType = init.pointerType ?? 'mouse'; + this.isPrimary = true; + } +} + +const SESSION_KEY = 'breakscale.session.v1'; + +function ownDesign(): Topology { + const client = { ...makeNode('client', 0, 0), id: 'mine-client', label: 'My client' }; + const svc = { ...makeNode('service', 240, 0), id: 'mine-svc', label: 'My service' }; + return { + nodes: [client, svc], + edges: [{ id: 'mine-client->mine-svc', from: client.id, to: svc.id, weight: 1 }], + }; +} + +let container: HTMLDivElement; +let root: Root; + +function mount(): void { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + act(() => root.render()); +} + +/** A press the way a finger or a mouse makes one, ending in the click. */ +function press(el: Element): void { + const at = { bubbles: true, cancelable: true, button: 0, clientX: 5, clientY: 5 }; + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerdown', { ...at, buttons: 1 })); + el.dispatchEvent(new MouseEvent('mousedown', { ...at, buttons: 1 })); + }); + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('mouseup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('click', { ...at, buttons: 0 })); + }); +} + +const clock = () => document.querySelector('.cv-ledger-time')?.textContent; + +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = + true; + vi.useFakeTimers(); + vi.stubGlobal('PointerEvent', FakePointerEvent); + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.reject(new Error('offline'))), + ); + localStorage.clear(); + window.history.replaceState(null, '', '/'); + localStorage.setItem( + SESSION_KEY, + JSON.stringify({ topology: ownDesign(), rps: 50, presetId: null }), + ); +}); + +afterEach(() => { + act(() => root.unmount()); + container.remove(); + document.body.innerHTML = ''; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +const speedBtn = () => document.querySelector('.transport-speed')!; + +function keyDown(key: string, init: KeyboardEventInit = {}): void { + act(() => { + window.dispatchEvent(new KeyboardEvent('keydown', { key, bubbles: true, ...init })); + }); +} + +/** Sim seconds on the ledger after `ms` of frames from a zeroed clock. */ +function simAfter(ms: number): number { + press(document.querySelector('[aria-label="Reset simulation"]')!); + act(() => { + vi.advanceTimersByTime(ms); + }); + return Number.parseFloat(clock() ?? 'NaN'); +} + +describe('play speed', () => { + it('starts at 1x and the button steps round the speeds', () => { + mount(); + expect(speedBtn().textContent).toBe('1×'); + press(speedBtn()); + expect(speedBtn().textContent).toBe('2×'); + press(speedBtn()); + expect(speedBtn().textContent).toBe('4×'); + press(speedBtn()); + expect(speedBtn().textContent).toBe('0.5×'); + expect(speedBtn().getAttribute('aria-label')).toBe( + 'Speed 0.5 times. Press for 1 times', + ); + }); + + it('[ and ] step slower and faster, hold at the ends, and are said aloud', () => { + mount(); + keyDown(']'); + keyDown(']'); + keyDown(']'); + expect(speedBtn().textContent).toBe('4×'); + keyDown('['); + expect(speedBtn().textContent).toBe('2×'); + expect(document.querySelector('.traffic [aria-live="polite"]')?.textContent).toBe( + 'Speed 2 times', + ); + keyDown('['); + keyDown('['); + keyDown('['); + expect(speedBtn().textContent).toBe('0.5×'); + // A modifier belongs to the browser. + keyDown(']', { metaKey: true }); + expect(speedBtn().textContent).toBe('0.5×'); + }); + + it('2x moves the clock twice as far in the same frames', () => { + mount(); + const one = simAfter(2000); + keyDown(']'); + const two = simAfter(2000); + expect(one).toBeGreaterThan(1); + expect(two / one).toBeGreaterThan(1.8); + expect(two / one).toBeLessThan(2.2); + }); +}); diff --git a/src/App.tsx b/src/App.tsx index 6fe695b..ac0b9a9 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -25,6 +25,9 @@ import type { } from './sim/types'; import { useCoarsePointer } from './useCoarsePointer'; import { useGithubStars, useCountUp, formatStars } from './useGithubStars'; +import { useBarFit } from './useBarFit'; +import { SpeedMeter, advanceAtSpeed, shortfall, stepSpeed, type Speed } from './speed'; +import type { PinnedRun } from './components/pinnedRun'; import { Engine } from './sim/engine'; import { PRESETS, makeNode } from './sim/presets'; import { CHALLENGES, challengeById } from './sim/challenges'; @@ -37,7 +40,7 @@ import { ChallengePanel } from './components/Challenge'; import { IncidentPanel } from './components/Incidents'; import { BreakPanel } from './components/BreakIt'; import type { Names } from './components/breakCopy'; -import { secs } from './components/breakCopy'; +import { clock, secs } from './components/breakCopy'; import { formatGoalMs, formatGoalPct, formatShareDown } from './components/format'; import { Challenges } from './components/Challenges'; import { @@ -71,11 +74,13 @@ import Canvas, { readoutFor, sourceBacklogs, } from './components/Canvas'; -import { Inspector, TrafficControl } from './components/Inspector'; +import { Inspector, TrafficControl, slowable } from './components/Inspector'; import { RouteAlert } from './components/RouteAlert'; import { + DEFAULT_SLOW_FACTOR, asReplacement, faultActionsFor, + formatFactor, faultViewFor, withEdgeLoss, withSchedule, @@ -85,9 +90,33 @@ import { Metrics } from './components/Metrics'; import { Palette } from './components/Palette'; import { Glossary } from './components/Glossary'; import { Shortcuts } from './components/Shortcuts'; +import { StripCue } from './components/StripCue'; +import { isMac, shortcutLabel } from './modKey'; import { Examples } from './components/Examples'; -import { cloneSubgraph, isTopology, selectionSubgraph } from './clipboard'; +import { + buildClipboardText, + cloneSubgraph, + isTopology, + parseClipboardText, + selectionSubgraph, +} from './clipboard'; import type { ClipboardSubgraph } from './clipboard'; +import { CanvasMenu } from './components/CanvasMenu'; +import { CommandPalette } from './components/CommandPalette'; +import { PresentBar, type PresentPart } from './components/PresentBar'; +import { buildCommands, type CommandActions, type CommandFacts } from './appCommands'; +import { loadRecent, pushRecent, saveRecent, type Command } from './commands'; +import { + canFullscreen, + toggleFullscreen, + useFocusedPart, + useFullscreen, + usePresenting, +} from './present'; +import { pinRun, trailingWindow } from './components/pinnedRun'; +import type { CanvasMenuActions } from './components/CanvasMenu'; +import type { CanvasMenuApi } from './components/Canvas'; +import type { CanvasMenuRequest } from './components/contextMenuItems'; import { NOTE_DEFAULT_WIDTH, NOTE_MAX_CHARS, @@ -112,15 +141,26 @@ import { FindProblem } from './learn/FindProblem'; import { currentFinding, spotlightOf, type Finding } from './learn/finding'; import { WhatHappened } from './learn/WhatHappened'; import { LearningPath } from './learn/LearningPath'; -import { usePathProgress } from './learn/pathProgress'; +import { + stepAfter, + stepName, + stepOfBrief, + usePathProgress, +} from './learn/pathProgress'; +import type { PathStep } from './content/learningPath'; +import { PassStrip } from './learn/PassStrip'; +import { useExampleTask } from './learn/useExampleTask'; +import { TaskCard } from './learn/TaskCard'; import { Tour } from './learn/Tour'; import { useTour } from './learn/useTour'; -import { togglePreference, usePreference } from './content/preferences'; +import { setPreference, togglePreference, usePreference } from './content/preferences'; import type { ThemeChoice } from './content/preferences'; +import { GLOSSARY } from './content/glossary'; +import { KIND_GROUPS, KIND_NAME } from './components/nodeVisuals'; import { EMPTY_BOOT_PARAMS, parseBootParams } from './urlParams'; import type { BootParams } from './urlParams'; import { Settings } from './components/Settings'; -import { MainMenu } from './components/MainMenu'; +import { MainMenu, type MenuItem } from './components/MainMenu'; import { Designs } from './components/Designs'; import { getDesign, saveDesign } from './savedDesigns'; import { downloadBackup, restoreBackup } from './backup'; @@ -131,6 +171,7 @@ import { SessionHistory, syncEngine } from './history'; import type { FaultApplier, HistoryEntry, HistorySnapshot } from './history'; import { ShareLinkTooLargeError, decodeTopology, hasShareHash } from './share'; import { ID_PARAM, ShareStoreError, fetchStored, hasStoredLink } from './share/store'; +import { challengeLink, exampleParam, routedHref } from './urlRoute'; import { buildLink, designTopology, @@ -140,7 +181,13 @@ import { import { Share, type ShareKind, type ShareResult } from './components/Share'; import { DESIGN_FILE_ACCEPT, downloadDesign, readDesignFile } from './designFile'; import { downloadBlob, svgToPng } from './imageExport'; +import { PHONE_QUERY } from './phoneQuery'; +import { isOneRail, libraryShown, useOneRail } from './oneRail'; +import { cycleRegion, focusDiagram } from './keyboardNav'; +import { revealTarget } from './revealTarget'; import './App.css'; +import './App.phone.css'; +import './App.present.css'; /* ------------------------------------------------------------------ * * Persistence @@ -173,6 +220,10 @@ const WARMUP_STEP_MS = 1000 / 60; const LAYOUT_KEY = 'breakscale.layout.v1'; +/** Presenting's bar goes to two rows before its load slider is narrower + than this, so the room can see it move. */ +const PRESENT_MIN_SLIDER_PX = 240; + /** * How far a sheet must be pulled down before releasing closes it. * @@ -240,11 +291,11 @@ const clampPanel = (key: PanelKey, v: unknown): number => { * exist to explain), and the components rail must not boot open, which is a * default rather than a style. * - * A media query rather than a device or touch test. The question is how much - * room the shell has, and a small desktop window has exactly the same - * problem as a phone; a tablet in landscape has neither. + * A media query rather than a device test. The question is how much room the + * shell has, and a small desktop window has exactly the same problem as a + * phone; a tablet in landscape has neither. A phone on its side is the one + * place a pointer test joins in; see phoneQuery.ts. */ -const PHONE_QUERY = '(max-width: 720px)'; const SOURCE_URL = 'https://github.com/workersio/breakscale'; @@ -255,6 +306,25 @@ function subscribePhone(onChange: () => void): () => void { return () => mq.removeEventListener('change', onChange); } +/** + * Too narrow for the components rail, a brief or task card and a diagram + * between them. Measured at 820px: the canvas left between the rail and a + * brief was about 220px, and the part the brief was about sat under it. + */ +const CROWDED_QUERY = '(max-width: 1100px)'; + +function subscribeCrowded(onChange: () => void): () => void { + if (typeof window === 'undefined' || !window.matchMedia) return () => {}; + const mq = window.matchMedia(CROWDED_QUERY); + mq.addEventListener('change', onChange); + return () => mq.removeEventListener('change', onChange); +} + +function isCrowded(): boolean { + if (typeof window === 'undefined' || !window.matchMedia) return false; + return window.matchMedia(CROWDED_QUERY).matches; +} + function isPhone(): boolean { if (typeof window === 'undefined' || !window.matchMedia) return false; return window.matchMedia(PHONE_QUERY).matches; @@ -380,10 +450,18 @@ function PanelSlot({ edge, children, onDismiss, + scrim = true, }: { open: boolean; edge: 'left' | 'right' | 'bottom'; children: ReactNode; + /** + * Dim the canvas behind the sheet and close it on a tap there. Off for + * the inspector, whose sheet leaves the diagram above it in use: a tap on + * another part selects that part, and a tap on empty canvas clears the + * selection, which closes the sheet anyway. + */ + scrim?: boolean; /** * Close this panel from inside it. Phone only: on a desktop a rail sits * BESIDE the canvas and dismissing it by touching the canvas would fight @@ -484,7 +562,7 @@ function PanelSlot({ anywhere off the sheet closes it, and dims what is behind so the sheet reads as the layer in front. Hidden above the breakpoint by CSS, where the panels are rails and there is nothing to dismiss. */} - {onDismiss ? ( + {onDismiss && scrim ? (
+ canonical({ nodes: t.nodes.map((n) => [n.id, n.kind, n.config]), edges: t.edges }); + /** The reader's own design, held while a challenge has the canvas. */ interface Aside extends Session { /** @@ -915,8 +1015,20 @@ export default function App() { const [shareRun, setShareRun] = useState(null); const [topology, setTopology] = useState(initial.topology); + /** + * The design's 1x: its total client rate when it was opened (an example, a + * file, a share link, a brief), or when the reader said "make this 1x". + * The slider leaves it alone, so the header can say how far it has been + * pushed. Saved with the session, never put in a share link, so a shared + * design's 1x is whatever it was sending when the recipient opened it. + */ const [rps, setRps] = useState(initial.rps); const [presetId, setPresetId] = useState(initial.presetId); + /** Counts example loads, so opening the same one again restarts its task. */ + const [exampleRun, setExampleRun] = useState(0); + /** The task card takes focus as it next shows: see TaskCard's takeFocus. */ + const [taskFocus, setTaskFocus] = useState(false); + const handleTaskFocusTaken = useCallback(() => setTaskFocus(false), []); /** * Canvas selection. Node ids and edge ids share this one set; an edge id is * `from->to`, which can never collide with a node id, so the namespace is @@ -965,6 +1077,22 @@ export default function App() { const [shortcutsOpen, setShortcutsOpen] = useState(false); const [settingsOpen, setSettingsOpen] = useState(false); const [menuOpen, setMenuOpen] = useState(false); + /* The command palette (Ctrl+K), and what it ran last, newest first. */ + const [paletteOpen, setPaletteOpen] = useState(false); + const [recentCommands, setRecentCommands] = useState(loadRecent); + /* The menu and the chord are wired above the palette's builder; they + reach it through these. */ + const openPaletteRef = useRef<() => void>(() => {}); + const paletteOpenRef = useRef(false); + /* Presenting mode (present.ts). The fault keys are bound once, here, and + reach the fault controls declared further down through this ref. */ + const presentFaultRef = useRef<(kind: 'crash' | 'slow' | 'fix') => void>(() => {}); + const presentChangeRef = useRef<(on: boolean) => void>(() => {}); + const { presenting, togglePresenting, stopPresenting } = usePresenting( + useCallback((kind: 'crash' | 'slow' | 'fix') => presentFaultRef.current(kind), []), + useCallback((on: boolean) => presentChangeRef.current(on), []), + ); + const fullscreen = useFullscreen(); const [designsOpen, setDesignsOpen] = useState(false); /** @@ -1078,6 +1206,9 @@ export default function App() { */ const barRef = useRef(null); const [barBottom, setBarBottom] = useState(null); + /* Below the width where the islands fit on one row, the load island moves + to a row of its own and GitHub moves into the menu (see useBarFit). */ + const barCompact = useBarFit(barRef, presenting ? PRESENT_MIN_SLIDER_PX : 0); useLayoutEffect(() => { const el = barRef.current; @@ -1120,14 +1251,17 @@ export default function App() { and the reader loses the thing they changed it to see. The inspector is part of this too, and was not before, which is how three could stack. On a desktop they are rails on three different edges and coexist. */ - const toggleLibrary = useCallback(() => { - setLayout((l) => ({ - ...l, - library: !l.library, - metrics: !l.library && phone ? false : l.metrics, - })); - if (phone) setInspectorHidden(true); - }, [phone]); + /* Folded by an automatic fit that could not show the whole diagram beside + it (see handleFitClipped). Kept apart from layout.library, so the + reader's saved choice is never rewritten by it, and cleared by the next + design or by the reader opening the rail. */ + const [railMadeRoom, setRailMadeRoom] = useState(false); + /* With room for one rail (a tablet held upright, see oneRail.ts) the + components rail starts closed for this visit. Kept apart from + layout.library for the same reason as railMadeRoom. */ + const oneRail = useOneRail() && !phone; + const [railFolded, setRailFolded] = useState(() => isOneRail() && !isPhone()); + const libraryWanted = layout.library && !railMadeRoom && !railFolded; const toggleMetrics = useCallback(() => { setLayout((l) => ({ @@ -1154,11 +1288,20 @@ export default function App() { * settings back. Deliberately not persisted, for the same reason. */ + /* Set by an add from the components rail, so the part it adds does not + put the rail away where only one fits (see libraryShown). */ + const keepRailRef = useRef(false); useEffect(() => { - if (selectedIds.size > 0) setInspectorHidden(false); + const keep = keepRailRef.current; + keepRailRef.current = false; + if (selectedIds.size > 0 && !keep) setInspectorHidden(false); }, [selectedIds]); const toggleInspector = useCallback(() => setInspectorHidden((h) => !h), []); + /* Tapping the part that is already selected brings its settings back. On a + phone that is how a closed sheet is reopened: the selection never + changed, so nothing else would. */ + const showInspector = useCallback(() => setInspectorHidden(false), []); /** * The selection, split into the three things it can hold. Node ids and @@ -1188,7 +1331,31 @@ export default function App() { * produces a blank panel. */ const hasSelection = selectedNodes.length + selectedEdgeCount > 0; - const inspectorVisible = hasSelection && !inspectorHidden; + /* Presenting puts both side panels away without touching the saved + layout, so leaving it puts back whatever was open. */ + const inspectorVisible = hasSelection && !inspectorHidden && !presenting; + const libraryOpen = + !presenting && libraryShown(libraryWanted, oneRail, inspectorVisible); + + /** + * Where the next component picked from the rail lands, set by the canvas + * menu's "Add component here". Spent by that pick, and dropped when the + * rail closes without one. + */ + const addAtRef = useRef<{ x: number; y: number } | null>(null); + + const toggleLibrary = useCallback(() => { + const open = libraryOpen; + if (open) addAtRef.current = null; + setLayout((l) => ({ + ...l, + library: !open, + metrics: !open && phone ? false : l.metrics, + })); + setRailMadeRoom(false); + setRailFolded(false); + if (phone || (oneRail && !open)) setInspectorHidden(true); + }, [phone, oneRail, libraryOpen]); /** * The uncovered-canvas sentinel (see .stage-safe in App.css): an inert div @@ -1282,7 +1449,7 @@ export default function App() { { label: 'Keyboard shortcuts', icon: 'M2 5.5A2.5 2.5 0 0 1 4.5 3h15A2.5 2.5 0 0 1 22 5.5v13a2.5 2.5 0 0 1-2.5 2.5h-15A2.5 2.5 0 0 1 2 18.5zM6 9h.01M10 9h.01M14 9h.01M18 9h.01M6 13h.01M18 13h.01M9 13h6M7 17h10', - hint: 'Ctrl+/', + hint: shortcutLabel('Ctrl+/'), onSelect: () => setShortcutsOpen(true), }, ]), @@ -1293,7 +1460,7 @@ export default function App() { }, /* The phone header has no room for the GitHub link, so it moves here rather than going missing. */ - ...(phone + ...(phone || barCompact ? [ { label: 'Source on GitHub', @@ -1305,7 +1472,7 @@ export default function App() { ] : []), ], - [openGlossary, coarse, phone], + [openGlossary, coarse, phone, barCompact], ); /** @@ -1343,6 +1510,18 @@ export default function App() { */ const [routes, setRoutes] = useState(() => engine.routes()); + /* The per-wire outcome counts behind the traffic dots and the canvas's + retry and loss marks, which stay on with the dots turned off. The engine + keeps them outside the snapshot, so they never change what a replay or + a share link reproduces. */ + useEffect(() => { + engine.setEdgeOutcomes(true); + }, [engine]); + const readOutcomes = useCallback( + (edgeId: string, out: Float64Array) => engine.readEdgeOutcomes(edgeId, out), + [engine], + ); + // "Find the problem": the last answer, shown while it still applies. const [finding, setFinding] = useState(null); const shownFinding = currentFinding(finding, topology, snapshot); @@ -1357,6 +1536,24 @@ export default function App() { runningRef.current = running; }, [running]); + /* Play speed (speed.ts). A preference of this tab, not of the design: it + is in no link and no saved file, and every load starts at 1x. The loop + reads the ref; `slowAt` is the speed this machine really manages, shown + only when it falls clearly short of the one asked for. */ + const [speed, setSpeedState] = useState(1); + const [slowAt, setSlowAt] = useState(null); + const speedRef = useRef(1); + const speedMeterRef = useRef(new SpeedMeter()); + const setSpeed = useCallback((next: Speed) => { + speedRef.current = next; + speedMeterRef.current.clear(); + setSpeedState(next); + setSlowAt(null); + }, []); + + /* A run held still to compare against (PinBar). Session only. */ + const [pinned, setPinned] = useState(null); + /* ---------------- per-node sparkline history ---------------- * * `SimSnapshot.history` is system-wide — `HistoryPoint` carries no node id — @@ -1427,7 +1624,29 @@ export default function App() { if (!runningRef.current) return; // Clamp so a long tab-away does not replay minutes of simulated time. - engine.advance(Math.min(dt, MAX_FRAME_MS)); + const frameMs = Math.min(dt, MAX_FRAME_MS); + const s = speedRef.current; + if (s === 1) { + engine.advance(frameMs); + } else { + const done = advanceAtSpeed( + (d) => engine.advance(d), + frameMs, + s, + () => performance.now(), + ); + // At most once a second, and only when what is shown would change. + const measured = speedMeterRef.current.add(done, frameMs); + if (measured !== null) { + const short = shortfall(s, measured); + setSlowAt((prev) => + prev === short || + (prev !== null && short !== null && Math.abs(prev - short) < 0.05) + ? prev + : short, + ); + } + } // React re-renders at ~10Hz, not once per frame. The engine keeps // full temporal resolution regardless. @@ -1558,11 +1777,17 @@ export default function App() { * that something happened. `id` keys the element so consecutive undos * restart the entrance animation instead of freezing on one message. */ - const [toast, setToast] = useState<{ text: string; id: number } | null>(null); + const [toast, setToast] = useState<{ + text: string; + id: number; + /** A button in the toast, such as Undo after a delete. */ + action?: { label: string; run: () => void }; + } | null>(null); const toastSeq = useRef(0); useEffect(() => { if (!toast) return; - const t = window.setTimeout(() => setToast(null), 2200); + // Long enough to reach for the button when there is one. + const t = window.setTimeout(() => setToast(null), toast.action ? 5000 : 2200); return () => window.clearTimeout(t); }, [toast]); @@ -1589,6 +1814,17 @@ export default function App() { * student, and add/delete/undo must not move it. */ const [fitNonce, setFitNonce] = useState(0); + /* Presenting frees the width the panels held, so the diagram is fitted + again to fill it, and again on the way out. */ + /* Two frames late: the bar grows with the mode's larger figures, and the + clearance the fit frames under is measured from it a frame after. */ + useEffect(() => { + presentChangeRef.current = () => { + requestAnimationFrame(() => + requestAnimationFrame(() => setFitNonce((n) => n + 1)), + ); + }; + }, []); /** * The challenge sheet's size, kept in the uncovered-canvas sentinel. @@ -1698,7 +1934,10 @@ export default function App() { setRoutes(engine.routes()); // An answer read from the run that just ended would carry its numbers. setFinding(null); - if (fit) setFitNonce((n) => n + 1); + if (fit) { + setFitNonce((n) => n + 1); + setRailMadeRoom(false); + } }, [engine, resetLostRate], ); @@ -2188,6 +2427,16 @@ export default function App() { [applyTopology, history], ); + /** A part dragged from the components rail onto the canvas. */ + const handleDropNode = useCallback( + (kind: NodeKind, x: number, y: number) => { + addAtRef.current = null; + if (oneRail && libraryOpen) keepRailRef.current = true; + handleAddNode(kind, x, y); + }, + [handleAddNode, oneRail, libraryOpen], + ); + /** * Filled by the canvas with a "world point at the centre of the current * view" getter. A palette CLICK has no drop point of its own; the old @@ -2217,7 +2466,9 @@ export default function App() { /** Palette click (no drop point): place at the centre of the current view. */ const handlePaletteAdd = useCallback( (kind: NodeKind) => { - const centre = viewCenterRef.current?.(); + if (oneRail && libraryOpen) keepRailRef.current = true; + const centre = addAtRef.current ?? viewCenterRef.current?.(); + addAtRef.current = null; if (!centre) { // No canvas yet (should not happen in practice): old fallback. const maxX = topology.nodes.reduce((m, n) => Math.max(m, n.x), 0); @@ -2250,7 +2501,7 @@ export default function App() { const spot = ring.find(([dx, dy]) => !occupied(cx + dx, cy + dy)) ?? [0, 0]; handleAddNode(kind, cx + spot[0], cy + spot[1]); }, - [handleAddNode, topology.nodes], + [handleAddNode, topology.nodes, oneRail, libraryOpen], ); const handleConnect = useCallback( @@ -2320,8 +2571,28 @@ export default function App() { for (const id of dropAnns) next.delete(id); return next; }); + // No confirm before a delete; the toast offers the undo instead. + if (nodeIds.length > 0) { + const only = + nodeIds.length === 1 ? topology.nodes.find((n) => n.id === nodeIds[0]) : null; + // Only while the delete is still the last thing done: a later edit, + // settled or still settling, would be what Undo took back. + const entry = history.lastEntry; + toastSeq.current += 1; + setToast({ + text: only ? `Deleted ${only.label}` : `Deleted ${nodeIds.length} components`, + id: toastSeq.current, + action: { + label: 'Undo', + run: () => { + if (!history.settling && history.lastEntry === entry) handleUndo(); + else setToast(null); + }, + }, + }); + } }, - [applyTopology, setAnnotations, topology, history], + [applyTopology, setAnnotations, topology, history, handleUndo], ); /** The Inspector's single-node delete routes through the same path. */ @@ -2367,13 +2638,20 @@ export default function App() { * small enough that the copy reads as "yours, here" and large enough that * it never lands exactly on its source and looks like nothing happened. */ - const handleDuplicate = useCallback(() => { - const sub = selectionSubgraph(topology, selectedIds); - if (!sub) return; - // ONE entry for the whole duplicate, selection included. - history.commit('duplicate', snapRef.current); - appendClones(cloneSubgraph(sub, topology, GRID * 2, GRID * 2)); - }, [topology, selectedIds, history, appendClones]); + const duplicateIds = useCallback( + (ids: ReadonlySet) => { + const sub = selectionSubgraph(topology, ids); + if (!sub) return; + // ONE entry for the whole duplicate, selection included. + history.commit('duplicate', snapRef.current); + appendClones(cloneSubgraph(sub, topology, GRID * 2, GRID * 2)); + }, + [topology, history, appendClones], + ); + const handleDuplicate = useCallback( + () => duplicateIds(selectedIds), + [duplicateIds, selectedIds], + ); /** * Alt+drag: the same duplication as Ctrl+D, but born under the pointer as @@ -2442,6 +2720,115 @@ export default function App() { [topology, history, appendClones], ); + /* ---------------- context menu ---------------- */ + + /** + * The last thing copied in this tab, beside the system clipboard. Paste + * here reads it first: reading the system clipboard on a phone raises a + * permission prompt, and on some browsers it is not allowed at all. + */ + const [copied, setCopied] = useState(null); + + /** Copy from the menu or the inspector, where there is no copy event. */ + const handleCopyIds = useCallback( + (ids: readonly string[]) => { + const text = buildClipboardText(topology, new Set(ids)); + if (!text) return; + setCopied(text); + // Best effort, so Ctrl+V in another tab finds it too. + void navigator.clipboard?.writeText(text).catch(() => {}); + const only = + ids.length === 1 ? topology.nodes.find((n) => n.id === ids[0]) : null; + const what = only ? only.label : `${ids.length} components`; + toastSeq.current += 1; + setToast({ + text: coarse + ? `Copied ${what}. Press and hold the canvas to paste.` + : `Copied ${what}. ${shortcutLabel('Ctrl+V')} pastes at the pointer.`, + id: toastSeq.current, + }); + }, + [topology, coarse, setCopied], + ); + + const handleCopySelection = useCallback( + () => + handleCopyIds( + topology.nodes.filter((n) => selectedIds.has(n.id)).map((n) => n.id), + ), + [handleCopyIds, topology.nodes, selectedIds], + ); + + const handlePasteAt = useCallback( + async (at: { x: number; y: number }) => { + let text = copied; + if (!text && navigator.clipboard?.readText) { + try { + text = await navigator.clipboard.readText(); + } catch { + text = null; + } + } + const sub = text ? parseClipboardText(text) : null; + if (!sub) { + toastSeq.current += 1; + setToast({ + text: 'Nothing to paste yet. Copy a component first.', + id: toastSeq.current, + }); + return; + } + handlePaste(sub, at); + }, + [copied, handlePaste], + ); + + const [menu, setMenu] = useState<{ req: CanvasMenuRequest; seq: number } | null>( + null, + ); + const menuSeq = useRef(0); + const menuApiRef = useRef(null); + const handleCanvasMenu = useCallback((req: CanvasMenuRequest | null) => { + menuSeq.current += 1; + setMenu(req ? { req, seq: menuSeq.current } : null); + }, []); + const closeMenu = useCallback(() => setMenu(null), []); + + const menuActions = useMemo( + () => ({ + inspect: (ids) => { + if (ids.length !== selectedIds.size || ids.some((id) => !selectedIds.has(id))) { + setSelectedIds(new Set(ids)); + } + showInspector(); + }, + duplicate: (ids) => duplicateIds(new Set(ids)), + copy: handleCopyIds, + connect: (id, keyboard) => menuApiRef.current?.startLink(id, keyboard), + remove: (nodeIds, edgeIds) => handleDeleteSelection(nodeIds, edgeIds), + setLoss: handleEdgeLoss, + paste: (at) => void handlePasteAt(at), + add: (at) => { + addAtRef.current = at; + if (!libraryOpen) toggleLibrary(); + toastSeq.current += 1; + setToast({ text: 'Pick a component and it lands here.', id: toastSeq.current }); + }, + fit: () => menuApiRef.current?.fitAll(), + }), + [ + selectedIds, + showInspector, + duplicateIds, + handleCopyIds, + handleDeleteSelection, + handleEdgeLoss, + handlePasteAt, + libraryOpen, + toggleLibrary, + ], + ); + /* ---------------- live config edits ---------------- */ /** @@ -2546,7 +2933,6 @@ export default function App() { // A brief states its load and is judged at it. The slider is held // still while one is open; this is the same rule where it lands. if (challengeLiveRef.current !== null) return; - setRps(next); const clients = findClients(topology); if (clients.length === 0) return; if (clients.length === 1) { @@ -2703,7 +3089,10 @@ export default function App() { text = await file.text(); } catch { toastSeq.current += 1; - setToast({ text: 'That file could not be read.', id: toastSeq.current }); + setToast({ + text: 'That file could not be read. Choose a backup file saved from Breakscale (.json).', + id: toastSeq.current, + }); return; } @@ -2756,6 +3145,7 @@ export default function App() { preset.id, 'example load', ); + setExampleRun((n) => n + 1); if (left) { toastSeq.current += 1; setToast({ text: `Opened ${preset.name} ${IN_PLACE}`, id: toastSeq.current }); @@ -2768,6 +3158,21 @@ export default function App() { toastSeq.current += 1; setToast({ text, id: toastSeq.current }); }, []); + + /* A design opened too wide for the canvas beside the components rail, + even at the lowest zoom a card still says what it is at. The rail folds + for this design and the fit runs again; the reader is told, once, how + to get it back. A phone's rail is a sheet that starts closed. */ + const handleFitClipped = useCallback(() => { + if (phone || !libraryOpen) return; + setRailMadeRoom(true); + setFitNonce((n) => n + 1); + say( + coarse + ? 'Hid components to fit the diagram. The button at the top left shows them.' + : 'Hid components to fit the diagram. Press C to show them.', + ); + }, [phone, libraryOpen, coarse, say]); // Once, for what boot did before there was a toast to say it with. const bootNotice = boot.notice; useEffect(() => { @@ -2855,6 +3260,10 @@ export default function App() { updateStore((s) => withPass(s, brief, attemptFor(s, brief)?.hintsShown ?? 0, new Date()), ); + // On a phone the inspector's sheet covers the brief's. The pass is what + // the reader was working for, so the inspector steps down for it; the + // selection stays, and tapping the part brings its settings back. + if (phoneRef.current) setInspectorHidden(true); }, [updateStore], ); @@ -2954,12 +3363,21 @@ export default function App() { tourSubject, ); // A brief's canvas carries its example's id; that is not the example run. - // A finished tour broke and fixed the first example, so it counts too. - const explored = usePathProgress( + const exampleTask = useExampleTask( challengeId ? null : presetId, + exampleRun, topology, snapshot, - tour.open && tour.stage.kind === 'fixed' ? PRESETS[0]!.id : null, + ); + const taskView = exampleTask.view; + // An example is done when its task is. A finished tour broke and fixed + // the first example, so it counts too. + const explored = usePathProgress( + tour.open && tour.stage.kind === 'fixed' + ? PRESETS[0]!.id + : taskView.kind === 'live' && taskView.done + ? taskView.task.presetId + : null, ); /* ---------------- design files ---------------- @@ -3018,7 +3436,10 @@ export default function App() { } catch { // A failed export must say so. Silence here reads as a broken button. toastSeq.current += 1; - setToast({ text: 'That picture could not be saved.', id: toastSeq.current }); + setToast({ + text: 'The picture could not be saved. Try again, or save the design to a file.', + id: toastSeq.current, + }); } }, [presetId], @@ -3147,20 +3568,101 @@ export default function App() { // reload the link over the change they had just made. }, [switchWorkspace, installDesign]); - /* A `?challenge=` link has done its job once boot has followed it. - Taken off the URL so a reload after leaving the brief does not put the - reader straight back into it. The location is outside React, which is - why this is an effect. */ + /* The address bar says what is open: `?challenge=` inside a brief, + `?example=` while an example is open and unchanged, which an edit + ends by clearing presetId. Entering or leaving a brief is a step Back + can undo, so it pushes; the example only ever replaces, since a Back + press that quietly took an example off the canvas would be a surprise. + A share link on screen keeps its own URL. The location is outside + React, which is why this is an effect. */ + const routedChallenge = useRef(undefined); useEffect(() => { try { - const url = new URL(window.location.href); - if (!url.searchParams.has('challenge')) return; - url.searchParams.delete('challenge'); - window.history.replaceState(window.history.state, '', url.toString()); + const linked = shareHashPresent(); + if (sharePending && linked) return; + const href = window.location.href; + const example = challengeId === null ? presetId : null; + const next = routedHref(href, { + challengeId, + exampleId: example, + dropShare: example !== null && linked, + }); + const moved = + routedChallenge.current !== undefined && + routedChallenge.current !== challengeId; + routedChallenge.current = challengeId; + if (next === href) return; + if (moved) window.history.pushState(null, '', next); + else window.history.replaceState(window.history.state, '', next); + } catch { + // A locked-down location: the address stays as it was. + } + }, [challengeId, presetId, sharePending]); + + /* An `?example=` link opens that example, through the same undoable + load as the picker, unless a share link or a brief's link is on the URL + too: those go first, as boot puts them first. Read at mount, before + the effect above rewrites the query. */ + const [linkedExample] = useState(() => { + try { + if (shareHashPresent() || challengeParam(window.location.search)) return null; + const id = exampleParam(window.location.search); + return PRESETS.find((p) => p.id === id) ?? null; } catch { - // A locked-down location: the link stays, and only costs a resume. + // No DOM (a test importing App): no link to follow. + return null; } - }, []); + }); + const followedExample = useRef(false); + useEffect(() => { + if (!linkedExample || followedExample.current) return; + followedExample.current = true; + const own = snapRef.current; + if (own.challengeId === null && own.presetId === linkedExample.id) return; + handleLoadPreset(linkedExample); + // From a brief, the load has said so itself. From the reader's own + // design it says how to get that back; a fresh example needs no word. + if (own.challengeId === null && own.presetId === null) { + say(`Opened ${linkedExample.name}. Undo brings your design back.`); + } + }, [linkedExample, handleLoadPreset, say]); + + /* Back and Forward through a brief. The URL has already moved; this + moves the canvas to match, by the same paths the buttons use. */ + useEffect(() => { + const onPop = () => { + let id: string | null = null; + try { + id = challengeParam(window.location.search); + } catch { + return; + } + const want = id && challengeById(id) ? id : null; + if (want === challengeLiveRef.current) return; + if (want) handleStartChallenge(want); + else handleLeaveChallenge(); + }; + window.addEventListener('popstate', onPop); + return () => window.removeEventListener('popstate', onPop); + }, [handleStartChallenge, handleLeaveChallenge]); + + const handleCopyChallengeLink = useCallback(() => { + if (!challengeId) return; + let link: string; + try { + link = challengeLink(window.location.href, challengeId); + } catch { + return; + } + const failed = () => say('Could not copy the link. It is in the address bar.'); + try { + void navigator.clipboard + .writeText(link) + .then(() => say('Copied a link to this challenge.'), failed); + } catch { + failed(); + } + }, [challengeId, say]); /** * Open the share dialog without building anything. The design is only @@ -3221,6 +3723,56 @@ export default function App() { on purpose, and that is not a reason to lose it. An incident's panel takes the same room. */ const tourShown = tour.open && !breakShown && !incident; + /* The task card takes the tour's corner, so it waits for the tour, and + for the panels that take the same column. */ + const taskShown = + taskView.kind !== 'none' && !challenge && !tour.open && !breakShown && !incident; + const taskOpen = taskShown && !taskView.hidden && !(phone && inspectorVisible); + /* A brief, an outage or a task card takes a corner of the canvas as it + opens, so the diagram is framed again in what is left. Loading a design + frames it already; this is for the card that comes after, as the task + card does once the first-visit tour is skipped, when it covered the + very part its steps were about. + + On a narrow window it also closes the components rail, so the diagram + has the room between them. Once, as each one opens: a rail opened again + after that is the student's choice. A phone's rail is a sheet that is + already shut. + + A task is keyed by its load, and the last guide framed is remembered + across none: a delete hides the task card and undo brings the same one + back, and add, delete and undo never move the camera. */ + const crowded = useSyncExternalStore(subscribeCrowded, isCrowded, isPhoneServer); + const guide = challenge + ? `brief:${challenge.id}` + : incident + ? `outage:${incident.id}` + : taskShown + ? `task:${taskView.task.presetId}:${exampleRun}` + : null; + const [lastGuide, setLastGuide] = useState(null); + if (guide !== null && lastGuide !== guide) { + setLastGuide(guide); + if (crowded && !phone && layout.library) { + setLayout((l) => ({ ...l, library: false })); + } + setFitNonce((n) => n + 1); + // A brief or a story has the reader's attention now, not a task. + if (!guide.startsWith('task:') && taskFocus) setTaskFocus(false); + } + /** The part the current step is about, ringed while the card is open. */ + const taskRing = + taskView.kind === 'live' && !taskView.done + ? (taskView.task.steps[taskView.progress.step]?.ring ?? null) + : null; + /* A finished tour has just done the first example's task with the student, + so its card starts folded rather than asking for it all again. */ + const tourFixed = tour.open && tour.stage.kind === 'fixed'; + const [lastTourFixed, setLastTourFixed] = useState(tourFixed); + if (lastTourFixed !== tourFixed) { + setLastTourFixed(tourFixed); + if (tourFixed) exampleTask.setHidden(PRESETS[0]!.id, true); + } const breakSearch = useBreakSearch(breakShown, topology); const breakView = breakSearch.view; @@ -3241,16 +3793,22 @@ export default function App() { breakBlockedRef.current = breakBlocked; }, [breakBlocked]); + /* Names from the design as it is, then from the one the verdict ran on, + so a part deleted since keeps its name in that verdict. */ + const ranDesign = breakView.status === 'done' ? breakView.design : null; const breakNames = useMemo(() => { - const label = (id: string) => nodeNames[id] ?? id; + const ran = (id: string) => ranDesign?.nodes.find((n) => n.id === id)?.label; + const label = (id: string) => nodeNames[id] ?? ran(id) ?? id; return { node: label, edge: (id: string) => { - const e = topology.edges.find((x) => x.id === id); - return e ? `the cable from ${label(e.from)} to ${label(e.to)}` : id; + const e = + topology.edges.find((x) => x.id === id) ?? + ranDesign?.edges.find((x) => x.id === id); + return e ? `the connection from ${label(e.from)} to ${label(e.to)}` : id; }, }; - }, [nodeNames, topology.edges]); + }, [nodeNames, topology.edges, ranDesign]); /* The parts under attack, for the canvas: a ring while a schedule is tried, numbered badges on a break. */ @@ -3310,6 +3868,53 @@ export default function App() { ? breakWatchSet : null; + /* During the replay of a correctness break, the part where the checked + request went wrong, once the replay's clock passes that moment. The + moment is the one the search measured: the live run steps at the + display's rate, so on screen it can land a little apart. */ + const violationAt = useMemo(() => { + if (!breakWatch || breakView.status !== 'done') return null; + if (breakView.result.status !== 'broke') return null; + const v = breakView.result.run.violations?.[0]; + if (v === undefined) return null; + const count = breakView.result.run.actual ?? 0; + switch (v.check) { + case 'atMostOnce': + return { + node: v.nodeId, + atMs: v.chargedMs[1], + count, + text: `Charged twice: request ${v.rid}`, + past: `request ${v.rid} was charged a second time`, + }; + case 'lostAckedWrite': + return { + node: v.nodeId, + atMs: v.lostMs, + count, + text: `Lost after saved: request ${v.rid}`, + past: `request ${v.rid} was lost after it was saved`, + }; + case 'readYourWrites': + return { + node: v.nodeId, + atMs: v.readMs, + count, + text: `Stale read: request ${v.rid}`, + past: `request ${v.rid} read the value from before its own write`, + }; + } + }, [breakWatch, breakView]); + const violationShown = + violationAt !== null && snapshot !== null && engine.now >= violationAt.atMs; + const violationMarks = useMemo( + () => + violationAt !== null && violationShown + ? new Map([[violationAt.node, violationAt.text]]) + : undefined, + [violationAt, violationShown], + ); + /** The reader's design under a replay, and the replay as it went on. */ const breakBeforeRef = useRef<{ before: Topology; installed: Topology } | null>(null); @@ -3379,6 +3984,11 @@ export default function App() { }); }, [history, installDesign]); + const handleMarkChargeable = useCallback( + (id: string) => handleConfigChange(id, { chargeable: 1 }), + [handleConfigChange], + ); + /* The panel's search, with the moves that leave a verdict ending its replay. */ const breakPanelSearch = useMemo( () => ({ @@ -3430,11 +4040,17 @@ export default function App() { const breakWatchLine = useMemo(() => { if (!breakWatch || breakWatchSec < 0) return null; const now = engine.now; - const { firstMs, goal } = breakWatch; - const until = ` The first fault lands at ${secs(firstMs)} (in ${Math.ceil((firstMs - now) / 1000)}s).`; + const { goal } = breakWatch; + // A correctness goal is read from the run the search checked, not the + // live one, which keeps no operation log. + if (violationAt !== null) { + const where = breakNames.node(violationAt.node); + return now < violationAt.atMs + ? `Watch ${where} at ${clock(violationAt.atMs)}.` + : `At ${clock(violationAt.atMs)}, ${violationAt.past}, at ${where}. The search counted ${violationAt.count} in the window.`; + } const tally = now < BREAK_WARMUP_MS ? null : engine.readTally(); - if (!tally) - return `Replay: the first fault lands at ${secs(firstMs)} (in ${Math.ceil((firstMs - now) / 1000)}s).`; + if (!tally) return `Measuring starts at ${secs(BREAK_WARMUP_MS)}.`; const run = measureSeed(goal, tally, 0); // The verdict's own order: nothing through, then a backlog, then the // goal. Partway through, requests still on their way look like a @@ -3453,9 +4069,19 @@ export default function App() { ? `the slowest took ${run.actual === null ? 'nothing yet' : formatGoalMs(run.actual)}` : `${run.actual ?? 0} lost`; return now >= BREAK_END_MS - ? `Replay: between ${secs(BREAK_WARMUP_MS)} and ${secs(BREAK_END_MS)}, ${figure}.` - : `Replay: in the window so far, ${figure}.${now < firstMs ? until : ''}`; - }, [breakWatchSec, breakWatch, engine]); + ? `Between ${secs(BREAK_WARMUP_MS)} and ${secs(BREAK_END_MS)}, ${figure}.` + : `In the window so far, ${figure}.`; + }, [breakWatchSec, breakWatch, engine, violationAt, breakNames]); + /* The countdown reads the replay's own clock on every render rather than + riding in the memo above, so it can never be left showing a second that + has already gone. */ + const breakWatchView = useMemo( + () => + breakWatch && breakWatchLine !== null + ? { line: breakWatchLine, firstMs: breakWatch.firstMs, endMs: BREAK_END_MS } + : null, + [breakWatch, breakWatchLine], + ); const handleBreakLink = useCallback(() => { const r = breakReplay(); @@ -3486,48 +4112,174 @@ export default function App() { /** Bumped when a card is opened, to move focus to the panel. */ const [incidentFocus, setIncidentFocus] = useState(0); - /** The scene as it was installed by Watch, or null when not watching. */ + /** The scene as opening or Watch installed it, or null. */ const [incidentScene, setIncidentScene] = useState(null); + /** + * The undo depth right after an incident's scene was put on the canvas by + * opening it, or null. Fix it uses it to tell an untouched scene, whose + * undo is the reader's own design, from one they have since worked on. + */ + const incidentOpenDepthRef = useRef(null); + /** The scene opening installed has not been played yet. */ + const incidentUnplayedRef = useRef(false); + /** Whether the run was playing before opening paused it. */ + const runningBeforeIncidentRef = useRef(true); + /* Leaving the panel without playing the scene gives back the run's state + from before it opened: the pause was for Watch, not for what comes + next. */ + const resumeAfterIncident = useCallback(() => { + const unplayed = incidentUnplayedRef.current; + incidentUnplayedRef.current = false; + // Played from the bar instead of Watch: the reader has taken over. + if (!unplayed || runningRef.current || engine.now > 0) return; + setRunning(runningBeforeIncidentRef.current); + runningRef.current = runningBeforeIncidentRef.current; + }, [engine]); + /* Opening an incident puts its scene on the canvas, paused at the start, + as one undo step, the way an example opens: the panel is about that + diagram, and leaving the reader's own under it told them nothing. Paused + so Watch plays it from the top with the captions, on the same scene + and seed Watch has always installed. */ const handleOpenIncident = useCallback( - (id: string) => { - if (challengeLiveRef.current !== null) return; + /* `fromBrief`: the learning path may open a story while a brief is live. + Opening it replaces the design through replaceDesign, which leaves + the brief first, so one undo brings the reader's design back. */ + (id: string, fromBrief = false) => { + if (!fromBrief && challengeLiveRef.current !== null) return; + const picked = incidentById(id); + if (!picked) return; if (breakShown) handleCloseBreak(); + const scene = structuredClone(picked.scene); + replaceDesign(scene, null, 'incident'); + incidentOpenDepthRef.current = history.undoDepth; + if (!incidentUnplayedRef.current) + runningBeforeIncidentRef.current = runningRef.current; + incidentUnplayedRef.current = true; + setRunning(false); + runningRef.current = false; setIncidentId(id); - setIncidentScene(null); + setIncidentScene(scene); setIncidentFocus((n) => n + 1); + say(`Opened ${picked.name}. Undo brings your design back.`); }, - [breakShown, handleCloseBreak], + [breakShown, handleCloseBreak, replaceDesign, history, say], ); - /* A loaded example, one undo step back to what was there. */ + /* The scene opening installed, still at its first instant, only needs + playing; anything else (a watched run, an edited scene) is put back as + a fresh copy, as one undo step back to what was there. */ const handleWatchIncident = useCallback(() => { if (!incident) return; - const scene = structuredClone(incident.scene); - replaceDesign(scene, null, 'incident replay'); - setIncidentScene(scene); + const unplayed = incidentUnplayedRef.current; + incidentUnplayedRef.current = false; + if ( + unplayed && + engine.now === 0 && + sceneKey(topoLiveRef.current) === sceneKey(incident.scene) + ) { + setIncidentScene(structuredClone(incident.scene)); + } else { + const scene = structuredClone(incident.scene); + replaceDesign(scene, null, 'incident replay'); + setIncidentScene(scene); + } setRunning(true); runningRef.current = true; - }, [incident, replaceDesign]); + }, [incident, replaceDesign, engine]); + /* Fixing it sets aside the reader's own design, not the scene opening put + over it, so Back to my design brings theirs back. While the scene is + untouched, its open is undone first; once they have worked on it, what + is on the canvas is theirs, and that is what is set aside. */ const handleFixIncident = useCallback(() => { if (!incident) return; + const depth = incidentOpenDepthRef.current; + incidentOpenDepthRef.current = null; + if ( + depth !== null && + depth === history.undoDepth && + !history.settling && + sceneKey(topoLiveRef.current) === sceneKey(incident.scene) + ) { + const entry = history.undo(snapRef.current); + if (entry) { + // The brief starts from here in this same handler, before React has + // rendered the undo, so the mirrors it reads are brought up to date + // by hand. + topoLiveRef.current = entry.topology; + snapRef.current = { + topology: entry.topology, + selectedIds: new Set(entry.selectedIds), + rps: entry.rps, + presetId: entry.presetId, + challengeId: entry.challengeId, + }; + } + } + resumeAfterIncident(); setIncidentId(null); setIncidentScene(null); handleStartChallenge(incident.brief.id); - }, [incident, handleStartChallenge]); + }, [incident, handleStartChallenge, history, resumeAfterIncident]); + + /* An outage's story cannot open inside a brief, so from the path it goes + back to the reader's design first, as opening an example does. */ + const handleOpenPathIncident = useCallback( + (id: string) => handleOpenIncident(id, true), + [handleOpenIncident], + ); + /* An example from the path puts away an outage's story, which would + otherwise stay over it, and hands focus to its task card, since the + dialog or brief that was pressed is gone. */ + const handlePathExample = useCallback( + (preset: Preset) => { + setIncidentId(null); + setIncidentScene(null); + setTaskFocus(true); + handleLoadPreset(preset); + }, + [handleLoadPreset], + ); + /** Open a step of the learning path through the handler its own picker uses. */ + const openPathStep = useCallback( + (step: PathStep) => { + if (step.kind === 'challenge') handleStartChallenge(step.id); + else if (step.kind === 'incident') handleOpenPathIncident(step.id); + else { + const preset = PRESETS.find((p) => p.id === step.id); + if (preset) handlePathExample(preset); + } + }, + [handleStartChallenge, handleOpenPathIncident, handlePathExample], + ); + /* "Next" after an example's task: the step after it on the path. */ + const taskAfter = + taskView.kind === 'none' ? null : stepAfter(taskView.task.presetId, 'example'); + const taskNext = taskAfter + ? { name: stepName(taskAfter), open: () => openPathStep(taskAfter) } + : null; + /* A brief on the path goes on along the path, an outage's brief too. One + that is not on it keeps the picker's order. */ + const briefStep = challenge ? stepOfBrief(challenge.id) : null; + const briefAfter = briefStep ? stepAfter(briefStep.id, briefStep.kind) : null; + const handleBriefNext = useCallback(() => { + if (briefAfter) openPathStep(briefAfter); + }, [briefAfter, openPathStep]); + const challengePassed = + check?.view.status === 'verdict' && check.view.verdict.status === 'passed'; const handleCloseIncident = useCallback(() => { + incidentOpenDepthRef.current = null; + resumeAfterIncident(); setIncidentId(null); setIncidentScene(null); menuBtnRef.current?.focus(); - }, []); + }, [resumeAfterIncident]); /* The captions follow the run only while the canvas is still the scene that was installed. Moved boxes keep them; a changed design ends them, because the story no longer describes what is playing. */ - const sceneKey = (t: Topology) => - canonical({ nodes: t.nodes.map((n) => [n.id, n.kind, n.config]), edges: t.edges }); const incidentPlaying = useMemo( () => incident !== undefined && @@ -3535,7 +4287,57 @@ export default function App() { sceneKey(topology) === sceneKey(incidentScene), [incident, incidentScene, topology], ); - const incidentSec = incidentPlaying && snapshot ? Math.floor(engine.now / 1000) : -1; + // No caption before the scene has started: paused at its first instant, + // the panel offers Watch rather than a story that has not begun. + const incidentSec = + incidentPlaying && snapshot && (running || engine.now > 0) + ? Math.floor(engine.now / 1000) + : -1; + + /* What the canvas keeps in view as panels open: see revealTarget.ts. */ + const chartsUp = layout.metrics && snapshot !== null; + const brokeTargets = useMemo( + () => + breakShown && breakView.status === 'done' && breakView.result.status === 'broke' + ? breakView.result.attacks.map((a) => a.target) + : null, + [breakShown, breakView], + ); + const breaking = useMemo( + () => (breakShown && !brokeTargets ? topology.nodes.map((n) => n.id) : null), + [breakShown, brokeTargets, topology.nodes], + ); + const inspecting = useMemo( + () => (inspectorVisible ? selectedNodes.map((n) => n.id) : null), + [inspectorVisible, selectedNodes], + ); + const reveal = useMemo( + () => + revealTarget({ + inspecting, + broke: brokeTargets, + breaking, + verdict: + challenge && check?.view.status === 'verdict' ? check.view.verdict : null, + incident: + incident && incidentPlaying + ? { id: incident.id, faults: incident.scene.faults ?? [] } + : null, + charts: chartsUp, + guided: taskOpen, + }), + [ + inspecting, + brokeTargets, + breaking, + challenge, + check, + incident, + incidentPlaying, + chartsUp, + taskOpen, + ], + ); const incidentCaption = useMemo(() => { if (!incident || incidentSec < 0) return null; const c = captionAt(incident, incidentSec * 1000); @@ -3572,8 +4374,76 @@ export default function App() { setRoutes(engine.routes()); }, [engine]); + /** + * The transport again, first in the menu. The bar's own buttons are the + * quick way, but a touch screen has no Space or S key, and the menu is + * the one place every layout can always reach. + */ + const runMenuItems = useMemo( + () => [ + { + label: running ? 'Pause' : 'Play', + icon: running ? 'M6 4h4v16H6zM14 4h4v16h-4z' : 'M6 3l14 9-14 9z', + ...(coarse ? {} : { hint: 'Space' }), + onSelect: handleToggleRun, + }, + { + label: 'Step', + icon: 'M6 4v16M10 4l10 8-10 8z', + ...(coarse ? {} : { hint: 'S' }), + onSelect: handleStep, + }, + { + label: 'Reset', + icon: 'M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8M3 3v5h5', + onSelect: handleReset, + divider: true, + }, + ], + [running, coarse, handleToggleRun, handleStep, handleReset], + ); + /* The palette heads the menu, so it can be found without its chord. + Presenting follows the run controls: it is how they get shown to a + room. */ + const searchMenuItem = useMemo( + () => ({ + label: 'Search actions', + icon: 'M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM21 21l-4.35-4.35', + ...(coarse ? {} : { hint: shortcutLabel('Ctrl+K') }), + onSelect: () => openPaletteRef.current(), + divider: true, + }), + [coarse], + ); + const presentMenuItem = useMemo( + () => ({ + label: presenting ? 'Stop presenting' : 'Start presenting', + icon: 'M3 4h18v12H3zM12 16v4M8 20h8', + ...(coarse ? {} : { hint: 'Shift+P' }), + onSelect: togglePresenting, + divider: true, + }), + [coarse, presenting, togglePresenting], + ); + const allMenuItems = useMemo( + () => [searchMenuItem, ...runMenuItems, presentMenuItem, ...menuItems], + [searchMenuItem, runMenuItems, presentMenuItem, menuItems], + ); + /* ---------------- keyboard ---------------- */ + /* F6 steps between the bar, the diagram and the open panels, Shift+F6 + back. Before the typing guard below: no field uses F6, and a reader in + the inspector's name box is exactly who wants to get out of it. */ + useEffect(() => { + const onF6 = (e: KeyboardEvent) => { + if (e.key !== 'F6' || e.ctrlKey || e.metaKey || e.altKey) return; + if (cycleRegion(e.shiftKey ? -1 : 1) >= 0) e.preventDefault(); + }; + window.addEventListener('keydown', onF6); + return () => window.removeEventListener('keydown', onF6); + }, []); + useEffect(() => { const onKeyDown = (e: KeyboardEvent) => { // Never steal keys from a field the user is typing into. @@ -3639,6 +4509,14 @@ export default function App() { return; } + // Slower and faster, by the character so it works on any layout that + // types a bracket. A held modifier is left to the browser. + if ((e.key === '[' || e.key === ']') && !e.metaKey && !e.ctrlKey && !e.altKey) { + e.preventDefault(); + setSpeed(stepSpeed(speedRef.current, e.key === ']' ? 1 : -1)); + return; + } + // Step one tick. Ignored with a modifier held so it cannot shadow // browser shortcuts like Cmd/Ctrl+S. if ((e.key === 's' || e.key === 'S') && !e.metaKey && !e.ctrlKey && !e.altKey) { @@ -3716,6 +4594,17 @@ export default function App() { } return; } + // In a challenge the key used to do nothing at all, which reads as + // broken. Say why instead. + if (e.key === 'f' || e.key === 'F') { + e.preventDefault(); + toastSeq.current += 1; + setToast({ + text: 'Can you break it? is off during a challenge.', + id: toastSeq.current, + }); + return; + } if (e.key === 'g' || e.key === 'G') { e.preventDefault(); togglePreference('snapToGrid'); @@ -3735,6 +4624,7 @@ export default function App() { handleUndo, handleRedo, handleDuplicate, + setSpeed, glossaryOpen, openGlossary, closeGlossary, @@ -3812,11 +4702,26 @@ export default function App() { /** * The header's offered load, derived from the topology's client nodes (the * sum, so multi-client presets add up) rather than mirrored in a separate - * state cell that add/delete paths forgot to reconcile. `rps` state remains - * only as the persisted slider value for session restore. + * state cell that add/delete paths forgot to reconcile. `rps` state is the + * design's 1x, which this is measured against. */ const offeredRps = useMemo(() => clientRps(topology), [topology]); + // The 1x follows the clients. With none left there is nothing to measure + // against, and the first client to appear sets it, so a design built on an + // empty canvas gets a multiple and one rebuilt after a clear is not + // measured against the design that was there before. Adjusted during + // render, as React suggests for state that tracks other state. + const hasClients = topology.nodes.some((n) => n.kind === 'client'); + // A session saved with a 1x but no clients counts as having had them, so + // the first render clears that stale 1x. + const [hadClients, setHadClients] = useState(() => hasClients || rps > 0); + if (hasClients !== hadClients) { + setHadClients(hasClients); + // A 1x set in the same update (undo, a design opened) is kept. + setRps(hasClients ? (rps > 0 ? rps : offeredRps) : 0); + } + /** * Requests actually lost PER SECOND, derived from the engine's per-reason * counters. This is the single source of truth for "dropped": the top bar @@ -3884,9 +4789,227 @@ export default function App() { setLostRps(delta > 0 ? (delta * 1000) / dtMs : 0); }, [cumulativeLost, simTimeMs]); + /* ---------------- presenting and the command palette ---------------- */ + + /* The part X, W and R act on while presenting: the one keyboard focus is + on, so Tab is enough, or else the one selected. */ + const focusedPart = useFocusedPart(presenting); + const presentId = focusedPart ?? selectedNode?.id ?? null; + const presentPart = useMemo(() => { + if (!presenting || presentId === null) return null; + const n = topology.nodes.find((x) => x.id === presentId); + if (!n) return null; + return { + id: n.id, + label: n.label, + fault: snapshot?.activeFailures.find((f) => f.nodeId === n.id) ?? null, + canSlow: slowable(n.kind), + }; + }, [presenting, presentId, topology.nodes, snapshot]); + + const presentCrash = useCallback( + (id: string) => faultActions.onInject(id, 'crash'), + [faultActions], + ); + const presentSlow = useCallback( + (id: string) => faultActions.onInject(id, 'slow', { factor: DEFAULT_SLOW_FACTOR }), + [faultActions], + ); + const presentFix = useCallback( + (id: string) => faultActions.onFix(id), + [faultActions], + ); + + /* A key that cannot act says why, rather than doing nothing: a teacher + pressing X in front of a room needs to know it was heard. */ + useEffect(() => { + presentFaultRef.current = (kind) => { + const p = presentPart; + if (!p) { + say('Pick a part first. Click one or Tab to it.'); + return; + } + const f = p.fault; + if (kind === 'crash') { + if (f?.kind === 'crash') say(`${p.label} is already crashed. R fixes it.`); + else presentCrash(p.id); + } else if (kind === 'slow') { + if (!p.canSlow) say(`${p.label} does no work of its own to slow down.`); + else if (f !== null) say(`Fix ${p.label} first. R fixes it.`); + else presentSlow(p.id); + } else if (f === null) { + say(`${p.label} has nothing to fix.`); + } else presentFix(p.id); + }; + }, [presentPart, presentCrash, presentSlow, presentFix, say]); + + /* Ctrl+K, or Cmd+K on a Mac. Before any typing guard on purpose: the + palette is how you get out of a field and do something else. By e.code + for the same layout reasons as undo. */ + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (!(e.metaKey || e.ctrlKey) || e.altKey || e.shiftKey || e.code !== 'KeyK') + return; + e.preventDefault(); + if (paletteOpenRef.current) setPaletteOpen(false); + else openPaletteRef.current(); + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }, []); + + const snapToGrid = usePreference('snapToGrid'); + /* + * The rows are built when the palette opens, from an event, not on every + * render: a palette left open would otherwise rebuild a hundred rows ten + * times a second as snapshots land, and nothing in it is read live. The + * builder is refreshed after each render so the open press sees the + * latest state. + */ + const buildCommandsRef = useRef<() => Command[]>(() => []); + useEffect(() => { + buildCommandsRef.current = () => { + const sel = selectedNode?.id ?? null; + const ordered = sel + ? [ + ...topology.nodes.filter((n) => n.id === sel), + ...topology.nodes.filter((n) => n.id !== sel), + ] + : topology.nodes; + const parts = ordered.map((n) => ({ + id: n.id, + label: n.label, + fault: snapshot?.activeFailures.find((f) => f.nodeId === n.id)?.kind ?? null, + canSlow: slowable(n.kind), + })); + const hasClient = topology.nodes.some((n) => n.kind === 'client'); + const facts: CommandFacts = { + running, + speed, + canUndo, + canRedo, + empty: topology.nodes.length === 0, + inChallenge: challenge !== undefined, + breakBlocked, + canPin: hasClient && (snapshot?.history.length ?? 0) > 0, + pinned: pinned !== null, + libraryOpen, + metricsOpen: layout.metrics, + snapToGrid, + theme: themeChoice, + presenting, + canFullscreen: canFullscreen(), + fullscreen, + parts, + selectedId: selectedNode?.id ?? null, + kinds: KIND_GROUPS.flatMap((g) => + g.kinds.map((kind) => ({ kind, name: KIND_NAME[kind], group: g.title })), + ), + examples: PRESETS.map((p) => ({ id: p.id, name: p.name, tagline: p.tagline })), + challenges: CHALLENGES.map((c) => ({ id: c.id, name: c.name })), + incidents: INCIDENTS.map((i) => ({ id: i.id, name: i.name })), + glossary: GLOSSARY, + mac: isMac(), + coarse, + }; + const select = (id: string) => setSelectedIds(new Set([id])); + const actions: CommandActions = { + toggleRun: handleToggleRun, + step: handleStep, + reset: handleReset, + setSpeed, + undo: handleUndo, + redo: handleRedo, + add: handlePaletteAdd, + openExample: (id) => { + const p = PRESETS.find((x) => x.id === id); + if (p) handleLoadPreset(p); + }, + startChallenge: handleStartChallenge, + openIncident: handleOpenIncident, + // The part is selected as well, so the change is seen where it lands. + crash: (id) => { + select(id); + presentCrash(id); + }, + slow: (id) => { + select(id); + presentSlow(id); + }, + fix: (id) => { + select(id); + presentFix(id); + }, + pin: () => { + if (!snapshot) return; + setPinned( + pinRun(snapshot.system, trailingWindow(snapshot.history), offeredRps), + ); + if (!layout.metrics) toggleMetrics(); + }, + clearPin: () => setPinned(null), + toggleLibrary, + toggleMetrics, + toggleSnap: () => togglePreference('snapToGrid'), + setTheme: (t) => setPreference('theme', t), + togglePresenting, + toggleFullscreen, + fit: () => menuApiRef.current?.fitAll(), + share: handleOpenShare, + breakIt: () => { + setBreakOpen(true); + setIncidentId(null); + }, + glossary: openGlossary, + examples: () => setExamplesOpen(true), + challenges: () => setChallengesOpen(true), + path: () => setPathOpen(true), + designs: () => setDesignsOpen(true), + shortcuts: () => setShortcutsOpen(true), + settings: () => setSettingsOpen(true), + }; + return buildCommands(facts, actions, formatFactor(DEFAULT_SLOW_FACTOR)); + }; + }); + const [paletteCommands, setPaletteCommands] = useState([]); + useEffect(() => { + paletteOpenRef.current = paletteOpen; + openPaletteRef.current = () => { + setMenuOpen(false); + setPaletteCommands(buildCommandsRef.current()); + setPaletteOpen(true); + }; + }, [paletteOpen]); + + const runCommand = useCallback( + (cmd: Command) => { + const next = pushRecent(recentCommands, cmd.id); + setRecentCommands(next); + saveRecent(next); + cmd.run(); + }, + [recentCommands], + ); + return ( -
-
+
+ {/* The first stop for Tab, shown only when it has focus. Without it + the diagram was behind the bar and every row of the rail. */} + { + e.preventDefault(); + focusDiagram(); + }} + > + Skip to diagram + +
{/* The wordmark is the one place the product speaks in its own voice. Two words, sentence case, no abbreviation — a student @@ -3899,13 +5022,13 @@ export default function App() { {/* Says the work is safe. - role=status, so it is announced rather than only drawn: someone - who cannot see the dot has the same reason to worry about closing - the tab as someone who can. + Text, so a screen reader finds it in the bar. Not a live region: + every edit flips it to Saving and back, and announced, that pair + talked over each step of the load slider and each nudge of a + part. Someone who cannot see the dot reads it when they wonder. */}

@@ -4162,10 +5298,11 @@ export default function App() {
- - - setLayout((l) => ({ ...l, railW }))} - onReset={() => setLayout((l) => ({ ...l, railW: PANEL_LIMITS.railW.base }))} - label="Resize the components rail" - /> - -
{/* The canvas plus the chrome that floats OVER it. The toggles are @@ -4227,7 +5342,9 @@ export default function App() { browser would leave the app to display the JSON. */}
@@ -4245,6 +5362,7 @@ export default function App() { topology={topology} snapshot={snapshot} routes={routes} + readOutcomes={readOutcomes} selectedIds={selectedIds} onSelectionChange={setSelectedIds} onMoveNode={handleMoveNode} @@ -4252,10 +5370,13 @@ export default function App() { onMoveEnd={handleMoveEnd} onConnect={handleConnect} onDeleteSelection={handleDeleteSelection} - onDropNode={handleAddNode} + onDropNode={handleDropNode} onRename={handleRename} onDuplicateForDrag={handleDuplicateForDrag} onPaste={handlePaste} + onContextMenu={handleCanvasMenu} + onClipboardWrite={setCopied} + menuApiRef={menuApiRef} onMoveAnnotation={handleMoveAnnotation} onResizeSection={handleResizeSection} onResizeNote={handleResizeNote} @@ -4273,16 +5394,36 @@ export default function App() { exportSvgRef={exportSvgRef} onToolChange={setArmedTool} fitSignal={fitNonce} + frameKey={barBottom} visibleRef={stageSafeRef} breakMarks={breakMarks} + violationMarks={violationMarks} emptyActions={emptyActions} - fitTight={challenge !== undefined} + narrowFit={phone} + onFitClipped={handleFitClipped} + reveal={reveal} + onReselect={showInspector} spotlightId={ - (tourShown ? tour.spotlight : null) ?? spotlightOf(shownFinding) + (tourShown ? tour.spotlight : null) ?? + spotlightOf(shownFinding) ?? + (taskOpen ? taskRing : null) } spotlightKey={shownFinding?.atMs ?? null} /> + {presenting ? ( + + ) : null} {/* Hidden in a challenge, where finding it is the exercise. */} {!challenge && topology.nodes.length > 0 ? ( setSelectedIds(new Set([id]))} onOpenPath={() => setPathOpen(true)} + onHandOff={() => setTaskFocus(true)} + /> + ) : null} + {taskShown ? ( + p.id === taskView.task.presetId)?.name ?? '' + } + topology={topology} + snapshot={snapshot} + selectedId={tourSubject} + squeezed={phone && inspectorVisible} + next={taskNext} + onSetLoad={handleRpsChange} + onSelect={(id) => setSelectedIds(new Set([id]))} + onHide={(hide) => { + exampleTask.setHidden(taskView.task.presetId, hide); + // On a phone the settings sheet is what folded it, so + // showing the task again puts that sheet away. + if (!hide && phone && inspectorVisible) setSelectedIds(new Set()); + }} + onReload={() => { + const p = PRESETS.find((x) => x.id === taskView.task.presetId); + if (p) handleLoadPreset(p); + }} + onOpenPath={() => setPathOpen(true)} + takeFocus={taskFocus} + onFocusTaken={handleTaskFocusTaken} + /> + ) : null} + {challenge && challengePassed && phone && inspectorVisible ? ( + setSelectedIds(new Set())} /> ) : null} {challenge && check ? ( @@ -4321,13 +5497,24 @@ export default function App() { onCheckAgain={check.checkAgain} onWatch={handleWatchRun} onStartOver={check.key !== freshKey ? handleStartOver : null} - onNext={next ? handleNextChallenge : null} + onNext={ + briefAfter ? handleBriefNext : next ? handleNextChallenge : null + } + nextLabel={ + briefAfter + ? `Next: ${stepName(briefAfter)}` + : next + ? `Next challenge: ${next.name}` + : undefined + } onLeave={handleLeaveChallenge} + onCopyLink={handleCopyChallengeLink} focusSignal={panelFocus} nameOf={nameOf} besideInspector={inspectorVisible && !phone} - foldOnStart={phone} onSheetResize={handleSheetResize} + fresh={check.key === freshKey} + liveMs={snapshot ? snapshot.system.timeMs : null} /> ) : null} {incident ? ( @@ -4350,7 +5537,10 @@ export default function App() { onClose={handleCloseBreak} onWatch={handleWatchBreak} onReplayLink={handleBreakLink} - watchLine={breakWatchLine} + onMarkChargeable={handleMarkChargeable} + watch={breakWatchView} + watchAtMs={breakWatchView ? engine.now : 0} + onStopWatch={endBreakWatch} foldOnStart={false} onSheetResize={handleSheetResize} /> @@ -4359,9 +5549,9 @@ export default function App() { type="button" className="btn btn-sm btn-icon stage-toggle stage-toggle-library" data-chrome="layout" - aria-expanded={layout.library} - aria-label={layout.library ? 'Hide components' : 'Show components'} - title={layout.library ? 'Hide components (C)' : 'Show components (C)'} + aria-expanded={libraryOpen} + aria-label={libraryOpen ? 'Hide components' : 'Show components'} + title={libraryOpen ? 'Hide components (C)' : 'Show components (C)'} onClick={toggleLibrary} > @@ -4409,6 +5599,9 @@ export default function App() { nodeNames={nodeNames} nodes={topology.nodes} routes={routes} + pin={pinned} + rps={offeredRps} + onPin={setPinned} idle={ !topology.nodes.some((n) => n.kind === 'client') ? 'no-client' @@ -4418,6 +5611,7 @@ export default function App() { } /> ) : null} + {snapshot ? : null}
+ {/* + The rails come after the canvas in the page, though the components + rail is drawn on its left: Tab goes bar, diagram, then panels, and + the canvas was 82 presses in behind 33 rail rows. They float, so the + order changes nothing on screen. + */} + + + setLayout((l) => ({ ...l, railW }))} + onReset={() => setLayout((l) => ({ ...l, railW: PANEL_LIMITS.railW.base }))} + label="Resize the components rail" + /> + + + + {/* + The toasts sit inside .app-body so its has-* classes can centre them + on the uncovered canvas, above the zoom row, and on a phone just + under the header (App.css). Fixed at the window's foot they covered + the stats bar, the charts toggle and the phone's tab bar. + */} + {toast || importError ? ( +
+ {/* + Undo/redo receipt. role="status" (polite live region) so a screen + reader hears the same confirmation a sighted user sees; keyed by id + so rapid consecutive undos restart the entrance rather than sitting + still on a message that appears not to change. + */} + {toast ? ( +
+ {toast.text} + {toast.action ? ( + + ) : null} +
+ ) : null} + {/* + A refused import. role="alert" rather than "status" because this + reports a failure the student needs to notice, and it sits longer + than the toast does: the sentence names what was wrong with the + file, and there is nothing else on screen that changed to say so. + Nothing on the canvas moved, which is the point. + */} + {importError ? ( +
+ {importError} +
+ ) : null} +
+ ) : null} + + setPaletteOpen(false)} + commands={paletteCommands} + recent={recentCommands} + onRun={runCommand} + /> + + {menu ? ( + + ) : null}
{/* @@ -4484,7 +5776,7 @@ export default function App() {
); diff --git a/src/App.url.test.tsx b/src/App.url.test.tsx new file mode 100644 index 0000000..26032a0 --- /dev/null +++ b/src/App.url.test.tsx @@ -0,0 +1,303 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import App from './App'; +import { encodeTopology } from './share'; +import { challengeById } from './sim/challenges'; +import { PRESETS, makeNode } from './sim/presets'; +import type { Topology } from './sim/types'; + +/** + * The address bar says what is open. An example nobody has changed is + * `?example=`, a brief is `?challenge=`, and Back and Forward move + * through briefs the way they move through pages. A share link goes first. + */ + +class FakePointerEvent extends MouseEvent { + pointerId: number; + pointerType: string; + isPrimary: boolean; + constructor( + type: string, + init: MouseEventInit & { pointerId?: number; pointerType?: string } = {}, + ) { + super(type, init); + this.pointerId = init.pointerId ?? 1; + this.pointerType = init.pointerType ?? 'mouse'; + this.isPrimary = true; + } +} + +const SESSION_KEY = 'breakscale.session.v1'; + +/** The reader's own design: something they made, not an example. */ +function ownDesign(): Topology { + const client = { ...makeNode('client', 0, 0), id: 'mine-client', label: 'My client' }; + const svc = { ...makeNode('service', 240, 0), id: 'mine-svc', label: 'My service' }; + svc.config = { ...svc.config, capacity: 7 }; + return { + nodes: [client, svc], + edges: [{ id: 'mine-client->mine-svc', from: client.id, to: svc.id, weight: 1 }], + }; +} + +let container: HTMLDivElement; +let root: Root; + +function mount(): void { + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + act(() => root.render()); +} + +function unmount(): void { + act(() => root.unmount()); + container.remove(); +} + +function advance(ms: number): void { + act(() => { + vi.advanceTimersByTime(ms); + }); +} + +/** A press the way a finger or a mouse makes one, ending in the click. */ +function press(el: Element): void { + const at = { bubbles: true, cancelable: true, button: 0, clientX: 5, clientY: 5 }; + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerdown', { ...at, buttons: 1 })); + el.dispatchEvent(new MouseEvent('mousedown', { ...at, buttons: 1 })); + }); + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('mouseup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('click', { ...at, buttons: 0 })); + }); +} + +function byName(name: string, root: ParentNode = document): HTMLElement | null { + return ( + [...root.querySelectorAll('button, [role="menuitem"]')].find( + (b) => + b.getAttribute('aria-label') === name || + b.textContent?.trim() === name || + b.querySelector('.ex-item-name')?.textContent === name, + ) ?? null + ); +} + +function must(name: string): HTMLElement { + const el = byName(name); + if (!el) throw new Error(`no control named ${name}`); + return el; +} + +function openMenu(item: string): void { + press(must('Menu')); + press(must(item)); +} + +function startChallenge(name: string): void { + openMenu('Challenges'); + press(must(name)); + // The dialog's exit. + advance(400); +} + +const panel = () => document.querySelector('section.chal'); +const canvasIds = () => + [...document.querySelectorAll('[data-hit="node"]')].map((n) => + n.getAttribute('data-id'), + ); +const canvasKinds = () => + [...document.querySelectorAll('[data-hit="node"]')].map((n) => + n.getAttribute('data-kind'), + ); + +const hold = challengeById('hold-the-line')!; +const holdPreset = PRESETS.find((p) => p.id === hold.presetId)!; + +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = + true; + vi.useFakeTimers(); + vi.stubGlobal('PointerEvent', FakePointerEvent); + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.reject(new Error('offline'))), + ); + localStorage.clear(); + window.history.replaceState(null, '', '/'); + localStorage.setItem( + SESSION_KEY, + JSON.stringify({ topology: ownDesign(), rps: 50, presetId: null }), + ); +}); + +afterEach(() => { + if (container?.isConnected) unmount(); + document.body.innerHTML = ''; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +const netflix = PRESETS.find((p) => p.id === 'netflix')!; + +function openExample(name: string): void { + openMenu('Examples'); + press(must(name)); + advance(400); +} + +/** A press on a node, then its inspector's Delete: an edit. */ +function deleteFirstNode(): void { + press(document.querySelector('[data-hit="node"]')!); + press(document.querySelector('.ins-delete')!); + advance(10); +} + +/** What a Back or Forward press does: the URL moves, then popstate. */ +function travel(to: string): void { + act(() => { + window.history.replaceState(null, '', to); + window.dispatchEvent(new PopStateEvent('popstate')); + }); + advance(10); +} + +describe('an example on the URL', () => { + it('names an example nobody has changed, and an edit takes it off', () => { + mount(); + advance(10); + expect(window.location.search).toBe(''); + const before = window.history.length; + openExample(netflix.name); + expect(window.location.search).toBe('?example=netflix'); + // Replaced, not pushed: Back never quietly takes an example away. + expect(window.history.length).toBe(before); + deleteFirstNode(); + expect(window.location.search).toBe(''); + press(must('Undo')); + advance(10); + expect(window.location.search).toBe('?example=netflix'); + }); + + it('opens from a link as one undo step, and says how to get back', () => { + window.history.replaceState(null, '', '/?example=netflix'); + mount(); + advance(10); + expect(canvasIds()).toEqual(netflix.topology.nodes.map((n) => n.id)); + expect(document.querySelector('.app-toast')?.textContent).toBe( + `Opened ${netflix.name}. Undo brings your design back.`, + ); + press(must('Undo')); + advance(10); + expect(canvasIds()).toEqual(['mine-client', 'mine-svc']); + expect(window.location.search).toBe(''); + }); + + it('ignores an example it does not know', () => { + window.history.replaceState(null, '', '/?example=nope'); + mount(); + advance(10); + expect(canvasIds()).toEqual(['mine-client', 'mine-svc']); + expect(window.location.search).toBe(''); + }); + + it('lets a share link go first', async () => { + const shared = PRESETS.find((p) => p.id === 'cache-aside')!.topology; + const hash = await encodeTopology(shared); + window.history.replaceState(null, '', `/?example=netflix#${hash}`); + vi.useRealTimers(); + mount(); + await act(async () => { + for (let i = 0; i < 50 && canvasKinds().length !== shared.nodes.length; i++) { + await new Promise((r) => setTimeout(r, 10)); + } + }); + expect(canvasKinds()).toEqual(shared.nodes.map((n) => n.kind)); + // The link on screen keeps its own address. + expect(window.location.hash).toBe(`#${hash}`); + }); + + it('takes a share link off once an example replaces it', async () => { + const shared = PRESETS.find((p) => p.id === 'cache-aside')!.topology; + window.history.replaceState(null, '', `/#${await encodeTopology(shared)}`); + vi.useRealTimers(); + mount(); + await act(async () => { + for (let i = 0; i < 50 && canvasKinds().length !== shared.nodes.length; i++) { + await new Promise((r) => setTimeout(r, 10)); + } + }); + openMenu('Examples'); + press(must(netflix.name)); + await act(async () => { + await new Promise((r) => setTimeout(r, 450)); + }); + expect(window.location.hash).toBe(''); + expect(window.location.search).toBe('?example=netflix'); + }); +}); + +describe('a challenge on the URL', () => { + it('pushes a brief, and Back brings the design that was set aside', () => { + mount(); + advance(10); + const before = window.history.length; + startChallenge(hold.name); + expect(window.location.search).toBe('?challenge=hold-the-line'); + expect(window.history.length).toBe(before + 1); + + travel('/'); + expect(panel()).toBeNull(); + expect(canvasIds()).toEqual(['mine-client', 'mine-svc']); + + travel('/?challenge=hold-the-line'); + expect(panel()?.textContent).toContain(hold.name); + expect(canvasIds()).toEqual(holdPreset.topology.nodes.map((n) => n.id)); + }); + + it('leaving by the button is a step too, and an example comes back named', () => { + mount(); + openExample(netflix.name); + startChallenge(hold.name); + const inside = window.history.length; + press(must('Back to my design')); + advance(10); + expect(window.location.search).toBe('?example=netflix'); + expect(window.history.length).toBe(inside + 1); + }); + + it('follows Back to a brief it was never in this session', () => { + mount(); + advance(10); + travel('/?challenge=keep-it-warm'); + expect(panel()?.textContent).toContain(challengeById('keep-it-warm')!.name); + travel('/?challenge=not-a-brief'); + expect(panel()).toBeNull(); + }); + + it('copies a link that opens only this brief', async () => { + const writeText = vi.fn(() => Promise.resolve()); + Object.defineProperty(navigator, 'clipboard', { + value: { writeText }, + configurable: true, + }); + mount(); + startChallenge(hold.name); + press(must('Copy link')); + await act(async () => { + await Promise.resolve(); + }); + expect(writeText).toHaveBeenCalledWith( + `${window.location.origin}/?challenge=hold-the-line`, + ); + expect(document.querySelector('.app-toast')?.textContent).toBe( + 'Copied a link to this challenge.', + ); + }); +}); diff --git a/src/App.verification.test.tsx b/src/App.verification.test.tsx new file mode 100644 index 0000000..21cf74a --- /dev/null +++ b/src/App.verification.test.tsx @@ -0,0 +1,144 @@ +// @vitest-environment jsdom +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import App from './App'; +import { challengeById } from './sim/challenges'; + +/** + * A brief from the "Checking correctness" track, played the way a reader + * plays it: open it, let the check fail it on the data, put idempotency + * keys on Payments with a real press, and watch the check pass it. + */ + +class FakePointerEvent extends MouseEvent { + pointerId: number; + pointerType: string; + isPrimary: boolean; + constructor( + type: string, + init: MouseEventInit & { pointerId?: number; pointerType?: string } = {}, + ) { + super(type, init); + this.pointerId = init.pointerId ?? 1; + this.pointerType = init.pointerType ?? 'mouse'; + this.isPrimary = true; + } +} + +let container: HTMLDivElement; +let root: Root; + +function advance(ms: number): void { + act(() => { + vi.advanceTimersByTime(ms); + }); +} + +function press(el: Element): void { + const at = { bubbles: true, cancelable: true, button: 0, clientX: 5, clientY: 5 }; + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerdown', { ...at, buttons: 1 })); + el.dispatchEvent(new MouseEvent('mousedown', { ...at, buttons: 1 })); + }); + act(() => { + el.dispatchEvent(new FakePointerEvent('pointerup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('mouseup', { ...at, buttons: 0 })); + el.dispatchEvent(new MouseEvent('click', { ...at, buttons: 0 })); + }); +} + +function must(name: string): HTMLElement { + const el = [ + ...document.querySelectorAll('button, [role="menuitem"]'), + ].find( + (b) => + b.getAttribute('aria-label') === name || + b.textContent?.trim() === name || + b.querySelector('.ex-item-name')?.textContent === name, + ); + if (!el) throw new Error(`no control named ${name}`); + return el; +} + +const chip = () => document.querySelector('.chal-chip')?.textContent; +const panel = () => document.querySelector('section.chal'); + +function settleCheck(): void { + for (let i = 0; i < 80; i++) { + advance(250); + const c = chip(); + if (c && c !== 'Changed' && c !== 'Not checked yet' && c !== 'Checking') return; + } +} + +beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = + true; + vi.useFakeTimers(); + vi.stubGlobal('PointerEvent', FakePointerEvent); + vi.stubGlobal( + 'fetch', + vi.fn(() => Promise.reject(new Error('offline'))), + ); + localStorage.clear(); + window.history.replaceState(null, '', '/'); +}); + +afterEach(() => { + act(() => root.unmount()); + container.remove(); + document.body.innerHTML = ''; + vi.unstubAllGlobals(); + vi.restoreAllMocks(); + vi.useRealTimers(); +}); + +describe('Charged twice', () => { + it('fails on the data, names a charged request, and passes with keys at Payments', () => { + const brief = challengeById('charged-twice'); + if (!brief) throw new Error('no brief'); + container = document.createElement('div'); + document.body.appendChild(container); + root = createRoot(container); + act(() => root.render()); + + press(must('Menu')); + press(must('Challenges')); + press(must(brief.name)); + advance(400); + expect(panel()?.textContent).toContain(brief.name); + + settleCheck(); + // The design as the brief hands it over, so the miss is the brief's own. + expect(chip()).toBe('As it starts'); + expect(panel()?.textContent).toMatch( + /\d+ payments were charged more than once, and the goal is none\./, + ); + press(must('Details')); + expect(panel()?.textContent).toMatch(/Request \d+ was charged twice at Payments/); + expect(panel()?.textContent).toContain('Then it plays 5s more'); + + const pay = [...document.querySelectorAll('[data-hit="node"]')].find( + (n) => n.getAttribute('data-id') === 'pay', + ); + if (!pay) throw new Error('no Payments on the canvas'); + press(pay); + const toggle = [...document.querySelectorAll('.ins .ins-toggle')].find((l) => + l.textContent?.includes('idempotency key'), + ); + const box = toggle?.querySelector('input'); + if (!box) throw new Error('no idempotency key toggle'); + // Whether Payments charges is the brief's, not the reader's. + const charges = [...document.querySelectorAll('.ins .ins-toggle')].find((l) => + l.textContent?.includes('charges money'), + ); + expect(charges?.querySelector('input')?.disabled).toBe(true); + press(box); + expect(box.checked).toBe(true); + + settleCheck(); + expect(chip()).toBe('Passed'); + expect(panel()?.textContent).toContain(brief.lesson); + }, 60_000); +}); diff --git a/src/appCommands.test.ts b/src/appCommands.test.ts new file mode 100644 index 0000000..17e2473 --- /dev/null +++ b/src/appCommands.test.ts @@ -0,0 +1,161 @@ +import { describe, expect, it, vi } from 'vitest'; +import { + buildCommands, + inSentence, + type CommandActions, + type CommandFacts, +} from './appCommands'; +import { rankCommands } from './commands'; + +const facts = (over: Partial = {}): CommandFacts => ({ + running: true, + speed: 1, + canUndo: false, + canRedo: false, + empty: false, + inChallenge: false, + breakBlocked: null, + canPin: true, + pinned: false, + libraryOpen: true, + metricsOpen: false, + snapToGrid: true, + theme: 'system', + presenting: false, + canFullscreen: true, + fullscreen: false, + parts: [ + { id: 'api', label: 'API Server', fault: null, canSlow: true }, + { id: 'db', label: 'Database', fault: 'crash', canSlow: true }, + { id: 'client', label: 'Client', fault: null, canSlow: false }, + ], + selectedId: 'api', + kinds: [{ kind: 'lb', name: 'Load balancer', group: 'Traffic' }], + examples: [{ id: 'netflix', name: 'Netflix: streaming at scale', tagline: 'Video' }], + challenges: [{ id: 'hold-the-line', name: 'Hold the line' }], + incidents: [{ id: 's3', name: 'S3 goes down in one region' }], + glossary: [{ id: 'p99', term: 'p99' }], + mac: false, + coarse: false, + ...over, +}); + +const actions = (): CommandActions => { + const fn = () => vi.fn(); + return { + toggleRun: fn(), + step: fn(), + reset: fn(), + setSpeed: fn(), + undo: fn(), + redo: fn(), + add: fn(), + openExample: fn(), + startChallenge: fn(), + openIncident: fn(), + crash: fn(), + slow: fn(), + fix: fn(), + pin: fn(), + clearPin: fn(), + toggleLibrary: fn(), + toggleMetrics: fn(), + toggleSnap: fn(), + setTheme: fn(), + togglePresenting: fn(), + toggleFullscreen: fn(), + fit: fn(), + share: fn(), + breakIt: fn(), + glossary: fn(), + examples: fn(), + challenges: fn(), + path: fn(), + designs: fn(), + shortcuts: fn(), + settings: fn(), + }; +}; + +const labels = (f: CommandFacts) => + buildCommands(f, actions(), '5x').map((c) => c.label); +const byId = (f: CommandFacts, a = actions()) => + new Map(buildCommands(f, a, '5x').map((c) => [c.id, c] as const)); + +describe('buildCommands', () => { + it('names the run action by what it will do', () => { + expect(labels(facts())).toContain('Pause'); + expect(labels(facts({ running: false }))).toContain('Play'); + }); + + it('offers only the faults that apply to each part', () => { + const l = labels(facts()); + expect(l).toContain('Crash API Server'); + expect(l).toContain('Slow down API Server 5x'); + expect(l).not.toContain('Fix API Server'); + expect(l).not.toContain('Crash Database'); + expect(l).toContain('Fix Database'); + expect(l).not.toContain('Slow down Client 5x'); + }); + + it("shows the selected part's faults before anything is typed, and finds the rest", () => { + const list = buildCommands(facts(), actions(), '5x'); + const bare = rankCommands(list, '').map((c) => c.label); + expect(bare).toContain('Crash API Server'); + expect(bare).not.toContain('Fix Database'); + expect(rankCommands(list, 'fix data')[0]?.label).toBe('Fix Database'); + }); + + it('runs the handler with the right id', () => { + const a = actions(); + byId(facts(), a).get('fault.crash.api')?.run(); + expect(a.crash).toHaveBeenCalledWith('api'); + byId(facts(), a).get('example.netflix')?.run(); + expect(a.openExample).toHaveBeenCalledWith('netflix'); + byId(facts(), a).get('run.speed.2')?.run(); + expect(a.setSpeed).toHaveBeenCalledWith(2); + }); + + it('says why a row cannot run', () => { + const m = byId(facts({ inChallenge: true, canPin: false, empty: true })); + expect(m.get('share.break')?.disabled).toBe('Off during a challenge.'); + expect(m.get('incident.s3')?.disabled).toBe('Leave the challenge first.'); + expect(m.get('run.pin')?.disabled).toMatch(/^Nothing measured yet/); + expect(m.get('view.fit')?.disabled).toBe('The diagram is empty.'); + const blocked = byId(facts({ breakBlocked: 'Add a client first.' })); + expect(blocked.get('share.break')?.disabled).toBe('Add a client first.'); + }); + + it('prints keys in the reader’s own form, and none on touch', () => { + expect(byId(facts({ mac: true })).get('help.shortcuts')?.hint).toBe('⌘/'); + expect(byId(facts()).get('help.shortcuts')?.hint).toBe('Ctrl+/'); + const touch = byId(facts({ coarse: true })); + expect(touch.get('run.toggle')?.hint).toBeUndefined(); + expect(touch.has('help.shortcuts')).toBe(false); + }); + + it('follows presenting and full screen', () => { + const on = byId(facts({ presenting: true, fullscreen: true })); + expect(on.get('view.present')?.label).toBe('Stop presenting'); + expect(on.get('view.fullscreen')?.label).toBe('Leave full screen'); + expect(on.get('view.library')?.disabled).toBe('Hidden while presenting.'); + expect(byId(facts({ canFullscreen: false })).has('view.fullscreen')).toBe(false); + }); + + it('keeps glossary terms out of the bare list', () => { + const list = buildCommands(facts(), actions(), '5x'); + expect(rankCommands(list, '').some((c) => c.group === 'Glossary')).toBe(false); + expect(rankCommands(list, 'p99')[0]?.label).toBe('p99'); + }); + + it('keeps the capitals a name has inside a sentence', () => { + expect(inSentence('Load balancer')).toBe('load balancer'); + expect(inSentence('CDN')).toBe('CDN'); + expect(inSentence('API gateway')).toBe('API gateway'); + expect(inSentence('WebSocket gateway')).toBe('WebSocket gateway'); + }); + + it('has no dashes in its copy', () => { + for (const l of labels(facts())) expect(l).not.toMatch(/[—–]/); + }); +}); diff --git a/src/appCommands.ts b/src/appCommands.ts new file mode 100644 index 0000000..5029a58 --- /dev/null +++ b/src/appCommands.ts @@ -0,0 +1,428 @@ +import type { Command } from './commands'; +import type { FailureKind, NodeKind } from './sim/types'; +import type { ThemeChoice } from './content/preferences'; +import { SPEEDS, formatSpeed, type Speed } from './speed'; +import { shortcutLabel } from './modKey'; + +/* ------------------------------------------------------------------ * + * Everything the command palette can do, built from what the shell knows. + * + * Pure: the shell passes the facts and the handlers it already uses for the + * bar, the menu, the rail and the inspector, and gets the rows back. Every + * row runs one of those handlers, so the palette has no undo story or + * validation of its own to drift from the real one. + * ------------------------------------------------------------------ */ + +export interface CommandPart { + id: string; + label: string; + /** The fault in force on it now, or null. */ + fault: FailureKind | null; + /** False for a kind with no service time, where Slow changes nothing. */ + canSlow: boolean; +} + +export interface CommandFacts { + running: boolean; + speed: Speed; + canUndo: boolean; + canRedo: boolean; + /** The design has no parts at all. */ + empty: boolean; + /** Inside a challenge brief. */ + inChallenge: boolean; + /** Why Can you break it? cannot run, or null. */ + breakBlocked: string | null; + /** Something has been measured, so a pin would hold real samples. */ + canPin: boolean; + pinned: boolean; + libraryOpen: boolean; + metricsOpen: boolean; + snapToGrid: boolean; + theme: ThemeChoice; + presenting: boolean; + /** The Fullscreen API exists here. iPhone Safari has none. */ + canFullscreen: boolean; + fullscreen: boolean; + /** The selected part first, then the rest in diagram order. */ + parts: readonly CommandPart[]; + /** The one selected part, whose faults show before anything is typed. */ + selectedId: string | null; + kinds: readonly { kind: NodeKind; name: string; group: string }[]; + examples: readonly { id: string; name: string; tagline: string }[]; + challenges: readonly { id: string; name: string }[]; + incidents: readonly { id: string; name: string }[]; + glossary: readonly { id: string; term: string; aliases?: readonly string[] }[]; + mac: boolean; + /** No keys to print on a touch screen. */ + coarse: boolean; +} + +export interface CommandActions { + toggleRun: () => void; + step: () => void; + reset: () => void; + setSpeed: (s: Speed) => void; + undo: () => void; + redo: () => void; + add: (kind: NodeKind) => void; + openExample: (id: string) => void; + startChallenge: (id: string) => void; + openIncident: (id: string) => void; + crash: (id: string) => void; + slow: (id: string) => void; + fix: (id: string) => void; + pin: () => void; + clearPin: () => void; + toggleLibrary: () => void; + toggleMetrics: () => void; + toggleSnap: () => void; + setTheme: (t: ThemeChoice) => void; + togglePresenting: () => void; + toggleFullscreen: () => void; + fit: () => void; + share: () => void; + breakIt: () => void; + glossary: (id?: string) => void; + examples: () => void; + challenges: () => void; + path: () => void; + designs: () => void; + shortcuts: () => void; + settings: () => void; +} + +/** Slowing a part in the palette uses the same factor as the menu and the + inspector's first press. */ +export const PALETTE_SLOW_LABEL = 'Slow down'; + +const FAULT_WORD: Record = { + crash: 'crashed', + 'crash-instance': 'one instance down', + slow: 'slowed', + errors: 'glitching', + partition: 'cut off', + restart: 'restarting', + pause: 'paused', +}; + +export function buildCommands( + f: CommandFacts, + a: CommandActions, + slowFactor: string, +): Command[] { + const key = (k: string): string | undefined => + f.coarse ? undefined : shortcutLabel(k, f.mac); + const out: Command[] = []; + const push = (c: Command) => out.push(c); + + /* ---- run ---- */ + push({ + id: 'run.toggle', + label: f.running ? 'Pause' : 'Play', + group: 'Run', + keywords: ['play', 'pause', 'start', 'stop', 'resume'], + hint: key('Space'), + run: a.toggleRun, + }); + push({ + id: 'run.step', + label: 'Step one tick', + group: 'Run', + keywords: ['advance'], + hint: key('S'), + run: a.step, + }); + push({ + id: 'run.reset', + label: 'Reset the run', + group: 'Run', + keywords: ['restart', 'clock', 'zero'], + run: a.reset, + }); + for (const s of SPEEDS) { + push({ + id: `run.speed.${s}`, + label: `Play at ${formatSpeed(s)}`, + group: 'Run', + keywords: ['speed', 'faster', 'slower', 'fast', 'slow motion'], + hint: s === f.speed ? 'Now' : undefined, + run: () => a.setSpeed(s), + }); + } + push({ + id: 'run.pin', + label: f.pinned ? 'Pin this run again' : 'Pin this run', + group: 'Run', + keywords: ['compare', 'before', 'after', 'baseline', 'snapshot'], + ...(f.canPin ? {} : { disabled: 'Nothing measured yet. Let some traffic run.' }), + run: a.pin, + }); + if (f.pinned) { + push({ + id: 'run.unpin', + label: 'Clear the pinned run', + group: 'Run', + keywords: ['unpin', 'remove'], + run: a.clearPin, + }); + } + + /* ---- faults, the selected part first ---- */ + for (const p of f.parts) { + // Every other part's faults wait for a search: a forty-part design + // would otherwise fill the list with them. + const searchOnly = p.id !== f.selectedId; + if (p.fault !== 'crash') { + push({ + id: `fault.crash.${p.id}`, + label: `Crash ${p.label}`, + group: 'Faults', + keywords: ['break', 'kill', 'fail', 'down'], + searchOnly, + run: () => a.crash(p.id), + }); + } + if (p.fault === null && p.canSlow) { + push({ + id: `fault.slow.${p.id}`, + label: `${PALETTE_SLOW_LABEL} ${p.label} ${slowFactor}`, + group: 'Faults', + keywords: ['slow', 'latency', 'lag', 'degrade'], + searchOnly, + run: () => a.slow(p.id), + }); + } + if (p.fault !== null) { + push({ + id: `fault.fix.${p.id}`, + label: `Fix ${p.label}`, + group: 'Faults', + keywords: ['repair', 'heal', 'recover', 'restore', FAULT_WORD[p.fault]], + searchOnly, + run: () => a.fix(p.id), + }); + } + } + + /* ---- view ---- */ + if (f.canUndo) { + push({ + id: 'edit.undo', + label: 'Undo', + group: 'View', + hint: key('Ctrl+Z'), + run: a.undo, + }); + } + if (f.canRedo) { + push({ + id: 'edit.redo', + label: 'Redo', + group: 'View', + hint: key('Ctrl+Shift+Z'), + run: a.redo, + }); + } + push({ + id: 'view.present', + label: f.presenting ? 'Stop presenting' : 'Start presenting', + group: 'View', + keywords: ['present', 'teach', 'projector', 'class', 'big', 'lecture'], + hint: key('Shift+P'), + run: a.togglePresenting, + }); + if (f.canFullscreen) { + push({ + id: 'view.fullscreen', + label: f.fullscreen ? 'Leave full screen' : 'Full screen', + group: 'View', + keywords: ['fullscreen', 'projector', 'present'], + run: a.toggleFullscreen, + }); + } + push({ + id: 'view.fit', + label: 'Fit the diagram', + group: 'View', + keywords: ['zoom', 'whole', 'everything', 'center'], + hint: key('Shift+1'), + ...(f.empty ? { disabled: 'The diagram is empty.' } : {}), + run: a.fit, + }); + push({ + id: 'view.library', + label: f.libraryOpen ? 'Hide components' : 'Show components', + group: 'View', + keywords: ['rail', 'palette', 'panel', 'library'], + hint: key('C'), + ...(f.presenting ? { disabled: 'Hidden while presenting.' } : {}), + run: a.toggleLibrary, + }); + push({ + id: 'view.metrics', + label: f.metricsOpen ? 'Hide charts' : 'Show charts', + group: 'View', + keywords: ['metrics', 'graphs', 'strip', 'panel'], + hint: key('M'), + run: a.toggleMetrics, + }); + push({ + id: 'view.snap', + label: f.snapToGrid ? 'Turn grid snap off' : 'Turn grid snap on', + group: 'View', + keywords: ['grid', 'align', 'snap'], + hint: key('G'), + run: a.toggleSnap, + }); + const themes: [ThemeChoice, string][] = [ + ['light', 'Use the light theme'], + ['dark', 'Use the dark theme'], + ['system', 'Match the system theme'], + ]; + for (const [t, label] of themes) { + push({ + id: `view.theme.${t}`, + label, + group: 'View', + keywords: ['theme', 'colour', 'color', 'mode', 'appearance'], + hint: f.theme === t ? 'Now' : undefined, + run: () => a.setTheme(t), + }); + } + + /* ---- share and test ---- */ + push({ + id: 'share.link', + label: 'Share a link to this design', + group: 'Share', + keywords: ['share', 'url', 'copy', 'send'], + run: a.share, + }); + push({ + id: 'share.break', + label: 'Can you break it?', + group: 'Share', + keywords: ['break', 'fault', 'test', 'attack', 'chaos'], + hint: key('F'), + ...(f.inChallenge + ? { disabled: 'Off during a challenge.' } + : f.breakBlocked + ? { disabled: f.breakBlocked } + : {}), + run: a.breakIt, + }); + + /* ---- help ---- */ + push({ + id: 'help.examples', + label: 'Browse examples', + group: 'Help', + run: a.examples, + }); + push({ + id: 'help.challenges', + label: 'Browse challenges', + group: 'Help', + run: a.challenges, + }); + push({ id: 'help.path', label: 'Learning path', group: 'Help', run: a.path }); + push({ + id: 'help.designs', + label: 'Your designs', + group: 'Help', + keywords: ['saved', 'open', 'files'], + run: a.designs, + }); + push({ + id: 'help.glossary', + label: 'Open the glossary', + group: 'Help', + keywords: ['terms', 'definitions', 'words'], + hint: key('?'), + run: () => a.glossary(), + }); + if (!f.coarse) { + push({ + id: 'help.shortcuts', + label: 'Keyboard shortcuts', + group: 'Help', + keywords: ['keys', 'bindings'], + hint: key('Ctrl+/'), + run: a.shortcuts, + }); + } + push({ + id: 'help.settings', + label: 'Settings', + group: 'Help', + keywords: ['preferences', 'options', 'tooltips', 'vendor', 'minimap'], + run: a.settings, + }); + /* ---- build and open ---- */ + for (const k of f.kinds) { + push({ + id: `add.${k.kind}`, + label: `Add ${inSentence(k.name)}`, + group: 'Add', + keywords: [k.kind, k.group, 'component', 'new'], + run: () => a.add(k.kind), + }); + } + + /* ---- open something ---- */ + for (const e of f.examples) { + push({ + id: `example.${e.id}`, + label: e.name, + group: 'Example', + keywords: ['example', 'open', e.tagline], + run: () => a.openExample(e.id), + }); + } + for (const c of f.challenges) { + push({ + id: `challenge.${c.id}`, + label: c.name, + group: 'Challenge', + keywords: ['challenge', 'start', 'brief'], + run: () => a.startChallenge(c.id), + }); + } + for (const i of f.incidents) { + push({ + id: `incident.${i.id}`, + label: i.name, + group: 'Incident', + keywords: ['incident', 'outage', 'postmortem', 'real'], + ...(f.inChallenge ? { disabled: 'Leave the challenge first.' } : {}), + run: () => a.openIncident(i.id), + }); + } + + for (const g of f.glossary) { + push({ + id: `glossary.${g.id}`, + // The term alone: many are not nouns ("Crashed", "Waiting on its + // calls"), so "What is" around them reads wrong. The group says what + // the row is. + label: g.term, + group: 'Glossary', + keywords: [...(g.aliases ?? []), 'what is', 'meaning', 'define'], + searchOnly: true, + run: () => a.glossary(g.id), + }); + } + return out; +} + +/** + * A component name inside a sentence: "Load balancer" becomes "load + * balancer", while a first word with capitals of its own ("CDN", "API", + * "WebSocket") keeps them. + */ +export function inSentence(name: string): string { + const first = name.split(' ', 1)[0] ?? ''; + if (/[A-Z]/.test(first.slice(1))) return name; + return name.charAt(0).toLowerCase() + name.slice(1); +} diff --git a/src/clipboard.ts b/src/clipboard.ts index a214bbb..79f1a3a 100644 --- a/src/clipboard.ts +++ b/src/clipboard.ts @@ -96,6 +96,9 @@ export function isTopology(value: unknown): value is Topology { ]) { if (!Number.isFinite(cfg[key])) return false; } + for (const key of ['chargeable', 'idempotencyKeys', 'flushEveryMs', 'freshReads']) { + if (cfg[key] !== undefined && !Number.isFinite(cfg[key])) return false; + } if (ids.has(n.id)) return false; ids.add(n.id); } diff --git a/src/commands.test.ts b/src/commands.test.ts new file mode 100644 index 0000000..77aa7e9 --- /dev/null +++ b/src/commands.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from 'vitest'; +import { + fuzzyScore, + pushRecent, + rankCommands, + RECENT_MAX, + type Command, +} from './commands'; + +const cmd = (id: string, label: string, extra: Partial = {}): Command => ({ + id, + label, + group: 'View', + run: () => {}, + ...extra, +}); + +describe('fuzzyScore', () => { + it('matches a scattered subsequence and refuses a missing letter', () => { + expect(fuzzyScore('netf', 'Netflix: streaming at scale')).not.toBeNull(); + expect(fuzzyScore('lb', 'Add load balancer')).not.toBeNull(); + expect(fuzzyScore('xyz', 'Add load balancer')).toBeNull(); + }); + + it('ranks a word start above the same letters mid-word', () => { + const start = fuzzyScore('ser', 'User service') ?? 0; + const mid = fuzzyScore('ser', 'Userland') ?? 0; + expect(start).toBeGreaterThan(mid); + }); + + it('ranks a substring above a scattered match', () => { + expect(fuzzyScore('cache', 'Add cache') ?? 0).toBeGreaterThan( + fuzzyScore('cache', 'Crash a cool hen') ?? 0, + ); + }); + + it('takes the words of the query in any order, against label or keywords', () => { + expect(fuzzyScore('db crash', 'Crash Database')).not.toBeNull(); + expect(fuzzyScore('speed', 'Play at 2×', ['speed'])).not.toBeNull(); + expect(fuzzyScore('db missing', 'Crash Database')).toBeNull(); + }); + + it('scores an empty query as a match', () => { + expect(fuzzyScore(' ', 'Anything')).toBe(0); + }); +}); + +describe('rankCommands', () => { + const list = [ + cmd('a', 'Pause'), + cmd('b', 'Netflix: streaming at scale', { group: 'Example' }), + cmd('c', 'Discord: real-time chat', { group: 'Example' }), + cmd('g', 'What is p99?', { group: 'Glossary', searchOnly: true }), + cmd('d', 'Can you break it?', { disabled: 'Off during a challenge.' }), + ]; + + it('with nothing typed: recent first, then the rest, search-only rows held back', () => { + const ids = rankCommands(list, '', ['c']).map((c) => c.id); + expect(ids).toEqual(['c', 'a', 'b', 'd']); + }); + + it('leaves a disabled command out of the recent head', () => { + expect(rankCommands(list, '', ['d'])[0]?.id).toBe('a'); + }); + + it('"netf" puts Netflix first', () => { + expect(rankCommands(list, 'netf')[0]?.id).toBe('b'); + }); + + it('finds search-only rows once something is typed', () => { + expect(rankCommands(list, 'p99').map((c) => c.id)).toContain('g'); + }); + + it('keeps the given order between equal scores', () => { + const twins = [cmd('x', 'Open one'), cmd('y', 'Open one')]; + expect(rankCommands(twins, 'open').map((c) => c.id)).toEqual(['x', 'y']); + }); + + it('caps a query at the limit', () => { + const many = Array.from({ length: 100 }, (_, i) => cmd(`n${i}`, `Node ${i}`)); + expect(rankCommands(many, 'node', [], 10)).toHaveLength(10); + expect(rankCommands(many, '')).toHaveLength(100); + }); +}); + +describe('pushRecent', () => { + it('moves to the front, drops the duplicate and caps', () => { + let r: string[] = []; + for (const id of ['a', 'b', 'c', 'd', 'e', 'f', 'b']) r = pushRecent(r, id); + expect(r).toEqual(['b', 'f', 'e', 'd', 'c']); + expect(r).toHaveLength(RECENT_MAX); + }); +}); diff --git a/src/commands.ts b/src/commands.ts new file mode 100644 index 0000000..75f7a0e --- /dev/null +++ b/src/commands.ts @@ -0,0 +1,177 @@ +/* ------------------------------------------------------------------ * + * The command palette's list and its search, as data. + * + * The shell assembles the commands from handlers it already has + * (appCommands.ts), so a row is never a second implementation of an action. + * This module only scores and orders them. The scoring is a subsequence + * match with bonuses for letters that start a word and for runs of + * consecutive letters, which is what lets "netf" find Netflix and "lb" find + * Load balancer without pulling in a search library. + * ------------------------------------------------------------------ */ + +export type CommandGroup = + | 'Run' + | 'Faults' + | 'Add' + | 'Example' + | 'Challenge' + | 'Incident' + | 'View' + | 'Share' + | 'Help' + | 'Glossary'; + +export interface Command { + /** Stable across renders and reloads; the recent list stores it. */ + id: string; + label: string; + group: CommandGroup; + /** Other words that should find this row. Never shown. */ + keywords?: readonly string[]; + /** The key that does the same thing, printed on the right. */ + hint?: string; + /** Why the row cannot run now. Shown under the label; Enter does nothing. */ + disabled?: string; + /** Left out of the list until something is typed. The glossary has a + hundred terms, which would bury every action under them. */ + searchOnly?: boolean; + run: () => void; +} + +const isWordStart = (text: string, i: number): boolean => { + if (i === 0) return true; + const prev = text[i - 1] ?? ' '; + return !/[a-z0-9]/.test(prev); +}; + +/** + * How well one search word matches `text`, or null when it does not. + * Both are expected lower-cased. A plain substring always outranks a + * scattered subsequence, and one at the start of a word outranks one in the + * middle of it. + */ +function wordScore(word: string, text: string): number | null { + const at = text.indexOf(word); + if (at >= 0) { + let best = at; + // Prefer a later hit that starts a word: "ser" in "user service". + for (let i = at; i >= 0; i = text.indexOf(word, i + 1)) { + if (isWordStart(text, i)) { + best = i; + break; + } + } + return 100 + word.length * 4 + (best === 0 ? 40 : isWordStart(text, best) ? 25 : 0); + } + let score = 0; + let from = 0; + let prev = -2; + for (const ch of word) { + const j = text.indexOf(ch, from); + if (j < 0) return null; + score += 1; + if (j === prev + 1) score += 3; + if (isWordStart(text, j)) score += 6; + prev = j; + from = j + 1; + } + return score; +} + +/** + * The score of `query` against a label and its keywords, or null when any + * word of the query matches neither. Words can match in any order, so + * "db crash" finds "Crash Database". + */ +export function fuzzyScore( + query: string, + label: string, + keywords: readonly string[] = [], +): number | null { + const words = query.toLowerCase().split(/\s+/).filter(Boolean); + if (words.length === 0) return 0; + const name = label.toLowerCase(); + const extra = keywords.map((k) => k.toLowerCase()); + let total = 0; + for (const w of words) { + const onLabel = wordScore(w, name); + let best = onLabel; + for (const k of extra) { + const s = wordScore(w, k); + // A keyword hit counts for a little less than the same hit on the + // label, so the row a reader can SEE matching comes first. + if (s !== null && (best === null || s - 5 > best)) best = s - 5; + } + if (best === null) return null; + total += best; + } + return total; +} + +/** + * The rows to show for `query`, best first. + * + * With nothing typed: the recent commands, newest first, then everything + * not marked search-only in the order given, uncapped. With a query, at + * most `limit` rows. With a query: by score, then a + * small lift for a recent command, then the given order, so ties never + * shuffle between keystrokes. + */ +export function rankCommands( + commands: readonly Command[], + query: string, + recent: readonly string[] = [], + limit = 60, +): Command[] { + const recentRank = new Map(recent.map((id, i) => [id, i] as const)); + if (query.trim() === '') { + const byId = new Map(commands.map((c) => [c.id, c] as const)); + const head: Command[] = []; + for (const id of recent) { + const c = byId.get(id); + if (c && !c.disabled) head.push(c); + } + const seen = new Set(head.map((c) => c.id)); + const rest = commands.filter((c) => !c.searchOnly && !seen.has(c.id)); + return [...head, ...rest]; + } + const scored: { c: Command; s: number; i: number }[] = []; + commands.forEach((c, i) => { + const s = fuzzyScore(query, c.label, c.keywords); + if (s === null) return; + const r = recentRank.get(c.id); + scored.push({ c, s: s + (r === undefined ? 0 : 8 - r), i }); + }); + scored.sort((a, b) => b.s - a.s || a.i - b.i); + return scored.slice(0, limit).map((x) => x.c); +} + +export const RECENT_MAX = 5; + +/** `id` moved to the front, without duplicates, capped. */ +export function pushRecent(recent: readonly string[], id: string): string[] { + return [id, ...recent.filter((r) => r !== id)].slice(0, RECENT_MAX); +} + +const RECENT_KEY = 'breakscale.commands.v1'; + +/** The recent list from this browser, or empty when storage is unavailable. */ +export function loadRecent(): string[] { + try { + const raw = localStorage.getItem(RECENT_KEY); + const parsed: unknown = raw ? JSON.parse(raw) : []; + return Array.isArray(parsed) + ? parsed.filter((x): x is string => typeof x === 'string').slice(0, RECENT_MAX) + : []; + } catch { + return []; + } +} + +export function saveRecent(recent: readonly string[]): void { + try { + localStorage.setItem(RECENT_KEY, JSON.stringify(recent)); + } catch { + // A private window or full storage: the list is a convenience. + } +} diff --git a/src/components/BreakIt.css b/src/components/BreakIt.css index 910861e..7034623 100644 --- a/src/components/BreakIt.css +++ b/src/components/BreakIt.css @@ -19,13 +19,14 @@ flex-direction: column; gap: var(--sp-1); padding: var(--sp-2) var(--sp-3); - border-radius: var(--r-sm); + border-radius: var(--r-btn); background: var(--surface-2); } +/* The chosen goal: the shared "this is the one" fill, not an outline, which + is kept for keyboard focus. */ .brk-goal.is-on { - outline: 2px solid var(--accent); - outline-offset: -2px; + background: var(--accent-soft); } /* At least 44px tall, so a row is a comfortable target on a phone. */ @@ -45,7 +46,7 @@ .brk-goal-sentence { margin: 0; font-size: var(--fs-sm); - line-height: 2; + line-height: var(--lh-prose); } .brk-num { @@ -67,7 +68,7 @@ margin: 0; padding-left: var(--sp-4); font-size: var(--fs-sm); - line-height: var(--lh-body); + line-height: var(--lh-base); } .brk-check { @@ -91,13 +92,38 @@ padding: 0; } +/* A drawn chevron that turns a quarter, in place of the native marker. */ .brk-more summary { + display: flex; + align-items: center; + gap: var(--sp-1); min-height: 32px; font-size: var(--fs-sm); font-weight: var(--fw-med); + list-style: none; cursor: pointer; } +.brk-more summary::-webkit-details-marker { + display: none; +} + +.brk-more summary::before { + content: ''; + flex: none; + width: 6px; + height: 6px; + margin: 0 var(--sp-1); + border-right: 2px solid currentColor; + border-bottom: 2px solid currentColor; + transform: rotate(-45deg); + transition: transform var(--dur-fast) var(--ease-out); +} + +.brk-more[open] > summary::before { + transform: rotate(45deg); +} + .brk-more[open] { display: flex; flex-direction: column; @@ -116,7 +142,7 @@ .brk-verdict { margin: 0; - line-height: var(--lh-body); + line-height: var(--lh-base); } .brk-schedule { @@ -143,6 +169,41 @@ } /* The replay's clock, readable with the panel folded. */ +/* A replay as it plays: clock, bar, figure, Stop. */ +.brk-watch { + display: flex; + flex-direction: column; + gap: var(--sp-2); +} + +.brk-watch-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--sp-2); +} + +.brk-watch-clock { + margin: 0; + font-family: var(--mono); + font-size: var(--fs-sm); + font-variant-numeric: tabular-nums; + color: var(--text); +} + +.brk-watch-bar { + height: 4px; + border-radius: var(--r-pill); + background: var(--track); + overflow: hidden; +} + +.brk-watch-bar > span { + display: block; + height: 100%; + background: var(--accent); +} + .brk-pill { margin: 0; padding: var(--sp-2) var(--sp-3); @@ -188,3 +249,55 @@ min-height: 44px; } } + +/* A request's story: time, then what happened. A bad step says so in a word + as well as in colour. */ +.brk-follow { + display: flex; + flex-direction: column; + gap: var(--sp-2); +} + +.brk-story { + display: flex; + flex-direction: column; + gap: var(--sp-1); + max-height: 16rem; + margin: 0; + padding: var(--sp-2); + overflow-y: auto; + list-style: none; + font-size: var(--fs-sm); + line-height: var(--lh-sm); + background: var(--surface-2); + border-radius: var(--r-sm); +} + +.brk-story[hidden] { + display: none; +} + +.brk-story-row { + display: grid; + grid-template-columns: 3.75rem 1fr; + gap: var(--sp-2); + min-width: 0; +} + +.brk-story-t { + color: var(--text-dim); +} + +.brk-story-row.is-bad { + color: var(--danger); + font-weight: var(--fw-med); +} + +.brk-story-tag { + display: inline-block; + margin-left: var(--sp-2); + padding: 0 var(--sp-1); + border: 1px solid currentColor; + border-radius: var(--r-sm); + font-size: var(--fs-label); +} diff --git a/src/components/BreakIt.test.tsx b/src/components/BreakIt.test.tsx index 936f8b8..c9d8e5d 100644 --- a/src/components/BreakIt.test.tsx +++ b/src/components/BreakIt.test.tsx @@ -21,7 +21,7 @@ import { } from '../sim/breakit'; import type { Attack, SearchProgress } from '../sim/breakit'; import type { Goal } from '../sim/challenge'; -import { PRESETS } from '../sim/presets'; +import { PRESETS, defaultConfig } from '../sim/presets'; import type { Topology } from '../sim/types'; import type { BreakSearch, BreakView } from '../useBreakSearch'; @@ -79,7 +79,7 @@ const names: Names = { node: (id) => t.nodes.find((n) => n.id === id)?.label ?? id, edge: (id) => { const e = t.edges.find((x) => x.id === id); - return e ? `the cable from ${names.node(e.from)} to ${names.node(e.to)}` : id; + return e ? `the connection from ${names.node(e.from)} to ${names.node(e.to)}` : id; }, }; const goal: Goal = { metric: 'errorRate', max: 1 }; @@ -110,6 +110,7 @@ function fake(view: BreakView, over: Partial = {}): BreakSearch { view, stale: false, goalGone: false, + goneId: null, remembered: [], start: vi.fn(), stop: vi.fn(), @@ -131,7 +132,8 @@ function show( onClose: vi.fn(), onWatch: vi.fn(), onReplayLink: vi.fn(), - watchLine: null, + onMarkChargeable: vi.fn(), + watch: null, ...extra, }; act(() => root.render()); @@ -154,7 +156,7 @@ describe('BreakPanel', () => { expect(text).toContain('Keep everyone up'); expect(text).toContain('Stay fast'); expect(text).toContain( - 'Every request from Client has to pass through API Server, Database and the cable from API Server to Database.', + 'Every request from Client has to pass through API Server, Database and the connection from API Server to Database.', ); expect(container.querySelector('fieldset legend')?.textContent).toBe( 'What has to hold', @@ -274,6 +276,35 @@ describe('BreakPanel', () => { expect(props.onReplayLink).toHaveBeenCalledTimes(1); }); + it('shows a replay as a clock, a bar and a Stop button, counting down to the first fault', () => { + if (broke.status !== 'broke') throw new Error('should break'); + const onStopWatch = vi.fn(); + const watch = { line: 'Nothing measured yet.', firstMs: 10_000, endMs: 35_000 }; + show(fake(done(broke)), { watch, watchAtMs: 4_300, onStopWatch }); + expect(container.querySelector('.brk-watch-clock')?.textContent).toBe( + 'Replay 4s of 35s', + ); + const bar = container.querySelector('[role="progressbar"][aria-label="Replay"]'); + expect(bar?.getAttribute('aria-valuenow')).toBe('4'); + expect(container.querySelector('.brk-pill')?.textContent).toBe( + 'Nothing measured yet. The first fault lands at 10s, in 6s.', + ); + // The clock moves with the replay, not with a remembered second. + show(fake(done(broke)), { watch, watchAtMs: 12_000, onStopWatch }); + expect(container.querySelector('.brk-pill')?.textContent).toBe( + 'Nothing measured yet.', + ); + show(fake(done(broke)), { watch, watchAtMs: 36_000, onStopWatch }); + expect(container.querySelector('.brk-watch-clock')?.textContent).toBe( + 'Replay done', + ); + const stop = [...container.querySelectorAll('button')].find( + (b) => b.textContent === 'Stop replay', + ); + press(stop as Element); + expect(onStopWatch).toHaveBeenCalledTimes(1); + }); + it('folds to the break and remembers it when asked to fix it', () => { if (broke.status !== 'broke') throw new Error('should break'); const search = fake(done(broke)); @@ -356,7 +387,251 @@ describe('break copy', () => { ), ).toMatch(/Requests started to pile up\.$/); expect(lines[0]).toBe( - 'Crash Database at 10s for 0.5s and cut the cable from API Server to Database at 10s, then make API Server fail 50% of requests at 12s for 2s, then take down one machine of API Server at 15s.', + 'Crash Database at 10s for 0.5s and cut the connection from API Server to Database at 10s, then make API Server fail 50% of requests at 12s for 2s, then take down one machine of API Server at 15s.', + ); + }); +}); + +describe('BreakPanel: correctness goals', () => { + /** The double-charge fixture: a retry after a timeout charges twice. */ + const pay: Topology = { + nodes: [ + { + ...t.nodes[0], + id: 'client', + kind: 'client', + label: 'Client', + config: { ...t.nodes[0].config, rps: 100 }, + }, + { + id: 'checkout', + kind: 'service', + label: 'Checkout', + x: 0, + y: 0, + config: { + ...defaultConfig('service'), + capacity: 64, + serviceMs: 5, + timeoutMs: 300, + retries: 2, + }, + }, + { + id: 'pay', + kind: 'service', + label: 'Payment Provider', + x: 0, + y: 0, + config: { + ...defaultConfig('service'), + capacity: 64, + serviceMs: 100, + serviceCv: 0.3, + }, + }, + ], + edges: [ + { id: 'a', from: 'client', to: 'checkout', weight: 1 }, + { id: 'b', from: 'checkout', to: 'pay', weight: 1 }, + ], + }; + const payNames: Names = { + node: (id) => pay.nodes.find((n) => n.id === id)?.label ?? id, + edge: (id) => id, + }; + const once: Goal = { metric: 'doubleCharges', max: 0 }; + + function picking(design: Topology) { + const search = fake( + { status: 'picking' }, + { templates: breakGoals(design), goalId: 'once', goal: once, maxOf: () => 0 }, + ); + act(() => + root.render( + , + ), + ); + return search; + } + const mark = vi.fn(); + + it('asks which part charges the card before it can run', () => { + picking(pay); + const text = container.textContent ?? ''; + expect(text).toContain('Every payment charged at most once'); + expect(text).toContain('Pick the part that charges the card to measure it.'); + const run = [...container.querySelectorAll('button')].find( + (b) => b.textContent === 'Try to break it', + ); + expect(run?.disabled).toBe(true); + const select = [...container.querySelectorAll('select')].find((s) => + s.labels?.[0]?.textContent?.includes('Which part charges the card?'), + ); + if (!select) throw new Error('no picker'); + // Every part a call finishes at, and not the client. + expect([...select.options].map((o) => o.value)).toEqual(['', 'checkout', 'pay']); + act(() => { + select.value = 'pay'; + select.dispatchEvent(new Event('change', { bubbles: true })); + }); + expect(mark).toHaveBeenCalledWith('pay'); + // The terms in the goal are explained on hover. + const terms = [...container.querySelectorAll('[data-term]')].map((e) => + e.getAttribute('data-term'), + ); + expect(terms).toEqual(expect.arrayContaining(['at-most-once', 'idempotency-key'])); + }); + + it('runs once a part is marked, and says which', () => { + const marked = { + ...pay, + nodes: pay.nodes.map((n) => + n.id === 'pay' ? { ...n, config: { ...n.config, chargeable: 1 } } : n, + ), + }; + picking(marked); + expect(container.textContent).toContain('Counted at Payment Provider'); + const run = [...container.querySelectorAll('button')].find( + (b) => b.textContent === 'Try to break it', + ); + expect(run?.disabled).toBe(false); + }); + + it('shows the first double charge and follows that request', () => { + const marked = { + ...pay, + nodes: pay.nodes.map((n) => + n.id === 'pay' ? { ...n, config: { ...n.config, chargeable: 1 } } : n, + ), + }; + const result = runSearch(marked, once, DEFAULT_OPTIONS); + if (result.status !== 'broke') + throw new Error(`expected a break, got ${result.status}`); + const first = result.run.violations?.[0]; + if (first?.check !== 'atMostOnce') throw new Error('no double charge'); + const search = fake( + { + status: 'done', + result, + design: searchDesign(marked), + goal: once, + designSig: 'x', + }, + { templates: breakGoals(marked), goalId: 'once', goal: once }, + ); + act(() => + root.render( + , + ), + ); + expect(container.textContent).toContain( + `Request ${first.rid} was charged twice at Payment Provider`, + ); + const follow = [...container.querySelectorAll('button')].find( + (b) => b.textContent === `Follow request ${first.rid}`, + ); + if (!follow) throw new Error('no follow button'); + expect(follow.getAttribute('aria-expanded')).toBe('false'); + press(follow); + expect(follow.getAttribute('aria-expanded')).toBe('true'); + const list = container.querySelector( + `#${CSS.escape(follow.getAttribute('aria-controls') ?? '')}`, + ); + expect(list?.tagName).toBe('OL'); + const bad = [...(list?.querySelectorAll('.is-bad') ?? [])]; + expect(bad).toHaveLength(1); + expect(bad[0].textContent).toContain('Payment Provider charges the card again.'); + expect(bad[0].textContent).toContain('Charged again'); + }, 60_000); + function render(search: BreakSearch, design: Topology) { + act(() => + root.render( + , + ), + ); + } + + it('says a hold comes from nothing retrying when nothing before the charge retries', () => { + const noRetry = { + ...pay, + nodes: pay.nodes.map((n) => + n.id === 'pay' + ? { ...n, config: { ...n.config, chargeable: 1 } } + : n.id === 'checkout' + ? { ...n, config: { ...n.config, retries: 0 } } + : n, + ), + }; + // With cables delivering twice left out: a duplicate needs no retry. + const result = runSearch(noRetry, once, { + ...DEFAULT_OPTIONS, + kinds: DEFAULT_OPTIONS.kinds.filter((k) => k !== 'duplicate'), + budget: 5, + }); + if (result.status !== 'held') + throw new Error(`expected held, got ${result.status}`); + render( + fake( + { + status: 'done', + result, + design: searchDesign(noRetry), + goal: once, + designSig: 'x', + }, + { templates: breakGoals(noRetry), goalId: 'once', goal: once }, + ), + noRetry, + ); + expect(container.textContent).toContain( + 'Nothing on the way to Payment Provider sends a call again', + ); + }, 60_000); + + it('does not quietly run another goal once the one it ran is gone', () => { + const search = fake(done(broke), { stale: true, goneId: 'saved', goalGone: true }); + render(search, pay); + const text = container.textContent ?? ''; + expect(text).toContain('no saved write can be lost this way'); + expect( + [...container.querySelectorAll('button')].some( + (b) => b.textContent === 'Run again', + ), + ).toBe(false); + const pick = [...container.querySelectorAll('button')].find( + (b) => b.textContent === 'Pick another goal', ); + if (!pick) throw new Error('no pick button'); + press(pick); + expect(search.backToGoals).toHaveBeenCalled(); + expect(search.start).not.toHaveBeenCalled(); }); }); diff --git a/src/components/BreakIt.tsx b/src/components/BreakIt.tsx index 9fadd94..d7c3bcd 100644 --- a/src/components/BreakIt.tsx +++ b/src/components/BreakIt.tsx @@ -1,24 +1,43 @@ -import { useEffect, useId, useLayoutEffect, useRef, useState } from 'react'; +import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react'; import type { KeyboardEvent } from 'react'; -import { HARDER_BUDGET } from '../sim/breakit'; -import type { AttackKind, BreakOptions, SearchProgress } from '../sim/breakit'; +import { takesCorrectness } from '../sim/behaviour'; +import { + HARDER_BUDGET, + kindFits, + replayOf, + retriesTowardCharges, +} from '../sim/breakit'; +import type { Attack, AttackKind, BreakOptions, SearchProgress } from '../sim/breakit'; +import { isCorrectnessGoal } from '../sim/challenge'; import type { Goal } from '../sim/challenge'; -import type { SimNode } from '../sim/types'; +import type { Violation } from '../sim/oplog'; +import type { SimNode, Topology } from '../sim/types'; +import { followRequest } from '../sim/verify'; import type { BreakSearch } from '../useBreakSearch'; import { baselineSentence, + checkedLine, + clock, closestLine, effectSentence, + evidenceSentence, faultPhrase, goalLine, + goneLine, + nothingRetriesLine, phaseLine, scheduleSentence, singlePointLines, + timelineWords, + TRUNCATED_LINE, triedLine, } from './breakCopy'; -import type { Names } from './breakCopy'; +import type { Names, TimelineTag } from './breakCopy'; +import { secs } from './breakCopy'; +import { Term } from './Tooltip'; import './Challenge.css'; import './BreakIt.css'; +import { CloseButton } from './CloseButton'; /** * "Can you break it?": pick what has to hold, and Breakscale throws faults @@ -37,21 +56,37 @@ export interface BreakPanelProps { onClose: () => void; onWatch: () => void; onReplayLink: () => void; + /** Mark a part as charging money, through the same undoable edit the Inspector makes. */ + onMarkChargeable: (id: string) => void; /** - * While a replay plays: where it is, in a line. The panel folds to it. - * Null otherwise. + * While a replay plays: what it has measured so far, when its first fault + * lands and when its window ends. The panel folds to it. Null otherwise. */ - watchLine: string | null; + watch: ReplayWatch | null; + /** The replay's own clock, read on every render. */ + watchAtMs?: number; + /** Stop watching and put the reader's design back. */ + onStopWatch?: () => void; foldOnStart?: boolean; onSheetResize?: (height: number | null, shut: boolean) => void; } +export interface ReplayWatch { + /** The figure so far, as a sentence. */ + line: string; + firstMs: number; + endMs: number; +} + const KIND_LABEL: Record = { crash: 'Crashes', - 'crash-instance': 'Losing one machine', + 'crash-instance': 'Losing one instance', slow: 'Slowdowns', - errors: 'Glitches (errors)', - cut: 'Cut cables', + errors: 'Random errors', + cut: 'Cut connections', + duplicate: 'Requests delivered twice', + pause: 'Stalls (a process pauses)', + 'cut-replies': 'Answers lost on the way back', }; /** A template's name in the radio group. */ @@ -67,6 +102,12 @@ function templateLabel(goal: Goal, names: Names): string { return 'No lost writes'; case 'lostJobs': return 'No lost jobs'; + case 'doubleCharges': + return 'Every payment charged at most once'; + case 'lostAckedWrites': + return 'No saved write is lost'; + case 'staleReads': + return 'Read your own writes'; case 'queueDepth': return ''; } @@ -91,6 +132,24 @@ function templateSentence(goal: Goal): { before: string; after: string; unit: st }; case 'lostWrites': return { before: 'At most', after: 'saved writes are lost.', unit: 'writes' }; + case 'doubleCharges': + return { + before: 'At most', + after: 'payments are charged more than once.', + unit: 'payments', + }; + case 'lostAckedWrites': + return { + before: 'At most', + after: 'writes the client was told were saved are lost.', + unit: 'writes', + }; + case 'staleReads': + return { + before: 'At most', + after: 'reads miss a write the same client was told was saved.', + unit: 'reads', + }; default: return { before: 'At most', after: 'accepted jobs fail.', unit: 'jobs' }; } @@ -140,8 +199,8 @@ function GoalNumber({ function Chevron({ open }: { open: boolean }) { return ( { + headingRef.current?.focus({ preventScroll: true }); + }, []); + /* Focus goes to a verdict's heading as it lands, so a screen reader is where the answer is. Keyed on the result object, which is new per run. */ const result = view.status === 'done' ? view.result : null; @@ -278,7 +348,7 @@ export function BreakPanel({
- +

{announcement(search, names)}

- {watchLine !== null ? ( -

- {watchLine} -

+ {watch !== null ? ( + { + setCollapsed(false); + onStopWatch(); + } + : undefined + } + /> ) : null} ) : null} @@ -337,6 +396,7 @@ export function BreakPanel({ names={names} nodes={nodes} baselineId={baselineId} + onMarkChargeable={onMarkChargeable} /> ) : view.status === 'searching' || view.status === 'stopped' ? (
- + + ) : null} +
+
+ +
+

+ {watch.line} + {until > 0 + ? ` The first fault lands at ${secs(watch.firstMs)}, in ${until}s.` + : ''} +

+ + ); +} + function Picking({ search, names, nodes, baselineId, + onMarkChargeable, }: { search: BreakSearch; names: Names; nodes: readonly SimNode[]; baselineId: string; + onMarkChargeable: (id: string) => void; }) { const { templates, baselines, opts } = search; const set = (patch: Partial) => search.setOpts({ ...opts, ...patch }); @@ -417,6 +522,9 @@ function Picking({ const selected = templates.findIndex((t) => t.id === search.goalId); const base = selected >= 0 ? baselines?.[selected] : undefined; const targets = nodes.filter((n) => n.kind !== 'client'); + const charging = search.goal.metric === 'doubleCharges'; + const charged = nodes.filter((n) => n.config.chargeable === 1); + const unmarked = charging && charged.length === 0; return ( <> @@ -424,8 +532,8 @@ function Picking({ Pick what has to hold. Breakscale throws faults at your design until it fails, or until it runs out of tries.

- {search.goalGone ? ( -

That traffic source is gone. Pick another goal.

+ {search.goneId !== null ? ( +

{goneLine(search.goneId)} Pick another goal.

) : null}
What has to hold @@ -457,14 +565,25 @@ function Picking({ {s.after}

) : null} + {on ? : null} + {on && t.goal.metric === 'doubleCharges' ? ( + + ) : null} ); })}

- {base - ? `${baselineSentence(base.worst, search.goal, names)} That is the worst of three runs of traffic.` - : 'Measuring it with no faults…'} + {unmarked + ? 'Pick the part that charges the card to measure it.' + : base + ? `${baselineSentence(base.worst, search.goal, names)} That is the worst of three runs of traffic.` + : 'Measuring it with no faults…'}

{search.singlePoints.length > 0 ? ( @@ -475,19 +594,33 @@ function Picking({
  • {line}
  • ))} -

    - Each of these is a single point of failure: lose one and that traffic has - nowhere to go, which breaks any goal. So the search only slows them and - takes down single machines. -

    - + {isCorrectnessGoal(search.goal) ? ( + // An outage cannot break a goal about the data, and a crash of the + // one store is how its writes get lost, so nothing is spared. +

    + Each of these is a single point of failure. This goal is about the data, + not about staying up, so the search crashes and cuts them like any other + part. +

    + ) : ( + <> +

    + Each of these is a single point of failure: lose one and that traffic + has nowhere to go, which breaks any goal. So the search only slows them + and takes down single machines. +

    + + + )} ) : null} @@ -495,16 +628,18 @@ function Picking({ What can go wrong
    Kinds of fault - {(Object.keys(KIND_LABEL) as AttackKind[]).map((k) => ( - - ))} + {(Object.keys(KIND_LABEL) as AttackKind[]) + .filter((k) => kindFits(k, search.goal)) + .map((k) => ( + + ))}