Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/components/PartDescription.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export function PartDescriptionView({
</Typography>
{summary && <Typography variant="body2">{summary}</Typography>}
{table && (
<Box sx={{ mt: 0.5 }}>
<Box sx={{ mt: 0.5, overflowX: "auto" }}>
<TruthTableView table={table} />
</Box>
)}
Expand Down
19 changes: 17 additions & 2 deletions src/i18n/en.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { englishSimulationErrorTexts } from "../store/simulationErrorTexts";
import type { TutorialStageId } from "../tutorial/stages";
import type { TutorialPartId, TutorialStageId } from "../tutorial/stages";

const bitWidths = (widths: readonly number[]) => `${widths.join("/")} bit`;
const listOf = (names: readonly string[]) =>
Expand Down Expand Up @@ -66,7 +66,7 @@ const stageTexts: Record<TutorialStageId, StageTexts> = {
},
"decimal-digit": {
title: "One decimal digit",
goal: "Writing numbers with 0 to 9, carrying over after 9 as everyday numbers do, is called decimal. Make Count go up by 1 only at the time steps when Up is ON, and go back to 0000 after 1001. 1001 is 9, 8 plus 1. At a time step when Count is 1001 and Up is ON, make Carry turn ON: it tells the digit above to go up. Check turns Up ON for time steps 1 to 9, OFF for 10 and 11, and ON again from 12.",
goal: "Writing numbers with 0 to 9, carrying over after 9 as everyday numbers do, is called decimal. Make Count go up by 1 only at the time steps when Up is ON, and go back to 0000 after 1001. 1001 is 9, 8 plus 1. At a time step when Count is 1001 and Up is ON, make Carry turn ON: it tells the digit above to go up. Check turns Up ON until Count reaches 1001, then OFF for two time steps to see that Count stays at 1001 and Carry stays OFF, and then ON again to see that Count goes back to 0000.",
steps: [
'The Const, Broadcast and And on the left send 0001 to B of "Adding four digits" when Up is ON, and 0000 when it is OFF. A Broadcast spreads a one-bit value over several bits: 1111 for ON, 0000 for OFF. An And given values of several bits makes each bit 1 only where both are 1.',
"Make Carry. From 0000 to 1001, only 1001 has 1 in both the eights and the ones digit. Join the top pin (eights) and the bottom pin (ones) on the right of the Decompose at the bottom with an And, join its output and Up with another And, and connect that to Carry.",
Expand All @@ -75,6 +75,16 @@ const stageTexts: Record<TutorialStageId, StageTexts> = {
"While playing, click Up to switch it ON and OFF, and go through the time steps with the right arrow. The circuit works when the number on the Display goes up only while Up is ON, and goes back to 0 after 9.",
],
},
stopwatch: {
title: "Stopwatch",
goal: "Finally, a stopwatch counting minutes and seconds like 12:34. It goes on by one second at each time step when Start is ON. The Display at the top right shows, from the left, the tens digit of the minutes (M10), the ones digit of the minutes (M1), a colon, the tens digit of the seconds (S10) and the ones digit of the seconds (S1). M10 and S10 count 0 to 5, and M1 and S1 count 0 to 9. After 59:59 it goes back to 00:00. The 7segs, Const, Decompose and Aggregate left of the Display put the four numerals and the colon side by side on that one Display. Check keeps Start ON until 59:59 has gone back to 00:00, then turns it OFF for two time steps to see that the stopwatch stops, and ON again to see that it goes on.",
steps: [
'Place two "One base-6 digit" and two "One decimal digit". "One base-6 digit" is built like "One decimal digit", but counts 0 to 5 and carries over after 5, as decimal does after 9.',
'Give each of the four parts one of M10, M1, S10 and S1: "One base-6 digit" for M10 and S10, and "One decimal digit" for M1 and S1. Connect the Count of each to the output on the right named after its digit, and to the 7seg of that digit. The 7segs are, from the top, for M10, M1, S10 and S1.',
"Connect Start to Up of the part connected to S1. Then connect Carry of the part for S1 to Up of the part for S10, Carry for S10 to Up for M1, and Carry for M1 to Up for M10. A digit then goes on only when the digit one lower goes back to 0.",
'Press the play button. If Start is OFF at the first time step, click it to turn it ON. Press "Auto", and the Display goes on like a clock, one time step a second. To see what comes after 59:59, stop Auto, click the number at the bottom, enter 3600 and press the Enter key. It goes to that time step at once and shows 59:59, and the right arrow shows 00:00.',
],
},
};

export const en = {
Expand Down Expand Up @@ -188,6 +198,7 @@ export const en = {
stepsHeading: "Steps",
digitsLegend: "The tables write ON as 1 and OFF as 0.",
check: "Check",
checking: "Checking…",
passed: "Cleared! The circuit works for every combination of the inputs.",
passedSteps: (count: number) =>
`Cleared! The circuit works at every time step up to time step ${count}.`,
Expand Down Expand Up @@ -224,6 +235,10 @@ export const en = {
},
resetStageFailed: "Could not reset the stage.",
stageTexts,
partTitles: { "senary-digit": "One base-6 digit" } satisfies Record<
TutorialPartId,
string
>,
},
componentProperties: {
title: (componentName: string) => `${componentName} Properties`,
Expand Down
14 changes: 13 additions & 1 deletion src/i18n/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export const ja: Messages = {
stepsHeading: "手順",
digitsLegend: "表では、ON を 1、OFF を 0 と書いています。",
check: "確かめる",
checking: "確かめています…",
passed: "クリア!どの入力の組み合わせでも正しく動きます。",
passedSteps: (count) =>
`クリア!${count} ステップ目まで、どのステップでも正しく動きます。`,
Expand All @@ -137,6 +138,7 @@ export const ja: Messages = {
confirm: "やり直す",
},
resetStageFailed: "課題をやり直せませんでした。",
partTitles: { "senary-digit": "6進の1桁" },
stageTexts: {
and: {
title: "両方のスイッチ",
Expand Down Expand Up @@ -191,7 +193,7 @@ export const ja: Messages = {
},
"decimal-digit": {
title: "10進の1桁",
goal: "ふだんの数のように、0 から 9 までを使い、9 の次で桁が上がる書き方を10進数といいます。Up が ON のステップだけ Count が 1 増え、1001 の次は 0000 に戻るようにしましょう。1001 は、8 と 1 を足した 9 です。Count が 1001 で Up が ON のステップでは、Carry が ON になるようにします。Carry は、上の桁に桁上がりを知らせる合図です。「確かめる」を押すと、Up を 1〜9 ステップ目は ON、10・11 ステップ目は OFF、12 ステップ目からはまた ON にして調べます。",
goal: "ふだんの数のように、0 から 9 までを使い、9 の次で桁が上がる書き方を10進数といいます。Up が ON のステップだけ Count が 1 増え、1001 の次は 0000 に戻るようにしましょう。1001 は、8 と 1 を足した 9 です。Count が 1001 で Up が ON のステップでは、Carry が ON になるようにします。Carry は、上の桁に桁上がりを知らせる合図です。「確かめる」は、Up を ON にして Count を 1001 まで進めたあと、2ステップだけ Up を OFF にして、Count が 1001 のまま止まり、Carry が OFF のままかを調べます。そのあと Up をまた ON にして、0000 に戻るかを調べます。",
steps: [
"左の Const・Broadcast・And は、Up が ON のときは 0001 を、OFF のときは 0000 を「4桁の足し算」の B に送っています。Broadcast は、1ビットの値を、同じ値が並んだ何ビットもの値に広げます(ON なら 1111、OFF なら 0000)。And に何ビットもの値をつなぐと、ビットごとに、両方が 1 のビットだけ 1 になります。",
"Carry を作ります。0000 から 1001 のうち、8の位と1の位がどちらも 1 なのは 1001 だけです。一番下の Decompose の右側の、一番上(8の位)と一番下(1の位)のピンを And でまとめ、その出力と Up をもう1つの And でまとめて、Carry につなぎます。",
Expand All @@ -200,6 +202,16 @@ export const ja: Messages = {
"再生中は、Up をクリックして ON と OFF を切り替えながら、右の矢印でステップを進めます。Up が ON のときだけ Display の数が進み、9 の次に 0 に戻れば、うまく動いています。",
],
},
stopwatch: {
title: "ストップウォッチ",
goal: "いよいよ、分と秒を 12:34 のように数えるストップウォッチです。Start が ON のステップごとに、1秒ずつ進めます。右上の Display には、左から分の10の位(M10)、分の1の位(M1)、コロン、秒の10の位(S10)、秒の1の位(S1)が出ます。M10 と S10 は 0 から 5 を、M1 と S1 は 0 から 9 を数えます。59:59 の次は 00:00 に戻ります。Display の左にある 7seg・Const・Decompose・Aggregate は、4つの数字とコロンを1つの Display に並べるためのものです。「確かめる」は、Start を ON にしたまま、59:59 の次に 00:00 に戻るまで進めます。そのあと2ステップだけ Start を OFF にして止まるかを、また ON にしてまた進むかを調べます。",
steps: [
"「6進の1桁」を2つと、「10進の1桁」を2つ置きます。「6進の1桁」は「10進の1桁」と同じつくりで、0 から 5 を数え、5 の次で 0 に戻って上の桁が上がります。10進数が 9 の次で桁が上がるのと同じです。",
"置いた4つの部品を、M10・M1・S10・S1 に1つずつ割り当てます。M10 と S10 には「6進の1桁」を、M1 と S1 には「10進の1桁」を使います。それぞれの Count を、割り当てた桁と同じ名前の右の出力と、その桁の 7seg につなぎます。7seg は、上から M10・M1・S10・S1 用です。",
"S1 につないだ部品の Up に Start をつなぎます。次に、S1 の部品の Carry を S10 の部品の Up に、S10 の Carry を M1 の Up に、M1 の Carry を M10 の Up につなぎます。こうすると、1つ下の桁が 0 に戻るときだけ、その上の桁が進みます。",
"再生ボタンを押します。最初のステップで Start が OFF なら、クリックして ON にします。「自動」を押すと、1秒に1ステップずつ、Display が時計のように進みます。59:59 の次を見るには、「自動」を止めて下の数字をクリックし、3600 と入れて Enter キーを押します。そのステップまで一度に進んで 59:59 になり、右の矢印を押すと 00:00 に戻ります。",
],
},
},
},
componentProperties: {
Expand Down
28 changes: 23 additions & 5 deletions src/pages/edit/Editor/components/FrameControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
isValidPlaybackSpeed,
MAX_PLAYBACK_SPEED,
MIN_PLAYBACK_SPEED,
parseTimeStepNumber,
} from "../store/slices/core/types";

export default function CCComponentEditorFrameControl() {
Expand All @@ -17,6 +18,7 @@ export default function CCComponentEditorFrameControl() {
const [speedInput, setSpeedInput] = useState(
String(componentEditorState.playbackSpeed),
);
const [stepDraft, setStepDraft] = useState<string | null>(null);
const isAutomatic = componentEditorState.playbackMode === "auto";
const isSpeedValid = isValidPlaybackSpeed(Number(speedInput));

Expand Down Expand Up @@ -92,12 +94,28 @@ export default function CCComponentEditorFrameControl() {
outline: "none",
fontSize: "20px",
}}
value={componentEditorState.timeStep + 1}
onChange={(e) => {
const value = Number(e.target.value);
if (Number.isSafeInteger(value) && value > 0) {
componentEditorState.setTimeStep(value - 1);
inputMode="numeric"
value={stepDraft ?? String(componentEditorState.timeStep + 1)}
onFocus={(e) => {
const field = e.currentTarget;
// After the click, which in WebKit would undo a selection made now
requestAnimationFrame(() => field.select());
}}
onChange={(e) => setStepDraft(e.target.value)}
onKeyDown={(e) => {
if (e.key === "Enter" && !e.nativeEvent.isComposing) {
e.currentTarget.blur();
}
}}
// Every step up to the one entered is simulated, so a step is only
// gone to once it is typed in full, not at each key
onBlur={() => {
const stepNumber =
stepDraft === null ? null : parseTimeStepNumber(stepDraft);
if (stepNumber !== null) {
componentEditorState.setTimeStep(stepNumber - 1);
}
setStepDraft(null);
}}
/>
<IconButton
Expand Down
22 changes: 22 additions & 0 deletions src/pages/edit/Editor/store/slices/core/types.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vitest";
import { MAX_TIME_STEP_NUMBER, parseTimeStepNumber } from "./types";

describe("parseTimeStepNumber", () => {
it("reads a step typed in half-width or full-width digits", () => {
expect(parseTimeStepNumber("3600")).toBe(3600);
expect(parseTimeStepNumber("3600")).toBe(3600);
expect(parseTimeStepNumber(" 12 ")).toBe(12);
});

it("refuses what is no step", () => {
expect(parseTimeStepNumber("")).toBeNull();
expect(parseTimeStepNumber("0")).toBeNull();
expect(parseTimeStepNumber("-3")).toBeNull();
expect(parseTimeStepNumber("1.5")).toBeNull();
expect(parseTimeStepNumber("abc")).toBeNull();
});

it("stops a jump at the furthest step that can be gone to", () => {
expect(parseTimeStepNumber("153600")).toBe(MAX_TIME_STEP_NUMBER);
});
});
13 changes: 13 additions & 0 deletions src/pages/edit/Editor/store/slices/core/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,19 @@ export function isValidPlaybackSpeed(speed: number): boolean {
);
}

/** Every time step up to the one gone to is simulated and kept, so a jump stops here */
export const MAX_TIME_STEP_NUMBER = 10000;

/**
* The time step, counted from 1, that the text typed in the step field asks for, or
* null for none. Full-width digits, as typed with a Japanese input method, count.
*/
export function parseTimeStepNumber(text: string): number | null {
const value = Number(text.normalize("NFKC").trim());
if (!Number.isSafeInteger(value) || value < 1) return null;
return Math.min(value, MAX_TIME_STEP_NUMBER);
}

export type RangeSelect = { start: Vector2; end: Vector2 } | null;

export type TimeStep = number;
Expand Down
69 changes: 50 additions & 19 deletions src/pages/tutorial/stage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import {
Typography,
} from "@mui/material";
import nullthrows from "nullthrows";
import { type ReactNode, useEffect, useState } from "react";
import { type ReactNode, useEffect, useRef, useState } from "react";
import {
Navigate,
Link as RouterLink,
Expand Down Expand Up @@ -40,9 +40,11 @@ import {
} from "../../tutorial/stageStore";
import {
findTutorialStage,
givenPartById,
isStageComponent,
isStagePart,
isStagePinNode,
isTutorialStageId,
type StageTitleOf,
stageAreaOf,
type TutorialStage,
Expand Down Expand Up @@ -71,7 +73,8 @@ function StageView({ stage }: { stage: TutorialStage }) {
const navigate = useNavigate();
const stageIndex = tutorialStages.indexOf(stage);
const nextStage = tutorialStages[stageIndex + 1];
const titleOf: StageTitleOf = (id) => texts.stageTexts[id].title;
const titleOf: StageTitleOf = (id) =>
isTutorialStageId(id) ? texts.stageTexts[id].title : texts.partTitles[id];
const goalTable = goalTableOf(stage.check);
const stageTexts = texts.stageTexts[stage.id];

Expand All @@ -80,6 +83,7 @@ function StageView({ stage }: { stage: TutorialStage }) {
);
const [editedComponentId, setEditedComponentId] = useState(stage.componentId);
const [result, setResult] = useState<CheckResult | null>(null);
const [isChecking, setIsChecking] = useState(false);
const [isConfirmingReset, setIsConfirmingReset] = useState(false);
const [hasResetFailed, setHasResetFailed] = useState(false);
// The editor keeps state of the store it was made with, so it starts anew on a reset
Expand All @@ -96,15 +100,39 @@ function StageView({ stage }: { stage: TutorialStage }) {
};
}, [store]);

const cancelCheckRef = useRef<(() => void) | null>(null);
const cancelCheck = () => {
cancelCheckRef.current?.();
cancelCheckRef.current = null;
setIsChecking(false);
};
useEffect(() => () => cancelCheckRef.current?.(), []);

const check = () => {
const checked = checkCircuit(store, stage.componentId, stage.check);
if (checked.type === "checkFailed") console.error(checked.error);
setResult(checked);
if (checked.type === "passed") markStageCleared(stage.id);
setIsChecking(true);
const run = () => {
cancelCheckRef.current = null;
const checked = checkCircuit(store, stage.componentId, stage.check);
if (checked.type === "checkFailed") console.error(checked.error);
setResult(checked);
if (checked.type === "passed") markStageCleared(stage.id);
setIsChecking(false);
};
// A check over many time steps holds the page for a moment, so the button says
// it is checking before the check starts
let timeout: ReturnType<typeof setTimeout> | undefined;
const frame = requestAnimationFrame(() => {
timeout = setTimeout(run);
});
cancelCheckRef.current = () => {
cancelAnimationFrame(frame);
clearTimeout(timeout);
};
};

const resetStage = () => {
setIsConfirmingReset(false);
cancelCheck();
try {
setStore(resetTutorialStage(stage, titleOf));
setResetCount((count) => count + 1);
Expand All @@ -129,7 +157,9 @@ function StageView({ stage }: { stage: TutorialStage }) {
<div
style={{
display: "grid",
gridTemplateColumns: "300px max-content 200px max-content 1fr",
// Wider on a wide screen, for long texts and tables of many columns
gridTemplateColumns:
"clamp(300px, 25vw, 420px) max-content 200px max-content 1fr",
minHeight: 0,
}}
>
Expand Down Expand Up @@ -161,7 +191,9 @@ function StageView({ stage }: { stage: TutorialStage }) {
<Typography>{stageTexts.goal}</Typography>
{goalTable && (
<Box sx={{ mt: 1 }}>
<TruthTableView table={goalTable} />
<Box sx={{ overflowX: "auto" }}>
<TruthTableView table={goalTable} />
</Box>
{stage.tableNotation === "digits" && (
<Typography variant="body2" sx={{ mt: 0.5 }}>
{texts.digitsLegend}
Expand Down Expand Up @@ -193,16 +225,14 @@ function StageView({ stage }: { stage: TutorialStage }) {
}
/>
))}
{stage.givenParts
.map((id) => nullthrows(findTutorialStage(id)))
.map((given) => (
<PartDescriptionView
key={given.id}
name={titleOf(given.id)}
summary={null}
table={goalTableOf(given.check)}
/>
))}
{stage.givenParts.map(givenPartById).map((given) => (
<PartDescriptionView
key={given.id}
name={titleOf(given.id)}
summary={null}
table={goalTableOf(given.check)}
/>
))}
</Stack>
</div>
<Box sx={{ flexGrow: 1 }} />
Expand All @@ -223,9 +253,10 @@ function StageView({ stage }: { stage: TutorialStage }) {
<Button
variant="contained"
onClick={check}
disabled={isChecking}
sx={{ background: theme.colors.tutorial }}
>
{texts.check}
{isChecking ? texts.checking : texts.check}
</Button>
{result?.type === "passed" && (
<>
Expand Down
10 changes: 4 additions & 6 deletions src/tutorial/progress.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
import { type TutorialStageId, tutorialStageIds } from "./stages";
import { isTutorialStageId, type TutorialStageId } from "./stages";

const progressStorageKey = "ccTutorialProgress";

function isStageId(value: unknown): value is TutorialStageId {
return tutorialStageIds.some((id) => id === value);
}

// What was cleared only decorates the list of stages, so the tutorial goes on when the
// storage cannot keep it, e.g. when it is full
export function readClearedStages(): ReadonlySet<TutorialStageId> {
try {
const parsed: unknown = JSON.parse(
window.localStorage.getItem(progressStorageKey) ?? "[]",
);
return new Set(Array.isArray(parsed) ? parsed.filter(isStageId) : []);
return new Set(
Array.isArray(parsed) ? parsed.filter(isTutorialStageId) : [],
);
} catch (error) {
console.warn("Could not read the tutorial progress", error);
return new Set();
Expand Down
Loading
Loading