⚡ CodeMirror 6 Architecture Cheat Sheet

🏗️ Core Architecture: State vs. View

[ User/System Event ] 
        │
        ▼
   Transaction (State Transition) ──► Produces ──► New EditorState (Immutable)
        │                                                │
        ▼                                                ▼
   EditorView (DOM) ◄────────────── Updates ─────────────┘
  • EditorState (Immutable Data)
    • 📄 doc: Current document text.
    • 📍 selection: Cursor position(s) and ranges.
    • 🔌 facets / extensions: Configuration and plugins.
  • EditorView (Mutable DOM)
    • 👁️ Renders the current state to the screen.
    • 👂 Handles DOM events (clicks, keypresses).
    • 📨 Dispatches transactions.
  • Transaction (State Transitions)
    • ⚠️ Rule: State is never mutated directly. Changes are dispatched as transactions to produce a new state.

📦 Core Package Matrix

  • 📦 @codemirror/state ── Core primitives (EditorState, Transaction, Selection).
  • 📦 @codemirror/view ── DOM display, event handling, and layout (EditorView, Decoration).
  • 📦 @codemirror/language ── Syntax parsing trees, foldings, and language definitions (LRLanguage).
  • 📦 @codemirror/commands ── Standard editing actions (keymaps, cursor movement, deletion).

🚀 Minimal Implementation

import { EditorState } from "@codemirror/state";
import { EditorView, keymap } from "@codemirror/view";
import { defaultKeymap } from "@codemirror/commands";
 
const state = EditorState.create({
  doc: "Hello World",
  extensions: [keymap.of(defaultKeymap)]
});
 
const view = new EditorView({
  state,
  parent: document.body
});
 
// Update State via Transaction
view.dispatch({
  changes: { from: 0, insert: "⚡ " }
});