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
59 changes: 34 additions & 25 deletions src/components/TruthTableView.tsx
Original file line number Diff line number Diff line change
@@ -1,30 +1,39 @@
import { Box, type Theme } from "@mui/material";
import { useContext } from "react";
import { bitDigit, bitLabel } from "../common/bitLabel";
import { useMessages } from "../i18n";
import type { TruthTable } from "../store/intrinsics/truthTable";
import type { SimulationValue } from "../store/simulation";
import { theme } from "../style";
import { BitNotationContext } from "./bitNotation";
import { truthTableColumnsOf, truthTableLinesOf } from "./truthTableLayout";

const divider = (muiTheme: Theme) => `1px solid ${muiTheme.palette.divider}`;
const onSx = { color: theme.colors.primary, fontWeight: "bold" } as const;
const binaryOf = (value: SimulationValue) => value.map(bitDigit).join("");

export function TruthTableView({ table }: { table: TruthTable }) {
const messages = useMessages();
const singleBitLabel =
useContext(BitNotationContext) === "digits" ? bitDigit : bitLabel;
const columns = [
...table.inputs.map((name) => ({ key: `in-${name}`, name })),
...table.outputs.map((name) => ({ key: `out-${name}`, name })),
];
const columns = truthTableColumnsOf(table, messages.truthTable.timeStep);
const cellSx = (column: number) =>
({
px: 1,
py: 0.25,
textAlign: "center",
...(table.inputs.length > 0 &&
column === table.inputs.length && { borderLeft: divider }),
...(columns[column]?.startsGroup && { borderLeft: divider }),
}) as const;
const valueCell = (value: SimulationValue) =>
value.map((bit, index) => (
<Box
// biome-ignore lint/suspicious/noArrayIndexKey: bits are identified by their index
key={index}
component="span"
sx={bit ? onSx : {}}
>
{value.length === 1 ? singleBitLabel(bit) : bitDigit(bit)}
</Box>
));

return (
<Box
Expand All @@ -49,24 +58,24 @@ export function TruthTableView({ table }: { table: TruthTable }) {
</tr>
</thead>
<tbody>
{table.rows.map((row) => (
<tr key={row.inputs.map(binaryOf).join()}>
{[...row.inputs, ...row.outputs].map((value, i) => (
<Box key={columns[i]?.key} component="td" sx={cellSx(i)}>
{value.map((bit, index) => (
<Box
// biome-ignore lint/suspicious/noArrayIndexKey: bits are identified by their index
key={index}
component="span"
sx={bit ? onSx : {}}
>
{value.length === 1 ? singleBitLabel(bit) : bitDigit(bit)}
</Box>
))}
</Box>
))}
</tr>
))}
{truthTableLinesOf(table).map((line) => {
const cells =
line.type === "gap"
? columns.map(() => "⋮")
: [
...(line.stepLabel === null ? [] : [line.stepLabel]),
...line.values.map(valueCell),
];
return (
<tr key={line.key}>
{cells.map((cell, i) => (
<Box key={columns[i]?.key} component="td" sx={cellSx(i)}>
{cell}
</Box>
))}
</tr>
);
})}
</tbody>
</Box>
);
Expand Down
54 changes: 54 additions & 0 deletions src/components/truthTableLayout.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import type { TruthTable } from "../store/intrinsics/truthTable";
import { truthTableColumnsOf, truthTableLinesOf } from "./truthTableLayout";

const overTime: TruthTable = {
inputs: [],
outputs: ["Count"],
rows: [1, 2, 16, 17].map((stepNumber) => ({
inputs: [],
outputs: [[stepNumber % 2 === 0]],
stepNumber,
})),
};

describe("truthTableColumnsOf", () => {
it("parts the inputs from the outputs", () => {
const table: TruthTable = { inputs: ["A"], outputs: ["Out"], rows: [] };

expect(truthTableColumnsOf(table, "Step")).toEqual([
{ key: "in-A", name: "A", startsGroup: false },
{ key: "out-Out", name: "Out", startsGroup: true },
]);
});

it("puts the time steps first, parted from a table without inputs", () => {
expect(truthTableColumnsOf(overTime, "Step")).toEqual([
{ key: "step", name: "Step", startsGroup: false },
{ key: "out-Count", name: "Count", startsGroup: true },
]);
});
});

describe("truthTableLinesOf", () => {
it("puts a gap only where steps are skipped, and keys rows by their step", () => {
expect(
truthTableLinesOf(overTime).map((line) =>
line.type === "gap" ? "gap" : `${line.key}:${line.stepLabel}`,
),
).toEqual(["1:1", "2:2", "gap", "16:16", "17:17"]);
});

it("gives no step to a table that does not run over time", () => {
const table: TruthTable = {
inputs: ["A"],
outputs: ["Out"],
rows: [false, true].map((a) => ({ inputs: [[a]], outputs: [[!a]] })),
};

expect(truthTableLinesOf(table)).toEqual([
{ type: "row", key: "0", stepLabel: null, values: [[false], [true]] },
{ type: "row", key: "1", stepLabel: null, values: [[true], [false]] },
]);
});
});
68 changes: 68 additions & 0 deletions src/components/truthTableLayout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { bitDigit } from "../common/bitLabel";
import type { TruthTable } from "../store/intrinsics/truthTable";
import type { SimulationValue } from "../store/simulation";

export type TruthTableColumn = {
key: string;
name: string;
/** A line on its left parts it from the columns before */
startsGroup: boolean;
};

export type TruthTableLine =
| {
type: "row";
key: string;
/** null when the table has no column of time steps */
stepLabel: string | null;
values: SimulationValue[];
}
| { type: "gap"; key: string };

const binaryOf = (value: SimulationValue) => value.map(bitDigit).join("");

const hasStepColumn = (table: TruthTable) =>
table.rows.some((row) => row.stepNumber !== undefined);

export function truthTableColumnsOf(
table: TruthTable,
stepColumnName: string,
): TruthTableColumn[] {
const groups = [
hasStepColumn(table) ? [{ key: "step", name: stepColumnName }] : [],
table.inputs.map((name) => ({ key: `in-${name}`, name })),
table.outputs.map((name) => ({ key: `out-${name}`, name })),
].filter((group) => group.length > 0);
return groups.flatMap((group, groupIndex) =>
group.map((column, index) => ({
...column,
startsGroup: groupIndex > 0 && index === 0,
})),
);
}

/** The rows of a table, with a gap where it skips time steps */
export function truthTableLinesOf(table: TruthTable): TruthTableLine[] {
const hasSteps = hasStepColumn(table);
return table.rows.flatMap((row, index): TruthTableLine[] => {
const { stepNumber } = row;
const previousStepNumber = table.rows[index - 1]?.stepNumber;
const isAfterGap =
stepNumber !== undefined &&
previousStepNumber !== undefined &&
stepNumber > previousStepNumber + 1;
const key =
stepNumber === undefined
? row.inputs.map(binaryOf).join()
: String(stepNumber);
return [
...(isAfterGap ? [{ type: "gap" as const, key: `gap-${key}` }] : []),
{
type: "row",
key,
stepLabel: hasSteps ? String(stepNumber ?? "") : null,
values: [...row.inputs, ...row.outputs],
},
];
});
}
18 changes: 17 additions & 1 deletion src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,16 @@ const stageTexts: Record<TutorialStageId, StageTexts> = {
"While playing, click a digit of A or B to switch it between 0 and 1. The sum S is shown as one character on the Display at the top right. The 7seg before it turns the binary number into the shape of a numeral. To write 10 to 15 with one character, A (10), b (11), C (12), d (13), E (14) and F (15) are used. This way of writing is called hexadecimal.",
],
},
counter: {
title: "Counter",
goal: "After pressing the play button, a number with an arrow button on each side appears at the bottom. The number is called the time step, and the right arrow goes to the next one. The circuit runs one time step at a time. Make Count go up by 1 at each time step, and go back to 0000 after 1111. 0000 to 1111 are 0 to F in hexadecimal.",
steps: [
"Place a FlipFlop. A FlipFlop outputs what it received at the time step before, and 0 at the first time step. Connect its output to Count and to the 7seg at the top right.",
"Place a Const. A Const always outputs the value written in it. Change 00000000 in its box to 0001 and press Apply (four digits, to match the B it connects to).",
'Place "Adding four digits". Connect the output of the FlipFlop to its A, the Const to its B, and its S to the input of the FlipFlop. Then the number the FlipFlop outputs plus 1 comes out of the FlipFlop at the next time step. C is not used.',
'Press the play button and go through the time steps with the right arrow. Press "Auto" to go on by itself, one time step a second. The circuit works when the Display at the top right shows 0 to F in turn.',
],
},
};

export const en = {
Expand All @@ -77,6 +87,9 @@ export const en = {
"Splits a number of several digits, from the highest digit down",
AGGREGATE:
"Joins values into one number, the upper pins as the higher digits",
FLIPFLOP:
"Outputs what it received at the time step before (0 at the first time step)",
CONST: "Always outputs the value written in it",
},
about: (name: string) => `About ${name}`,
ofStage: "Available parts",
Expand Down Expand Up @@ -145,6 +158,9 @@ export const en = {
startOverFailed: "Could not start over.",
},
},
truthTable: {
timeStep: "Time step",
},
tutorial: {
lead: "Going from the top is recommended, but you can start from any stage.",
stageNumber: (number: number) => `Stage ${number}`,
Expand All @@ -160,7 +176,7 @@ export const en = {
parts: "Parts",
goalHeading: "Goal",
stepsHeading: "Steps",
digitsLegend: "In the tables, 1 is ON and 0 is OFF.",
digitsLegend: "The tables write ON as 1 and OFF as 0.",
check: "Check",
passed: "Cleared! The circuit works for every combination of the inputs.",
passedSteps: (count: number) =>
Expand Down
17 changes: 16 additions & 1 deletion src/i18n/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export const ja: Messages = {
FALSE: "いつも OFF",
DECOMPOSE: "何桁もある数を、上の桁から順に分ける",
AGGREGATE: "上のピンを大きい桁として、1つの数にまとめる",
FLIPFLOP: "1つ前のステップで受け取った値を出す(最初のステップでは 0)",
CONST: "中に書いた値をいつも出す",
},
about: (name) => `${name} について`,
ofStage: "使える部品",
Expand Down Expand Up @@ -90,6 +92,9 @@ export const ja: Messages = {
startOverFailed: "やり直せませんでした。",
},
},
truthTable: {
timeStep: "ステップ",
},
tutorial: {
lead: "上から順に進めるのがおすすめですが、どの課題からでも始められます。",
stageNumber: (number) => `課題 ${number}`,
Expand All @@ -105,7 +110,7 @@ export const ja: Messages = {
parts: "部品",
goalHeading: "目標",
stepsHeading: "手順",
digitsLegend: "表の 1 は ON、0 は OFF です。",
digitsLegend: "表では、ON を 1、OFF を 0 と書いています。",
check: "確かめる",
passed: "クリア!どの入力の組み合わせでも正しく動きます。",
passedSteps: (count) =>
Expand Down Expand Up @@ -173,6 +178,16 @@ export const ja: Messages = {
"再生中は、A と B の桁をクリックして 0 と 1 を切り替えられます。答えの S は、右上の Display に1文字で表示されます。その手前の 7seg が、2進数を数字の形に変えています。10 から 15 は1文字で書くために、A(10)、b(11)、C(12)、d(13)、E(14)、F(15)を使います。この書き方を16進数といいます。",
],
},
counter: {
title: "カウンタ",
goal: "再生ボタンを押すと、下に数字と、その左右に矢印のボタンが出ます。この数字を「ステップ」といい、右の矢印を押すと次のステップに進みます。回路はステップごとに動きます。Count が 1 ステップごとに 1 ずつ増え、1111 の次は 0000 に戻るようにしましょう。0000 から 1111 は、16進数の 0 から F です。",
steps: [
"FlipFlop を置きます。FlipFlop は、1つ前のステップで受け取った値を出します。最初のステップでは 0 を出します。FlipFlop の出力を、Count と、右上の 7seg につなぎます。",
"Const を置きます。Const は、中に書いた値をいつも出します。欄の 00000000 を 0001 に書きかえて、「適用」を押します(つなぐ先の B に合わせて、4桁で書きます)。",
"「4桁の足し算」を置き、FlipFlop の出力を A に、Const を B に、S を FlipFlop の入力につなぎます。こうすると、FlipFlop が出している数に 1 を足した数が、次のステップで FlipFlop から出てきます。C は使いません。",
"再生ボタンを押し、右の矢印でステップを進めます。「自動」を押すと、1秒に1ステップずつひとりでに進みます。右上の Display に 0 から F が順に出れば、うまく動いています。",
],
},
},
},
componentProperties: {
Expand Down
4 changes: 4 additions & 0 deletions src/pages/edit/Editor/store/index.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { createContext, useContext, useState } from "react";
import invariant from "tiny-invariant";
import { create } from "zustand";
import type { Rect } from "../../../../common/rect";
import type CCStore from "../../../../store";
import type { CCComponentId } from "../../../../store/component";
import type { CCNodeId } from "../../../../store/node";
Expand All @@ -16,6 +17,7 @@ export type EditorStoreOptions = {
isOffered?: OffersComponent;
canCreateComponents?: boolean;
fitsNodesInView?: boolean;
areaToFit?: Rect | null;
hasProperties?: (componentId: CCComponentId) => boolean;
};

Expand All @@ -28,6 +30,7 @@ export function createEditorStore(
hasProperties = () => true,
canCreateComponents = true,
fitsNodesInView = false,
areaToFit = null,
}: EditorStoreOptions = {},
) {
const props = { store, componentId };
Expand All @@ -41,6 +44,7 @@ export function createEditorStore(
hasProperties,
canCreateComponents,
fitsNodesInView,
areaToFit,
...coreSlice.define(set, get),
...perspectiveSlice.define(set, get),
...contextMenuSlice.define(set, get),
Expand Down
17 changes: 10 additions & 7 deletions src/pages/edit/Editor/store/slices/perspective/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,13 +71,16 @@ const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator<
rendererSize,
...(fitsNow && {
perspective: perspectiveFitting(
store.nodes
.getManyByParentComponentId(componentId)
.map(
(node) =>
getCCComponentEditorRendererNodeGeometry(store, node.id)
.rect,
),
[
...store.nodes
.getManyByParentComponentId(componentId)
.map(
(node) =>
getCCComponentEditorRendererNodeGeometry(store, node.id)
.rect,
),
...(state.areaToFit ? [state.areaToFit] : []),
],
rendererSize,
),
}),
Expand Down
3 changes: 3 additions & 0 deletions src/pages/edit/Editor/store/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { StoreApi } from "zustand";
import type { Rect } from "../../../../common/rect";
import type CCStore from "../../../../store";
import type { CCComponentId } from "../../../../store/component";
import type { CCNodeId } from "../../../../store/node";
Expand All @@ -14,6 +15,8 @@ export type ComponentEditorStoreValue = {
readonly canCreateComponents: boolean;
/** whether the view is fitted to the nodes when the editor first gets its size */
readonly fitsNodesInView: boolean;
/** taken in too when the view is fitted, e.g. where the nodes are to be placed */
readonly areaToFit: Rect | null;
readonly hasProperties: (componentId: CCComponentId) => boolean;
} & EditorStoreCoreSlice &
PerspectiveStoreSlice &
Expand Down
Loading
Loading