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
3 changes: 2 additions & 1 deletion src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ const stageTexts: Record<TutorialStageId, StageTexts> = {
steps: [
"The pieces a circuit is built from are called components. Pick one in the Components list and drag it onto the editor on the right.",
"The small squares on the edges of a component are its pins. A pin on the left side is an input, which receives [ON] or [OFF], and a pin on the right side is an output, which sends [ON] or [OFF]. Drag between an output pin and an input pin to connect them with a wire.",
"Once {Out} and every input pin of the components you placed are connected, the play button <play> at the bottom right can be pressed. It cannot be pressed while a component has a free input pin.",
"Once {Out} and every input pin of the components you placed are connected, the play button <play> at the bottom right turns green. Pressed while a component still has a free input pin, it shows which pin is free.",
"After pressing the play button <play>, click the switches {A} and {B} to turn them [ON] and [OFF], and watch the lamp {Out}. To fix the circuit, the pencil button <edit> in the same place takes you back to editing.",
"When it works as in the table, press <check>.",
],
Expand Down Expand Up @@ -322,6 +322,7 @@ export const en = {
keptOnDelete: (names: readonly string[]) =>
`${listOf(names)} ${names.length === 1 ? "is" : "are"} kept, as the stage uses ${themOf(names)}`,
},
viewMode: { play: "Play", edit: "Back to editing" },
frameControl: {
auto: "Auto",
autoPlay: "Auto play",
Expand Down
3 changes: 2 additions & 1 deletion src/i18n/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -173,7 +173,7 @@ export const ja: Messages = {
steps: [
"回路を組み立てる部品を「コンポーネント」といいます。「コンポーネント」の一覧から1つ選び、右のエディタにドラッグして置きます。",
"コンポーネントの端にある小さな四角を「ピン」といいます。左側のピンは [ON] か [OFF] を受け取る「入力」、右側のピンは [ON] か [OFF] を送り出す「出力」です。出力のピンと入力のピンのあいだをドラッグして、線でつなぎます。",
"{Out} と、置いたコンポーネントの入力のピンがすべてつながると、右下の再生ボタン<play>が押せるようになります。入力のピンが空いているコンポーネントが残っていると押せません。",
"{Out} と、置いたコンポーネントの入力のピンがすべてつながると、右下の再生ボタン<play>が緑色になります。入力のピンが空いているコンポーネントが残っているときに押すと、どのピンが空いているかが表示されます。",
"再生ボタン<play>を押したら、スイッチ {A} と {B} をクリックして [ON] と [OFF] を切り替え、ランプ {Out} を見ます。回路を直すときは、同じ場所の鉛筆のボタン<edit>で編集に戻ります。",
"表のとおりに動いたら、<check>を押します。",
],
Expand Down Expand Up @@ -286,6 +286,7 @@ export const ja: Messages = {
cannotDelete: (names) => `${names.join("、")} は課題で使うので消せません`,
keptOnDelete: (names) => `${names.join("、")} は課題で使うので残ります`,
},
viewMode: { play: "再生", edit: "編集に戻る" },
frameControl: {
auto: "自動",
autoPlay: "自動再生",
Expand Down
31 changes: 24 additions & 7 deletions src/pages/edit/Editor/components/ViewModeSwitcher.tsx
Original file line number Diff line number Diff line change
@@ -1,25 +1,42 @@
import { Edit, PlayArrow } from "@mui/icons-material";
import { Fab } from "@mui/material";
import { useCanSimulate } from "../../../../store/react/selectors";
import { useMessages } from "../../../../i18n";
import { useIsEachInputPinConnected } from "../../../../store/react/selectors";
import { useComponentEditorStore } from "../store";

export default function CCComponentEditorViewModeSwitcher() {
const componentEditorState = useComponentEditorStore()();
const canSimulate = useCanSimulate(componentEditorState.componentId);
const texts = useMessages().editor.viewMode;
const isEditing = componentEditorState.editorMode === "edit";
const isEachInputPinConnected = useIsEachInputPinConnected(
componentEditorState.componentId,
);
// Pressed even when pale, so that the simulation names the free pin
const looksDisabled = isEditing && !isEachInputPinConnected;

return (
<Fab
style={{ position: "absolute", bottom: "40px", right: "40px" }}
color="primary"
onClick={() => {
componentEditorState.setEditorMode(
componentEditorState.editorMode === "edit" ? "play" : "edit",
);
componentEditorState.setEditorMode(isEditing ? "play" : "edit");
componentEditorState.setTimeStep(0);
}}
disabled={!canSimulate}
aria-label={isEditing ? texts.play : texts.edit}
aria-disabled={looksDisabled}
sx={
looksDisabled
? {
color: "action.disabled",
bgcolor: "action.disabledBackground",
boxShadow: "none",
"&:hover": { bgcolor: "action.disabledBackground" },
"&:active": { boxShadow: "none" },
}
: {}
}
>
{componentEditorState.editorMode === "edit" ? <PlayArrow /> : <Edit />}
{isEditing ? <PlayArrow /> : <Edit />}
</Fab>
);
}
11 changes: 11 additions & 0 deletions src/pages/edit/Editor/renderer/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { useContext, useEffect } from "react";
import { parseDataTransferAsComponent } from "../../../../common/serialization";
import { vector2 } from "../../../../common/vector2";
import { CCNodeStore } from "../../../../store/node";
Expand All @@ -7,6 +8,7 @@ import {
useNodeIds,
} from "../../../../store/react/selectors";
import { canPlaceComponent } from "../../placement";
import { OutlinedNodeIdsContext } from "../outlinedNodes";
import { useComponentEditorStore } from "../store";
import CCComponentEditorRendererBackground from "./Background";
import CCComponentEditorRendererConnection from "./Connection";
Expand All @@ -19,6 +21,15 @@ export default function CCComponentEditorRenderer() {
const nodeIds = useNodeIds(componentEditorState.componentId);
const connectionIds = useConnectionIds(componentEditorState.componentId);

const { showNodes, simulationError } = componentEditorState;
const outlinedNodeIds = useContext(OutlinedNodeIdsContext);
useEffect(() => {
showNodes(outlinedNodeIds);
}, [showNodes, outlinedNodeIds]);
useEffect(() => {
if (simulationError) showNodes(simulationError.nodeIds);
}, [showNodes, simulationError]);

return (
// biome-ignore lint/a11y/noSvgWithoutTitle: This svg is not a graphic
<svg
Expand Down
23 changes: 23 additions & 0 deletions src/pages/edit/Editor/store/slices/core/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,29 @@ describe("simulation errors", () => {
);
expect(simulationError?.nodeIds).toEqual(new Set([first.id, second.id]));
});

it("tells which pin is free when play is pressed with one", () => {
const store = createTestStore();
const root = registerTestComponent(store, "Root");
const source = registerTestNode(store, root.id, true_.component.id);
const gate = registerTestNode(store, root.id, and.component.id);
connectTestNodePins(
store,
root.id,
testNodePin(store, source, true_.outputPin.Out),
testNodePin(store, gate, and.inputPin.A),
);
const editorStore = createEditorStore(root.id, store);

editorStore.getState().setEditorMode("play");

const { editorMode, simulationError } = editorStore.getState();
expect(editorMode).toBe("edit");
expect(simulationError?.messageByLanguage.ja).toBe(
"And の B のピンがつながっていません。",
);
expect(simulationError?.nodeIds).toEqual(new Set([gate.id]));
});
});

describe("editor mode", () => {
Expand Down
42 changes: 41 additions & 1 deletion src/pages/edit/Editor/store/slices/perspective/fit.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import type { Perspective } from "../../../../../../common/types";
import type { Vector2 } from "../../../../../../common/vector2";
import { fitPadding, perspectiveFitting } from "./fit";
import { fitPadding, isShownInRoom, perspectiveFitting } from "./fit";

const rendererSize = { x: 900, y: 800 };

Expand Down Expand Up @@ -77,3 +77,43 @@ describe("perspectiveFitting", () => {
});
});
});

describe("isShownInRoom", () => {
const perspective = { center: { x: 0, y: 0 }, scale: 1 };

it("tells a rectangle inside the room from one reaching past its edge", () => {
expect(
isShownInRoom(
{ position: { x: -50, y: -20 }, size: { x: 100, y: 40 } },
perspective,
rendererSize,
),
).toBe(true);
expect(
isShownInRoom(
{ position: { x: 300, y: 0 }, size: { x: 200, y: 40 } },
perspective,
rendererSize,
),
).toBe(false);
});

it("counts the padding under the title bar as out of the room", () => {
const underTitleBar = {
position: { x: 0, y: -rendererSize.y / 2 + fitPadding.top - 10 },
size: { x: 50, y: 30 },
};
expect(isShownInRoom(underTitleBar, perspective, rendererSize)).toBe(false);
});

it("shows every rectangle in the room once the perspective fits them", () => {
const rects = [
{ position: { x: -2000, y: 50 }, size: { x: 100, y: 30 } },
{ position: { x: 400, y: 900 }, size: { x: 100, y: 30 } },
];
const fitted = perspectiveFitting(rects, rendererSize);
for (const rect of rects) {
expect(isShownInRoom(rect, fitted, rendererSize)).toBe(true);
}
});
});
65 changes: 51 additions & 14 deletions src/pages/edit/Editor/store/slices/perspective/fit.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,41 @@
import type { Rect } from "../../../../../../common/rect";
import type { Perspective } from "../../../../../../common/types";
import type { Vector2 } from "../../../../../../common/vector2";

type Padding = { top: number; right: number; bottom: number; left: number };

/** Room kept clear of nodes: the title bar is at the top and the play button at the bottom right */
export const fitPadding = { top: 130, right: 30, bottom: 110, left: 30 };
export const fitPadding: Padding = {
top: 130,
right: 30,
bottom: 110,
left: 30,
};

/** As `fitPadding`, with room at the bottom for the message about an error */
export const errorFitPadding: Padding = { ...fitPadding, bottom: 200 };

export function stageToCanvas(
point: Vector2,
perspective: Perspective,
rendererSize: Vector2,
): Vector2 {
return {
x:
(point.x - perspective.center.x) / perspective.scale + rendererSize.x / 2,
y:
(point.y - perspective.center.y) / perspective.scale + rendererSize.y / 2,
};
}

/**
* The perspective showing every rectangle inside a renderer of `rendererSize`, zoomed
* out only as far as needed, never in
*/
export function perspectiveFitting(
rects: readonly { position: Vector2; size: Vector2 }[],
rects: readonly Rect[],
rendererSize: Vector2,
padding: Padding = fitPadding,
): Perspective {
if (rects.length === 0) return { center: { x: 0, y: 0 }, scale: 1 };
const left = Math.min(...rects.map((rect) => rect.position.x));
Expand All @@ -20,23 +45,35 @@ export function perspectiveFitting(
...rects.map((rect) => rect.position.y + rect.size.y),
);
// A renderer smaller than the padding still gets a finite scale
const roomX = Math.max(
1,
rendererSize.x - fitPadding.left - fitPadding.right,
);
const roomY = Math.max(
1,
rendererSize.y - fitPadding.top - fitPadding.bottom,
);
const roomX = Math.max(1, rendererSize.x - padding.left - padding.right);
const roomY = Math.max(1, rendererSize.y - padding.top - padding.bottom);
const scale = Math.max(1, (right - left) / roomX, (bottom - top) / roomY);
// The middle of the room is off the middle of the renderer by half the uneven padding
return {
center: {
x:
(left + right) / 2 - ((fitPadding.left - fitPadding.right) / 2) * scale,
y:
(top + bottom) / 2 - ((fitPadding.top - fitPadding.bottom) / 2) * scale,
x: (left + right) / 2 - ((padding.left - padding.right) / 2) * scale,
y: (top + bottom) / 2 - ((padding.top - padding.bottom) / 2) * scale,
},
scale,
};
}

export function isShownInRoom(
rect: Rect,
perspective: Perspective,
rendererSize: Vector2,
padding: Padding = fitPadding,
): boolean {
const topLeft = stageToCanvas(rect.position, perspective, rendererSize);
const bottomRight = stageToCanvas(
{ x: rect.position.x + rect.size.x, y: rect.position.y + rect.size.y },
perspective,
rendererSize,
);
return (
topLeft.x >= padding.left &&
topLeft.y >= padding.top &&
bottomRight.x <= rendererSize.x - padding.right &&
bottomRight.y <= rendererSize.y - padding.bottom
);
}
93 changes: 93 additions & 0 deletions src/pages/edit/Editor/store/slices/perspective/index.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { not } from "../../../../../../store/intrinsics/definitions";
import {
createTestStore,
registerTestComponent,
registerTestNode,
} from "../../../../../../store/testUtils";
import { getCCComponentEditorRendererNodeGeometry } from "../../../renderer/Node/geometry";
import { createEditorStore } from "../..";
import { stubResizeObserver } from "../../testUtils";
import { errorFitPadding, isShownInRoom } from "./fit";

stubResizeObserver();

const rendererSize = { x: 900, y: 800 };
const perspective = { center: { x: 0, y: 0 }, scale: 1 };

function setUp() {
const store = createTestStore();
const root = registerTestComponent(store, "Root");
const near = registerTestNode(store, root.id, not.component.id);
store.nodes.update(near.id, { position: { x: 0, y: 0 } });
const far = registerTestNode(store, root.id, not.component.id);
store.nodes.update(far.id, { position: { x: 5000, y: 0 } });
const editorStore = createEditorStore(root.id, store);
editorStore.setState({ rendererSize, perspective });
const isShown = (nodeId: typeof near.id) =>
isShownInRoom(
getCCComponentEditorRendererNodeGeometry(store, nodeId).rect,
editorStore.getState().perspective,
rendererSize,
errorFitPadding,
);
return { store, root, near, far, editorStore, isShown };
}

describe("showNodes", () => {
it("leaves the view as it is when the nodes are in it", () => {
const { near, editorStore } = setUp();

editorStore.getState().showNodes(new Set([near.id]));

expect(editorStore.getState().perspective).toBe(perspective);
});

it("brings every node into view when one is out of it", () => {
const { near, far, editorStore, isShown } = setUp();
expect(isShown(far.id)).toBe(false);

editorStore.getState().showNodes(new Set([far.id]));

expect(isShown(far.id)).toBe(true);
expect(isShown(near.id)).toBe(true);
});

it("brings a node out from under the error message", () => {
const { store, near, editorStore, isShown } = setUp();
const rectOfNear = () =>
getCCComponentEditorRendererNodeGeometry(store, near.id).rect;
const bottomUnderMessage = rendererSize.y / 2 - errorFitPadding.bottom + 10;
const { position, size } = rectOfNear();
const offset = position.y - near.position.y;
store.nodes.update(near.id, {
position: { x: 0, y: bottomUnderMessage - size.y - offset },
});
expect(isShownInRoom(rectOfNear(), perspective, rendererSize)).toBe(true);
expect(isShown(near.id)).toBe(false);

editorStore.getState().showNodes(new Set([near.id]));

expect(isShown(near.id)).toBe(true);
});

it("ignores nodes of other components", () => {
const { store, editorStore } = setUp();
const other = registerTestComponent(store, "Other");
const elsewhere = registerTestNode(store, other.id, not.component.id);
store.nodes.update(elsewhere.id, { position: { x: 9000, y: 0 } });

editorStore.getState().showNodes(new Set([elsewhere.id]));

expect(editorStore.getState().perspective).toBe(perspective);
});

it("waits for the size of the renderer", () => {
const { far, editorStore } = setUp();
editorStore.setState({ rendererSize: { x: 0, y: 0 } });

editorStore.getState().showNodes(new Set([far.id]));

expect(editorStore.getState().perspective).toBe(perspective);
});
});
Loading
Loading