Monaco 中添加 CodeLens

发布于:2024-07-09 ⋅ 阅读:(38) ⋅ 点赞:(0)

CodeLens 会在指定代码行上添加一行可点击的文字,点击时可以触发定义的命令,效果如下:

在这里插入图片描述

通过调用 API 注册 LensProvider,点击时触发 Command,首先要注册命令,通过 editor.addCommand () 方法进行注册。三个参数分别为快捷键、处理实现方法 和 上下文。
在这里插入图片描述

registerCodeLensProvider 提供两个函数

  • provideCodeLenses: 创建 Lens
  • resolveCodeLens:返回 Lens

export function codeLensProvider(editor, monaco){

    var commandId = editor.addCommand(
        monaco.KeyCode.F9,
        function () {
            // services available in `ctx`
            alert("my command is executing!");
        }
    );
    // Add CodeLens provider
    let removeCodeLens =  monaco.languages.registerCodeLensProvider('javascript', {
        provideCodeLenses: function(model, token) {
            return {
                lenses: [
                    {
                        range: {
                            startLineNumber: editor.getPosition().lineNumber,
                            startColumn: 1,
                            endLineNumber: editor.getPosition().lineNumber,
                            endColumn: 1
                        },
                        id: 'helloWorldLens'
                    }
                ],
                dispose: function() {}
            };
        },
        resolveCodeLens: function(model, codeLens, token) {
            codeLens.command = {
                id: commandId,
                title: 'Run Hello World',
                tooltip: 'Click to run the helloWorld function'
            };
            return codeLens;
        }
    });
    console.log(removeCodeLens)
    return removeCodeLens
}

点击时添加 Provider,同时删除上一个 Provider, 否则会出现重复提示。

import logo from './logo.svg';
import './App.css';
import MonacoEditor from 'react-monaco-editor';
import {codeLensProvider} from './editor'
import { useRef, useState,useEffect }  from 'react';

function App() {
  const editorRef = useRef(null);
  const monacoRef = useRef(null);
  const decorationsRef = useRef([]);

  const [removeCodeLens, setRemoveCodeLens] = useState(null);

  const handleEditorDidMount = (editor, monaco) => {
    editorRef.current = editor;
    monacoRef.current = monaco;

    editor.onDidChangeCursorPosition(() => {
      setRemoveCodeLens(codeLensProvider(editor, monaco))
    });  
    

  };
  useEffect(() => {
     
     return ()=>{ if (removeCodeLens && typeof removeCodeLens.dispose === 'function') {
        removeCodeLens.dispose();
      }}
    
  }, [removeCodeLens]);

  useEffect(() => {
    // Define custom styles for the decorations
    const style = document.createElement('style');
    style.innerHTML = `
      .myAfterContentDecoration::after {
        content: ' // 备注';
        color: green;
        font-weight: bold;
      }
    `;
    document.head.appendChild(style);
  }, []);
  return (
    <div style={{'margin':'100px auto', 'width': '800px'}}>
   <MonacoEditor
        width="800"
        height="600"
        language="javascript"
        theme="vs-dark"
        value={`// Write your JavaScript code here
function helloWorld() {
  console.log('Hello, world!');
}
helloWorld();`}
        options={{
          selectOnLineNumbers: true
        }}
        editorDidMount={handleEditorDidMount}
      />
    </div>
      
  );
}

export default App;



最终效果,点击事件发生时,在当前代码行上加一行文字并可以点击。
请添加图片描述


网站公告

今日签到

点亮在社区的每一天
去签到