diff --git a/src/pages/edit/Editor/renderer/index.tsx b/src/pages/edit/Editor/renderer/index.tsx
index b0a9cf7..39994c1 100644
--- a/src/pages/edit/Editor/renderer/index.tsx
+++ b/src/pages/edit/Editor/renderer/index.tsx
@@ -6,6 +6,7 @@ import {
useConnectionIds,
useNodeIds,
} from "../../../../store/react/selectors";
+import { canPlaceComponent } from "../../placement";
import { useComponentEditorStore } from "../store";
import CCComponentEditorRendererBackground from "./Background";
import CCComponentEditorRendererConnection from "./Connection";
@@ -61,7 +62,16 @@ export default function CCComponentEditorRenderer() {
}}
onDrop={(e) => {
const droppedComponentId = parseDataTransferAsComponent(e.dataTransfer);
- if (!droppedComponentId || componentEditorState.editorMode === "play")
+ if (
+ !droppedComponentId ||
+ componentEditorState.editorMode === "play" ||
+ !canPlaceComponent(
+ store,
+ componentEditorState.componentId,
+ droppedComponentId,
+ componentEditorState.isOffered,
+ )
+ )
return;
store.nodes.register(
CCNodeStore.create({
diff --git a/src/pages/edit/Editor/store/index.tsx b/src/pages/edit/Editor/store/index.tsx
index 590a0e7..55463e3 100644
--- a/src/pages/edit/Editor/store/index.tsx
+++ b/src/pages/edit/Editor/store/index.tsx
@@ -3,19 +3,41 @@ import invariant from "tiny-invariant";
import { create } from "zustand";
import type CCStore from "../../../../store";
import type { CCComponentId } from "../../../../store/component";
+import type { CCNodeId } from "../../../../store/node";
import { useStore } from "../../../../store/react";
+import type { OffersComponent } from "../../placement";
import createComponentEditorStoreContextMenuSlice from "./slices/contextMenu";
import { createComponentEditorStoreCoreSlice } from "./slices/core";
import createComponentEditorStorePerspectiveSlice from "./slices/perspective";
import type { ComponentEditorStoreValue } from "./types";
-export function createEditorStore(componentId: CCComponentId, store: CCStore) {
+export type EditorStoreOptions = {
+ isProtectedNode?: (nodeId: CCNodeId) => boolean;
+ isOffered?: OffersComponent;
+ canCreateComponents?: boolean;
+ hasProperties?: (componentId: CCComponentId) => boolean;
+};
+
+export function createEditorStore(
+ componentId: CCComponentId,
+ store: CCStore,
+ {
+ isProtectedNode = () => false,
+ isOffered = () => true,
+ hasProperties = () => true,
+ canCreateComponents = true,
+ }: EditorStoreOptions = {},
+) {
const props = { store, componentId };
const coreSlice = createComponentEditorStoreCoreSlice(props);
const perspectiveSlice = createComponentEditorStorePerspectiveSlice(props);
const contextMenuSlice = createComponentEditorStoreContextMenuSlice(props);
const editorStore = create
((set, get) => ({
componentId,
+ isProtectedNode,
+ isOffered,
+ hasProperties,
+ canCreateComponents,
...coreSlice.define(set, get),
...perspectiveSlice.define(set, get),
...contextMenuSlice.define(set, get),
@@ -32,13 +54,18 @@ const context = createContext(null);
export function ComponentEditorStoreProvider({
componentId,
+ options,
children,
}: {
componentId: CCComponentId;
+ options: EditorStoreOptions;
children: React.ReactNode;
}) {
const { store } = useStore();
- const [editorStore] = useState(() => createEditorStore(componentId, store));
+ // Read once, so a caller changes them by remounting with another key
+ const [editorStore] = useState(() =>
+ createEditorStore(componentId, store, options),
+ );
return {children};
}
diff --git a/src/pages/edit/Editor/store/slices/contextMenu/index.test.ts b/src/pages/edit/Editor/store/slices/contextMenu/index.test.ts
index 534c5e5..1d61bec 100644
--- a/src/pages/edit/Editor/store/slices/contextMenu/index.test.ts
+++ b/src/pages/edit/Editor/store/slices/contextMenu/index.test.ts
@@ -6,11 +6,13 @@ import {
connectTestNodePins,
createTestStore,
registerTestComponent,
+ registerTestInputNode,
registerTestNode,
testNodePin,
} from "../../../../../../store/testUtils";
import { createEditorStore } from "../..";
import { stubResizeObserver } from "../../testUtils";
+import { getContextMenuItems } from "./items";
stubResizeObserver();
@@ -32,7 +34,9 @@ function setUp() {
const [connection] = store.connections.getMany();
const editorStore = createEditorStore(root.id, store);
return {
+ store,
editorStore,
+ inverter,
intrinsicNode,
subNode,
connectionId: nullthrows(connection).id,
@@ -106,4 +110,68 @@ describe("Context menu slice", () => {
expect(editorStore.getState().contextMenuState).not.toBeNull();
});
+
+ it("protects nothing unless told to", () => {
+ const { store, editorStore, intrinsicNode, inverter } = setUp();
+ editorStore.getState().selectNode([intrinsicNode.id, inverter.id], true);
+
+ expect(getContextMenuItems(store, editorStore.getState())).toMatchObject({
+ removableNodeIds: [intrinsicNode.id, inverter.id],
+ });
+ });
+
+ it("keeps protected nodes from deleting and moving, and names them", () => {
+ const store = createTestStore();
+ const root = registerTestComponent(store, "Root");
+ const pin = registerTestInputNode(store, root.id, "A");
+ const gate = registerTestNode(store, root.id, not.component.id);
+ connectTestNodePins(
+ store,
+ root.id,
+ pin.out,
+ testNodePin(store, gate, not.inputPin.In),
+ );
+ const editorStore = createEditorStore(root.id, store, {
+ isProtectedNode: (nodeId) => nodeId === pin.node.id,
+ });
+ const items = () => getContextMenuItems(store, editorStore.getState());
+
+ editorStore.getState().selectNode([pin.node.id, gate.id], true);
+ expect(items()).toMatchObject({
+ removableNodeIds: [gate.id],
+ keptNodeNames: ["A"],
+ canDelete: true,
+ });
+
+ editorStore.getState().selectNode([pin.node.id], true);
+ expect(items()).toMatchObject({ keptNodeNames: ["A"], canDelete: false });
+ editorStore.getState().openContextMenu(rightClick);
+ expect(editorStore.getState().contextMenuState).not.toBeNull();
+
+ editorStore.getState().setEditorMode("play");
+ expect(editorStore.getState().editorMode).toBe("play");
+ editorStore.getState().openContextMenu(rightClick);
+ expect(editorStore.getState().contextMenuState).toBeNull();
+ });
+
+ it("offers no new component when the editor is told not to", () => {
+ const { store, editorStore, inverter } = setUp();
+ const closed = createEditorStore(
+ editorStore.getState().componentId,
+ store,
+ {
+ canCreateComponents: false,
+ },
+ );
+ editorStore.getState().selectNode([inverter.id], true);
+ closed.getState().selectNode([inverter.id], true);
+
+ expect(getContextMenuItems(store, editorStore.getState()).canExtract).toBe(
+ true,
+ );
+ expect(getContextMenuItems(store, closed.getState())).toMatchObject({
+ canExtract: false,
+ canDelete: true,
+ });
+ });
});
diff --git a/src/pages/edit/Editor/store/slices/contextMenu/items.ts b/src/pages/edit/Editor/store/slices/contextMenu/items.ts
index 56d827b..c98a9b6 100644
--- a/src/pages/edit/Editor/store/slices/contextMenu/items.ts
+++ b/src/pages/edit/Editor/store/slices/contextMenu/items.ts
@@ -1,3 +1,4 @@
+import { partition } from "es-toolkit";
import nullthrows from "nullthrows";
import type CCStore from "../../../../../../store";
import type { CCComponent } from "../../../../../../store/component";
@@ -7,13 +8,24 @@ import type { CCNodeId } from "../../../../../../store/node";
import type { ComponentEditorStoreValue } from "../../types";
export type ContextMenuItems = {
- selectedNodeIds: CCNodeId[];
selectedConnectionIds: CCConnectionId[];
+ removableNodeIds: CCNodeId[];
+ keptNodeNames: string[];
canExtract: boolean;
canDelete: boolean;
componentToEdit: CCComponent | null;
};
+function nameOfNode(store: CCStore, nodeId: CCNodeId): string {
+ const exposedPin = store.nodePins
+ .getManyByNodeId(nodeId)
+ .map((nodePin) => store.componentPins.getByImplementation(nodePin.id))
+ .find((componentPin) => componentPin !== undefined);
+ if (exposedPin) return exposedPin.name;
+ const node = nullthrows(store.nodes.get(nodeId));
+ return nullthrows(store.components.get(node.componentId)).name;
+}
+
export function getContextMenuItems(
store: CCStore,
state: ComponentEditorStoreValue,
@@ -26,6 +38,9 @@ export function getContextMenuItems(
(connectionId) => store.connections.get(connectionId),
);
const isEditMode = state.editorMode === "edit";
+ const [keptNodeIds, removableNodeIds] = partition(selectedNodeIds, (nodeId) =>
+ state.isProtectedNode(nodeId),
+ );
const [targetNodeId] = selectedNodeIds;
const targetComponent =
selectedNodeIds.length === 1 && targetNodeId
@@ -36,17 +51,27 @@ export function getContextMenuItems(
)
: null;
return {
- selectedNodeIds,
selectedConnectionIds,
+ removableNodeIds,
+ keptNodeNames: isEditMode
+ ? keptNodeIds.map((nodeId) => nameOfNode(store, nodeId))
+ : [],
canExtract:
- isEditMode && getExtractableNodeIds(store, selectedNodeIds).length > 0,
+ isEditMode &&
+ state.canCreateComponents &&
+ getExtractableNodeIds(store, removableNodeIds).length > 0,
canDelete:
isEditMode &&
- (selectedNodeIds.length > 0 || selectedConnectionIds.length > 0),
+ (removableNodeIds.length > 0 || selectedConnectionIds.length > 0),
componentToEdit: targetComponent?.intrinsicType ? null : targetComponent,
};
}
export function hasContextMenuItems(items: ContextMenuItems): boolean {
- return items.canExtract || items.canDelete || items.componentToEdit !== null;
+ return (
+ items.canExtract ||
+ items.canDelete ||
+ items.keptNodeNames.length > 0 ||
+ items.componentToEdit !== null
+ );
}
diff --git a/src/pages/edit/Editor/store/types.ts b/src/pages/edit/Editor/store/types.ts
index a3acc55..cb5ad00 100644
--- a/src/pages/edit/Editor/store/types.ts
+++ b/src/pages/edit/Editor/store/types.ts
@@ -1,12 +1,18 @@
import type { StoreApi } from "zustand";
import type CCStore from "../../../../store";
import type { CCComponentId } from "../../../../store/component";
+import type { CCNodeId } from "../../../../store/node";
+import type { OffersComponent } from "../../placement";
import type { ContextMenuStoreSlice } from "./slices/contextMenu/types";
import type { EditorStoreCoreSlice } from "./slices/core/types";
import type { PerspectiveStoreSlice } from "./slices/perspective/types";
export type ComponentEditorStoreValue = {
readonly componentId: CCComponentId;
+ readonly isProtectedNode: (nodeId: CCNodeId) => boolean;
+ readonly isOffered: OffersComponent;
+ readonly canCreateComponents: boolean;
+ readonly hasProperties: (componentId: CCComponentId) => boolean;
} & EditorStoreCoreSlice &
PerspectiveStoreSlice &
ContextMenuStoreSlice;
diff --git a/src/pages/edit/SidePanel.tsx b/src/pages/edit/SidePanel.tsx
index 5d97b98..fa9c0a2 100644
--- a/src/pages/edit/SidePanel.tsx
+++ b/src/pages/edit/SidePanel.tsx
@@ -4,16 +4,16 @@ import { useState } from "react";
import invariant from "tiny-invariant";
import { setDataTransferAsComponent } from "../../common/serialization";
import { useMessages } from "../../i18n";
-import { type CCComponentId, isIncluding } from "../../store/component";
+import type { CCComponentId } from "../../store/component";
import { ccPinTypes } from "../../store/componentPin";
import { useStore } from "../../store/react";
import { useComponents } from "../../store/react/selectors";
import { theme } from "../../style";
+import { canPlaceComponent, type OffersComponent } from "./placement";
export type SidePanelProps = {
editedComponentId: CCComponentId;
- /** the intrinsic components to offer, if not all of them */
- parts?: readonly CCComponentId[];
+ isOffered?: OffersComponent;
};
function ComponentRenderer({ componentId }: { componentId: CCComponentId }) {
@@ -90,7 +90,7 @@ function ComponentRenderer({ componentId }: { componentId: CCComponentId }) {
}
export default function SidePanel(sidePanelProps: SidePanelProps) {
- const { editedComponentId, parts } = sidePanelProps;
+ const { editedComponentId, isOffered = () => true } = sidePanelProps;
const { store } = useStore();
const messages = useMessages();
const components = useComponents();
@@ -119,16 +119,14 @@ export default function SidePanel(sidePanelProps: SidePanelProps) {
/>
{components
- .filter(
- (component) =>
- !parts ||
- !component.intrinsicType ||
- parts.includes(component.id),
- )
.filter((component) => component.name.includes(searchText))
- .filter((component) => component.id !== editedComponentId)
- .filter(
- (component) => !isIncluding(store, component.id, editedComponentId),
+ .filter((component) =>
+ canPlaceComponent(
+ store,
+ editedComponentId,
+ component.id,
+ isOffered,
+ ),
)
.map((component) => (
{
+ const anything = () => true;
+
+ it("places a component that exists and is offered", () => {
+ const store = createTestStore();
+ const edited = registerTestComponent(store, "Edited");
+
+ expect(
+ canPlaceComponent(store, edited.id, and.component.id, anything),
+ ).toBe(true);
+ expect(
+ canPlaceComponent(store, edited.id, and.component.id, () => false),
+ ).toBe(false);
+ });
+
+ it("refuses an id this store does not know, as from another tab", () => {
+ const store = createTestStore();
+ const edited = registerTestComponent(store, "Edited");
+
+ expect(
+ canPlaceComponent(
+ store,
+ edited.id,
+ "elsewhere" as CCComponentId,
+ anything,
+ ),
+ ).toBe(false);
+ });
+
+ it("refuses the edited component and those that use it", () => {
+ const store = createTestStore();
+ const edited = registerTestComponent(store, "Edited");
+ const user = registerTestComponent(store, "User");
+ registerTestNode(store, user.id, edited.id);
+
+ expect(canPlaceComponent(store, edited.id, edited.id, anything)).toBe(
+ false,
+ );
+ expect(canPlaceComponent(store, edited.id, user.id, anything)).toBe(false);
+ });
+});
diff --git a/src/pages/edit/placement.ts b/src/pages/edit/placement.ts
new file mode 100644
index 0000000..832a2b9
--- /dev/null
+++ b/src/pages/edit/placement.ts
@@ -0,0 +1,27 @@
+import type CCStore from "../../store";
+import {
+ type CCComponent,
+ type CCComponentId,
+ isIncluding,
+} from "../../store/component";
+
+export type OffersComponent = (
+ component: CCComponent,
+ editedComponentId: CCComponentId,
+) => boolean;
+
+// A drop can carry any id, e.g. one dragged from another tab
+export function canPlaceComponent(
+ store: CCStore,
+ editedComponentId: CCComponentId,
+ componentId: CCComponentId,
+ isOffered: OffersComponent,
+): boolean {
+ const component = store.components.get(componentId);
+ return (
+ !!component &&
+ component.id !== editedComponentId &&
+ !isIncluding(store, component.id, editedComponentId) &&
+ isOffered(component, editedComponentId)
+ );
+}
diff --git a/src/pages/tutorial/stage.tsx b/src/pages/tutorial/stage.tsx
index 169d9d7..15e67d7 100644
--- a/src/pages/tutorial/stage.tsx
+++ b/src/pages/tutorial/stage.tsx
@@ -30,10 +30,13 @@ import {
} from "../../tutorial/stageStore";
import {
findTutorialStage,
+ isStagePart,
+ isStagePinNode,
type TutorialStage,
tutorialStages,
} from "../../tutorial/stages";
import CCComponentEditor from "../edit/Editor";
+import type { OffersComponent } from "../edit/placement";
import SidePanel from "../edit/SidePanel";
function formatValue(value: SimulationValue, texts: Messages["tutorial"]) {
@@ -120,6 +123,9 @@ function StageView({ stage }: { stage: TutorialStage }) {
}
};
+ const isOffered: OffersComponent = (component, componentId) =>
+ isStagePart(stage, component, componentId);
+
const shownComponentId = store.components.get(editedComponentId)
? editedComponentId
: stage.componentId;
@@ -197,12 +203,21 @@ function StageView({ stage }: { stage: TutorialStage }) {
>
{texts.parts}
-
+
isStagePinNode(store, stage, nodeId),
+ isOffered,
+ canCreateComponents: stage.allowsNewComponents,
+ hasProperties: (componentId) => componentId !== stage.componentId,
+ }}
onEditComponent={setEditedComponentId}
onClose={() => {
if (shownComponentId === stage.componentId) navigate("/tutorial");
diff --git a/src/tutorial/check.test.ts b/src/tutorial/check.test.ts
index 4b58b79..0499f0d 100644
--- a/src/tutorial/check.test.ts
+++ b/src/tutorial/check.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it } from "vitest";
+import { extractNodesIntoNewComponent } from "../store/extractComponent";
import { and, not, or } from "../store/intrinsics/definitions";
import {
connectTestNodePins,
@@ -106,6 +107,30 @@ describe("checkCombinational", () => {
});
});
+ it("passes a circuit grouped into a component of the player's own", async () => {
+ const store = wireGate(andStage, and);
+ const gates = store.nodes
+ .getManyByParentComponentId(andStage.componentId)
+ .filter((node) => node.componentId === and.component.id);
+
+ await extractNodesIntoNewComponent(
+ store,
+ gates.map((node) => node.id),
+ "Mine",
+ );
+
+ expect(
+ store.nodes
+ .getManyByParentComponentId(andStage.componentId)
+ .some((node) => node.componentId === and.component.id),
+ ).toBe(false);
+ expect(
+ checkCombinational(store, andStage.componentId, andStage.check),
+ ).toEqual({
+ type: "passed",
+ });
+ });
+
it("tells the first inputs for which an output is wrong", () => {
const store = wireGate(andStage, or);
diff --git a/src/tutorial/check.ts b/src/tutorial/check.ts
index 13106ee..41a5fdc 100644
--- a/src/tutorial/check.ts
+++ b/src/tutorial/check.ts
@@ -56,11 +56,6 @@ function isSameValue(a: SimulationValue, b: SimulationValue | undefined) {
);
}
-/**
- * Simulate the component for every combination of its inputs and compare its outputs
- * with `check`. Its pins are found by name, as the player may have removed or renamed
- * the ones the stage placed.
- */
export function checkCombinational(
store: CCStore,
componentId: CCComponentId,
diff --git a/src/tutorial/stages.test.ts b/src/tutorial/stages.test.ts
new file mode 100644
index 0000000..086dd98
--- /dev/null
+++ b/src/tutorial/stages.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from "vitest";
+import { and, input, output, xor } from "../store/intrinsics/definitions";
+import {
+ createTestStore,
+ registerTestComponent,
+ registerTestNode,
+} from "../store/testUtils";
+import {
+ isStagePart,
+ isStagePinNode,
+ setUpTutorialStage,
+ tutorialStages,
+} from "./stages";
+
+const [stage] = tutorialStages;
+if (!stage) throw new Error("No stage");
+
+describe("isStagePinNode", () => {
+ it("tells the pins the stage placed from the nodes the player adds", () => {
+ const store = createTestStore();
+ setUpTutorialStage(store, stage, "Lamp");
+ const placed = store.nodes.getManyByParentComponentId(stage.componentId);
+ const gate = registerTestNode(store, stage.componentId, and.component.id);
+ const own = registerTestComponent(store, "Mine");
+ const pinOfOwn = registerTestNode(store, own.id, input.component.id);
+
+ expect(placed).toHaveLength(3);
+ for (const node of placed) {
+ expect(isStagePinNode(store, stage, node.id)).toBe(true);
+ }
+ expect(isStagePinNode(store, stage, gate.id)).toBe(false);
+ expect(isStagePinNode(store, stage, pinOfOwn.id)).toBe(false);
+ });
+});
+
+describe("isStagePart", () => {
+ it("offers the stage's parts and the components the player made", () => {
+ const store = createTestStore();
+ const own = registerTestComponent(store, "Mine");
+ const inStage = (component: Parameters[1]) =>
+ isStagePart(stage, component, stage.componentId);
+
+ expect(inStage(and.component)).toBe(true);
+ expect(inStage(own)).toBe(true);
+ expect(inStage(xor.component)).toBe(false);
+ expect(inStage(input.component)).toBe(false);
+ });
+
+ it("offers pins inside a component the player made", () => {
+ const store = createTestStore();
+ const own = registerTestComponent(store, "Mine");
+
+ expect(isStagePart(stage, input.component, own.id)).toBe(true);
+ expect(isStagePart(stage, output.component, own.id)).toBe(true);
+ expect(isStagePart(stage, xor.component, own.id)).toBe(false);
+ });
+});
diff --git a/src/tutorial/stages.ts b/src/tutorial/stages.ts
index 8fd175e..c086665 100644
--- a/src/tutorial/stages.ts
+++ b/src/tutorial/stages.ts
@@ -1,6 +1,10 @@
import nullthrows from "nullthrows";
import type CCStore from "../store";
-import { type CCComponentId, CCComponentStore } from "../store/component";
+import {
+ type CCComponent,
+ type CCComponentId,
+ CCComponentStore,
+} from "../store/component";
import type { CCComponentPin } from "../store/componentPin";
import { and, input, not, or, output } from "../store/intrinsics/definitions";
import { type CCNodeId, CCNodeStore } from "../store/node";
@@ -15,6 +19,7 @@ export type TutorialStage = {
componentId: CCComponentId;
/** the intrinsic components the side panel offers */
parts: readonly CCComponentId[];
+ allowsNewComponents: boolean;
/** also the input and output pins the stage starts with */
check: CombinationalCheck;
};
@@ -30,6 +35,7 @@ function twoSwitchesStage(
id,
componentId: `tutorial-${id}` as CCComponentId,
parts: [and.component.id, or.component.id, not.component.id],
+ allowsNewComponents: false,
check: {
inputs: [
{ name: "A", bitWidth: 1 },
@@ -52,6 +58,35 @@ export function findTutorialStage(id: string | undefined) {
return tutorialStages.find((stage) => stage.id === id);
}
+export function isStagePart(
+ stage: TutorialStage,
+ component: CCComponent,
+ editedComponentId: CCComponentId,
+) {
+ if (!component.intrinsicType || stage.parts.includes(component.id)) {
+ return true;
+ }
+ // A component of the player's own gets its pins from Input and Output nodes
+ return (
+ editedComponentId !== stage.componentId &&
+ (component.id === input.component.id ||
+ component.id === output.component.id)
+ );
+}
+
+export function isStagePinNode(
+ store: CCStore,
+ stage: TutorialStage,
+ nodeId: CCNodeId,
+): boolean {
+ const node = store.nodes.get(nodeId);
+ return (
+ node?.parentComponentId === stage.componentId &&
+ (node.componentId === input.component.id ||
+ node.componentId === output.component.id)
+ );
+}
+
function renamePinOfNode(
store: CCStore,
nodeId: CCNodeId,