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
20 changes: 20 additions & 0 deletions src/common/bitLabel.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { describe, expect, it } from "vitest";
import { stringifySimulationValue } from "../pages/edit/Editor/store/slices/core";
import { bitLabel, valueLabel } from "./bitLabel";

describe("labels of values", () => {
it("write one bit as ON or OFF", () => {
expect(bitLabel(true)).toBe("ON");
expect(bitLabel(false)).toBe("OFF");
expect(valueLabel([false])).toBe("OFF");
expect(stringifySimulationValue([true])).toBe("ON");
});

it("write more bits as binary digits, and wide ones on a wire in hexadecimal", () => {
expect(valueLabel([false, true])).toBe("01");
expect(stringifySimulationValue([true, false, true, true])).toBe("1011");
expect(stringifySimulationValue([true, false, true, true, true])).toBe(
"0x17",
);
});
});
11 changes: 11 additions & 0 deletions src/common/bitLabel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import type { SimulationValue } from "../store/simulation";

export function bitLabel(bit: boolean): string {
return bit ? "ON" : "OFF";
}

export function valueLabel(value: SimulationValue): string {
const [bit] = value;
if (value.length === 1 && bit !== undefined) return bitLabel(bit);
return value.map((b) => (b ? "1" : "0")).join("");
}
92 changes: 92 additions & 0 deletions src/components/PartDescription.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
import { Box, Typography } from "@mui/material";
import { bitLabel } from "../common/bitLabel";
import { type Messages, useMessages } from "../i18n";
import type { CCComponent } from "../store/component";
import { definitionByComponentId } from "../store/intrinsics/definitions";
import { truthTableOf } from "../store/intrinsics/truthTable";
import { theme } from "../style";

type Summaries = Messages["parts"]["summaries"];

export function partSummary(
messages: Messages,
component: CCComponent,
): string | null {
const type = component.intrinsicType;
return type && type in messages.parts.summaries
? messages.parts.summaries[type as keyof Summaries]
: null;
}

export function PartDescription({ component }: { component: CCComponent }) {
const messages = useMessages();
const summary = partSummary(messages, component);
const definition = definitionByComponentId.get(component.id);
const table = definition && truthTableOf(definition);
const columns = table
? [
...table.inputs.map((name) => ({ key: `in-${name}`, name })),
...table.outputs.map((name) => ({ key: `out-${name}`, name })),
]
: [];
const cellSx = (column: number) =>
({
px: 1,
py: 0.25,
textAlign: "center",
...(table &&
table.inputs.length > 0 &&
column === table.inputs.length && {
borderLeft: 1,
borderColor: "divider",
}),
}) as const;

return (
<div>
<Typography variant="subtitle2">{component.name}</Typography>
{summary && <Typography variant="body2">{summary}</Typography>}
{table && (
<Box
component="table"
sx={{ mt: 0.5, borderCollapse: "collapse", fontSize: "0.875rem" }}
>
<thead>
<tr>
{columns.map(({ key, name }, i) => (
<Box
key={key}
component="th"
sx={{ ...cellSx(i), borderBottom: 1, borderColor: "divider" }}
>
{name}
</Box>
))}
</tr>
</thead>
<tbody>
{table.rows.map((row) => (
<tr key={row.inputs.join()}>
{[...row.inputs, ...row.outputs].map((value, i) => (
<Box
key={columns[i]?.key}
component="td"
sx={{
...cellSx(i),
...(value && {
color: theme.colors.primary,
fontWeight: "bold",
}),
}}
>
{bitLabel(value)}
</Box>
))}
</tr>
))}
</tbody>
</Box>
)}
</div>
);
}
18 changes: 14 additions & 4 deletions src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,18 @@ export const en = {
apply: "Apply",
delete: "Delete",
},
parts: {
summaries: {
AND: "ON only when both inputs are ON",
OR: "ON when at least one input is ON",
NOT: "Turns ON into OFF, and OFF into ON",
XOR: "ON when exactly one input is ON",
TRUE: "Always ON",
FALSE: "Always OFF",
},
about: (name: string) => `About ${name}`,
ofStage: "Parts you can use in this stage",
},
header: {
language: "Language",
modes: {
Expand Down Expand Up @@ -95,8 +107,6 @@ export const en = {
stages: "Stages",
parts: "Parts",
check: "Check",
on: "on",
off: "off",
passed: "Cleared! The circuit works for every combination of the inputs.",
next: "Next stage",
backToStages: "Back to the stages",
Expand All @@ -121,11 +131,11 @@ export const en = {
stageTexts: {
and: {
title: "Both switches",
goal: "Make the lamp Out light up only when both switches A and B are on. Drag parts from the Parts list onto the editor, and drag from pin to pin to connect them. The play button at the bottom right lets you try the switches. When it works, press Check.",
goal: "Make the lamp Out light up only when both switches A and B are ON. Drag parts from the Parts list onto the editor, and drag from pin to pin to connect them. The play button at the bottom right lets you try the switches. When it works, press Check.",
},
xor: {
title: "Only one switch",
goal: "Make the lamp Out light up when exactly one of the switches A and B is on. It stays off when both are on.",
goal: "Make the lamp Out light up when exactly one of the switches A and B is ON. It does not light up when both are ON.",
},
},
},
Expand Down
18 changes: 14 additions & 4 deletions src/i18n/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@ export const ja: Messages = {
apply: "適用",
delete: "削除",
},
parts: {
summaries: {
AND: "両方が ON のときだけ ON",
OR: "少なくとも一方が ON なら ON",
NOT: "ON と OFF を逆にする",
XOR: "片方だけが ON のとき ON",
TRUE: "いつも ON",
FALSE: "いつも OFF",
},
about: (name) => `${name} について`,
ofStage: "この課題で使える部品",
},
header: {
language: "言語",
modes: {
Expand Down Expand Up @@ -90,8 +102,6 @@ export const ja: Messages = {
stages: "課題の一覧",
parts: "部品",
check: "確かめる",
on: "オン",
off: "オフ",
passed: "クリア!どの入力の組み合わせでも正しく動きます。",
next: "次の課題へ",
backToStages: "課題の一覧へ",
Expand All @@ -111,11 +121,11 @@ export const ja: Messages = {
stageTexts: {
and: {
title: "両方のスイッチ",
goal: "スイッチ A と B が両方オンのときだけ、ランプ Out がつくようにしましょう。「部品」の一覧から部品をエディタにドラッグして置き、ピンからピンへドラッグしてつなぎます。右下の再生ボタンで、スイッチを切り替えて試せます。できたら「確かめる」を押してください。",
goal: "スイッチ A と B が両方 ON のときだけ、ランプ Out がつくようにしましょう。「部品」の一覧から部品をエディタにドラッグして置き、ピンからピンへドラッグしてつなぎます。右下の再生ボタンで、スイッチを切り替えて試せます。できたら「確かめる」を押してください。",
},
xor: {
title: "片方だけのスイッチ",
goal: "スイッチ A と B のどちらか片方だけがオンのときに、ランプ Out がつくようにしましょう。両方オンのときはつきません。",
goal: "スイッチ A と B のどちらか片方だけが ON のときに、ランプ Out がつくようにしましょう。両方 ON のときはつきません。",
},
},
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import clsx from "clsx";
import { bitLabel } from "../../../../../../../../common/bitLabel";
import type { SimulationValue } from "../../../../../../../../store/simulation";
import { stringifySimulationValue } from "../../../../../store/slices/core";
import { CCComponentEditorRendererNodeInterfaceRendererValueEditButton } from "./EditButton";
Expand Down Expand Up @@ -45,7 +46,7 @@ export function CCComponentEditorRendererNodeInterfaceRendererValue({
>
{value.map((bit, index) => {
const className = clsx(styles.bit, bit && styles.on);
const label = isSingleBit ? (bit ? "ON" : "OFF") : bit ? "1" : "0";
const label = isSingleBit ? bitLabel(bit) : bit ? "1" : "0";
return onChange ? (
<button
// biome-ignore lint/suspicious/noArrayIndexKey: bits are identified by their index
Expand Down
3 changes: 2 additions & 1 deletion src/pages/edit/Editor/store/slices/core/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { mapValues } from "es-toolkit";
import nullthrows from "nullthrows";
import invariant from "tiny-invariant";
import { valueLabel } from "../../../../../../common/bitLabel";
import { messagesByLanguage } from "../../../../../../i18n/messages";
import type { CCComponentPinId } from "../../../../../../store/componentPin";
import {
Expand Down Expand Up @@ -31,8 +32,8 @@ import {
} from "./types";

export function stringifySimulationValue(value: SimulationValue): string {
if (value.length <= 4) return valueLabel(value);
const binary = value.map((v) => (v ? "1" : "0")).join("");
if (value.length <= 4) return binary;
return `0x${Number.parseInt(binary, 2).toString(16)}`;
}

Expand Down
52 changes: 48 additions & 4 deletions src/pages/edit/SidePanel.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import { Search } from "@mui/icons-material";
import { Box, InputAdornment, TextField } from "@mui/material";
import { InfoOutlined, Search } from "@mui/icons-material";
import {
Box,
IconButton,
InputAdornment,
Popover,
TextField,
} from "@mui/material";
import { useState } from "react";
import invariant from "tiny-invariant";
import { setDataTransferAsComponent } from "../../common/serialization";
import { PartDescription, partSummary } from "../../components/PartDescription";
import { useMessages } from "../../i18n";
import type { CCComponentId } from "../../store/component";
import type { CCComponent, CCComponentId } from "../../store/component";
import { ccPinTypes } from "../../store/componentPin";
import { useStore } from "../../store/react";
import { useComponents } from "../../store/react/selectors";
Expand Down Expand Up @@ -95,6 +102,10 @@ export default function SidePanel(sidePanelProps: SidePanelProps) {
const messages = useMessages();
const components = useComponents();
const [searchText, setSearchText] = useState("");
const [describedPart, setDescribedPart] = useState<{
component: CCComponent;
anchorEl: HTMLElement;
} | null>(null);

return (
<Box sx={{ overflowY: "auto" }}>
Expand Down Expand Up @@ -133,15 +144,48 @@ export default function SidePanel(sidePanelProps: SidePanelProps) {
key={component.id}
component="li"
draggable
sx={{ cursor: "grab", p: 2 }}
sx={{ cursor: "grab", p: 2, position: "relative" }}
onDragStart={(e) => {
setDataTransferAsComponent(e.dataTransfer, component.id);
}}
>
<ComponentRenderer componentId={component.id} />
{partSummary(messages, component) && (
<IconButton
size="small"
aria-label={messages.parts.about(component.name)}
aria-haspopup="dialog"
sx={{ position: "absolute", top: 8, right: 8 }}
onClick={(e) =>
setDescribedPart({ component, anchorEl: e.currentTarget })
}
>
<InfoOutlined fontSize="small" />
</IconButton>
)}
</Box>
))}
</Box>
<Popover
open={describedPart !== null}
anchorEl={describedPart?.anchorEl ?? null}
anchorOrigin={{ vertical: "top", horizontal: "right" }}
onClose={() => setDescribedPart(null)}
slotProps={{
paper: {
role: "dialog",
"aria-label": describedPart
? messages.parts.about(describedPart.component.name)
: "",
},
}}
>
{describedPart && (
<Box sx={{ p: 2, maxWidth: 280 }}>
<PartDescription component={describedPart.component} />
</Box>
)}
</Popover>
</Box>
);
}
31 changes: 22 additions & 9 deletions src/pages/tutorial/stage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,19 +8,22 @@ import {
Stack,
Typography,
} from "@mui/material";
import nullthrows from "nullthrows";
import { useEffect, useState } from "react";
import {
Navigate,
Link as RouterLink,
useNavigate,
useParams,
} from "react-router";
import { valueLabel } from "../../common/bitLabel";
import { ConfirmDialog } from "../../components/ConfirmDialog";
import { PartDescription } from "../../components/PartDescription";
import { type Messages, useMessages } from "../../i18n";
import type CCStore from "../../store";
import { definitionByComponentId } from "../../store/intrinsics/definitions";
import { SimulationNodeError } from "../../store/netlist";
import { StoreScope } from "../../store/react";
import type { SimulationValue } from "../../store/simulation";
import { theme } from "../../style";
import { type CheckResult, checkCombinational } from "../../tutorial/check";
import { markStageCleared } from "../../tutorial/progress";
Expand All @@ -39,11 +42,6 @@ import CCComponentEditor from "../edit/Editor";
import type { OffersComponent } from "../edit/placement";
import SidePanel from "../edit/SidePanel";

function formatValue(value: SimulationValue, texts: Messages["tutorial"]) {
if (value.length === 1) return value[0] ? texts.on : texts.off;
return value.map((bit) => (bit ? "1" : "0")).join("");
}

function describeFailure(
result: Exclude<CheckResult, { type: "passed" }>,
store: CCStore,
Expand All @@ -57,11 +55,11 @@ function describeFailure(
return texts.wrongOutput(
result.inputs.map(({ name, value }) => ({
name,
value: formatValue(value, texts),
value: valueLabel(value),
})),
result.pinName,
formatValue(result.expected, texts),
result.actual ? formatValue(result.actual, texts) : null,
valueLabel(result.expected),
result.actual ? valueLabel(result.actual) : null,
);
case "simulationFailed":
return texts.simulationFailed(
Expand Down Expand Up @@ -181,6 +179,21 @@ function StageView({ stage }: { stage: TutorialStage }) {
{describeFailure(result, store, messages)}
</Alert>
)}
<div>
<Typography color="textSecondary" variant="body2" gutterBottom>
{messages.parts.ofStage}
</Typography>
<Stack spacing={1.5}>
{stage.parts.map((partId) => (
<PartDescription
key={partId}
component={
nullthrows(definitionByComponentId.get(partId)).component
}
/>
))}
</Stack>
</div>
<Box sx={{ flexGrow: 1 }} />
{hasResetFailed && (
<Alert severity="error">{texts.resetStageFailed}</Alert>
Expand Down
Loading
Loading