Tom MacWright

tom@macwright.com

Code-folding JSX elements in CodeMirror

This came up for Val Town - we implemented code folding in our default editor which uses CodeMirror, but wanted it to work with JSX elements, not just functions and control flow statements. It’s not enough to justify a module of its own because CodeMirror’s API is unbelievably well-designed:

import {
  tsxLanguage,
} from "@codemirror/lang-javascript";
import {
  foldInside,
  foldNodeProp,
} from "@codemirror/language";

/** tsxLanguage, with code folding for jsx elements */
tsxLanguage.configure({
  props: [
    foldNodeProp.add({
      JSXElement: foldInside,
    }),
  ],
})

Then you can plug that into a LanguageSupport instance and use it. Amazing.