Skip to content
10 changes: 10 additions & 0 deletions src/i18n/en.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { englishSimulationErrorTexts } from "../store/simulationErrorTexts";

const bitWidths = (widths: readonly number[]) => `${widths.join("/")} bit`;
const listOf = (names: readonly string[]) =>
names.length < 2
? names.join("")
: `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
const themOf = (names: readonly string[]) =>
names.length === 1 ? "it" : "them";

export const en = {
languageName: "English",
Expand Down Expand Up @@ -137,6 +143,10 @@ export const en = {
contextMenu: {
createComponent: "Create a new component...",
edit: "Edit...",
cannotDelete: (names: readonly string[]) =>
`${listOf(names)} cannot be deleted, as the stage uses ${themOf(names)}`,
keptOnDelete: (names: readonly string[]) =>
`${listOf(names)} ${names.length === 1 ? "is" : "are"} kept, as the stage uses ${themOf(names)}`,
},
frameControl: {
auto: "Auto",
Expand Down
2 changes: 2 additions & 0 deletions src/i18n/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ export const ja: Messages = {
contextMenu: {
createComponent: "新しいコンポーネントにまとめる...",
edit: "編集...",
cannotDelete: (names) => `${names.join("、")} は課題で使うので消せません`,
keptOnDelete: (names) => `${names.join("、")} は課題で使うので残ります`,
},
frameControl: {
auto: "自動",
Expand Down
25 changes: 25 additions & 0 deletions src/i18n/messages.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -112,3 +112,28 @@ describe("English messages", () => {
);
});
});

describe("the note on nodes a delete keeps", () => {
it("lists the nodes in a sentence", () => {
const { en, ja } = messagesByLanguage;

expect(en.editor.contextMenu.cannotDelete(["A"])).toBe(
"A cannot be deleted, as the stage uses it",
);
expect(en.editor.contextMenu.keptOnDelete(["A"])).toBe(
"A is kept, as the stage uses it",
);
expect(en.editor.contextMenu.keptOnDelete(["A", "Out"])).toBe(
"A and Out are kept, as the stage uses them",
);
expect(en.editor.contextMenu.cannotDelete(["A", "B", "Out"])).toBe(
"A, B and Out cannot be deleted, as the stage uses them",
);
expect(ja.editor.contextMenu.cannotDelete(["A"])).toBe(
"A は課題で使うので消せません",
);
expect(ja.editor.contextMenu.keptOnDelete(["A", "B", "Out"])).toBe(
"A、B、Out は課題で使うので残ります",
);
});
});
30 changes: 23 additions & 7 deletions src/pages/edit/Editor/components/ContextMenu.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import {
ClickAwayListener,
Divider,
ListItemText,
MenuItem,
MenuList,
Paper,
Expand Down Expand Up @@ -32,8 +33,9 @@ export default function CCComponentEditorContextMenu({
const items = getContextMenuItems(store, componentEditorState);
if (!hasContextMenuItems(items)) return null;
const {
selectedNodeIds,
selectedConnectionIds,
removableNodeIds,
keptNodeNames,
canExtract,
canDelete,
componentToEdit,
Expand All @@ -49,6 +51,7 @@ export default function CCComponentEditorContextMenu({
top: `${componentEditorState.contextMenuState.position.y}px`,
left: `${componentEditorState.contextMenuState.position.x}px`,
minWidth: "200px",
maxWidth: "280px",
}}
>
{/* <MenuItem onClick={componentEditorState.closeContextMenu}>
Expand All @@ -60,7 +63,7 @@ export default function CCComponentEditorContextMenu({
componentEditorState.closeContextMenu();
const newComponent = await extractNodesIntoNewComponent(
store,
selectedNodeIds,
removableNodeIds,
messages.common.newComponentName,
);
onComponentCreated(newComponent.id);
Expand All @@ -69,21 +72,34 @@ export default function CCComponentEditorContextMenu({
{messages.editor.contextMenu.createComponent}
</MenuItem>
)}
{canDelete && (
{(canDelete || keptNodeNames.length > 0) && (
<MenuItem
disabled={!canDelete}
onClick={() => {
if (selectedNodeIds.length > 0)
store.nodes.unregister(selectedNodeIds);
if (removableNodeIds.length > 0)
store.nodes.unregister(removableNodeIds);
if (selectedConnectionIds.length > 0)
store.connections.unregister(selectedConnectionIds);
componentEditorState.selectConnection([], true);
componentEditorState.closeContextMenu();
}}
>
{messages.common.delete}
<ListItemText
sx={{ m: 0 }}
slotProps={{ secondary: { sx: { whiteSpace: "normal" } } }}
primary={messages.common.delete}
secondary={
keptNodeNames.length === 0
? null
: canDelete
? messages.editor.contextMenu.keptOnDelete(keptNodeNames)
: messages.editor.contextMenu.cannotDelete(keptNodeNames)
}
/>
</MenuItem>
)}
{componentToEdit && (canExtract || canDelete) && <Divider />}
{componentToEdit &&
(canExtract || canDelete || keptNodeNames.length > 0) && <Divider />}
{componentToEdit && (
<MenuItem
onClick={() => {
Expand Down
16 changes: 9 additions & 7 deletions src/pages/edit/Editor/components/TitleBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,13 +54,15 @@ export default function CCComponentEditorTitleBar({
>
{component.name}
</Box>
<IconButton
size="small"
aria-label={messages.editor.editProperties}
onClick={onComponentPropertyDialogOpen}
>
<Edit fontSize="small" />
</IconButton>
{componentEditorState.hasProperties(component.id) && (
<IconButton
size="small"
aria-label={messages.editor.editProperties}
onClick={onComponentPropertyDialogOpen}
>
<Edit fontSize="small" />
</IconButton>
)}
<div aria-hidden style={{ flexGrow: 1 }} />
<IconButton
size="small"
Expand Down
7 changes: 4 additions & 3 deletions src/pages/edit/Editor/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,11 @@ import CCComponentEditorNotifications from "./components/Notifications";
import CCComponentEditorTitleBar from "./components/TitleBar";
import CCComponentEditorViewModeSwitcher from "./components/ViewModeSwitcher";
import CCComponentEditorRenderer from "./renderer";
import { ComponentEditorStoreProvider } from "./store";
import { ComponentEditorStoreProvider, type EditorStoreOptions } from "./store";

export type CCComponentEditorProps = {
componentId: CCComponentId;
options?: EditorStoreOptions;
onEditComponent: (componentId: CCComponentId) => void;
onClose: () => void;
};
Expand Down Expand Up @@ -74,9 +75,9 @@ function CCComponentEditorContent({
}

export default function CCComponentEditor(props: CCComponentEditorProps) {
const { componentId } = props;
const { componentId, options = {} } = props;
return (
<ComponentEditorStoreProvider componentId={componentId}>
<ComponentEditorStoreProvider componentId={componentId} options={options}>
<CCComponentEditorContent {...props} />
</ComponentEditorStoreProvider>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,14 @@ export function CCComponentEditorRendererNodeInterfaceRenderer(
{simulation === null ? (
<div className={styles.edit}>
<span className={styles.name}>{componentPin.name}</span>
<CCComponentEditorRendererNodeInterfaceRendererRenameButton
name={componentPin.name}
onNameChange={(name) =>
store.componentPins.update(componentPin.id, { name })
}
/>
{!editorState.isProtectedNode(props.node.id) && (
<CCComponentEditorRendererNodeInterfaceRendererRenameButton
name={componentPin.name}
onNameChange={(name) =>
store.componentPins.update(componentPin.id, { name })
}
/>
)}
</div>
) : (
<div className={styles.simulation}>
Expand Down
12 changes: 11 additions & 1 deletion src/pages/edit/Editor/renderer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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({
Expand Down
31 changes: 29 additions & 2 deletions src/pages/edit/Editor/store/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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<ComponentEditorStoreValue>((set, get) => ({
componentId,
isProtectedNode,
isOffered,
hasProperties,
canCreateComponents,
...coreSlice.define(set, get),
...perspectiveSlice.define(set, get),
...contextMenuSlice.define(set, get),
Expand All @@ -32,13 +54,18 @@ const context = createContext<ComponentEditorStore | null>(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 <context.Provider value={editorStore}>{children}</context.Provider>;
}

Expand Down
68 changes: 68 additions & 0 deletions src/pages/edit/Editor/store/slices/contextMenu/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();

Expand All @@ -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,
Expand Down Expand Up @@ -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,
});
});
});
Loading
Loading