⚡ CodeMirror 6 Keymaps & Dispatch

🛠️ Command Specification

type Command = (view: EditorView) => boolean;
  • Pattern:
    1. Check state: if (view.state.readOnly) return false;
    2. Update & Dispatch: view.dispatch(view.state.update(...specs));
    3. Return true (handled) or false (ignored).

🎹 Keymap Binding

import { keymap } from "@codemirror/view";
 
const myKeymap = keymap.of([
  { 
    key: "Ctrl-Enter", 
    run: (view) => { /* command */ return true; },
    shift: (view) => { /* shift-fallback */ return true; },
    preventDefault: true 
  }
]);
  • key: Key/modifier sequence.
  • run: Primary command function.
  • shift: Run when Shift is pressed.
  • any: Fallback command for unmapped keys.

🚦 Precedence Order

Keys resolve highest to lowest. First to return true wins.

import { Prec } from "@codemirror/state";
 
// Resolution Hierarchy:
Prec.highest(keymap.of([...]))
Prec.high(keymap.of([...]))
keymap.of([...]) // Default
Prec.low(keymap.of([...]))
Prec.lowest(keymap.of([...]))

🔄 Dispatch Flow

graph LR
    A[Key Event/Call] --> B[view.dispatch]
    B --> C{dispatchEffect Facet?}
    C -- Yes --> D[Custom Dispatcher]
    C -- No --> E[State Update Interceptor]
    E --> F[Apply Transaction -> New State]