Giter Club home page Giter Club logo

react-monacoeditor's Introduction

react-monacoeditor

CI jsDelivr CDN Downloads Open in unpkg npm version

Monaco Editor component for React. demo @uiwjs.github.io/react-monacoeditor/

Installation

npm install @uiw/react-monacoeditor --save

Using

Open in CodeSandbox

import React from 'react';
import MonacoEditor from '@uiw/react-monacoeditor';

export default function Demo() {
  return (
    <MonacoEditor
      language="html"
      value="<h1>I ♥ react-monacoeditor</h1>"
      height="300px"
      options={{
        theme: 'vs-dark',
      }}
    />
  );
}

Using with Webpack

import React from 'react';
import { render } from 'react-dom';
import MonacoEditor from '@uiw/react-monacoeditor';

const code = `import React, { PureComponent } from 'react';
import MonacoEditor from '@uiw/react-monacoeditor';

export default class App extends PureComponent {
  render() {
    return (
      <MonacoEditor
        language="html"
        value="<h1>I ♥ react-codemirror2</h1>"
        options={{
          selectOnLineNumbers: true,
          roundedSelection: false,
          cursorStyle: 'line',
          automaticLayout: false,
          theme: 'vs-dark',
        }}
      />
    );
  }
}
`;

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      code: '// type your code...',
    }
  }
  editorDidMount(editor, monaco) {
    console.log('editorDidMount', editor, monaco);
    editor.focus();
  }
  onChange(newValue, e) {
    console.log('onChange', newValue, e);
  }
  render() {
    const options = {
      selectOnLineNumbers: true,
      roundedSelection: false,
      readOnly: false,
      cursorStyle: 'line',
      automaticLayout: false,
      theme: 'vs-dark',
      scrollbar: {
        // Subtle shadows to the left & top. Defaults to true.
        useShadows: false,
        // Render vertical arrows. Defaults to false.
        verticalHasArrows: true,
        // Render horizontal arrows. Defaults to false.
        horizontalHasArrows: true,
        // Render vertical scrollbar.
        // Accepted values: 'auto', 'visible', 'hidden'.
        // Defaults to 'auto'
        vertical: 'visible',
        // Render horizontal scrollbar.
        // Accepted values: 'auto', 'visible', 'hidden'.
        // Defaults to 'auto'
        horizontal: 'visible',
        verticalScrollbarSize: 17,
        horizontalScrollbarSize: 17,
        arrowSize: 30,
      },
    };
    return (
      <MonacoEditor
        height="500px"
        language="javascript"
        editorDidMount={this.editorDidMount.bind(this)}
        onChange={this.onChange.bind(this)}
        value={code}
        options={options}
      />
    );
  }
}

render(
  <App />,
  document.getElementById('root')
);

Add the Monaco Editor Webpack Loader Plugin monaco-editor-webpack-plugin to your webpack.config.js:

const MonacoWebpackPlugin = require('monaco-editor-webpack-plugin');
module.exports = {
  plugins: [
    new MonacoWebpackPlugin()
  ]
};

Properties

If you specify value property, the component behaves in controlled mode. Otherwise, it behaves in uncontrolled mode.

  • width width of editor. Defaults to 100%.
  • height height of editor. Defaults to 100%.
  • value value of the auto created model in the editor.
  • defaultValue the initial value of the auto created model in the editor.
  • language the initial language of the auto created model in the editor.
  • theme the theme of the editor vs, vs-dark, hc-black
  • options refer to Monaco interface IEditorConstructionOptions.
  • editorDidMount(editor, monaco) an event emitted when the editor has been mounted (similar to componentDidMount of React).
  • onChange(newValue, event) an event emitted when the content of the current model has changed.
  • autoComplete?: (model: monaco.editor.ITextModel, position: monaco.Position) => languages.CompletionItem[]; User provided extension function provider for auto-complete. #47

Events & Methods

Refer to Monaco interface IEditor.

Related

Contributors

As always, thanks to our amazing contributors!

Made with github-action-contributors.

License

Licensed under the MIT License.

react-monacoeditor's People

Contributors

cs-miller avatar dbetter-endor avatar dependabot[bot] avatar jaywcjlove avatar pisecespeng avatar renovate-bot avatar renovate[bot] 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

react-monacoeditor's Issues

Webpack compilation warning in 0.29.0 with DOMPurify

Creating an optimized production build...
Failed to compile.

Cannot find module 'vs/basic-languages/flow9/flow9.contribution'
Require stack:
- /home/runner/work/react-monacoeditor/react-monacoeditor/node_modules/monaco-editor-webpack-plugin/out/index.js
- /home/runner/work/react-monacoeditor/react-monacoeditor/.kktrc.ts
- /home/runner/work/react-monacoeditor/react-monacoeditor/node_modules/kkt/lib/utils/loaderConf.js
- /home/runner/work/react-monacoeditor/react-monacoeditor/node_modules/kkt/lib/overrides/config.js
- /home/runner/work/react-monacoeditor/react-monacoeditor/node_modules/kkt/lib/scripts/build.js
- /home/runner/work/react-monacoeditor/react-monacoeditor/node_modules/kkt/lib/bin/kkt.js
Creating an optimized production build...
Failed to compile.

./node_modules/monaco-editor/esm/vs/base/browser/markdownRenderer.js
Attempted import error: 'addHook' is not exported from './dompurify/dompurify.js' (imported as 'dompurify').

microsoft/monaco-editor#2691

Support for error highlighting

Is there plan or timeline for introducing support for Error highlighting and linting for code editor UI created by react-monacoeditor?

PS - JSHint also quite heavy to use. :)

Add typescript types

This plugin is awesome .Thanks.
Small problem though trying to use it within typescript causes an error as it does not have typescript types.
Thanks.

Unexpected character '' error

image

my packages:

"electron": "^21.3.3",
"electron-builder": "^23.6.0",
"next": "^12.3.4",
"nextron": "^8.7.0",
"react": "^18.2.0",
"react-dom": "^18.2.0"
"@uiw/react-monacoeditor": "^3.5.9",

how can i fix this?

EditorSimpleWorker.loadForeignModule error

errors.js:8 Uncaught Error: Unexpected usage

Error: Unexpected usage
    at EditorSimpleWorker.loadForeignModule (editorSimpleWorker.js:450)
    at webWorker.js:38
    at errors.js:8errors.js:8 Uncaught Error: Unexpected usage

Error: Unexpected usage
    at EditorSimpleWorker.loadForeignModule (editorSimpleWorker.js:450)
    at webWorker.js:38
    at errors.js:8

I get this error when initializing the monaco editor, I am using react with vite bundler. Anytime I type, the cursor doesn't move and I get this error, when I click spacebar, the top line moves down and I am stuck on the first line. I tried using the sandbox to check the error but same thing, I got error 502 when opening it.
Is it a bug on my end or it is with the pacckage?

Cannot read properties of null (reading 'useState')

I am getting this error after I npm install and import MonacoEditor into my react functional component.

This is some of my code:
I have version 3.5.8 installed.

`import React, { useState, useContext } from "react";
import MonacoEditor from "@uiw/react-monacoeditor";

<MonacoEditor
value={code}
language={language}
onBlur={handleCodeChange}
onChange={handleCodeType}
options={{
theme: "vs-dark",
}}
/>
`
No matter what options I pass in, as long as MonacoEditor is there, I get this error:

Cannot read properties of null (reading 'useState')
TypeError: Cannot read properties of null (reading 'useState')
at useState (http://localhost:3000/static/js/bundle.js:257147:25)
at MonacoEditor (http://localhost:3000/static/js/bundle.js:64921:70)
at renderWithHooks (http://localhost:3000/static/js/bundle.js:30704:22)
at updateForwardRef (http://localhost:3000/static/js/bundle.js:33275:24)
at beginWork (http://localhost:3000/static/js/bundle.js:35322:20)
at HTMLUnknownElement.callCallback (http://localhost:3000/static/js/bundle.js:20296:18)
at Object.invokeGuardedCallbackDev (http://localhost:3000/static/js/bundle.js:20340:20)
at invokeGuardedCallback (http://localhost:3000/static/js/bundle.js:20397:35)
at beginWork$1 (http://localhost:3000/static/js/bundle.js:40271:11)
at performUnitOfWork (http://localhost:3000/static/js/bundle.js:39518:16)

如何自动格式化代码

求教,这个编辑器如何在初始化的时候格式化代码,而且我发现我这个右键格式化好像也不行是咋肥事,json格式的
image
我初始化格式代码是这样的

 editorDidMount={(editor) => {
          
                editor.getAction('editor.action.formatDocument').run();
              }}

发现没用

Error: Unexpected usage at EditorSimpleWorkerImpl.BaseEditorSimpleWorker.loadForeignModule (editorSimpleWorker.js:391)

Could not create web worker(s). Falling back to loading web worker code in main thread, which might cause UI freezes. Please see https://github.com/Microsoft/monaco-editor#faq
You must define a function MonacoEnvironment.getWorkerUrl or MonacoEnvironment.getWorker
Error: Unexpected usage
at EditorSimpleWorkerImpl.BaseEditorSimpleWorker.loadForeignModule (editorSimpleWorker.js:391)
at webWorker.js:38
at ShallowCancelThenPromise.CompletePromise_then [as then] (winjs.base.js:1587)
at MonacoWebWorkerImpl._getForeignProxy (webWorker.js:37)
at MonacoWebWorkerImpl.getProxy (webWorker.js:61)
at WorkerManager.webpackJsonp.2144.WorkerManager._getClient (workerManager.js:51)
at WorkerManager.webpackJsonp.2144.WorkerManager.getLanguageServiceWorker (workerManager.js:62)
at DocumentLinkAdapter.worker [as _worker] (htmlMode.js:15)
at DocumentLinkAdapter.webpackJsonp.2145.DocumentLinkAdapter.provideLinks (languageFeatures.js:322)
at getLinks.js:69
at Array.map ()
at getLinks (getLinks.js:68)
at links.js:246
at Object.createCancelablePromise [as i] (async.js:33)
at LinkDetector. (links.js:246)
at step (links.js:55)
at Object.next (links.js:36)
at links.js:30
at new Promise ()
at __awaiter (links.js:26)
at LinkDetector.beginCompute (links.js:234)
at LinkDetector.onModelModeChanged (links.js:227)
at links.js:206
at Emitter.fire (event.js:105)
at LanguageFeatureRegistry.register (languageFeatureRegistry.js:44)
at Object.registerLinkProvider (standaloneLanguages.js:313)
at Object.setupMode (htmlMode.js:21)
at monaco.contribution.js:89
at Object.notifySuccess [as _notify] (winjs.base.js:1191)
at Object.enter (winjs.base.js:867)
at _Base.Class.derive._creator._run (winjs.base.js:1089)
at _Base.Class.derive._creator._completed (winjs.base.js:1057)
at ````

YAML multiline code has invalid color highlighting

When using a multiline block (either | or > ) in yaml the highlighting color will often be incorrect. This mainly happens when brackets are involved. Example:

controller:
  config:
    modsecurity-snippet: |
        correct: true
        also-correct: true
        {
            incorrect: true 
            {
                also-incorrect: true
            }
        }

The expected outcome is that everything underneath the | pipe is highlighted as orange as expected with multiline color highlighting, however the outcome seems to be:

image

Is there any chance that you could look into this issue?

Thanks in advance.

Importing with browserify?

Looks like a great project, and exactly what I'm looking for. Unfortunately, when I try to import the component, my gulp/browserify build process fails with:

Error: Cannot find module 'monaco-editor' from '/<project path>/node_modules/@uiw/react-monacoeditor/lib/cjs'

I note that for webpack, a webpack plug in is required. Can it work with browserify?

Dependency Dashboard

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

Other Branches

These updates are pending. To force PRs open, click the checkbox below.

  • chore(deps): update actions/checkout action to v4
  • chore(deps): update actions/setup-node action to v4
  • chore(deps): update peaceiris/actions-gh-pages action to v4

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 v3
  • actions/setup-node v3
  • peaceiris/actions-gh-pages v3
.github/workflows/pull_requests.yml
  • actions/checkout v3
  • actions/setup-node v3
npm
core/package.json
  • @babel/runtime ^7.16.7
  • monaco-editor ^0.44.0
  • react >=16.8.0
  • react-dom >=16.8.0
package.json
  • husky ^8.0.3
  • lint-staged ^15.0.0
  • lerna ^7.0.1
  • prettier ^3.0.0
  • tsbb ^4.1.0
  • node >=16.0.0
  • typescript ^5.1.3
www/package.json
  • @uiw/react-markdown-preview-example ^1.5.6
  • code-example ^3.3.6
  • monaco-editor ^0.44.0
  • react ^18.2.0
  • react-dom ^18.2.0
  • @babel/plugin-proposal-private-property-in-object ^7.21.11
  • @kkt/raw-modules ^7.5.2
  • @kkt/scope-plugin-options ^7.5.2
  • @types/react ^18.0.31
  • @types/react-dom ^18.0.11
  • kkt ^7.5.2
  • markdown-react-code-preview-loader ^2.1.7
  • monaco-editor-webpack-plugin ~7.1.0
  • source-map-explorer ^2.5.3

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

error TS2451: Cannot redeclare block-scoped variable 'MonacoEnvironment'.

Hello

I am getting this Typescript error when I import MonacoEditor from '@uiw/react-monacoeditor';

node_modules/@uiw/react-monacoeditor/node_modules/monaco-editor/esm/vs/editor/editor.api.d.ts:12:9 - error TS2451: Cannot redeclare block-scoped variable 'MonacoEnvironment'.

12 let MonacoEnvironment: Environment | undefined;
~~~~~~~~~~~~~~~~~

node_modules/monaco-editor/esm/vs/editor/editor.api.d.ts:12:9
12 let MonacoEnvironment: Environment | undefined;
~~~~~~~~~~~~~~~~~
'MonacoEnvironment' was also declared here.

node_modules/monaco-editor/esm/vs/editor/editor.api.d.ts:12:9 - error TS2451: Cannot redeclare block-scoped variable 'MonacoEnvironment'.

12 let MonacoEnvironment: Environment | undefined;
~~~~~~~~~~~~~~~~~

node_modules/@uiw/react-monacoeditor/node_modules/monaco-editor/esm/vs/editor/editor.api.d.ts:12:9
12 let MonacoEnvironment: Environment | undefined;
~~~~~~~~~~~~~~~~~
'MonacoEnvironment' was also declared here.

[18:22:40] Found 2 errors. Watching for file changes.

Liquid not in the list on the demo website

Hi,

First of all, thanks for porting the Monaco Editor to React :)
I just wanted to note that on the demo page in the list of supported language you didn't put Liquid although it's supported (highlights Liquid and HTML).

image

Cheers

HOW TO USE CUSTOM THEMES?

HOW DO I WRITE CUSTOM RULES AND CUSTOM THEMES?

https://microsoft.github.io/monaco-editor/playground.html#customizing-the-appearence-exposed-colors

Like in the following example

monaco.editor.defineTheme('myTheme', {
    base: 'vs-dark',
    inherit: true,
    rules: [{ background: 'EDF9FA' }],
    colors: {
        'editor.foreground': '#000000',
        'editor.background': '#EDF9FA',
        'editorCursor.foreground': '#8B0000',
        'editor.lineHighlightBackground': '#0000FF20',
        'editorLineNumber.foreground': '#008800',
        'editor.selectionBackground': '#88000030',
        'editor.inactiveSelectionBackground': '#88000015'
    }
});

I want to change the background colour of the editor.

Action Required: Fix Renovate Configuration

There is an error with this repository's Renovate configuration that needs to be fixed. As a precaution, Renovate will stop PRs until it is resolved.

Error type: undefined. Note: this is a nested preset so please contact the preset author if you are unable to fix it yourself.

model.canUndo is not a function

Hello. When I usereact-router-dom with react-monacoeditor I get this error.
The error will appear when I refresh (F5) the page which contains the editor and navigate to another route (/about) and back to editor page, the editor stops working and I get this error.

ok

React render two Editors instead of one

Console log:

Uncaught Error: Unexpected usage

loadForeignModule@http://localhost:3000/static/js/bundle.js:130741:27
./node_modules/.pnpm/[email protected]/node_modules/monaco-editor/esm/vs/editor/browser/services/webWorker.js/_getForeignProxy/this._foreignProxy<@http://localhost:3000/static/js/bundle.js:79060:22

I'm installed react-monacoeditor on new CRA app with React 18.0.1 and add one editor, but react renders instead two.

The first window has class: overflow-guard
The second: monaco-editor no-user-select mac showUnused showDeprecated vs-dark

I'm tested it on Firefox, Opera and Chromium with the same results.
OS: macOS Big Sur.

Screenshot 2022-05-02 at 20 31 49

How can I fix it?

When the {value} is provided again, with the same value, the position returns to the beggining of the file.

I'm trying to MonacoEditor with redux. Which means that the text in the editor is stored in the redux store.

On each key, the new value of the text is presented to the MonacoEditor React componant. And it's working fine, but the "position" of the cursor keep beeing reseting the beggining of the file.

Is there a way to configure the component so the position doesn't change when presenting a new value (or at least the same value as the one already in the editor) ?

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.