diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 19bf8b4..41adf8b 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -219,7 +219,7 @@ export const en = { next: "Next stage", backToStages: "Back to the stages", missingPin: (pinType: "input" | "output", pinName: string) => - `There is no ${pinType} pin named ${pinName}. "Reset this stage" brings back how the stage started.`, + `The ${pinType} ${pinName} on the ${pinType === "input" ? "left" : "right"} is missing. Reset this stage to bring back how it started.`, wrongBitWidth: (pinName: string, expected: number, actual: number) => `${pinName} should have ${bitCount(expected)}, but it has ${bitCount(actual)}. Check what it is connected to.`, wrongOutput: ( @@ -239,8 +239,7 @@ export const en = { `At time step ${stepNumber}${inputs.length > 0 ? ` (${listOf(inputs.map(({ name, value }) => `${name} is ${value}`))})` : ""}, ${pinName} should be ${expected}, but it ${actual === null ? "has no value" : `is ${actual}`}.`, checkFailed: "Something went wrong while checking. Change the circuit a little and press Check again.", - simulationFailed: (detail: string) => - `The circuit could not be simulated. ${detail}`, + simulationFailed: (detail: string) => `The circuit cannot run. ${detail}`, resetStage: "Reset this stage", resetStageDialog: { title: "Reset this stage?", diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts index 0e21983..259c4bd 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -1,9 +1,6 @@ import type { Messages } from "./en"; const bitWidths = (widths: readonly number[]) => `${widths.join("/")} ビット`; -const fixOrFeedBack = - "線をつなぎ直すか、値をフィードバックさせたい場合はループに FlipFlop を入れてください。"; - export const ja: Messages = { languageName: "日本語", common: { @@ -132,7 +129,7 @@ export const ja: Messages = { next: "次の課題へ", backToStages: "課題の一覧へ", missingPin: (pinType, pinName) => - `${pinName} という名前の${pinType === "input" ? "入力" : "出力"}ピンが見つかりません。「この課題をやり直す」で最初の状態に戻せます。`, + `${pinType === "input" ? "左の入力" : "右の出力"} ${pinName} が見つかりません。この課題を最初の状態に戻してください。`, wrongBitWidth: (pinName, expected, actual) => `${pinName} は ${expected}ビットのはずですが、${actual}ビットになっています。つないだ先を確かめてください。`, wrongOutput: (inputs, pinName, expected, actual) => @@ -141,8 +138,7 @@ export const ja: Messages = { `${stepNumber} ステップ目${inputs.length > 0 ? `(${inputs.map(({ name, value }) => `${name} が ${value}`).join("、")})` : ""}に、${pinName} が ${expected} のはずが${actual === null ? "、値がありませんでした" : ` ${actual} でした`}。`, checkFailed: "確かめる途中で問題が起きました。回路を少し変えてから、もう一度押してください。", - simulationFailed: (detail) => - `回路をシミュレーションできませんでした。${detail}`, + simulationFailed: (detail) => `回路を動かせません。${detail}`, resetStage: "この課題をやり直す", resetStageDialog: { title: "この課題をやり直しますか?", @@ -293,12 +289,14 @@ export const ja: Messages = { }, simulation: { nodeName: (outerToInner) => outerToInner.join(" 内の "), + interfaceNode: (type, pin) => + `${type === "input" ? "入力" : "出力"} ${pin}`, sentences: (sentences) => sentences.join(""), - loop: `赤い枠のノードがループになっていて、値が決まりません。ループの${fixOrFeedBack}`, + loop: "赤い枠の部品は、自分の出力が線をたどって自分の入力に戻ってきます。出力を決めるのにその出力自身が必要になるので、このままでは動きません。線をつなぎ直すか、その途中に FlipFlop を入れてください。", loopInside: (place, component) => - `${place} の中にループがあり、値が決まりません。${component} を開いて${fixOrFeedBack}`, + `${place} の中に、自分の出力が線をたどって自分の入力に戻ってくる部品があります。出力を決めるのにその出力自身が必要になるので、このままでは動きません。${component} を開いて線をつなぎ直すか、その途中に FlipFlop を入れてください。`, unconnectedPin: (pin, node) => - `${node} の入力ピン ${pin} がつながっていません。`, + `${node} の ${pin} のピンがつながっていません。`, unconnectedNode: (node) => `${node} がつながっていません。`, openToConnect: (component) => `${component} を開いてつないでください。`, bitWidthConflict: (component) => diff --git a/src/i18n/messages.test.ts b/src/i18n/messages.test.ts index 058d914..1613938 100644 --- a/src/i18n/messages.test.ts +++ b/src/i18n/messages.test.ts @@ -69,7 +69,32 @@ describe("Japanese messages", () => { ); expect(error.describe(store, ja.simulation)).toBe( - "Half 内の And の入力ピン B がつながっていません。Half を開いてつないでください。", + "Half 内の And の B のピンがつながっていません。Half を開いてつないでください。", + ); + }); + + it("names an Output node by its role, so that it is not read as a pin of the part", () => { + const store = createTestStore(); + const half = registerTestComponent(store, "Half"); + registerTestInputNode(store, half.id, "In"); + registerTestOutputNode(store, half.id, "S"); + const root = registerTestComponent(store, "Root"); + const rootIn = registerTestInputNode(store, root.id, "In"); + const halfNode = registerTestNode(store, root.id, half.id); + connectTestNodePins( + store, + root.id, + rootIn.out, + testNodePin(store, halfNode, testComponentPin(store, half, "In")), + ); + + const error = thrownBy( + () => simulateComponent(store, root.id, new Map()), + SimulationUnconnectedPinError, + ); + + expect(error.describe(store, ja.simulation)).toBe( + "Half 内の 出力 S がつながっていません。Half を開いてつないでください。", ); }); diff --git a/src/pages/edit/Editor/outlinedNodes.ts b/src/pages/edit/Editor/outlinedNodes.ts new file mode 100644 index 0000000..7acd4ea --- /dev/null +++ b/src/pages/edit/Editor/outlinedNodes.ts @@ -0,0 +1,7 @@ +import { createContext } from "react"; +import type { CCNodeId } from "../../../store/node"; + +/** Nodes outlined as in a simulation error by something outside the editor, e.g. a check */ +export const OutlinedNodeIdsContext = createContext>( + new Set(), +); diff --git a/src/pages/edit/Editor/renderer/Node/index.tsx b/src/pages/edit/Editor/renderer/Node/index.tsx index f56ad9b..eb9a5db 100644 --- a/src/pages/edit/Editor/renderer/Node/index.tsx +++ b/src/pages/edit/Editor/renderer/Node/index.tsx @@ -1,5 +1,5 @@ import clsx from "clsx"; -import { useState } from "react"; +import { useContext, useState } from "react"; import { vector2 } from "../../../../../common/vector2"; import { type CCIntrinsicComponentType, @@ -8,6 +8,7 @@ import { import type { CCNodeId } from "../../../../../store/node"; import { useStore } from "../../../../../store/react"; import { useComponent, useNode } from "../../../../../store/react/selectors"; +import { OutlinedNodeIdsContext } from "../../outlinedNodes"; import { useComponentEditorStore } from "../../store"; import CCComponentEditorRendererNodePin from "../NodePin"; import { CCComponentEditorRendererNodeConstRenderer } from "./components/Const"; @@ -49,6 +50,7 @@ export default function CCComponentEditorRendererNode({ const node = useNode(nodeId); const component = useComponent(node?.componentId); const componentEditorState = useComponentEditorStore()(); + const outlinedNodeIds = useContext(OutlinedNodeIdsContext); const [dragging, setDragging] = useState(false); const [dragStartPosition, setDragStartPosition] = useState(vector2.zero); const [previousNodePosition, setPreviousNodePosition] = useState( @@ -108,7 +110,8 @@ export default function CCComponentEditorRendererNode({ className={clsx( styles.node, isSelected && styles.selected, - componentEditorState.simulationError?.nodeIds.has(nodeId) && + (componentEditorState.simulationError?.nodeIds.has(nodeId) || + outlinedNodeIds.has(nodeId)) && styles.simulationError, )} onPointerDown={handlePointerDown} diff --git a/src/pages/edit/Editor/store/slices/core/index.test.ts b/src/pages/edit/Editor/store/slices/core/index.test.ts index 2866b6b..86e6628 100644 --- a/src/pages/edit/Editor/store/slices/core/index.test.ts +++ b/src/pages/edit/Editor/store/slices/core/index.test.ts @@ -187,10 +187,10 @@ describe("simulation errors", () => { const { editorMode, simulationError } = editorStore.getState(); expect(editorMode).toBe("edit"); expect(simulationError?.messageByLanguage.en).toMatch( - /^The outlined nodes form a loop/, + /^The output of each part outlined in red/, ); expect(simulationError?.messageByLanguage.ja).toMatch( - /^赤い枠のノードがループになっていて/, + /^赤い枠の部品は、自分の出力が/, ); expect(simulationError?.nodeIds).toEqual(new Set([first.id, second.id])); }); diff --git a/src/pages/edit/Editor/store/slices/core/index.ts b/src/pages/edit/Editor/store/slices/core/index.ts index 2e977cf..2505001 100644 --- a/src/pages/edit/Editor/store/slices/core/index.ts +++ b/src/pages/edit/Editor/store/slices/core/index.ts @@ -325,11 +325,10 @@ export const createComponentEditorStoreCoreSlice: ComponentEditorSliceCreator< ? error.message : String(error), ), - nodeIds: new Set( + nodeIds: error instanceof SimulationNodeError - ? error.nodePaths.flatMap((path) => path.slice(0, 1)) - : [], - ), + ? error.outlinedNodeIds + : new Set(), }, })); return; diff --git a/src/pages/tutorial/stage.tsx b/src/pages/tutorial/stage.tsx index 4f1648a..d04eddf 100644 --- a/src/pages/tutorial/stage.tsx +++ b/src/pages/tutorial/stage.tsx @@ -13,6 +13,7 @@ import { type ReactNode, useCallback, useEffect, + useMemo, useRef, useState, } from "react"; @@ -31,6 +32,8 @@ import { import { TruthTableView } from "../../components/TruthTableView"; import { useMessages } from "../../i18n"; import { definitionByComponentId } from "../../store/intrinsics/definitions"; +import { SimulationNodeError } from "../../store/netlist"; +import type { CCNodeId } from "../../store/node"; import { StoreScope, useStore } from "../../store/react"; import { useComponents } from "../../store/react/selectors"; import { theme } from "../../style"; @@ -59,6 +62,7 @@ import { tutorialStages, } from "../../tutorial/stages"; import CCComponentEditor from "../edit/Editor"; +import { OutlinedNodeIdsContext } from "../edit/Editor/outlinedNodes"; import type { OffersComponent } from "../edit/placement"; import SidePanel from "../edit/SidePanel"; @@ -77,18 +81,39 @@ function SectionHeading({ children }: { children: ReactNode }) { function CheckFailure({ result, + onReset, }: { result: Exclude; + onReset: () => void; }) { const { store } = useStore(); const messages = useMessages(); // The message may name a part, which is renamed when the language changes useComponents(); return ( - {describeFailure(result, store, messages)} + + {describeFailure(result, store, messages)} + {/* The reset button at the end of the stage text may be out of view */} + {result.type === "missingPin" && ( + + + + )} + ); } +const noNodeIds: ReadonlySet = new Set(); + +function outlinedNodeIdsOf(result: CheckResult | null): ReadonlySet { + return result?.type === "simulationFailed" && + result.error instanceof SimulationNodeError + ? result.error.outlinedNodeIds + : noNodeIds; +} + function StageView({ stage }: { stage: TutorialStage }) { const messages = useMessages(); const texts = messages.tutorial; @@ -137,6 +162,8 @@ function StageView({ stage }: { stage: TutorialStage }) { }; useEffect(() => () => cancelCheckRef.current?.(), []); + const outlinedNodeIds = useMemo(() => outlinedNodeIdsOf(result), [result]); + const check = () => { setIsChecking(true); const run = () => { @@ -144,6 +171,10 @@ function StageView({ stage }: { stage: TutorialStage }) { const checked = checkCircuit(store, stage.componentId, stage.check); if (checked.type === "checkFailed") console.error(checked.error); setResult(checked); + // The outline is on the stage's own circuit, which a part opened would hide + if (outlinedNodeIdsOf(checked).size > 0) { + setEditedComponentId(stage.componentId); + } if (checked.type === "passed") markStageCleared(stage.id); setIsChecking(false); }; @@ -306,7 +337,10 @@ function StageView({ stage }: { stage: TutorialStage }) { )} {result && result.type !== "passed" && ( - + setIsConfirmingReset(true)} + /> )} @@ -325,27 +359,38 @@ function StageView({ stage }: { stage: TutorialStage }) { /> - isStagePinNode(store, stage, nodeId), - isOffered, - canCreateComponents: stage.allowsNewComponents, - fitsNodesInView: true, - areaToFit: - shownComponentId === stage.componentId - ? stageAreaOf(stage) - : null, - hasProperties: (componentId) => - !isStageComponent(stage, componentId), - }} - onEditComponent={setEditedComponentId} - onClose={() => { - if (shownComponentId === stage.componentId) navigate("/tutorial"); - else setEditedComponentId(stage.componentId); - }} - /> + + + isStagePinNode(store, stage, nodeId), + isOffered, + canCreateComponents: stage.allowsNewComponents, + fitsNodesInView: true, + areaToFit: + shownComponentId === stage.componentId + ? stageAreaOf(stage) + : null, + hasProperties: (componentId) => + !isStageComponent(stage, componentId), + }} + onEditComponent={setEditedComponentId} + onClose={() => { + if (shownComponentId === stage.componentId) + navigate("/tutorial"); + else setEditedComponentId(stage.componentId); + }} + /> + {isConfirmingReset && ( store.componentPins.getByImplementation(nodePin.id)) .find((componentPin) => componentPin !== undefined); - return exposedPin ? `${componentName} ${exposedPin.name}` : componentName; + return exposedPin + ? texts.interfaceNode(exposedPin.type, exposedPin.name) + : componentName; } export function describeNodePath( @@ -152,7 +158,7 @@ export function describeNodePath( path: readonly CCNodeId[], texts: SimulationErrorTexts = englishSimulationErrorTexts, ): string { - return texts.nodeName(path.map((nodeId) => nameOfNode(store, nodeId))); + return texts.nodeName(path.map((nodeId) => nameOfNode(store, nodeId, texts))); } function commonPrefixOf( @@ -185,6 +191,16 @@ export class SimulationNodeError extends Error { describe(_store: CCStore, _texts: SimulationErrorTexts): string { return this.message; } + + /** Whether `describe` words the error, rather than giving the English message */ + get isWorded(): boolean { + return false; + } + + /** The nodes of the simulated component itself that the error is in or under */ + get outlinedNodeIds(): ReadonlySet { + return new Set(this.nodePaths.flatMap((path) => path.slice(0, 1))); + } } function describeLoop( @@ -216,6 +232,10 @@ export class SimulationCombinationalLoopError extends SimulationNodeError { override describe(store: CCStore, texts: SimulationErrorTexts): string { return describeLoop(store, this.nodePaths, texts); } + + override get isWorded(): boolean { + return true; + } } function describeUnconnectedPin( @@ -267,6 +287,10 @@ export class SimulationUnconnectedPinError extends SimulationNodeError { texts, ); } + + override get isWorded(): boolean { + return true; + } } function describeBitWidthConflict( @@ -312,6 +336,10 @@ export class SimulationBitWidthConflictError extends SimulationNodeError { texts, ); } + + override get isWorded(): boolean { + return true; + } } /** diff --git a/src/store/simulation.test.ts b/src/store/simulation.test.ts index 5d058e5..60e8ab3 100644 --- a/src/store/simulation.test.ts +++ b/src/store/simulation.test.ts @@ -287,7 +287,7 @@ describe("simulateComponent", () => { SimulationCombinationalLoopError, ); expect(error.message).toBe( - "The outlined nodes form a loop, so their values cannot be determined. Fix the connections in the loop, or add a FlipFlop to it if the value should feed back.", + "The output of each part outlined in red comes back to its own input along the wires. Working out its output needs that same output, so the circuit cannot run as it is. Reconnect a wire, or put a FlipFlop somewhere along the way.", ); expect(new Set(error.nodePaths.map((path) => path[0]))).toEqual( new Set([first.id, second.id]), @@ -325,7 +325,7 @@ describe("simulateComponent", () => { SimulationCombinationalLoopError, ); expect(error.message).toBe( - "The outlined nodes form a loop, so their values cannot be determined. Fix the connections in the loop, or add a FlipFlop to it if the value should feed back.", + "The output of each part outlined in red comes back to its own input along the wires. Working out its output needs that same output, so the circuit cannot run as it is. Reconnect a wire, or put a FlipFlop somewhere along the way.", ); expect(new Set(error.nodePaths.map((path) => path[0]))).toEqual( new Set([first.id, second.id]), @@ -357,7 +357,7 @@ describe("simulateComponent", () => { SimulationCombinationalLoopError, ); expect(error.message).toBe( - "There is a loop inside Ring, so the values in it cannot be determined. Open Ring to fix the connections, or add a FlipFlop to the loop if the value should feed back.", + "Inside Ring, the output of some parts comes back to their own input along the wires. Working out their output needs that same output, so the circuit cannot run as it is. Open Ring to reconnect a wire, or put a FlipFlop somewhere along the way.", ); expect(new Set(error.nodePaths.map((path) => path[0]))).toEqual( new Set([ringNode.id]), @@ -434,7 +434,7 @@ describe("simulateComponent", () => { () => simulateComponent(store, root.id, new Map()), SimulationCombinationalLoopError, ); - expect(error.message).toMatch(/^The outlined nodes form a loop/); + expect(error.message).toMatch(/^The output of each part outlined in red/); expect(new Set(error.nodePaths.map((path) => path[0]))).toEqual( new Set([chainNode.id, bufferNode.id]), ); @@ -452,7 +452,7 @@ describe("simulateComponent", () => { SimulationCombinationalLoopError, ); expect(error.message).toMatch( - /^There is a loop inside Outer, .* Open Outer to fix/, + /^Inside Outer, .* Open Outer to reconnect/, ); expect(new Set(error.nodePaths.map((path) => path[0]))).toEqual( new Set([outerNode.id]), @@ -492,7 +492,7 @@ describe("simulateComponent", () => { () => simulateComponent(store, root.id, new Map()), SimulationCombinationalLoopError, ); - expect(error.message).toMatch(/^There is a loop inside Ring, .* Open Ring/); + expect(error.message).toMatch(/^Inside Ring, .* Open Ring/); expect(new Set(error.nodePaths.map((path) => path[0]))).toEqual( new Set([ringNode.id]), ); @@ -530,7 +530,7 @@ describe("simulateComponent", () => { () => simulateComponent(store, root.id, new Map()), SimulationUnconnectedPinError, ); - expect(error.message).toMatch(/^Input pin [AB] of And is not connected\.$/); + expect(error.message).toMatch(/^Pin [AB] of And is not connected\.$/); expect(error.nodePaths).toEqual([[andNode.id]]); }); @@ -567,7 +567,7 @@ describe("simulateComponent", () => { SimulationUnconnectedPinError, ); expect(error.message).toBe( - "Input pin B of And in Half is not connected. Open Half to connect it.", + "Pin B of And in Half is not connected. Open Half to connect it.", ); expect(error.nodePaths).toEqual([[halfNode.id, andNode.id]]); }); diff --git a/src/store/simulationErrorTexts.ts b/src/store/simulationErrorTexts.ts index a4df1c6..99b5ef0 100644 --- a/src/store/simulationErrorTexts.ts +++ b/src/store/simulationErrorTexts.ts @@ -1,6 +1,8 @@ export type SimulationErrorTexts = { /** a node by the names of the nodes it is in, given from the outside in */ nodeName(outerToInner: readonly string[]): string; + /** an Input or Output node, by the pin it adds */ + interfaceNode(type: "input" | "output", pin: string): string; sentences(sentences: readonly string[]): string; loop: string; loopInside(place: string, component: string): string; @@ -13,12 +15,13 @@ export type SimulationErrorTexts = { export const englishSimulationErrorTexts: SimulationErrorTexts = { nodeName: (outerToInner) => outerToInner.toReversed().join(" in "), + interfaceNode: (type, pin) => + `${type === "input" ? "Input" : "Output"} ${pin}`, sentences: (sentences) => sentences.join(" "), - loop: "The outlined nodes form a loop, so their values cannot be determined. Fix the connections in the loop, or add a FlipFlop to it if the value should feed back.", + loop: "The output of each part outlined in red comes back to its own input along the wires. Working out its output needs that same output, so the circuit cannot run as it is. Reconnect a wire, or put a FlipFlop somewhere along the way.", loopInside: (place, component) => - `There is a loop inside ${place}, so the values in it cannot be determined. Open ${component} to fix the connections, or add a FlipFlop to the loop if the value should feed back.`, - unconnectedPin: (pin, node) => - `Input pin ${pin} of ${node} is not connected.`, + `Inside ${place}, the output of some parts comes back to their own input along the wires. Working out their output needs that same output, so the circuit cannot run as it is. Open ${component} to reconnect a wire, or put a FlipFlop somewhere along the way.`, + unconnectedPin: (pin, node) => `Pin ${pin} of ${node} is not connected.`, unconnectedNode: (node) => `${node} is not connected.`, openToConnect: (component) => `Open ${component} to connect it.`, bitWidthConflict: (component) => diff --git a/src/tutorial/failure.test.ts b/src/tutorial/failure.test.ts index e5a4854..f400acc 100644 --- a/src/tutorial/failure.test.ts +++ b/src/tutorial/failure.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "vitest"; import { messagesByLanguage } from "../i18n/messages"; +import { SimulationNodeError } from "../store/netlist"; import { createTestStore } from "../store/testUtils"; import { describeFailure } from "./failure"; @@ -22,4 +23,38 @@ describe("describeFailure", () => { "3 ステップ目(Start が ON)に、Count が 0011 のはずが 0010 でした。", ); }); + + it("gives a worded simulation error as it is", () => { + class WordedError extends SimulationNodeError { + override get isWorded() { + return true; + } + } + expect( + describeFailure( + { + type: "simulationFailed", + error: new WordedError("Output Out is not connected.", []), + }, + createTestStore(), + messagesByLanguage.en, + ), + ).toBe("Output Out is not connected."); + }); + + it.each([ + new Error("Broken"), + new SimulationNodeError("And could not be evaluated", []), + ])( + "says the circuit cannot run before an error without a wording: %s", + (error) => { + expect( + describeFailure( + { type: "simulationFailed", error }, + createTestStore(), + messagesByLanguage.ja, + ), + ).toBe(`回路を動かせません。${error.message}`); + }, + ); }); diff --git a/src/tutorial/failure.ts b/src/tutorial/failure.ts index 32a3b37..751d397 100644 --- a/src/tutorial/failure.ts +++ b/src/tutorial/failure.ts @@ -35,12 +35,17 @@ export function describeFailure( case "checkFailed": return texts.checkFailed; case "simulationFailed": + // A worded error tells by itself what keeps the circuit from running + if ( + result.error instanceof SimulationNodeError && + result.error.isWorded + ) { + return result.error.describe(store, messages.simulation); + } return texts.simulationFailed( - result.error instanceof SimulationNodeError - ? result.error.describe(store, messages.simulation) - : result.error instanceof Error - ? result.error.message - : String(result.error), + result.error instanceof Error + ? result.error.message + : String(result.error), ); } }