diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 4c6fe51..7b7e4c2 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -27,7 +27,7 @@ const stageTexts: Record = { 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 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 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 , click the switches {A} and {B} to turn them [ON] and [OFF], and watch the lamp {Out}. To fix the circuit, the pencil button in the same place takes you back to editing.", "When it works as in the table, press .", ], @@ -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", diff --git a/src/i18n/ja.ts b/src/i18n/ja.ts index 9ec7642..efc0ef3 100644 --- a/src/i18n/ja.ts +++ b/src/i18n/ja.ts @@ -173,7 +173,7 @@ export const ja: Messages = { steps: [ "回路を組み立てる部品を「コンポーネント」といいます。「コンポーネント」の一覧から1つ選び、右のエディタにドラッグして置きます。", "コンポーネントの端にある小さな四角を「ピン」といいます。左側のピンは [ON] か [OFF] を受け取る「入力」、右側のピンは [ON] か [OFF] を送り出す「出力」です。出力のピンと入力のピンのあいだをドラッグして、線でつなぎます。", - "{Out} と、置いたコンポーネントの入力のピンがすべてつながると、右下の再生ボタンが押せるようになります。入力のピンが空いているコンポーネントが残っていると押せません。", + "{Out} と、置いたコンポーネントの入力のピンがすべてつながると、右下の再生ボタンが緑色になります。入力のピンが空いているコンポーネントが残っているときに押すと、どのピンが空いているかが表示されます。", "再生ボタンを押したら、スイッチ {A} と {B} をクリックして [ON] と [OFF] を切り替え、ランプ {Out} を見ます。回路を直すときは、同じ場所の鉛筆のボタンで編集に戻ります。", "表のとおりに動いたら、を押します。", ], @@ -286,6 +286,7 @@ export const ja: Messages = { cannotDelete: (names) => `${names.join("、")} は課題で使うので消せません`, keptOnDelete: (names) => `${names.join("、")} は課題で使うので残ります`, }, + viewMode: { play: "再生", edit: "編集に戻る" }, frameControl: { auto: "自動", autoPlay: "自動再生", diff --git a/src/pages/edit/Editor/components/ViewModeSwitcher.tsx b/src/pages/edit/Editor/components/ViewModeSwitcher.tsx index 4421f34..8645948 100644 --- a/src/pages/edit/Editor/components/ViewModeSwitcher.tsx +++ b/src/pages/edit/Editor/components/ViewModeSwitcher.tsx @@ -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 ( { - 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" ? : } + {isEditing ? : } ); } diff --git a/src/pages/edit/Editor/renderer/index.tsx b/src/pages/edit/Editor/renderer/index.tsx index 39994c1..598a0c1 100644 --- a/src/pages/edit/Editor/renderer/index.tsx +++ b/src/pages/edit/Editor/renderer/index.tsx @@ -1,3 +1,4 @@ +import { useContext, useEffect } from "react"; import { parseDataTransferAsComponent } from "../../../../common/serialization"; import { vector2 } from "../../../../common/vector2"; import { CCNodeStore } from "../../../../store/node"; @@ -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"; @@ -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 { ); 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", () => { diff --git a/src/pages/edit/Editor/store/slices/perspective/fit.test.ts b/src/pages/edit/Editor/store/slices/perspective/fit.test.ts index a33d480..08e7c39 100644 --- a/src/pages/edit/Editor/store/slices/perspective/fit.test.ts +++ b/src/pages/edit/Editor/store/slices/perspective/fit.test.ts @@ -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 }; @@ -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); + } + }); +}); diff --git a/src/pages/edit/Editor/store/slices/perspective/fit.ts b/src/pages/edit/Editor/store/slices/perspective/fit.ts index 4748959..c565cf1 100644 --- a/src/pages/edit/Editor/store/slices/perspective/fit.ts +++ b/src/pages/edit/Editor/store/slices/perspective/fit.ts @@ -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)); @@ -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 + ); +} diff --git a/src/pages/edit/Editor/store/slices/perspective/index.test.ts b/src/pages/edit/Editor/store/slices/perspective/index.test.ts new file mode 100644 index 0000000..2b8050d --- /dev/null +++ b/src/pages/edit/Editor/store/slices/perspective/index.test.ts @@ -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); + }); +}); diff --git a/src/pages/edit/Editor/store/slices/perspective/index.tsx b/src/pages/edit/Editor/store/slices/perspective/index.tsx index a2053b5..058dbef 100644 --- a/src/pages/edit/Editor/store/slices/perspective/index.tsx +++ b/src/pages/edit/Editor/store/slices/perspective/index.tsx @@ -1,7 +1,17 @@ +import type { Rect } from "../../../../../../common/rect"; import { vector2 } from "../../../../../../common/vector2"; +import type { CCNodeId } from "../../../../../../store/node"; import { getCCComponentEditorRendererNodeGeometry } from "../../../renderer/Node/geometry"; -import type { ComponentEditorSliceCreator } from "../../types"; -import { perspectiveFitting } from "./fit"; +import type { + ComponentEditorSliceCreator, + ComponentEditorStoreValue, +} from "../../types"; +import { + errorFitPadding, + isShownInRoom, + perspectiveFitting, + stageToCanvas, +} from "./fit"; import type { PerspectiveStoreSlice } from "./types"; const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator< @@ -16,6 +26,14 @@ const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator< if (element) resizeObserver.observe(element); rendererElement = element; }; + const rectOf = (nodeId: CCNodeId) => + getCCComponentEditorRendererNodeGeometry(store, nodeId).rect; + const rectsToFit = (state: ComponentEditorStoreValue): Rect[] => [ + ...store.nodes + .getManyByParentComponentId(componentId) + .map((node) => rectOf(node.id)), + ...(state.areaToFit ? [state.areaToFit] : []), + ]; return { define: (set, get) => ({ perspective: { center: vector2.zero, scale: 1 }, @@ -25,6 +43,32 @@ const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator< return rect ? { x: rect.left, y: rect.top } : vector2.zero; }, setPerspective: (perspective) => set((s) => ({ ...s, perspective })), + showNodes: (nodeIds) => { + const { perspective, rendererSize } = get(); + if (rendererSize.x <= 0 || rendererSize.y <= 0) return; + const isEachShown = [...nodeIds] + .filter( + (nodeId) => + store.nodes.get(nodeId)?.parentComponentId === componentId, + ) + .every((nodeId) => + isShownInRoom( + rectOf(nodeId), + perspective, + rendererSize, + errorFitPadding, + ), + ); + if (isEachShown) return; + set((s) => ({ + ...s, + perspective: perspectiveFitting( + rectsToFit(get()), + rendererSize, + errorFitPadding, + ), + })); + }, registerRendererElement, fromCanvasToStage: (point) => vector2.add( @@ -35,13 +79,7 @@ const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator< get().perspective.center, ), fromStageToCanvas: (point) => - vector2.add( - vector2.div( - vector2.sub(point, get().perspective.center), - get().perspective.scale, - ), - vector2.div(get().rendererSize, 2), - ), + stageToCanvas(point, get().perspective, get().rendererSize), getViewBox: () => { const viewBoxTopLeft = get().fromCanvasToStage(vector2.zero); const viewBoxBottomRight = get().fromCanvasToStage(get().rendererSize); @@ -70,19 +108,7 @@ const createComponentEditorStorePerspectiveSlice: ComponentEditorSliceCreator< editorStore.setState({ rendererSize, ...(fitsNow && { - perspective: perspectiveFitting( - [ - ...store.nodes - .getManyByParentComponentId(componentId) - .map( - (node) => - getCCComponentEditorRendererNodeGeometry(store, node.id) - .rect, - ), - ...(state.areaToFit ? [state.areaToFit] : []), - ], - rendererSize, - ), + perspective: perspectiveFitting(rectsToFit(state), rendererSize), }), }); }); diff --git a/src/pages/edit/Editor/store/slices/perspective/types.ts b/src/pages/edit/Editor/store/slices/perspective/types.ts index 3382c56..25feb60 100644 --- a/src/pages/edit/Editor/store/slices/perspective/types.ts +++ b/src/pages/edit/Editor/store/slices/perspective/types.ts @@ -1,11 +1,14 @@ import type { Perspective } from "../../../../../../common/types"; import type { Vector2 } from "../../../../../../common/vector2"; +import type { CCNodeId } from "../../../../../../store/node"; export type PerspectiveStoreSlice = { perspective: Perspective; rendererSize: Vector2; getRendererPosition: () => Vector2; setPerspective: (perspective: Perspective) => void; + /** Fits every node in view, if any of `nodeIds` in the edited component is out of it */ + showNodes: (nodeIds: ReadonlySet) => void; registerRendererElement: (element: SVGSVGElement | null) => void; fromCanvasToStage: (point: Vector2) => Vector2; fromStageToCanvas: (point: Vector2) => Vector2; diff --git a/src/store/react/selectors.ts b/src/store/react/selectors.ts index c605821..99712ba 100644 --- a/src/store/react/selectors.ts +++ b/src/store/react/selectors.ts @@ -156,7 +156,7 @@ export function useComponentPin(componentPinId: CCComponentPinId | undefined) { return useSyncExternalStore(subscribe, getSnapshot); } -export function useCanSimulate(componentId: CCComponentId) { +export function useIsEachInputPinConnected(componentId: CCComponentId) { const { store } = useStore(); const getSnapshot = useCallback( () => isEachInputPinConnected(store, componentId),