摩纳哥编辑器动态调整大小

ele*_*ova 8 javascript node.js reactjs monaco-editor

我一直在寻找一个讨论是否有可能模仿html标签textarea 在整个互联网上使用Monaco Editor的字段时调整大小,但我找不到回答我的问题.

我在React应用程序中使用monaco-editor npm包.您是否知道这是否易于实施?

先感谢您!

解决方案
使用纯css我选择了目标html元素并添加了以下属性:

__CODE__

小智 21

对于任何在基本网络应用程序(html、css、javascript)中遇到此问题的人,我已经找到了解决我遇到的调整大小问题的解决方案。

我将摩纳哥编辑器放在一个可调整大小的弹性容器中。它只会增加宽度,不会缩小宽度,并且垂直调整大小似乎无法开箱即用。

如果您使用摩纳哥配置“automaticLayout:true”和以下CSS,它似乎会按预期调整大小:

.monaco-editor { position: absolute !important; }
Run Code Online (Sandbox Code Playgroud)

我尝试了最大宽度 99% 技巧,但当增加页面边缘附近的宽度时,它会导致延迟效果。


Dav*_*dio 13

TL; DR:添加automaticLayout: true到编辑器的配置中.

NL; PR:

Monaco有一个内置的自动调整大小到父容器功能:

反应> = 16.3.0(推荐)

constructor(props){super(props); this.ref = React.createRef();}

render(){
 return <div ref={this.editorDiv} className="editor" ></div>
}

componentDidMount(){
 let editor = monaco.editor.create(this.editorDiv.current, {
        value: "var x = 0;",
        language: 'javascript',
        automaticLayout: true // the important part
      });
}
Run Code Online (Sandbox Code Playgroud)

反应<16.3.0

render(){
 return <div ref={el=>{this.editorDiv = el}} className="editor" ></div>
}
 // I use this configuration in the editor:
componentDidMount(){
 let editor = monaco.editor.create(this.editorDiv, {
        value: "var x = 0;",
        language: 'javascript',
        automaticLayout: true // the important part
      });
}
Run Code Online (Sandbox Code Playgroud)

编辑器的CSS(它避免了第一次像10px高度渲染编辑器):

.editor{
 height: 100%;
} 
Run Code Online (Sandbox Code Playgroud)

摩纳哥版本:^ 0.10.1,最后测试:0.12.0

注意: 该机制不会监听其容器大小的变化,而是轮询它们.

  • 如果需要性能,建议不要这样做。https://github.com/Microsoft/monaco-editor/issues/28 (2认同)

Sim*_*erT 12

如果你有编辑器的参考,你可以调用 editor.layout() 一些调整大小的事件。例如,在调整窗口大小时:

window.onresize = function (){
    editor.layout();
};
Run Code Online (Sandbox Code Playgroud)


Sov*_*iut 7

对于后代,我找到的解决方案是进行设置automaticLayout: false,以便我可以在调整大小事件侦听器中执行所有布局。

const placeholder = document.getElementById('placeholder')

const editor = monaco.editor.create(placeholder, {
  value: '// hello world',
  language: 'javascript',
  automaticLayout: false // or remove, it defaults to false
})

// we need the parent of the editor
const parent = placeholder.parentElement

window.addEventListener('resize', () => {
  // make editor as small as possible
  editor.layout({ width: 0, height: 0 })

  // wait for next frame to ensure last layout finished
  window.requestAnimationFrame(() => {
    // get the parent dimensions and re-layout the editor
    const rect = parent.getBoundingClientRect()
    editor.layout({ width: rect.width, height: rect.height })
  })
})
Run Code Online (Sandbox Code Playgroud)

通过首先将编辑器布局减少到 0,我们可以安全地查询父元素的尺寸,而无需子元素(编辑器)影响其大小。然后我们可以将编辑器与新的父尺寸进行匹配。由于这是在单个帧上发生的,因此不应出现闪烁或滞后。