@uiw/react-codemirror

repository·master·Indexed 25 days ago

https://github.com/uiwjs/react-codemirror

A CodeMirror 6 component for React that provides a collection of extensions for features like hyperlink detection, syntax highlighting, and UI decorations. It includes the useCodeMirror hook for lifecycle management, a basicSetup helper for common editor behaviors, and specialized extensions for color pickers and dynamic CSS line classes. The library supports themes, read-only modes, and state restoration via JSON.

Tokens
34.9K
Snippets
59
Records
187
Agent score
75%

What's inside @uiw/react-codemirror

  1. Avoid echoing remote changes with ExternalChange

    master

    When synchronizing the editor state with an external source (like a remote collaborator), you can prevent the onChange handler from triggering an infinite loop by marking transactions with the ExternalChange annotation.

    When useCodeMirror dispatches a change to match the value prop, it automatically attaches the ExternalChange annotation. The internal updateListener checks for this annotation and skips calling the user-provided onChange callback if it is present, ensuring that programmatic updates from the parent don't trigger a feedback loop.

  2. Handle DOM events in CodeMirror with @uiw/codemirror-extensions-events

    master

    The @uiw/codemirror-extensions-events package provides utilities to bind standard HTML events to specific parts of the CodeMirror editor DOM. You can target three different DOM layers:

    • scroll: The DOM element that wraps the entire editor view (view.scrollDOM).
    • dom: The DOM element that can be styled to scroll (view.dom).
    • content: The editable DOM element holding the editor content (view.contentDOM). Note: You should generally avoid interacting with this element directly via the DOM as the editor may undo changes.

    Use the element, scroll, dom, or content functions to create a ViewPlugin that attaches event listeners and manages their lifecycle (automatically removing them when the plugin is destroyed).

  3. Handle changes with CodeMirrorMerge onChange

    master

    When using react-codemirror-merge, you can track content changes in both the Original and Modified components using the onChange prop. This prop provides the updated content string as its argument, allowing you to sync the editor state with your application's state (e.g., using React useState).

    To prevent unnecessary re-renders during the merge process, it is recommended to set the destroyRerender prop to false on the CodeMirrorMerge parent component.

    import React, { useState } from 'react';
    import CodeMirrorMerge from 'react-codemirror-merge';
    
    const Original = CodeMirrorMerge.Original;
    const Modified = CodeMirrorMerge.Modified;
    let doc = `one\ntwo\nthree\nfour\nfive`;
    
    export default function App() {
      const [value, setValue] = useState(doc);
      const [valueModified, setValueModified] = useState(doc);
      return (
        <div>
          <CodeMirrorMerge destroyRerender={false}>
            <Original
              onChange={(val) => {
                setValue(val);
              }}
              value={value}
            />
            <Modified
              onChange={(val) => {
                setValueModified(val);
              }}
              value={valueModified}
            />
          </CodeMirrorMerge>
          <div style={{ display: 'flex', marginTop: 10 }}>
            <pre style={{ flex: 1 }}>{value} </pre>
            <pre style={{ backgroundColor: '#fff', flex: 1 }}>{valueModified} </pre>
          </div>
        </div>
      );
    }
  4. Color extension configuration and themes

    master

    The color extension uses a specific CSS theme to style the color widgets. The widgets are rendered as a span with data-color attribute, containing an input[type='color'].

    Key CSS properties applied by colorTheme:

    • span[data-color]: Sets the swatch size (12px x 12px), border-radius, and alignment.
    • span[data-color] input[type="color"]: Resets the input appearance to fit within the swatch.
    • span[data-color] input[type="color"]::-webkit-color-swatch: Adjusts the internal swatch padding.
  5. Configure ZebraStripesOptions

    master

    The ZebraStripesOptions object allows you to customize the appearance and behavior of the zebra stripes extension:

    • step: A number defining the interval between stripes (e.g., 2 stripes every 2 lines). If set to null, the extension relies on the lineNumber option.
    • lightColor: A CSS color string applied to the stripe in light mode. Defaults to #eef6ff.
    • darkColor: A CSS color string applied to the stripe in dark mode. Defaults to #3a404d.
    • lineNumber: An array of numbers or nested arrays representing line ranges to be striped. For example, [1, [2, 6], 10] will stripe lines 1, 2, 3, 4, 5, 6, and 10. If this is provided, step is ignored.
    • className: The CSS class name applied to the striped lines. Defaults to cm-zebra-stripe.
    type ZebraStripesOptions = {
      step?: number | null;
      lightColor?: string;
      darkColor?: string;
      /**
       * @example `[1,[2,6], 10]`
       */
      lineNumber?: (number | number[])[] | null;
      /** @default `cm-zebra-stripe` */
      className?: string;
    };
  6. Use the Solarized Dark theme

    master

    The Solarized Dark theme can be applied to a CodeMirror instance using the solarizedDark constant or by calling solarizedDarkInit for custom configurations.

    solarizedDark provides the default Solarized Dark settings and styles.

    solarizedDarkInit allows you to override specific settings or append additional styles to the base Solarized Dark theme.

  7. Use the Console Light theme

    master

    The consoleLight theme is a pre-configured light theme designed to mimic a console appearance. It can be used directly or customized via the consoleLightInit function.

    To use the default theme, import consoleLight and pass it to the theme prop of a CodeMirror component.

    To create a custom version of the console light theme, use consoleLightInit and provide overrides for theme, settings, or styles.

  8. Use the Duotone theme

    master
    The Duotone theme provides a specialized color palette for CodeMirror. You can use the pre-configured duotoneLight or duotoneDark instances directly, or use the duotoneLightInit and duotoneDarkInit functions to create a custom version of the theme by overriding default settings or adding new styles.
  9. Use the color extension to show color pickers in the editor

    master

    The color extension provides visual color pickers for various color formats in the editor, including RGB, HSL, HEX, and named colors. When a color is detected, a small color swatch is rendered. Clicking the swatch opens a native color picker that, when used, updates the color value directly in the editor text.

    Supported color formats:

    • RGB/RGBA: rgb(0, 107, 128) or rgba(0 107 128 / 0.5)
    • HSL/HSLA: hsl(240, 100%, 50%) or hsla(240 100% 50% / 0.1)
    • HEX: #ffffff
    • Named Colors: red, blue, etc.

    To use it, add color to your editor extensions array.