|
| 1 | +import { useReactFlow } from "@xyflow/react"; |
| 2 | +import { useEffect } from "react"; |
| 3 | + |
| 4 | +import { useDialog } from "@/providers/DialogProvider/hooks/useDialog"; |
| 5 | +import { ESCAPE } from "@/routes/v2/shared/shortcuts/keys"; |
| 6 | +import { useSharedStores } from "@/routes/v2/shared/store/SharedStoreContext"; |
| 7 | + |
| 8 | +function hasReactFlowSelection( |
| 9 | + reactFlow: ReturnType<typeof useReactFlow>, |
| 10 | +): boolean { |
| 11 | + return ( |
| 12 | + reactFlow.getNodes().some((n) => n.selected) || |
| 13 | + reactFlow.getEdges().some((e) => e.selected) |
| 14 | + ); |
| 15 | +} |
| 16 | + |
| 17 | +/** |
| 18 | + * Centralized ESC handler for the editor. Priority: |
| 19 | + * 1. If a dialog is open, return false so Radix's portal handler closes it. |
| 20 | + * 2. Restore the front-most maximized window (if any). |
| 21 | + * 3. Otherwise clear ReactFlow + editor selection state. |
| 22 | + * Returns false when nothing applies, so the event keeps propagating. |
| 23 | + */ |
| 24 | +export function useEditorEscapeShortcut(): void { |
| 25 | + const { stack } = useDialog(); |
| 26 | + const { editor, keyboard, windows } = useSharedStores(); |
| 27 | + const reactFlow = useReactFlow(); |
| 28 | + |
| 29 | + useEffect(() => { |
| 30 | + const unregister = keyboard.registerShortcut({ |
| 31 | + id: "editor-escape", |
| 32 | + keys: [ESCAPE], |
| 33 | + label: "Dismiss / clear selection", |
| 34 | + allowInEditable: true, |
| 35 | + action: () => { |
| 36 | + if (stack.length > 0) return false; |
| 37 | + |
| 38 | + const front = windows.getFrontMaximizedWindow(); |
| 39 | + if (front) { |
| 40 | + front.restore(); |
| 41 | + return; |
| 42 | + } |
| 43 | + |
| 44 | + const rfSelected = hasReactFlowSelection(reactFlow); |
| 45 | + const editorSelected = editor.hasAnySelection; |
| 46 | + if (!rfSelected && !editorSelected) return false; |
| 47 | + |
| 48 | + editor.clearSelection(); |
| 49 | + if (rfSelected) { |
| 50 | + reactFlow.setNodes((ns) => |
| 51 | + ns.map((n) => (n.selected ? { ...n, selected: false } : n)), |
| 52 | + ); |
| 53 | + reactFlow.setEdges((es) => |
| 54 | + es.map((e) => (e.selected ? { ...e, selected: false } : e)), |
| 55 | + ); |
| 56 | + } |
| 57 | + }, |
| 58 | + }); |
| 59 | + return unregister; |
| 60 | + }, [editor, keyboard, reactFlow, stack, windows]); |
| 61 | +} |
0 commit comments