@@ -48,18 +48,14 @@ class CodeElement extends EventTarget {
4848 // init editor on first focus
4949 this . onFocus = this . initEditor . bind ( this ) ;
5050 this . el . addEventListener ( "focus" , this . onFocus ) ;
51+ setTimeout ( ( ) => this . fixFormatting ( ) , 0 ) ;
5152 }
5253
5354 // initEditor removes prepares the code snippet
5455 // for editing for the first time.
5556 initEditor ( event ) {
5657 const code = event . target ;
5758 if ( code . innerHTML . includes ( "</span>" ) ) {
58- // Docusaurus uses <br> for new lines inside code blocks,
59- // so we need to replace it with \n.
60- if ( code . innerHTML . includes ( "<br>" ) ) {
61- code . innerHTML = code . innerHTML . replaceAll ( "<br>" , "\n" ) ;
62- }
6359 code . textContent = code . textContent ;
6460 }
6561 code . removeEventListener ( "focus" , this . onFocus ) ;
@@ -106,6 +102,17 @@ class CodeElement extends EventTarget {
106102 document . execCommand ( "insertText" , false , text ) ;
107103 }
108104
105+ // fixFormatting removes invalid formatting from the code,
106+ // while preserving the syntax highlighting.
107+ fixFormatting ( ) {
108+ this . el . innerHTML = this . el . innerHTML
109+ // Docusaurus uses <br> for new lines inside code blocks,
110+ // so we need to replace it with \n
111+ . replaceAll ( "<br>" , "\n" )
112+ // convert non-breaking spaces to normal ones
113+ . replace ( / [ \u00A0 ] / g, " " ) ;
114+ }
115+
109116 // focusEnd sets the cursor to the end of the element's content.
110117 focusEnd ( ) {
111118 this . el . focus ( ) ;
@@ -121,8 +128,7 @@ class CodeElement extends EventTarget {
121128
122129 // value is the plain text code value.
123130 get value ( ) {
124- // trim and convert non-breaking spaces to normal ones
125- return this . el . textContent . trim ( ) . replace ( / [ \u00A0 ] / g, " " ) ;
131+ return this . el . textContent . trim ( ) ;
126132 }
127133 set value ( val ) {
128134 this . el . textContent = val ;
0 commit comments