Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Preserve cursor position in editors #3485

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
36 changes: 35 additions & 1 deletion client/homebrew/editor/editor.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,17 @@ const Editor = createClass({
editorTheme : editorTheme
});
}
if(this.refs.codeEditor){
this.refs.codeEditor.codeMirror.focus();
this.refs.codeEditor.codeMirror.setCursor(this.getStoredCursorPosition(this.state.view))

}

},

componentWillUnmount : function() {
window.removeEventListener('resize', this.updateEditorSize);
this.setStoredCursorPosition(this.state.view);
},

componentDidUpdate : function(prevProps, prevState, snapshot) {
Expand All @@ -79,6 +86,27 @@ const Editor = createClass({
};
},

/**
* Stores the current cursor position in local storage.
* @param {string} view - The editor type ('text' or 'style').
*/
setStoredCursorPosition : function(view){
if(view === 'text' || view === 'style'){
const cursorPos = this.refs.codeEditor.codeMirror.getCursor();
window.localStorage.setItem(`CURSOR_POS-${view}`, JSON.stringify(cursorPos))
}
},

/**
* Retrieves the stored cursor position from local storage.
* @param {string} view - The editor type ('text' or 'style').
* @returns {Object} - The cursor position object or { line: 0, ch: 0 } if not found.
*/
getStoredCursorPosition : function(view){
const cursorPos = JSON.parse(window.localStorage.getItem(`CURSOR_POS-${view}`)) ?? { line: 0, ch: 0 };
return cursorPos;
},

updateEditorSize : function() {
if(this.refs.codeEditor) {
let paneHeight = this.refs.main.parentNode.clientHeight;
Expand All @@ -93,9 +121,15 @@ const Editor = createClass({

handleViewChange : function(newView){
this.props.setMoveArrows(newView === 'text');
this.setStoredCursorPosition(this.state.view);
const tempCursor = this.getStoredCursorPosition(newView);
this.setState({
view : newView
}, this.updateEditorSize); //TODO: not sure if updateeditorsize needed
}, ()=>{
this.updateEditorSize;
this.refs.codeEditor?.codeMirror.focus();
this.refs.codeEditor?.codeMirror.setCursor(tempCursor)
}); //TODO: not sure if updateeditorsize needed
},

getCurrentPage : function(){
Expand Down