Duplicate, fit and deselect nodes from the keyboard in the node editor

The node editor only took Delete; Ctrl+D, F (also Home) and Esc now duplicate, show every node and clear the choice, and Backspace deletes. The keys are rebindable studio shortcuts, shown beside Duplicate and Delete in the node menu, and take precedence over the map's F while the editor is shown.

v3: 1c8af6484
This commit is contained in:
piexel committed 2026-11-10 13:08:05 +01:00
1 parent e2ebc7fe8a
commit dbfc1d0c34
4 files changed
+86 -25

No files matched your search

+17 -4
View File
@@ -1,9 +1,10 @@
import { Box, Circle, Flower2, GitCommitVertical, GitFork, Group, Link2, Paintbrush, Sparkles, type LucideIcon } from 'lucide-react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger } from '@/components/ui/context-menu'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { ContextMenu, ContextMenuContent, ContextMenuItem, ContextMenuSeparator, ContextMenuShortcut, ContextMenuSub, ContextMenuSubContent, ContextMenuSubTrigger, ContextMenuTrigger } from '@/components/ui/context-menu'
import { cn } from '@/lib/utils'
import type { GraphEdit, GraphNode, JsonPath } from '../bridge/types'
import { idOf, isWithin, layoutNodes, NODE_HEIGHT, NODE_WIDTH, type NodeLayout, type PlacedNode } from '../editor/nodeLayout'
import { useKeyText } from './useBindings'
const KIND_ICONS: Record<string, LucideIcon> = {
Object: Box,
@@ -48,18 +49,27 @@ interface NodeCanvasProps {
fileKey: string
selectedId: string | null
locked: boolean
/** Filled with the way to fit every node into view, for the keys that live outside the canvas. */
showAllRef: React.RefObject<(() => void) | null>
onSelect(node: GraphNode | null): void
onEdit(edit: GraphEdit): void
}
/** The file as a tree of nodes: drag the background to look around, drag a node onto another to grow it from there. */
export function NodeCanvas({ roots, fileKey, selectedId, locked, onSelect, onEdit }: NodeCanvasProps): React.JSX.Element {
export function NodeCanvas({ roots, fileKey, selectedId, locked, showAllRef, onSelect, onEdit }: NodeCanvasProps): React.JSX.Element {
const layout = useMemo(() => layoutNodes(roots), [roots])
const frame = useRef<HTMLDivElement>(null)
const [camera, setCamera] = useCamera(frame, layout, fileKey)
const [drag, setDrag] = useState<NodeDrag | null>(null)
const [menuNode, setMenuNode] = useState<GraphNode | null>(null)
const pan = useRef<{ x: number; y: number } | null>(null)
const showAll = useCallback(() => setCamera(fitted(frame.current!, layout)), [setCamera, layout])
useEffect(() => {
showAllRef.current = showAll
return () => {
showAllRef.current = null
}
}, [showAllRef, showAll])
const canvasPoint = (clientX: number, clientY: number): { x: number; y: number } => {
const bounds = frame.current!.getBoundingClientRect()
@@ -138,7 +148,7 @@ export function NodeCanvas({ roots, fileKey, selectedId, locked, onSelect, onEdi
onSelect(placed.node)
}
}}
onDoubleClick={(event) => nodeAt(layout, canvasPoint(event.clientX, event.clientY)) === null && setCamera(fitted(frame.current!, layout))}
onDoubleClick={(event) => nodeAt(layout, canvasPoint(event.clientX, event.clientY)) === null && showAll()}
>
<div className="absolute top-0 left-0 origin-top-left" style={{ transform: `translate(${camera.x}px, ${camera.y}px) scale(${camera.scale})` }}>
<Wires layout={layout} />
@@ -211,6 +221,7 @@ function Wires({ layout }: { layout: NodeLayout }): React.JSX.Element {
}
function NodeMenu({ node, locked, onEdit }: { node: GraphNode; locked: boolean; onEdit(edit: GraphEdit): void }): React.JSX.Element {
const keyText = useKeyText()
const removable = node.duplicable
return (
<ContextMenuContent className="min-w-[180px]">
@@ -228,10 +239,12 @@ function NodeMenu({ node, locked, onEdit }: { node: GraphNode; locked: boolean;
)}
<ContextMenuItem disabled={locked || !node.duplicable} onSelect={() => onEdit({ op: 'duplicate', path: node.path })}>
Duplicate
<ContextMenuShortcut>{keyText('duplicateNode')}</ContextMenuShortcut>
</ContextMenuItem>
<ContextMenuSeparator />
<ContextMenuItem variant="destructive" disabled={locked || !removable} onSelect={() => onEdit({ op: 'delete', path: node.path })}>
Delete
<ContextMenuShortcut>{keyText('deleteNode')}</ContextMenuShortcut>
</ContextMenuItem>
</ContextMenuContent>
)
+33 -18
View File
@@ -1,10 +1,10 @@
import { Lock, Redo2, Undo2 } from 'lucide-react'
import { useEffect } from 'react'
import { useEffect, useRef } from 'react'
import { Button } from '@/components/ui/button'
import type { GraphNode } from '../bridge/types'
import type { NodeEditor } from '../editor/useNodeEditor'
import { NodeCanvas } from './NodeCanvas'
import { isTypingInto, matches } from './shortcuts'
import { isTypingInto, nodeEditorActionFor, type NodeEditorAction } from './shortcuts'
import { useBindings } from './useBindings'
interface NodePaneProps {
@@ -19,7 +19,8 @@ interface NodePaneProps {
export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps): React.JSX.Element {
const { state } = editor
const locked = state === null || state.locked !== null
useEditorKeys(editor, selected, locked)
const showAllRef = useRef<(() => void) | null>(null)
useEditorKeys(editor, selected, locked, showAllRef, onSelect)
return (
<section className="flex min-h-0 flex-[9] flex-col border-t">
@@ -55,6 +56,7 @@ export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps
fileKey={entryKey}
selectedId={selected === null ? null : JSON.stringify(selected.path)}
locked={locked}
showAllRef={showAllRef}
onSelect={onSelect}
onEdit={editor.edit}
/>
@@ -64,29 +66,42 @@ export function NodePane({ editor, entryKey, selected, onSelect }: NodePaneProps
)
}
function useEditorKeys(editor: NodeEditor, selected: GraphNode | null, locked: boolean): void {
function useEditorKeys(
editor: NodeEditor,
selected: GraphNode | null,
locked: boolean,
showAllRef: React.RefObject<(() => void) | null>,
onSelect: (node: GraphNode | null) => void
): void {
const { undo, redo, edit } = editor
const bindings = useBindings()
useEffect(() => {
if (locked) {
return
}
const down = (event: KeyboardEvent): void => {
if (isTypingInto(event.target)) {
return
}
if (matches(event, 'undo', bindings)) {
const editSelected = (action: NodeEditorAction, event: KeyboardEvent): void => {
if (action === 'undo') {
event.preventDefault()
undo()
} else if (matches(event, 'redo', bindings)) {
} else if (action === 'redo') {
event.preventDefault()
redo()
} else if (event.key === 'Delete' && selected !== null && selected.duplicable) {
} else if (selected !== null && selected.duplicable) {
event.preventDefault()
edit({ op: 'delete', path: selected.path })
edit({ op: action === 'deleteNode' ? 'delete' : 'duplicate', path: selected.path })
}
}
window.addEventListener('keydown', down)
return () => window.removeEventListener('keydown', down)
}, [undo, redo, edit, selected, locked, bindings])
// Captured, so the editor's keys come before the window's own: F fits the nodes instead of following the player.
const down = (event: KeyboardEvent): void => {
const action = isTypingInto(event.target) ? null : nodeEditorActionFor(event, bindings)
if (action === 'dismiss') {
onSelect(null)
} else if (action === 'showAllNodes' && showAllRef.current !== null) {
event.preventDefault()
event.stopImmediatePropagation()
showAllRef.current()
} else if (action !== null && action !== 'showAllNodes' && !locked) {
editSelected(action, event)
}
}
window.addEventListener('keydown', down, true)
return () => window.removeEventListener('keydown', down, true)
}, [undo, redo, edit, selected, locked, bindings, showAllRef, onSelect])
}
@@ -8,6 +8,7 @@ import {
isChord,
keyTextOf,
matches,
nodeEditorActionFor,
sanitizeBindings,
shortcutRows,
viewShortcutId,
@@ -84,6 +85,24 @@ describe('shortcuts', () => {
expect(matches(press('Control', { ctrlKey: true }), 'undo', {})).toBe(false)
})
it('finds the node editor action of a key press, by default and once rebound', () => {
expect(nodeEditorActionFor(press('d', { ctrlKey: true }), {})).toBe('duplicateNode')
expect(nodeEditorActionFor(press('F'), {})).toBe('showAllNodes')
expect(nodeEditorActionFor(press('Home'), {})).toBe('showAllNodes')
expect(nodeEditorActionFor(press('Escape'), {})).toBe('dismiss')
expect(nodeEditorActionFor(press('Delete'), {})).toBe('deleteNode')
expect(nodeEditorActionFor(press('Backspace'), {})).toBe('deleteNode')
expect(nodeEditorActionFor(press('d'), {})).toBeNull()
expect(nodeEditorActionFor(press('f'), { showAllNodes: ['a'] })).toBeNull()
expect(nodeEditorActionFor(press('a'), { showAllNodes: ['a'] })).toBe('showAllNodes')
})
it('keeps the node editor keys out of the map shortcuts, which share F', () => {
expect(windowShortcutFor(press('f'), ROWS, {})).toBe('follow')
expect(ROWS.find((row) => row.id === 'showAllNodes')!.group).toBe('Node editor')
expect(clashesWith(ROWS.find((row) => row.id === 'showAllNodes')!, 'f', ROWS, {})).toEqual([])
})
it('reports the shortcuts a new key would clash with, only where both work together', () => {
const grid = ROWS.find((row) => row.id === 'grid')!
const undo = ROWS.find((row) => row.id === 'undo')!
+17 -3
View File
@@ -15,6 +15,9 @@ export type ShortcutAction =
| 'help'
| 'undo'
| 'redo'
| 'deleteNode'
| 'duplicateNode'
| 'showAllNodes'
export type ShortcutGroup = 'Views' | 'Everywhere' | 'Map' | 'Node editor'
@@ -46,7 +49,7 @@ export const SHORTCUTS: ShortcutDefinition[] = [
{ id: 'zoomIn', label: 'Zoom in', group: 'Everywhere', chords: ['=', '+'] },
{ id: 'zoomOut', label: 'Zoom out', group: 'Everywhere', chords: ['-'] },
{ id: 'resetZoom', label: 'Reset zoom', group: 'Everywhere', chords: ['\\'] },
{ id: 'dismiss', label: 'Clear the highlight', group: 'Everywhere', chords: ['Escape'] },
{ id: 'dismiss', label: 'Clear the highlight or the chosen node', group: 'Everywhere', chords: ['Escape'] },
{ id: 'follow', label: 'Follow your player', group: 'Map', chords: ['f'] },
{ id: 'grid', label: 'Chunk and region grid', group: 'Map', chords: ['g'] },
{ id: 'entities', label: 'Show entities', group: 'Map', chords: ['e'] },
@@ -55,7 +58,10 @@ export const SHORTCUTS: ShortcutDefinition[] = [
{ id: 'borders', label: 'Region borders', group: 'Map', chords: ['b'] },
{ id: 'help', label: 'Show the shortcuts', group: 'Map', chords: ['/', '?'] },
{ id: 'undo', label: 'Undo', group: 'Node editor', chords: ['ctrl+z'] },
{ id: 'redo', label: 'Redo', group: 'Node editor', chords: ['ctrl+y', 'ctrl+shift+z'] }
{ id: 'redo', label: 'Redo', group: 'Node editor', chords: ['ctrl+y', 'ctrl+shift+z'] },
{ id: 'deleteNode', label: 'Delete the chosen node', group: 'Node editor', chords: ['Delete', 'Backspace'] },
{ id: 'duplicateNode', label: 'Duplicate the chosen node', group: 'Node editor', chords: ['ctrl+d'] },
{ id: 'showAllNodes', label: 'Show every node', group: 'Node editor', chords: ['f', 'Home'] }
]
/** The key of each view; 4 stays free for the 3D world, as in v3e. */
@@ -88,7 +94,10 @@ const GROUP_SCOPES: Record<ShortcutGroup, { windowWide: boolean; nodeEditor: boo
'Node editor': { windowWide: false, nodeEditor: true }
}
const VIEW_ID_PREFIX = 'view:'
const NODE_EDITOR_ACTIONS = ['undo', 'redo', 'deleteNode', 'duplicateNode', 'showAllNodes', 'dismiss'] as const
export type NodeEditorAction = (typeof NODE_EDITOR_ACTIONS)[number]
const VIEW_ID_PREFIX ='view:'
const MODIFIER_PREFIXES = ['ctrl+', 'alt+', 'shift+'] as const
const MODIFIER_KEYS = new Set(['Control', 'Shift', 'Alt', 'Meta', 'AltGraph', 'CapsLock', 'Dead', 'Unidentified'])
const KEY_NAMES: Record<string, string> = { Escape: 'Esc', ' ': 'Space' }
@@ -185,6 +194,11 @@ export function windowShortcutFor(press: KeyPress, rows: ShortcutRow[], bindings
return rows.filter((row) => GROUP_SCOPES[row.group].windowWide).find((row) => chordsOf(row.id, bindings).includes(chord))?.id ?? null
}
/** The node editor shortcut a key press triggers, if any. */
export function nodeEditorActionFor(press: KeyPress, bindings: Bindings): NodeEditorAction | null {
return NODE_EDITOR_ACTIONS.find((action) => matches(press, action, bindings)) ?? null
}
/** The other shortcuts the chord already triggers where {@code row} works too. */
export function clashesWith(row: ShortcutRow, chord: Chord, rows: ShortcutRow[], bindings: Bindings): ShortcutRow[] {
return rows.filter((other) => other.id !== row.id && sharesKeys(row.group, other.group) && chordsOf(other.id, bindings).includes(chord))