react-codemirror icon indicating copy to clipboard operation
react-codemirror copied to clipboard

Line numbers sometimes don't load properly using fromTextArea

Open DiMono opened this issue 6 years ago • 0 comments

I have the following code to load a codemirror text area dynamically, changing the contents and styling based on the file:

var myCodeMirror = {};
function loadpage(filename) {
  $.ajax({
    method: 'GET',
    url: 'path/to/file/'+filename,
    success: function(xhrRequest, responseText, fullResponse) {
      var results = JSON.parse(fullResponse.responseText);
      $('#editor').val(results);
      $('#filename').val(filename);
      if (typeof(myCodeMirror.setOption) == 'undefined') {
        setTimeout(function() {
          myCodeMirror = CodeMirror.fromTextArea($('#editor')[0], {
           mode: 'css',
           lineNumbers: true
          });
        }, 200);
      } else {
        myCodeMirror.setOption('mode',(filename=='stylescss'?'text/css':'application/x-httpd-php'));
        myCodeMirror.getDoc().setValue(results);
      }
    },
    error: function(xhrRequest, textStatus, errorThrown) {
      // Handle errors
    }
  });
}

$(window).on('load', function() {
	loadpage('initialpage');
});

You might notice the setTimeout. That's because for some reason, when I load the editor the first time, there's a chance that the gutters will be almost 1000px wide. This will persist until I load other files a few times, at which point it will eventually correct itself. Delaying the load seems to be the only semi-reliable way I've found to prevent this from happening. Is there a better way?

DiMono avatar Nov 21 '19 18:11 DiMono