Giter VIP home page Giter VIP logo

uiwjs / react-codemirror Goto Github PK

View Code? Open in Web Editor NEW
1.4K 7.0 119.0 32.1 MB

CodeMirror 6 component for React. @codemirror https://uiwjs.github.io/react-codemirror/

Home Page: https://uiwjs.github.io/react-codemirror/

License: MIT License

HTML 4.25% TypeScript 93.39% JavaScript 2.20% CSS 0.16%
react codemirror react-codemirror editor ide codemirror6 hook react-codemirror2 typescript codemirror-themes

react-codemirror's Introduction

react-codemirror logo

react-codemirror

Buy me a coffee NPM Downloads Build & Deploy Open in unpkg npm version Coverage Status Open in Gitpod

CodeMirror component for React. Demo Preview: @uiwjs.github.io/react-codemirror

Features:

🚀 Quickly and easily configure the API.
🌱 Versions after @uiw/react-codemirror@v4 use codemirror 6. #88.
⚛️ Support the features of React Hook(requires React 16.8+).
📚 Use Typescript to write, better code hints.
🌐 The bundled version supports use directly in the browser #267.
🌎 There are better sample previews.
🎨 Support theme customization, provide theme editor.

Install

Not dependent on uiw.

npm install @uiw/react-codemirror --save

All Packages

Name NPM Version
@uiw/react-codemirror npm version NPM Downloads
react-codemirror-merge npm version NPM Downloads
@uiw/codemirror-extensions-basic-setup npm version NPM Downloads
@uiw/codemirror-extensions-color npm version NPM Downloads
@uiw/codemirror-extensions-classname npm version NPM Downloads
@uiw/codemirror-extensions-events npm version NPM Downloads
@uiw/codemirror-extensions-hyper-link npm version NPM Downloads
@uiw/codemirror-extensions-langs npm version NPM Downloads
@uiw/codemirror-extensions-line-numbers-relative npm version NPM Downloads
@uiw/codemirror-extensions-mentions npm version NPM Downloads
@uiw/codemirror-extensions-zebra-stripes npm version NPM Downloads
@uiw/codemirror-themes npm version NPM Downloads
Name NPM Version
@uiw/codemirror-themes-all npm version NPM Downloads
@uiw/codemirror-theme-abcdef npm version NPM Downloads
@uiw/codemirror-theme-abyss npm version NPM Downloads
@uiw/codemirror-theme-androidstudio npm version NPM Downloads
@uiw/codemirror-theme-andromeda npm version NPM Downloads
@uiw/codemirror-theme-atomone npm version NPM Downloads
@uiw/codemirror-theme-aura npm version NPM Downloads
@uiw/codemirror-theme-basic npm version NPM Downloads
@uiw/codemirror-theme-bbedit npm version NPM Downloads
@uiw/codemirror-theme-bespin npm version NPM Downloads
@uiw/codemirror-theme-console npm version NPM Downloads
@uiw/codemirror-theme-copilot npm version NPM Downloads
@uiw/codemirror-theme-duotone npm version NPM Downloads
@uiw/codemirror-theme-dracula npm version NPM Downloads
@uiw/codemirror-theme-darcula npm version NPM Downloads
@uiw/codemirror-theme-eclipse npm version NPM Downloads
@uiw/codemirror-theme-github npm version NPM Downloads
@uiw/codemirror-theme-gruvbox-dark npm version NPM Downloads
@uiw/codemirror-theme-kimbie npm version NPM Downloads
@uiw/codemirror-theme-kimbie npm version NPM Downloads
@uiw/codemirror-theme-material npm version NPM Downloads
@uiw/codemirror-theme-monokai npm version NPM Downloads
@uiw/codemirror-theme-noctis-lilac npm version NPM Downloads
@uiw/codemirror-theme-nord npm version NPM Downloads
@uiw/codemirror-theme-okaidia npm version NPM Downloads
@uiw/codemirror-theme-quietlight npm version NPM Downloads
@uiw/codemirror-theme-red npm version NPM Downloads
@uiw/codemirror-theme-solarized npm version NPM Downloads
@uiw/codemirror-theme-sublime npm version NPM Downloads
@uiw/codemirror-theme-tokyo-night npm version NPM Downloads
@uiw/codemirror-theme-tokyo-night-storm npm version NPM Downloads
@uiw/codemirror-theme-tokyo-night-day npm version NPM Downloads
@uiw/codemirror-theme-vscode npm version NPM Downloads
@uiw/codemirror-theme-white npm version NPM Downloads
@uiw/codemirror-theme-tomorrow-night-blue npm version NPM Downloads
@uiw/codemirror-theme-xcode npm version NPM Downloads

Usage

Open in CodeSandbox

import React from 'react';
import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';

function App() {
  const [value, setValue] = React.useState("console.log('hello world!');");
  const onChange = React.useCallback((val, viewUpdate) => {
    console.log('val:', val);
    setValue(val);
  }, []);
  return <CodeMirror value={value} height="200px" extensions={[javascript({ jsx: true })]} onChange={onChange} />;
}
export default App;

Support Language

Open in CodeSandbox

import CodeMirror from '@uiw/react-codemirror';
import { StreamLanguage } from '@codemirror/language';
import { go } from '@codemirror/legacy-modes/mode/go';

const goLang = `package main
import "fmt"

func main() {
  fmt.Println("Hello, 世界")
}`;

export default function App() {
  return <CodeMirror value={goLang} height="200px" extensions={[StreamLanguage.define(go)]} />;
}

Markdown Example

Markdown language code is automatically highlighted.

Open in CodeSandbox

import CodeMirror from '@uiw/react-codemirror';
import { markdown, markdownLanguage } from '@codemirror/lang-markdown';
import { languages } from '@codemirror/language-data';

const code = `## Title

\`\`\`jsx
function Demo() {
  return <div>demo</div>
}
\`\`\`

\`\`\`bash
# Not dependent on uiw.
npm install @codemirror/lang-markdown --save
npm install @codemirror/language-data --save
\`\`\`

[weisit ulr](https://uiwjs.github.io/react-codemirror/)

\`\`\`go
package main
import "fmt"
func main() {
  fmt.Println("Hello, 世界")
}
\`\`\`
`;

export default function App() {
  return <CodeMirror value={code} extensions={[markdown({ base: markdownLanguage, codeLanguages: languages })]} />;
}

Codemirror Merge

A component that highlights the changes between two versions of a file in a side-by-side view, highlighting added, modified, or deleted lines of code.

npm install react-codemirror-merge  --save
import CodeMirrorMerge from 'react-codemirror-merge';
import { EditorView } from 'codemirror';
import { EditorState } from '@codemirror/state';

const Original = CodeMirrorMerge.Original;
const Modified = CodeMirrorMerge.Modified;
let doc = `one
two
three
four
five`;

export const Example = () => {
  return (
    <CodeMirrorMerge>
      <Original value={doc} />
      <Modified
        value={doc.replace(/t/g, 'T') + 'Six'}
        extensions={[EditorView.editable.of(false), EditorState.readOnly.of(true)]}
      />
    </CodeMirrorMerge>
  );
};

Support Hook

Open in CodeSandbox

import { useEffect, useMemo, useRef } from 'react';
import { useCodeMirror } from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';

const code = "console.log('hello world!');\n\n\n";
// Define the extensions outside the component for the best performance.
// If you need dynamic extensions, use React.useMemo to minimize reference changes
// which cause costly re-renders.
const extensions = [javascript()];

export default function App() {
  const editor = useRef();
  const { setContainer } = useCodeMirror({
    container: editor.current,
    extensions,
    value: code,
  });

  useEffect(() => {
    if (editor.current) {
      setContainer(editor.current);
    }
  }, [editor.current]);

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

Using Theme

We have created a theme editor where you can define your own theme. We have also defined some themes ourselves, which can be installed and used directly. Below is a usage example:

import CodeMirror from '@uiw/react-codemirror';
import { javascript } from '@codemirror/lang-javascript';
import { okaidia } from '@uiw/codemirror-theme-okaidia';

const extensions = [javascript({ jsx: true })];

export default function App() {
  return (
    <CodeMirror
      value="console.log('hello world!');"
      height="200px"
      theme={okaidia}
      extensions={[javascript({ jsx: true })]}
    />
  );
}

Using custom theme

import CodeMirror from '@uiw/react-codemirror';
import { createTheme } from '@uiw/codemirror-themes';
import { javascript } from '@codemirror/lang-javascript';
import { tags as t } from '@lezer/highlight';

const myTheme = createTheme({
  theme: 'light',
  settings: {
    background: '#ffffff',
    backgroundImage: '',
    foreground: '#75baff',
    caret: '#5d00ff',
    selection: '#036dd626',
    selectionMatch: '#036dd626',
    lineHighlight: '#8a91991a',
    gutterBackground: '#fff',
    gutterForeground: '#8a919966',
  },
  styles: [
    { tag: t.comment, color: '#787b8099' },
    { tag: t.variableName, color: '#0080ff' },
    { tag: [t.string, t.special(t.brace)], color: '#5c6166' },
    { tag: t.number, color: '#5c6166' },
    { tag: t.bool, color: '#5c6166' },
    { tag: t.null, color: '#5c6166' },
    { tag: t.keyword, color: '#5c6166' },
    { tag: t.operator, color: '#5c6166' },
    { tag: t.className, color: '#5c6166' },
    { tag: t.definition(t.typeName), color: '#5c6166' },
    { tag: t.typeName, color: '#5c6166' },
    { tag: t.angleBracket, color: '#5c6166' },
    { tag: t.tagName, color: '#5c6166' },
    { tag: t.attributeName, color: '#5c6166' },
  ],
});
const extensions = [javascript({ jsx: true })];

export default function App() {
  const onChange = React.useCallback((value, viewUpdate) => {
    console.log('value:', value);
  }, []);
  return (
    <CodeMirror
      value="console.log('hello world!');"
      height="200px"
      theme={myTheme}
      extensions={extensions}
      onChange={onChange}
    />
  );
}

Use initialState to restore state from JSON-serialized representation

CodeMirror allows to serialize editor state to JSON representation with toJSON function for persistency or other needs. This JSON representation can be later used to recreate ReactCodeMirror component with the same internal state.

For example, this is how undo history can be saved in the local storage, so that it remains after the page reloads

import CodeMirror from '@uiw/react-codemirror';
import { historyField } from '@codemirror/commands';

// When custom fields should be serialized, you can pass them in as an object mapping property names to fields.
// See [toJSON](https://codemirror.net/docs/ref/#state.EditorState.toJSON) documentation for more details
const stateFields = { history: historyField };

export function EditorWithInitialState() {
  const serializedState = localStorage.getItem('myEditorState');
  const value = localStorage.getItem('myValue') || '';

  return (
    <CodeMirror
      value={value}
      initialState={
        serializedState
          ? {
              json: JSON.parse(serializedState || ''),
              fields: stateFields,
            }
          : undefined
      }
      onChange={(value, viewUpdate) => {
        localStorage.setItem('myValue', value);

        const state = viewUpdate.state.toJSON(stateFields);
        localStorage.setItem('myEditorState', JSON.stringify(state));
      }}
    />
  );
}

Props

  • value?: string value of the auto created model in the editor.
  • width?: string width of editor. Defaults to auto.
  • height?: string height of editor. Defaults to auto.
  • theme?: 'light' / 'dark' / Extension Defaults to 'light'.
import React from 'react';
import { EditorState, EditorStateConfig, Extension } from '@codemirror/state';
import { EditorView, ViewUpdate } from '@codemirror/view';
export * from '@codemirror/view';
export * from '@codemirror/basic-setup';
export * from '@codemirror/state';
export interface UseCodeMirror extends ReactCodeMirrorProps {
  container?: HTMLDivElement | null;
}
export declare function useCodeMirror(props: UseCodeMirror): {
  state: EditorState | undefined;
  setState: import('react').Dispatch<import('react').SetStateAction<EditorState | undefined>>;
  view: EditorView | undefined;
  setView: import('react').Dispatch<import('react').SetStateAction<EditorView | undefined>>;
  container: HTMLDivElement | null | undefined;
  setContainer: import('react').Dispatch<import('react').SetStateAction<HTMLDivElement | null | undefined>>;
};
export interface ReactCodeMirrorProps
  extends Omit<EditorStateConfig, 'doc' | 'extensions'>,
    Omit<React.HTMLAttributes<HTMLDivElement>, 'onChange' | 'placeholder'> {
  /** value of the auto created model in the editor. */
  value?: string;
  height?: string;
  minHeight?: string;
  maxHeight?: string;
  width?: string;
  minWidth?: string;
  maxWidth?: string;
  /** focus on the editor. */
  autoFocus?: boolean;
  /** Enables a placeholder—a piece of example content to show when the editor is empty. */
  placeholder?: string | HTMLElement;
  /**
   * `light` / `dark` / `Extension` Defaults to `light`.
   * @default light
   */
  theme?: 'light' | 'dark' | Extension;
  /**
   * Whether to optional basicSetup by default
   * @default true
   */
  basicSetup?: boolean | BasicSetupOptions;
  /**
   * This disables editing of the editor content by the user.
   * @default true
   */
  editable?: boolean;
  /**
   * This disables editing of the editor content by the user.
   * @default false
   */
  readOnly?: boolean;
  /**
   * Controls whether pressing the `Tab` key inserts a tab character and indents the text (`true`)
   * or behaves according to the browser's default behavior (`false`).
   * @default true
   */
  indentWithTab?: boolean;
  /** Fired whenever a change occurs to the document. */
  onChange?(value: string, viewUpdate: ViewUpdate): void;
  /** Some data on the statistics editor. */
  onStatistics?(data: Statistics): void;
  /** The first time the editor executes the event. */
  onCreateEditor?(view: EditorView, state: EditorState): void;
  /** Fired whenever any state change occurs within the editor, including non-document changes like lint results. */
  onUpdate?(viewUpdate: ViewUpdate): void;
  /**
   * Extension values can be [provided](https://codemirror.net/6/docs/ref/#state.EditorStateConfig.extensions) when creating a state to attach various kinds of configuration and behavior information.
   * They can either be built-in extension-providing objects,
   * such as [state fields](https://codemirror.net/6/docs/ref/#state.StateField) or [facet providers](https://codemirror.net/6/docs/ref/#state.Facet.of),
   * or objects with an extension in its `extension` property. Extensions can be nested in arrays arbitrarily deep—they will be flattened when processed.
   */
  extensions?: Extension[];
  /**
   * If the view is going to be mounted in a shadow root or document other than the one held by the global variable document (the default), you should pass it here.
   * Originally from the [config of EditorView](https://codemirror.net/6/docs/ref/#view.EditorView.constructor%5Econfig.root)
   */
  root?: ShadowRoot | Document;
  /**
   * Create a state from its JSON representation serialized with [toJSON](https://codemirror.net/docs/ref/#state.EditorState.toJSON) function
   */
  initialState?: {
    json: any;
    fields?: Record<'string', StateField<any>>;
  };
}
export interface ReactCodeMirrorRef {
  editor?: HTMLDivElement | null;
  state?: EditorState;
  view?: EditorView;
}
declare const ReactCodeMirror: React.ForwardRefExoticComponent<
  ReactCodeMirrorProps & React.RefAttributes<ReactCodeMirrorRef>
>;
export default ReactCodeMirror;
export interface BasicSetupOptions {
  lineNumbers?: boolean;
  highlightActiveLineGutter?: boolean;
  highlightSpecialChars?: boolean;
  history?: boolean;
  foldGutter?: boolean;
  drawSelection?: boolean;
  dropCursor?: boolean;
  allowMultipleSelections?: boolean;
  indentOnInput?: boolean;
  syntaxHighlighting?: boolean;
  bracketMatching?: boolean;
  closeBrackets?: boolean;
  autocompletion?: boolean;
  rectangularSelection?: boolean;
  crosshairCursor?: boolean;
  highlightActiveLine?: boolean;
  highlightSelectionMatches?: boolean;
  closeBracketsKeymap?: boolean;
  defaultKeymap?: boolean;
  searchKeymap?: boolean;
  historyKeymap?: boolean;
  foldKeymap?: boolean;
  completionKeymap?: boolean;
  lintKeymap?: boolean;
}
import { EditorSelection, SelectionRange } from '@codemirror/state';
import { ViewUpdate } from '@codemirror/view';
export interface Statistics {
  /** Get the number of lines in the editor. */
  lineCount: number;
  /** total length of the document */
  length: number;
  /** Get the proper [line-break](https://codemirror.net/docs/ref/#state.EditorState^lineSeparator) string for this state. */
  lineBreak: string;
  /** Returns true when the editor is [configured](https://codemirror.net/6/docs/ref/#state.EditorState^readOnly) to be read-only. */
  readOnly: boolean;
  /** The size (in columns) of a tab in the document, determined by the [`tabSize`](https://codemirror.net/6/docs/ref/#state.EditorState^tabSize) facet. */
  tabSize: number;
  /** Cursor Position */
  selection: EditorSelection;
  /** Make sure the selection only has one range. */
  selectionAsSingle: SelectionRange;
  /** Retrieves a list of all current selections. */
  ranges: readonly SelectionRange[];
  /** Get the currently selected code. */
  selectionCode: string;
  /**
   * The length of the given array should be the same as the number of active selections.
   * Replaces the content of the selections with the strings in the array.
   */
  selections: string[];
  /** Return true if any text is selected. */
  selectedText: boolean;
}
export declare const getStatistics: (view: ViewUpdate) => Statistics;

Development

  1. Install dependencies
$ npm install       # Installation dependencies
$ npm run build     # Compile all package
  1. Development @uiw/react-codemirror package:
$ cd core
# listen to the component compile and output the .js file
# listen for compilation output type .d.ts file
$ npm run watch # Monitor the compiled package `@uiw/react-codemirror`
  1. Launch documentation site
npm run start

Related

Contributors

As always, thanks to our amazing contributors!

Made with contributors.

License

Licensed under the MIT License.

react-codemirror's People

Contributors

11bit avatar a1ooha avatar arvigeus avatar bowen7 avatar dalejo96 avatar dependabot[bot] avatar djsavvy avatar ethan-vanderheijden avatar felixroos avatar g4rcez avatar gtn1024 avatar jabingp avatar jaller94 avatar jaywcjlove avatar jgbernalp avatar johnnydeuss avatar karlhorky avatar kitety avatar lloydlobo avatar meowtec avatar mu-hun avatar nickgirardo avatar orichcasperkevin avatar realabbas avatar renovate-bot avatar renovate[bot] avatar rugvip avatar shubhendusaurabh avatar snnsnn avatar willstott101 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-codemirror's Issues

使用react-codemirror作日志展示,如果固定显示最后一行

使用react-codemirror作日志展示,如果固定显示最后一行。
我现在是这么做的

const { height, clientHeight } = textareaRef?.current?.editor?.getScrollInfo() || {}
...
textareaRef?.current?.editor?.scrollTo(0, height)

这有个问题,value重新设置的时候,会跳回到顶部,然后再scrollTo到底部,导致出现闪动,怎么解决这个问题。。。

TypeError: name.toLowerCase is not a function in mode option

The documentation says you can also use an object as a configuration for prop mode. When I use the example ( {name: "javascript", json: true}) it says name.toLowerCase is not a function. Is this a bug regarding this package?

/** string|object. The mode to use. When not given, this will default to the first mode that was loaded.
It may be a string, which either simply names the mode or is a MIME type associated with the mode.
Alternatively, it may be an object containing configuration options for the mode,
with a name property that names the mode (for example {name: "javascript", json: true}). */
mode?: any;

meta.js:213 Uncaught (in promise) TypeError: name.toLowerCase is not a function
at Function.CodeMirror.findModeByName (meta.js:213)
at _callee$ (index.js:79)
at tryCatch (runtime.js:63)
at Generator.invoke [as _invoke] (runtime.js:293)
at Generator.next (runtime.js:118)
at asyncGeneratorStep (asyncToGenerator.js:3)
at _next (asyncToGenerator.js:25)
at asyncToGenerator.js:32
at new Promise ()
at asyncToGenerator.js:21

INI mode

There's no really good alternative for ini mode ;/

[Bug] Cursor will move to the beginning when using prop "value"

In example, the value is assigned as a constant. However if the value is read from a state, like minor tweak of the example below:

export default function App() {
  let [val, setVal] = useState('console.log') // add this line
  return (
    <CodeMirror
      value={val} // use val from state
      height="200px"
      extensions={[javascript({ jsx: true }), scrollPastEnd()]}
      onChange={(value, viewUpdate) => {
        console.log("value:", value);
        setVal(value); // add this line
      }}
    />
  );
}

Here's the bug in v4:

  1. put the cursor anywhere except the end of the text
  2. edit
  3. the cursor will be put in the very beginning of the text after every key stroke, which is a show stopper.
  4. also reproducable with useCodeMirror hook

CodeSandbox:
https://codesandbox.io/s/react-codemirror-example-codemirror-6-forked-d9u0g?file=/src/App.js

Codemirror 6

Hi, just curious to know if there is a plan to upgrade this to CodeMirror 6.

Thanks for all the amazing stuff so far.

Make basicSetup and indentWithTab optional

Could you make basicSetup and indentWithTab optional?

I am building a Tag Input component with CodeMirror and this use case doesn't require any styling or package overhead. It also increase the level of customization.

useCodeMirror.ts

let getExtensions = [basicSetup, keymap.of([indentWithTab]), updateListener, defaultThemeOption];

Getting "name.toLowerCase is not a function" when "mode" is an object

Brand new to Node & React, so not sure I have this right.

I tried to set option mode to an object, which is what CodeMirror supports and is the readme here, but it doesn't seem to work.

I get the following error:

Unhandled Rejection (TypeError): name.toLowerCase is not a function

If I am not wrong, this seems to be because setOptions assumes that mode is a string that is passed directly to CodeMirror.findModeByName.

If this is a real bug (rather than me doing something wrong), I can try to raise a PR to fix.

My code is this:

        <CodeMirror
          value={name}
          options={{
            theme: "monokai",
            keyMap: "sublime",
            mode: {
              name: "gfm",
              highlightFormatting: true,
            },
            lineNumbers: false
          }}
        />

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Open

These updates have all been created already. Click a checkbox below to force a retry/rebase of any.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/checkout v4
  • actions/setup-node v4
  • peaceiris/actions-gh-pages v4
  • ncipollo/release-action v1
.github/workflows/pr.yml
  • actions/checkout v4
  • actions/setup-node v4
npm
core/package.json
  • @babel/runtime ^7.18.6
  • @codemirror/commands ^6.1.0
  • @codemirror/state ^6.1.1
  • @codemirror/theme-one-dark ^6.0.0
  • codemirror ^6.0.0
  • @babel/runtime >=7.11.0
  • @codemirror/state >=6.0.0
  • @codemirror/theme-one-dark >=6.0.0
  • @codemirror/view >=6.0.0
  • codemirror >=6.0.0
  • react >=16.8.0
  • react-dom >=16.8.0
example/nextjs/package.json
  • next 14.0.3
  • react ~18.2.0
  • react-dom ~18.2.0
  • @types/node ^20
  • @types/react ^18
  • @types/react-dom ^18
  • autoprefixer ^10.0.1
  • eslint ^8
  • eslint-config-next 14.0.3
  • postcss ^8
  • tailwindcss ^3.3.0
  • typescript ^5
extensions/basic-setup/package.json
  • @codemirror/autocomplete ^6.0.0
  • @codemirror/commands ^6.0.0
  • @codemirror/language ^6.0.0
  • @codemirror/lint ^6.0.0
  • @codemirror/search ^6.0.0
  • @codemirror/state ^6.0.0
  • @codemirror/view ^6.0.0
  • @codemirror/autocomplete >=6.0.0
  • @codemirror/commands >=6.0.0
  • @codemirror/language >=6.0.0
  • @codemirror/lint >=6.0.0
  • @codemirror/search >=6.0.0
  • @codemirror/state >=6.0.0
  • @codemirror/view >=6.0.0
extensions/classname/package.json
  • @codemirror/state ^6.1.0
  • @codemirror/view ^6.0.0
  • @codemirror/state >=6.0.0
  • @codemirror/view >=6.0.0
extensions/color/package.json
  • colors-named ^1.0.0
  • colors-named-hex ^1.0.0
  • hsl-matcher ^1.2.3
  • @codemirror/language ^6.0.0
  • @codemirror/state ^6.0.0
  • @codemirror/view ^6.0.0
  • @codemirror/language >=6.0.0
  • @codemirror/state >=6.0.0
  • @codemirror/view >=6.0.0
extensions/events/package.json
  • @codemirror/view ^6.0.0
  • @codemirror/view >=6.0.0
extensions/hyper-link/package.json
  • @codemirror/state ^6.1.0
  • @codemirror/view ^6.0.0
  • @codemirror/state >=6.0.0
  • @codemirror/view >=6.0.0
extensions/langs/package.json
  • @codemirror/lang-angular ^0.1.0
  • @codemirror/lang-cpp ^6.0.0
  • @codemirror/lang-css ^6.2.0
  • @codemirror/lang-html ^6.4.0
  • @codemirror/lang-java ^6.0.0
  • @codemirror/lang-javascript ^6.1.0
  • @codemirror/lang-json ^6.0.0
  • @codemirror/lang-less ^6.0.1
  • @codemirror/lang-lezer ^6.0.0
  • @codemirror/lang-liquid ^6.0.1
  • @codemirror/lang-markdown ^6.1.0
  • @codemirror/lang-php ^6.0.0
  • @codemirror/lang-python ^6.1.0
  • @codemirror/lang-rust ^6.0.0
  • @codemirror/lang-sass ^6.0.1
  • @codemirror/lang-sql ^6.4.0
  • @codemirror/lang-vue ^0.1.1
  • @codemirror/lang-wast ^6.0.0
  • @codemirror/lang-xml ^6.0.0
  • @codemirror/language-data >=6.0.0
  • @codemirror/legacy-modes >=6.0.0
  • @nextjournal/lang-clojure ^1.0.0
  • @replit/codemirror-lang-csharp ^6.1.0
  • @replit/codemirror-lang-nix ^6.0.1
  • @replit/codemirror-lang-solidity ^6.0.1
  • @replit/codemirror-lang-svelte ^6.0.0
  • codemirror-lang-mermaid ^0.5.0
  • @codemirror/language-data >=6.0.0
  • @codemirror/legacy-modes >=6.0.0
extensions/line-numbers-relative/package.json
  • @codemirror/state ^6.1.0
  • @codemirror/view ^6.0.0
  • @codemirror/state >=6.0.0
  • @codemirror/view >=6.0.0
extensions/mentions/package.json
  • @codemirror/state ^6.1.0
  • @codemirror/view ^6.0.0
  • @codemirror/state >=6.0.0
  • @codemirror/view >=6.0.0
extensions/zebra-stripes/package.json
  • @codemirror/state ^6.1.0
  • @codemirror/view ^6.0.0
  • @codemirror/state >=6.0.0
  • @codemirror/view >=6.0.0
merge/package.json
  • @babel/runtime ^7.18.6
  • @codemirror/merge ^6.1.2
  • @babel/runtime >=7.11.0
  • @codemirror/state >=6.0.0
  • @codemirror/theme-one-dark >=6.0.0
  • @codemirror/view >=6.0.0
  • codemirror >=6.0.0
  • react >=16.8.0
  • react-dom >=16.8.0
package.json
  • @kkt/less-modules ^7.5.4
  • @kkt/ncc ^1.0.13
  • @types/react-test-renderer ~18.0.0
  • react ~18.2.0
  • react-dom ~18.2.0
  • husky ^9.0.11
  • kkt ^7.5.4
  • lerna ^8.0.0
  • lint-staged ^15.1.0
  • prettier ^3.0.2
  • react-test-renderer ~18.2.0
  • tsbb ^4.2.4
  • node >=16.0.0
themes/_scripts/package.json
themes/abcdef/package.json
themes/abyss/package.json
themes/all/package.json
themes/androidstudio/package.json
themes/andromeda/package.json
themes/atomone/package.json
themes/aura/package.json
themes/basic/package.json
themes/bbedit/package.json
themes/bespin/package.json
themes/console/package.json
themes/copilot/package.json
themes/darcula/package.json
themes/dracula/package.json
themes/duotone/package.json
themes/eclipse/package.json
themes/github/package.json
themes/gruvbox/package.json
themes/kimbie/package.json
themes/material/package.json
themes/monokai-dimmed/package.json
themes/monokai/package.json
themes/noctis-lilac/package.json
themes/nord/package.json
themes/okaidia/package.json
themes/quietlight/package.json
themes/red/package.json
themes/solarized/package.json
themes/sublime/package.json
themes/theme/package.json
  • @codemirror/language ^6.0.0
  • @codemirror/state ^6.0.0
  • @codemirror/view ^6.0.0
  • @codemirror/language >=6.0.0
  • @codemirror/state >=6.0.0
  • @codemirror/view >=6.0.0
themes/tokyo-night-day/package.json
themes/tokyo-night-storm/package.json
themes/tokyo-night/package.json
themes/tomorrow-night-blue/package.json
themes/vscode/package.json
themes/white/package.json
themes/xcode/package.json
www/package.json
  • @codemirror/lang-cpp ^6.0.0
  • @codemirror/lang-html ^6.4.0
  • @codemirror/lang-java ^6.0.0
  • @codemirror/lang-javascript ^6.1.0
  • @codemirror/lang-json ^6.0.0
  • @codemirror/lang-lezer ^6.0.0
  • @codemirror/lang-markdown ^6.1.0
  • @codemirror/lang-php ^6.0.0
  • @codemirror/lang-python ^6.1.0
  • @codemirror/lang-rust ^6.0.0
  • @codemirror/lang-sql ^6.4.0
  • @codemirror/lang-xml ^6.0.0
  • @codemirror/language-data ^6.1.0
  • @codemirror/legacy-modes ^6.3.0
  • @uiw/react-back-to-top ^1.1.2
  • @uiw/react-github-corners ~1.5.14
  • @uiw/react-markdown-preview ^5.0.2
  • @uiw/react-shields ^2.0.1
  • @wcj/dark-mode ~1.0.12
  • code-example ^3.3.6
  • markdown-react-code-preview-loader ^2.1.2
  • react ~18.2.0
  • react-code-preview-layout ^3.1.4
  • react-dom ~18.2.0
  • react-router-dom ^6.20.0
  • rehype-ignore ^2.0.1
  • styled-components ^6.1.1
  • @kkt/less-modules ^7.5.4
  • @kkt/raw-modules ^7.5.4
  • @kkt/scope-plugin-options ^7.5.4
  • @types/katex ^0.16.0
  • @types/react ^18.2.0
  • @types/react-dom ^18.2.0
  • cross-env ^7.0.3
  • kkt ^7.5.4
  • source-map-explorer ~2.5.3

  • Check this box to trigger a request for Renovate to run again on this repository

[Feature Request] Expose "root" props of EditorView

Hi Maintainer,

Could you please expose "root" config of EditorView (https://codemirror.net/6/docs/ref/#view.EditorView.constructor^config.root)?

I'm using shadow dom in my case, without this config the whole style would go broken. And there is no workaround currently.

I've read the code, seems only container is exposed by useCodeMirror hook, sadly that's not sufficient for cases using shadow dom.

I would be happy to submit a PR for this request. Just drop me some guidance if needed. The simple change would be add a prop just like container, but it would be better to expose all configs of state/view for better customization.

Use with Typescript returns an error

When trying to use in Typescript returns an error - JSX element class does not support attributes because it does not have a 'props' property.

Use with Snowpack

On an initial attempt to get this working with snowpack, I'm running into an issue resolving the mode:

Uncaught (in promise) TypeError: Failed to resolve module specifier 'codemirror/mode/jsx/jsx.js'

My code is minimal boilerplate:

import React from "react"
import CodeMirror from "@uiw/react-codemirror"
import "codemirror/keymap/sublime"
import "codemirror/theme/monokai.css"

const code = `const a = 0`

const App = () =>
	<div>
		<CodeMirror
			value={code}
			options={{
				theme: "monokai",
				keyMap: "sublime",
				mode: "jsx",
				lineNumbers: true,
			}}
		/>
	</div>

export default App

addon lint doesn't work

image
code like codemirror document for lint javascript code, but doesn't work
和官方文档一样编写的lint相关代码,并不起作用
image

升级webpack4后,@uiw/react-codemirror不能用了

client:180 ./node_modules/@uiw/react-codemirror/lib/CodeMirror.js 148:23
Module parse failed: Unexpected token (148:23)
You may need an appropriate loader to handle this file type.
| 
|                 _context2.next = 5;
>                 return import("codemirror/mode/".concat(mode.mode, "/").concat(mode.mode, ".js"));
| 
|               case 5:

动态导入有问题

Theme prop

It appears that the theme prop only supports 'light'|'dark'. How do I apply other themes like the ones found in Codemirror's GitHub?

Interested in adding testing?

I am looking at your package and it's very promising, I was wondering if you are interested, What exactly would you test in this project to ensure that it works properly?

If you are interested I could help you write these tests.

Wrong typescript signature for OnChange

Currently the onChange on react-codemirror is:

onChange?: (instance: CodeMirror.Editor, change: CodeMirror.EditorChangeLinkedList[]) => void;

However, when logging the parameter change I get:

"{"from":{"line":1,"ch":12,"sticky":null,"xRel":1,"outside":1},"to":{"line":1,"ch":12,"sticky":null,"xRel":1,"outside":1},"text":["a"],"removed":[""],"origin":"+input"}

Which make sense since it its a linked list. The type for the parameter change should simply be CodeMirror.EditorChangeLinkedList.

onChange uses old prop

I have my UI, and there are tabs with languages (english, german, etc.) so that when you change the tab, you are editing different language.

Now, I have my TextEditor functional component with codemirror (using useCodeMirror hook) and it has props:

  • languageId (0: en, 1: de)
  • text The string

So, in summary, somehting like this (sorry, I'm not writing JS/TS/JSX, because my project is using Kotlin/JS, but I don't think that's an issue, more in that later, but it's just a pseudocode):

texts = ["Hello", "Gutten tag"] // Fetched, just and example

tab = useState(0)

<Tabs tab={{tab}}>
  <!-- create tabs for languages -->
</Tabs>

<TextEditor languageId={{tab}} text={{texts[tab]}} />
TextEditor = FC { props ->
  cm = useCodeMirror {
    //other properties
    onChange = {text, _ ->
      console.log("onChange(${props.languageId}, $text)")
    }
    value = props.text
  }

  // <div>, useRef(), etc. to make CodeMirror work
}

Now to the issue. When I change the tab, for example from 0: english to 1: german, the followint thing appers in the console:

onChange(0, "Gutten tag")

See, the id (0) does not correspond to passed text (german). How is this even possible?! I'm in no way a React expert, but shouldn't the passing of properties be atomic? Or are the props somehow freezed in the hook or something?

Can you help me with this?

Disclaimer: I'm writing the code in Kotlin/JS, and using so called wrappers around JS libraries, but they are just helping with type safety, so I guess this is not an issue (but it might).

State is not updated

Reading the state.doc returned from useCodeMirror always returns an empty document, even when I write something in the editor!

Screenshot

TypeError: next is undefined. Minimal "<CodeMirror /> React Component Fails?

I'm trying to run the most basic uiwjs/react-codemirror example from Readme.md and it's failing now on two separate systems. (Ubuntu 20.04 and Ubuntu 20.10)

The strange thing, one week ago it react-codemirror was working fine for me.
I haven't been able to figure out what changed, but even the most basic examples are failing for me.
I've created a new empty app, and even that fails.

I'm using React 17.0.1, npm 6.14.8

npx create-react-app foo
cd foo
npm install @uiw/react-codemirror --save
npm install codemirror --save

src/App.js only contains:

import CodeMirror from '@uiw/react-codemirror';
import 'codemirror/keymap/sublime';
import 'codemirror/theme/monokai.css';

const code = 'const a = 0;';

function App() {
  return (
    <div className="App">
        <p>
          <CodeMirror
            value={code}
            options={{
              theme: 'monokai',
              keyMap: 'sublime',
              mode: 'jsx',
            }}
          />
        </p>
    </div>
  );
}

export default App;
npm start

When I open it under Firefox I get:

TypeError: next is undefined
defineOptions/<
node_modules/@uiw/react-codemirror/node_modules/codemirror/lib/codemirror.js:7723

  7720 |   var next = getKeyMap(val);
  7721 |   var prev = old != Init && getKeyMap(old);
  7722 |   if (prev && prev.detach) { prev.detach(cm, next); }
> 7723 |   if (next.attach) { next.attach(cm, prev || null); }
       | ^  7724 | });
  7725 | option("extraKeys", null);
  7726 | option("configureMouse", null);

When I open the this under Chrome I get a different error message, but it still fails on the same line.

TypeError: Cannot read property 'attach' of undefined
keyMap
node_modules/@uiw/react-codemirror/node_modules/codemirror/lib/codemirror.js:7723
  7720 |   var next = getKeyMap(val);
  7721 |   var prev = old != Init && getKeyMap(old);
  7722 |   if (prev && prev.detach) { prev.detach(cm, next); }
> 7723 |   if (next.attach) { next.attach(cm, prev || null); }
       | ^  7724 | });
  7725 | option("extraKeys", null);
  7726 | option("configureMouse", null);

How to get whole code after I edited?

This is absolutely great component, thank you guys.
But I can hardly found examples to guide me use this component.
One of my question is after I edited the code, how should I get the whole edited code.
Now, I use onChenge property, and I get two args, editor, and value, but the value only contains the content I just inputed just now. I wounder how could I get whole code content instead of the content I just typed in?
here is my code:

class YamlEditor extends React.Component {
  constructor(props) {
    super(props);
    this.updateCode = this.updateCode.bind(this);
  }

  updateCode(editor, value) {
    console.log("value:", value);
  }

  render() {
    return (
      <CodeMirror
        value={this.props.yamlData}
        options={{
          theme: "monokai",
          keyMap: "sublime",
          mode: "yaml",
          lineNumbers: true,
          lineWrapping: true
        }}
        onChange={this.updateCode}
      />
    );
  }
}

failed to display python style v0.19.2

I installed the lang-python 0.19.2 and it does not work.
It worked fine with the javascript example.
This my code with python.

import { python } from '@codemirror/lang-python';
<CodeMirror
            value = "print('hello world!')"
            height = "200px"
            extensions = {[python()]}
            theme = 'light'
            onChange = {(value, viewUpdate) => {
                // console.log('value:', value);
            }}
        />

Do you know why?

How can I show the results of the code?

I can't seem to find how can I preview the results of the code ex if I have mode html if I type <h1>Hello world</h1>
I want to show it as

Hello world

, or for any other mode

Line number is not updated

Hello,

I'm trying to use the lineNumbers extension to add an offset to each line number.
It works fine when the component is created/rendered for the first time.

But then if the lineNumberOffset prop is changed, the CodeMirror editor is not updated.
Any idea how to fix this?

import { CatalaCell, setCodeValue } from "../file/fileSlice";
import { connect, ConnectedProps } from "react-redux";
import { RootState } from "../../app/store";
import CodeMirror from '@uiw/react-codemirror';
import { lineNumbers } from "@codemirror/gutter";
import { EditorView } from "@codemirror/view";
import { useAppDispatch } from "../../app/hooks";

const mapState = (state: RootState) => ({
  fileContent: state.file.content,
});

const mapDispatch = {
};

const connector = connect(mapState, mapDispatch);

type PropsFromRedux = ConnectedProps<typeof connector>;

type Props = PropsFromRedux & {
  cellIndex: number;
  lineNumberOffset: number;
}

const CodeEditor = (props: Props) => {
  const dispatch = useAppDispatch();
  const cell: CatalaCell = props.fileContent![props.cellIndex];

  let theme = EditorView.theme({
    "&.cm-editor": {
      padding: "10px 0 10px 0",
      fontSize: ".9em",
      fontFamily: "Roboto Mono, sans-serif",
    },
    ".cm-lineNumbers .cm-gutterElement": {
      minWidth: "45px",
      paddingRight: "0px",
      fontSize: "15px",
      lineHeight: "24px",
      marginRight: "18px",
      fontFamily: "Roboto Mono, sans-serif",
    },
    /* Disable CodeMirror's active line highlighting. */
    "& .cm-activeLineGutter, & .cm-activeLine": {
      backgroundColor: "transparent !important",
    },
    /* Disable CodeMirror's focused editor outline. */
    "&.cm-editor.cm-focused": {
      outline: "none",
    },
  }, {dark: true});

  const extensions = [
    theme,
    lineNumbers({
      formatNumber: (n, s) => {
        return (n + props.lineNumberOffset).toString();
      }
    }),
  ];

  return (
    <div style={{ marginTop: 10, marginBottom: 10 }}>
      <CodeMirror
        basicSetup={false}
        value={cell?.code?.code}
        onChange={(value, viewUpdate) => {
          dispatch(setCodeValue([props.cellIndex, value]));
        }}
        extensions={extensions}
        theme="dark"
      />
    </div>
  );
}
  
export default connector(CodeEditor);

在modal弹框中使用react-codemirror的问题

  • 操作
    在modal弹框中使用react-codemirror,控制modal的显示与隐藏

  • 现象
    出现文字被截断,行号不出现,无光标(光标位于行号底层,看不见)
    image

  • 期望结果
    正常显示,正常输入
    image

处理事件有 bug

type 定义
image

处理事件的函数
image

现象
image

image


问题

比如 onDragOver 这种有两个大写字母的事件,只会转化成 dragOver ,绑定的是 dragOver 而不是 dragover,所以会失效。

临时解决办法

绑定事件用 onDragover onDragenter 这种

修复代码

const eventHandle = propNames.filter((prop) => {
  return /^on+/.test(prop);
});
// eventHandle 中确定都是 on 开头的

eventHandle.forEach((ele) => {
  // 直接去掉 on,然后小写化
  eventDict[ele] = ele.slice(2).toLowerCase();
});

Changing Cursor Color

Is it possible to change the cursor color without overwriting it using css ? By the cursor I am referring to the block cursor that appears in vim mode. I haven't found any option to change it in the provided documentation.

Edit : It Appears that native codemirror api too does not allow changing cursor color in vim mode

Boolean options won't update to false

When I set CodeMirror options readOnly on true and then update it to false it doesn't update and the editor stays locked. I'm passing the value in as a react prop.

I assume that it doesn't get through the if in index.js on line 49.

Error: Unrecognized extension value in extension set ([object Object]). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.

I have a project using uiw/react-codemirror version 4.0.6
It is run okay until mid night yesterday, when I clone my project and re install it. When it start some thing wrong is happended like this picture
Screenshot from 2021-11-06 14-59-31

I think some bug happend when you update new version confile with the codemirror dependency. Can you check for me?
Thank you!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.