Monaco-editor: Focus is not reset after a model change

Created on 18 Sep 2016  路  8Comments  路  Source: microsoft/monaco-editor

Steps to reproduce:

  1. call editor.focus
  2. call editor.setModel with a new model

the editor should be focused after a change but it is not

bug

Most helpful comment

Yes, the view state is reset when changing models (e.g. cursor position, scroll position, folding state, etc.) because we can't assume that we get 100% the same text as it appears to be in your case. I suggest using editor.saveViewState() and editor.restoreViewState().

All 8 comments

Most likely happening because we destroy and recreate the view when a model changes, so the dom node that holds focus gets detached from the DOM and a new textarea is created.

You can workaround on your side by restoring focus via editor.focus() if editor.isFocused() is true before the model is set.

@alexandrudima yes, i do exactly that, but there is one undesirable effect: if one has already started typing before editor.focus() is called, then the cursor jumps to the start of a model

@akosyakov Can you explain in greater detail the order of things, or the shape of your code, how could one start typing before editor.focus() if the code is written synchronously:

function setModelMaintainFocus(editor, model) {
  let isFocused = editor.isFocused();
  editor.setModel(model);
  if (isFocused) {
    editor.focus();
  }
}

@alexandrudima I see, you are right.

We create a model just to change an URI and expect that the state of an editor will be preserved, e.g. focus and position of the cursor. But it happens that the cursor is moved to the beginning of an editor after a model change. We could also store a cursor offset and reset it after, similar to focus.

Yes, the view state is reset when changing models (e.g. cursor position, scroll position, folding state, etc.) because we can't assume that we get 100% the same text as it appears to be in your case. I suggest using editor.saveViewState() and editor.restoreViewState().

@alexandrudima will it help with focus either, or we still have to apply the workaround?

The focus preserving is a valid bug.

restoreViewState will restore the scroll position, the selection state, etc. This is usually useful when implementing something as tabs, where there is one editor instance that consistently gets calls to setModel(..) to switch from one tab to another. For each tab, the view state can be maintained via saveViewState() and restoreViewState().

The view state gets reset with each setModel(...) call because one file could have 1000 lines and the next could have only 10, etc. So the cursor position, the scroll state from one file don't necessarily make sense for the next file...

got it, thx

Was this page helpful?
0 / 5 - 0 ratings