F0rce/ace

Calling focus on AceEditor doesn't work the first time

Closed this issue · 3 comments

Describe the bug
The first time we call AceEditor#focus does nothing and (TypeError) : Cannot read property 'focus' of undefined is displayed by Vaadin. The editor is already attached but has not been rendered yet. Calling focus works on subsequent calls.

Looks like problem in lit-ace.js. focusEditor method istrying to call this.editor.focus() while this.editor is undefined. this.editor is lazily initialized in firstUpdated. Could the initialization be moved to constructor? The same error happens when calling setCursorPosition before firstUpdated .

To Reproduce
Clicking on tabs of class described below causes the error.

Tab tab1 = new Tab("Tab1");
Tab tab2 = new Tab("Tab2");
tabs = new Tabs();
tabs.add(tab1, tab2);

Div div = new Div();
AceEditor aceEditor = new AceEditor();
aceEditor.setInitialFocus(true);
aceEditor.setVisible(false);

VerticalLayout layout = new VerticalLayout();
layout.add(tabs, div, aceEditor);
tabs.addSelectedChangeListener(e -> {
	if (div.isVisible()) {
		div.setVisible(false);
		aceEditor.setVisible(true);
		aceEditor.focus();
	} else {
		div.setVisible(true);
		aceEditor.setVisible(false);
	}
});

Screenshot
Screenshot_20210531_084758

F0rce commented

you clould use .setInitialFocus(true); to have the editor focussed when rendered.

F0rce commented

and I will be adding the securitys to not throw these errors anymore

I fixed #10 and #11 in local clone. Here are diffs:

diff.zip

It is worth noting that in lit-ace.js the focusEditor and calculateCursorPositionFromIndex methods add the event listener if editor is undefined:

focusEditor() {
  if (this.editor == undefined) {
    this.addEventListener('editorInitialized', e => this.editor.focus(), {once: true});
  } else {
    this.editor.focus();
  }
}

The event is triggered in initializeEditor:
this.dispatchEvent(new Event('editorInitialized'));