Monoca Editor代码框高度自动(显示所有行)

编辑器需要高度自动撑出,即有多少行,就显示多少行,这个目前看起来单独用配置的是无法实现的,主要原因是父容器高度未知。

参考issue: https://github.com/microsoft/monaco-editor/issues/794

实现思路是,代码发生变化后,就从dom那里算出应该有的宽度,然后应用

editor.onDidChangeModelDecorations(() => {
        updateEditorHeight() // typing
        requestAnimationFrame(updateEditorHeight) // folding
    })

    let prevHeight = 0

    const updateEditorHeight = () => {
    const editorElement = editor.getDomNode()

    if (!editorElement) {
        return
    }

    const lineHeight = editor.getOption(monaco.editor.EditorOption.lineHeight)
    const lineCount = editor.getModel()?.getLineCount() || 1
    const height = editor.getTopForLineNumber(lineCount + 1) + lineHeight

    if (prevHeight !== height) {
        prevHeight = height
        editorElement.style.height = `${height}px`
        editor.layout()
    }
}

参考一个react中的实现

import React, { useState, useEffect, useCallback } from 'react';
import MonacoEditor from 'react-monaco-editor';
import './index.less';

export default function CodeEditor() {
    const [value, setValue] = useState();
    // 高度缓存
    const [prevHeight, setPrevHeight] = useState(0);

    const handleEditorMount = (editor, monaco) => {
        editor.onDidChangeModelDecorations(() => {
            updateEditorHeight(); // typing
            requestAnimationFrame(updateEditorHeight); // folding
        });

        const updateEditorHeight = () => {
            const editorElement = editor.getDomNode();

            if (!editorElement) {
                return;
            }

            const padding = 40;

            const lineHeight = editor.getOption(
                monaco.editor.EditorOption.lineHeight
            );
            const lineCount = editor.getModel()?.getLineCount() || 1;
            const height =
                editor.getTopForLineNumber(lineCount + 1) +
                lineHeight +
                padding;

            if (prevHeight !== height) {
                setPrevHeight(height);
                editorElement.style.height = `${height}px`;
                editor.layout();
            }
        };
    };

    return (
        <div
            className="ui-code-editor"
        >
            <MonacoEditor
                editorDidMount={handleEditorMount}
                language="python"
                value={value}
                onChange={setValue}
                options={{
                    scrollBeyondLastLine: false,
                }}
            />
        </div>
    );
}

文章原始链接:https://sijie.wang/posts/monoca-editor-stretch-height/

本站文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请保留原始链接