Zenn Tech Blog

iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🪞

How to Build Zenn's Markdown Editor with CodeMirror v6

に公開

For Zenn, we use the CodeMirror library as the foundation for our Markdown editor used in "Articles" and "Book Chapters." Previously, we used CodeMirror v5 (or more precisely, a wrapper library dependent on v5), but we decided to upgrade to CodeMirror v6 to eliminate the risks of continuing to use an outdated version and to gain greater extensibility for our editor.

In this article, I will introduce everything from basic knowledge of CodeMirror v6 to how to customize it to implement Zenn's Markdown editor.

Basic Knowledge of CodeMirror

Introduction

CodeMirror is a library for implementing code editors on the Web. It comes equipped with features necessary for a modern code editor by default, such as syntax highlighting for many programming languages, auto-completion, code folding, keymaps, and multi-cursors. You can also add or modify features using various extensions and plugins.

To achieve this extensibility, the CodeMirror library is divided into several core modules and many extension modules. To build an editor tailored to your preferences, it is beneficial to understand the fundamental system design of CodeMirror.

For that, first read the System Guide in the documentation. Grabbing the overall picture of the system by reading this will make other documentation, such as Examples and the Reference Manual, much easier to understand.

CodeMirror System

To proceed with this article, I will roughly explain the most important parts of the CodeMirror system within the scope of my understanding.

Core Modules and Design Philosophy

CodeMirror's core modules are divided into the following three parts:

  • @codemirror/state
  • @codemirror/view
  • @codemirror/commands

state defines the state of the editor and the data structures used to update that state. view is a component that displays the editor state and converts user interactions into data structures that update the state. command defines many editing commands and their key bindings.

Editor state (state) is immutable; even when the editor transitions to a new state, the old state remains as is. This makes handling changes to the editor state easier. Additionally, operations related to the state are provided as pure functions.

State Management and Updates

This is the general data flow during user interactions as introduced in the System Guide's State and Updates section.

Think of view as the editor displayed in the browser. The view holds a state called state, and it renders the content of state to the browser. The view monitors DOM events (such as cursor movement or key inputs), and when an event occurs, it creates data to update the state, called a transaction. When a new state (new state) is dispatched from the transaction to the view, the view's state is updated and rendered.

Understanding this flow is useful when you want to customize editor behavior through "extensions."

Extensions

CodeMirror's core functionality is kept to a minimum, and many features are provided as extensions. It is explained that extensions can do anything from simple option settings to defining new fields in the state object, setting editor styles, or injecting custom instruction components into the view.

Systemically speaking, extensions can intervene in the transaction or new state of the data flow mentioned above to customize user interactions, or intervene in the view's rendering rules to customize the display.

Extensions are also managed as part of the state and can be changed dynamically.

Preparing to Use CodeMirror with React

Minimal Hook Implementation

Since Zenn is implemented in React, we will first create a Hook to make CodeMirror easier to use with React. Here, we implement a hook called useMarkdownEditor.

Implementation of the hook
export const useMarkdownEditor = (props: UseMarkdownEditorProps) => {
  const editor = useRef(null); // ref for the parent element of EditorView
  const [container, setContainer] = useState<HTMLDivElement>();
  const [view, setView] = useState<EditorView>();

  // Set the editor ref to the container
  useEffect(() => {
    if (editor.current) {
      setContainer(editor.current);
    }
  }, [setContainer]);

  // Initialize the view
  useEffect(() => {
    if (!view && container) {
      const state = EditorState.create();
      const viewCurrent = new EditorView({
        state,
        parent: container,
      });
      setView(viewCurrent);
    }
  }, [view, container]);

  return {
    editor
  };
};
Implementation of the component
  const { editor } = useMarkdownEditor({});

  return (
    <div ref={editor} />
  );

This is a minimal implementation, but CodeMirror will now appear inside the component's div element. In this state, it doesn't look much different from an HTML textarea.


Minimal state

Initializing and Saving Text

By adding functions to the hook, we will add features to load text into the editor and save edited text on the component side.

Implementation of the hook
export const useMarkdownEditor = ({
  doc,
  setDoc,
}: UseMarkdownEditorProps) => {

  // Process when the editor state is updated
  const updateListener = useMemo(() => {
    return EditorView.updateListener.of((update: ViewUpdate) => {
      if (update.docChanged) {
        // Update doc every time the editor text changes
        setDoc(update.state.doc.toString());
      }
    });
  }, [setDoc]);

  // Initialize the view
  useEffect(() => {
    if (!view && container) {
      const state = EditorState.create({
        doc, // Set doc as the initial value of the editor
        extensions: [updateListener],
      });
      const viewCurrent = new EditorView({
        state,
        parent: container,
      });
      setView(viewCurrent);
    }
  }, [view, container, doc, updateListener]);

  return {
    editor
  };
};

Now that the doc defined in useState is synchronized with the editor text, you can implement features to save the doc at any time on the component side.

Implementation of the component
  const [doc, setDoc] = useState<null | string>(null);
  
  const save = useCallback(() => {
    // Save the doc here
  }, [doc]);

  const { editor } = useMarkdownEditor({
    doc,
    setDoc,
  });

  return (
    <div ref={editor} />
  );

(Aside) You can also use react-codemirror if you want to create a code editor with React

To handle CodeMirror with React, we initially used react-codemirror, a wrapper library for CodeMirror v6. react-codemirror provides a hook called useCodeMirror.

In react-codemirror, an extension called basicSetup, which "combines several extensions to create a decent code editor from the start," is enabled by default, and for Zenn's Markdown editor, we needed to disable most of these items. Also, we wanted to avoid depending on library features as much as possible in other areas, so we eventually implemented the hook ourselves, removing the dependency on this library.

That said, the source code of react-codemirror was very helpful for learning how to turn CodeMirror into a hook and how to customize it.

How to build Zenn's Markdown Editor

From here on, I will introduce the main customizations for Zenn's Markdown editor using CodeMirror extensions.

The main customizations are as follows:

  • Keymaps (shortcut keys) and registering their corresponding processes
  • Image upload functionality via drag-and-drop or pasting
  • Markdown syntax highlighting
  • Editor style configuration
  • Settings for standard provided extensions (options)

I will explain how to implement these one by one.

Registering Keymaps (Shortcut Keys)

At Zenn, we enable saving by pressing Ctrl+s (Cmd+s on macOS) while operating the editor. In CodeMirror, you can implement shortcut keys by registering a keymap.

Implementation of the component
  const { editor } = useMarkdownEditor({
    doc,
    setDoc,
    save, // Add function to save doc
  });
Implementation of the hook
export const useMarkdownEditor = ({
  doc,
  setDoc,
  save,
}: UseMarkdownEditorProps) => {

  // Keymap settings inside the Editor
  const customKeymap = useMemo(() => {
    return keymap.of([
      {
        // Save document
        key: 'Mod-s',
        run() {
          save();
          return true;
        },
      },
    ]);
  }, [save]);

  // Grouping Editor extensions
  const extensions = useMemo(() => {
    return [
      updateListener,
      customKeymap,
    ];
  }, [customKeymap, updateListener]);

  // Initialize the view
  useEffect(() => {
    if (!view && container && doc) {
      const state = EditorState.create({
        doc,
        extensions,
      });
      const viewCurrent = new EditorView({
        state,
        parent: container,
      });
      setView(viewCurrent);
    }
  }, [view, container, doc, extensions]);

  // Update extensions
  useEffect(() => {
    if (view) {
      view.dispatch({ effects: StateEffect.reconfigure.of(extensions) });
    }
  }, [view, extensions]);

};

We create an extension for keymaps using keymap.of. Mod-s represents Ctrl+s (or Cmd+s on macOS). We set the function to be executed when the shortcut is pressed in run. Here, we execute the save function. By returning true, preventDefault and stopPropagation are executed.

Since the number of dependencies for extensions has increased, we grouped them into useMemo. When the content of the extensions is updated, we update them via view.dispatch. This allows us to dynamically change the editor's extensions.

In the Zenn editor, we have implemented several other features as shortcut keys. We add the following keymaps to the aforementioned keymap.of.

Implementation of the hook
      {
        // Toggle between preview and edit mode
        key: 'Mod-p',
        run() {
          togglePreview();
          return true;
        },
      },
      {
        // Toggle display of embed modal
        key: 'Mod-i',
        run() {
          toggleInsert();
          return true;
        },
      },
      {
        // Set/unset Bold
        key: 'Mod-b',
        run(view) {
          const range = view.state.selection.main;
          if (
            view.state.sliceDoc(range.from, range.from + 2) == '**' &&
            view.state.sliceDoc(range.to - 2, range.to) == '**'
          ) {
            const transaction = view.state.update({
              changes: {
                from: range.from,
                to: range.to,
                insert: view.state.sliceDoc(range.from + 2, range.to - 2),
              },
            });
            view.dispatch(transaction);
          } else {
            const transaction = view.state.update({
              changes: {
                from: range.from,
                to: range.to,
                insert: `**${view.state.sliceDoc(range.from, range.to)}**`,
              },
            });
            view.dispatch(transaction);
          }
          return true;
        },
      },

Mod-p and Mod-i control components outside the editor. Mod-b updates the text inside the editor. Since view is passed as an argument to run, we use it to get the current selection, create a transaction with the update, and call view.dispatch to update the text.


Mod-b, Mod-i, and Mod-p in action (also applying "Inserting text from outside" explained next)

Inserting text from outside

To insert text at the cursor position from the embed modal, we provide the following function from the hook:

Implementation of the hook
  // Insert text at the editor cursor position
  const insertTextToEditor = useCallback(
    (text: string) => {
      if (!view) return;

      const transaction = view.state.update({
        changes: {
          from: view.state.selection.main.head,
          insert: text,
        },
      });
      view.dispatch(transaction);
    },
    [view]
  );

  return {
    editor,
    focusToEditor,
    insertTextToEditor,
  };

view.state.selection indicates the current cursor position. While CodeMirror supports multi-cursors and multiple selections, Zenn does not use multi-cursors, so we retrieve the cursor position using main.

Problems encountered

We encountered an issue where the scroll position returned to the top after opening the embed modal via keymap and closing it. As a workaround, we solved this by focusing on the editor when the modal is closed.

Implementation of the hook
  // Focus the editor
  const focusToEditor = useCallback(() => {
    if (!view) return;
    view.focus();
  }, [view]);

  return {
    editor,
    focusToEditor,
  };

The cause is unknown, but we speculate that some event (state update) occurs in the editor when opening the modal via keymap, and because the editor loses focus when the modal is closed, it fails to calculate the correct scroll position and returns to the top.

When unknown issues occur like this, tracing the events occurring in the editor might provide clues.

Implementation of the hook
  // Add this to extensions
  const updateListener = EditorView.updateListener.of((update) => {
    console.log('update', update);
  });

Image Upload

In the Zenn editor, in addition to the image upload button, we allow image uploads by "dropping images into the editor" and "pasting images." These can be achieved by handling the editor's DOM events.

Implementation of the hook
  // Event handler for events occurring within the Editor (add to extensions)
  const eventHandlers = useMemo(
    () =>
      EditorView.domEventHandlers({
        // Processing when image files are dragged and dropped
        // ref: https://developer.mozilla.org/ja/docs/Web/API/HTML_Drag_and_Drop_API/File_drag_and_drop#%E3%83%89%E3%83%AD%E3%83%83%E3%83%97%E3%81%AE%E5%87%A6%E7%90%86
        drop(event, view) {
          if (!event.dataTransfer) return;

          const insertText = (url: string) => {
            // Get the cursor position where the event occurred
            const cursorPos = view.posAtCoords({
              x: event.pageX,
              y: event.pageY,
            });
            const insertText = `![](${url})`;
            const transaction = view.state.update({
              changes: {
                from: cursorPos || 0,
                insert: insertText,
              },
            });
            view.dispatch(transaction);
          };

          // Access files using DataTransferItemList interface
          if (event.dataTransfer.items) {
            for (let i = 0; i < event.dataTransfer.items.length; i++) {
              const item = event.dataTransfer.items[i];
              // Reject if dropped item is not a file
              if (item.kind === 'file') {
                const file = item.getAsFile();
                if (!file) return;

                imageUpload(file, (url) => {
                  insertText(url);
                });
              }
            }
          } else {
            // Access files using DataTransfer interface
            for (let i = 0; i < event.dataTransfer.files.length; i++) {
              const file = event.dataTransfer.files[i];

              imageUpload(file, (url) => {
                insertText(url);
              });
            }
          }
        },

        // Processing when image files are pasted
        paste(event, view) {
          if (!event.clipboardData?.files?.length) return;

          for (let i = 0; i < event.clipboardData.files.length; i++) {
            const file = event.clipboardData.files[i];

            imageUpload(file, (url) => {
              const insertText = `![](${url})`;
              const transaction = view.state.update({
                changes: {
                  from: view.state.selection.main.head,
                  insert: insertText,
                },
              });
              view.dispatch(transaction);
            });
          }
        },
      }),
    [imageUpload]
  );

We wrote drop and paste event handlers. The imageUpload function is one that uploads an image file and calls a callback function passing the file's URL as an argument. In the drop event, we obtain the cursor position on the browser from the DOM event, determine the position in the editor using view.posAtCoords, and insert the image URL there.


First attempt is drag-and-drop, second is copy-and-paste.

Styling Markdown Syntax

To style (syntax highlight) the Markdown syntax in the editor, two processes are necessary: "parsing the syntax via a Markdown parser" and "applying styles to the syntax."

Parsing syntax via the markdown extension

CodeMirror provides extensions for various programming languages, which allow text in the editor to be parsed. Since Zenn's editor is a Markdown editor, we add lang-markdown.

Implementation of the hook
  // Editor extensions
  const extensions = useMemo(() => {
    return [
      markdown({
        // Set markdown parser to GFM(https://github.github.com/gfm/).
        // Allows styling of syntax not found in CommonMark.
        base: markdownLanguage,
        completeHTMLTags: false, // Disable autocomplete for HTML tags
      }),
    ];
  }, []);

Applying styles to syntax

To apply styles to the syntax, we use the syntaxHighlighting extension. In Zenn's editor, we set the Markdown syntax styles as follows:

Implementation of the hook
  // Markdown syntax highlighting settings
  const highlightStyle = HighlightStyle.define([
    { tag: tags.heading1, color: 'black', fontSize: '1.4em', fontWeight: '700' },
    { tag: tags.heading2, color: 'black', fontSize: '1.3em', fontWeight: '700' },
    { tag: tags.heading3, color: 'black', fontSize: '1.2em', fontWeight: '700' },
    { tag: tags.heading4, color: 'black', fontSize: '1.1em', fontWeight: '700' },
    { tag: tags.strong, color: 'black', fontWeight: '700' }, // Bold
    { tag: tags.quote, color: '#6a737d' }, // Quote
    { tag: tags.emphasis, fontStyle: 'italic' }, // Italic
    { tag: tags.url, textDecoration: 'underline' }, // Underline URLs
    { tag: tags.strikethrough, textDecoration: 'line-through' }, // Strikethrough (GFM extension)
  ]);

  // Editor extensions
  const extensions = useMemo(() => {
    return [
      syntaxHighlighting(highlightStyle),
      markdown({
        base: markdownLanguage,
        completeHTMLTags: false,
      }),
    ];
  }, []);


Real-time syntax highlighting applied

Setting Editor CSS

Editor styles are set using a theme extension. In themes, styles are set using CSS-in-JS. Naturally, these can also be changed dynamically.

Implementation of the hook
  const editorStyle = useMemo(() => {
    return EditorView.theme({
      '&': {
        minHeight: '500px',
      },
      // Editor frame
      '&.cm-editor': {
        outline: 'none', // Hide editor outline
      },
      // Editor interior
      '&.cm-editor .cm-scroller': {
        fontFamily: `'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace, 'Segoe UI Emoji'`,
        '-webkit-font-smoothing': 'antialiased',
        letterSpacing: '0.02em',
        fontSize: '15px',
        lineHeight: '1.8',
        color: '#000000',
      },
      // Selection background color
      '.cm-selectionBackground': {
        backgroundColor: '#036dd626 !important',
      },
    });
  }, []);

  // Editor extensions
  const extensions = useMemo(() => {
    return [
      editorStyle,
    ];
  }, [editorStyle]);

Other Extensions

Additionally, we use standard CodeMirror extensions to adjust editor functionality.

Implementation of the hook
  // Editor extensions
  const extensions = useMemo(() => {
    return [
      placeholder('Write in markdown'),
      history(), // Enable undo/redo
      keymap.of(defaultKeymap), // Enable defaultKeymap
      keymap.of(historyKeymap), // Enable historyKeymap
      keymap.of([indentWithTab]), // Bind tab key to increase/decrease indentation.
      indentUnit.of('    '), // Set indentation unit to 4 spaces.
      EditorView.lineWrapping, // Enable text wrapping
      EditorState.tabSize.of(4), // Set Tab (\t) size to 4 spaces
    ];
  }, []);

Conclusion

I wrote this article because I had a hard time finding specific information when I started researching CodeMirror v6, making it difficult to understand how to use the library. While the content of this article only scratches the surface of CodeMirror, I hope it will be helpful for those who are about to build an editor using CodeMirror v6.

Zenn's Markdown editor will continue development, aiming to further improve the writing experience. Stay tuned!

GitHubで編集を提案
Zenn Tech Blog
Zenn Tech Blog

Discussion