How does Monaco Editor enable text editing on a web page?
Today I was puzzled by Microsoft’s Monaco Editor, which powers Visual Studio Code as well as a lot of online editors.
If you look at the HTML source for a line of code, it’s all using standard HTML elements (i.e. no use of <canvas>
or any other special renderer):
In other browser-based text editors like Quill.js, Quip, and Draft.js, they use the contenteditable
attribute to enable editing:
<div contenteditable="true">
<p>This text can be edited by the user!</p>
</div>
But in Monaco there is not one contenteditable
attribute:
It’s all an illusion
Turns out Monaco is pulling a sneaky trick. There’s an invisible <textarea>
element on the page which is what you’re actually typing into:
There is also CSS attached to make the box 0px x 0px
and have everything completely transparent.
Monaco gets all of your keystrokes from there and renders the nice HTML you actually see. An illusion pulled off very cleanly!
HTML CSS JavaScript Editable HTML Content