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
) : null}
@@ -495,16 +628,18 @@ function Picking({
What can go wrong
Watch the replay
@@ -769,3 +946,183 @@ function Verdict({
>
);
}
+
+/** A story line's tag, in words as well as colour. */
+const TAG_WORDS: Record, string> = {
+ 'charged-again': 'Charged again',
+ lost: 'Lost',
+ stale: 'Stale',
+};
+
+/**
+ * Run the search again, or, when the goal it ran is no longer offered by
+ * the design, say why and go back to the goals instead of quietly running
+ * another one.
+ */
+function RunAgain({
+ search,
+ primary = false,
+}: {
+ search: BreakSearch;
+ primary?: boolean;
+}) {
+ const cls = `btn btn-sm${primary ? ' btn-primary' : ''}`;
+ if (search.goneId !== null) {
+ return (
+ <>
+
{goneLine(search.goneId)}
+
+ Pick another goal
+
+ >
+ );
+ }
+ return (
+ search.start()}>
+ Run again
+
+ );
+}
+
+/** What a correctness goal counts, with its terms explained on hover. */
+function GoalTerms({ metric }: { metric: Goal['metric'] }) {
+ if (metric === 'doubleCharges') {
+ return (
+
+ A payment charged twice breaks the at most once{' '}
+ rule. It happens when a call that already charged looks failed to its caller,
+ after a timeout or an error further on, and the{' '}
+ retry charges again, or when the network delivers the
+ same call twice. An idempotency key on the
+ part that charges is the usual fix.
+
+ Checks read your writes: once a client is
+ told a write was saved, its next read of that record should show it. A{' '}
+ replica that is behind serves a{' '}
+ stale read instead.
+
+ );
+ }
+ return null;
+}
+
+/**
+ * For a correctness goal with nothing marked yet: which part charges the
+ * card. Once one is marked, says which, so the reader knows what is counted.
+ */
+function ChargeablePicker({
+ nodes,
+ charged,
+ names,
+ onMark,
+}: {
+ nodes: readonly SimNode[];
+ charged: readonly SimNode[];
+ names: Names;
+ onMark: (id: string) => void;
+}) {
+ const id = useId();
+ if (charged.length > 0) {
+ return (
+
+ Counted at {charged.map((n) => names.node(n.id)).join(', ')}, where each
+ finished call charges money. Change it in the part's settings.
+
+ );
+}
+
+/**
+ * The earliest violation in words, and the request's whole story on
+ * demand. The story is played again from the replay, headless and from the
+ * start, so it is the run the search measured; the canvas replay steps at
+ * the display's rate and can differ in the details.
+ */
+function FollowRequest({
+ design,
+ attacks,
+ seed,
+ violation,
+ names,
+}: {
+ design: Topology;
+ attacks: readonly Attack[];
+ seed: number;
+ violation: Violation;
+ names: Names;
+}) {
+ const [open, setOpen] = useState(false);
+ const listId = useId();
+ const lines = useMemo(() => {
+ if (!open) return null;
+ const tl = followRequest(replayOf(design, attacks, seed), violation.rid);
+ return tl === null ? [] : timelineWords(tl, names, violation);
+ }, [open, design, attacks, seed, violation, names]);
+ return (
+