모나코 에디터 동적 크기 조정 가능
인터넷을 통해 모나코 에디터 필드를 사용할 때 html 태그의 텍스트 영역 크기를 흉내낼 수 있는지 알아보고 있지만, 질문에 대한 답변을 찾을 수 없었습니다.
리액트 어플리케이션에서 모나코 에디터 npm 패키지를 사용하고 있습니다.구현이 쉬운지 알고 계십니까?
잘 부탁드립니다!
★★★★★★
을 추가했습니다.pure css target 、 target html 요 、 음음음음음 html 。
div {
resize: vertical;
overflow: auto;
}
TL;DR: 추가automaticLayout: true에디터의 설정에 맞추어 주세요.
NL;PR:
모나코에는 상위 컨테이너에 맞게 자동 크기 조정 기능이 내장되어 있습니다.
createEditorWithAutoResize(){
this.editor = monaco.editor.create(
this.editorDiv.current, {
value: "var x = 0;",
language: 'javascript',
automaticLayout: true // <<== the important part
}
);
}
componentDidMount(){this.createEditorWithAutoResize();}
constructor(props){super(props); this.editorDiv = React.createRef();}
render(){return <div ref={this.editorDiv} className="editor" ></div>}
에디터용 CSS(높이가 10px인 에디터를 처음 렌더링하지 않음):
.editor{
height: 100%;
}
최초 테스트: v0.10.1, 최종 테스트: v0.32.1
주의: < v0 . 20 . 0 :메커니즘은 컨테이너 크기 변경을 수신하지 않고 폴링합니다.
@nrayburn-tech(Monaco Editor의 기고자):버전 0.20에서는 모든 브라우저에서 MutationObserver가 사용됩니다.버전 0.21 이후에서는 지원되는 브라우저에서 ResizeObserver를 사용합니다.그렇지 않으면 폴링 기능을 폴백으로 사용합니다.
.editor.layout()이치노「 」 「 」 、 「 」 。
window.onresize = function (){
editor.layout();
};
기본 웹 앱(html, css, javascript)에서 이 문제를 겪고 있는 사람들을 위해 제가 겪고 있는 크기 조정 문제에 대한 해결책을 찾았습니다.
모나코 편집자가 크기가 조정 가능한 플렉시블 컨테이너에 있어요가로폭만 넓어질 뿐 세로 사이즈는 개봉 후 바로 사용할 수 없는 것 같습니다.
모나코 설정 "automatic Layout: true" 및 다음 CSS를 사용하면 예상대로 크기가 조정됩니다.
.syslog-syslog { 위치: 절대 !중요; }
max-width 99% trick을 시도했지만 페이지 가장자리 부근의 폭을 늘리면 지연이 발생합니다.
이것은 오래된 질문이지만 문제를 해결하고 반응-반응-반응-반응-반응-반응으로 해결한다.
ResizeObserver를 기반으로 요구 사항을 완벽하게 충족합니다(브라우저 호환성 확인
컴포넌트의 예:
import React, { Component } from 'react';
import ReactResizeDetector from 'react-resize-detector';
import * as monaco from 'monaco-editor';
class Editor extends Component {
constructor(props) {
super(props)
this.state = {
width: 0,
height: 0,
}
this.editor_div = React.createRef()
this.handle_rezise = this.handle_rezise.bind(this);
}
componentDidMount() {
const editor_model = monaco.editor.createModel('', 'sql');
this.monaco_editor = monaco.editor.create(this.editor_div.current, this.props.editorOptions);
this.monaco_editor.setModel(editor_model);
}
componentWillUnmount() {
this.monaco_editor && this.monaco_editor.dispose();
}
handle_rezise(width, height) {
this.monaco_editor.layout({ height, width });
}
render() {
return(
<div
className="editor-container"
style={{ height: '100%' }}>
<ReactResizeDetector
handleWidth
handleHeight
onResize={ this.handle_rezise }
refreshMode="debounce"
refreshRate={100} />
<div
className="editor"
ref={ this.editor_div }
style={{ height: '100%' }} />
</div>
)
}
}
export default Editor;
도움이 되었으면 좋겠다
후세를 위해 내가 도달한 해결책은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 })
})
})
먼저 편집기 레이아웃을 0으로 줄임으로써 부모 요소의 치수를 자식(편집자)이 크기에 기여하지 않아도 안전하게 조회할 수 있습니다.그런 다음 편집기를 새 부모 차원에 일치시킬 수 있습니다.이 작업은 단일 프레임에 걸쳐 이루어지므로 깜박임이나 지연이 발생하지 않습니다.
저 같은 경우에는 정확한 CSS를 사용하고 있습니다만, automatic Layout: true works(실제로 동작하고 있습니다)에서 오버킬이 검출되었습니다(DOM 100ms 인터벌을 풀링하는 것 같으며, 몇 개의 에디터가 문서에서 열려 있습니다.그래서 수동으로 실장하게 되었습니다.
만약을 위해, 나의 요구는 다릅니다.표준적인 방법으로 라이브러리와 퍼포먼스 모두 저렴하게 컨테이너 크기를 조정하고 싶다.제가 한 일은 다음과 같습니다.
css 컨테이너:resize: vertical; overflow: auto
그리고 이 js:
function installResizeWatcher(el, fn, interval){
let offset = {width: el.offsetWidth, height: el.offsetHeight}
setInterval(()=>{
let newOffset = {width: el.offsetWidth, height: el.offsetHeight}
if(offset.height!=newOffset.height||offset.width!=newOffset.width){
offset = newOffset
fn()
}
}, interval)
}
const typeScriptCodeContainer = document.getElementById('typeScriptCodeContainer')
typeScriptCodeEditor = monaco.editor.create(typeScriptCodeContainer, Object.assign(editorOptions, {value: example.codeValue}))
installResizeWatcher(typeScriptCodeContainer, typeScriptCodeEditor.layout.bind(typeScriptCodeEditor), 2000)
네, 2초 간격으로 1회만 등록해 주세요.모나코에서 자동 레이아웃을 위한 크기 조정 간격이 100ms에 있습니다. IMHO는 너무 심합니다.
실제 작업 보기: https://typescript-api-playground.glitch.me/?http=2
언급URL : https://stackoverflow.com/questions/47017753/monaco-editor-dynamically-resizable
'programing' 카테고리의 다른 글
| 컨트롤러의 Spring Boot @Async 메서드가 동시에 실행되고 있습니다. (0) | 2023.03.31 |
|---|---|
| Travis/Jest:TypeError: 개체 '#'의 읽기 전용 속성 'Symbol(Symbol.toStringTag)'에 할당할 수 없습니다. (0) | 2023.03.31 |
| 여러 요소에서 ng 클릭으로 클래스 전환 (0) | 2023.03.31 |
| Woocommerce에 고객 주문 코멘트(고객 메모) 표시 (0) | 2023.03.31 |
| 웹 API를 통해 전송된 문자열은 따옴표로 둘러싸여 있습니다. (0) | 2023.03.31 |