Mercurial > obsidian-remember-file-state
changeset 37:8be02002ed66
Use Obsidian's view APIs for scrolling state
Obsidian does some asynchronous formatting upon opening a file which can
affect the vertical positioning of things, especially when there are
tables for instance. Setting the scrolling position via the CM6 APIs
gets invalidated by this, so we're using the Obsidian view API instead
even if it only allows getting/setting vertical scrolling (not
horizontal).
author | Ludovic Chabant <ludovic@chabant.com> |
---|---|
date | Mon, 14 Aug 2023 10:44:55 -0700 |
parents | 16d304d586b1 |
children | a371a2001e95 |
files | src/main.ts |
diffstat | 1 files changed, 19 insertions(+), 12 deletions(-) [+] |
line wrap: on
line diff
--- a/src/main.ts Mon Aug 14 10:42:21 2023 -0700 +++ b/src/main.ts Mon Aug 14 10:44:55 2023 -0700 @@ -278,14 +278,15 @@ } private readonly rememberFileState = async (file: TFile, view: MarkdownView): Promise<void> => { - const scrollInfo = view.editor.getScrollInfo(); + // Save scrolling position (Obsidian API only gives vertical position). + const scrollInfo = {top: view.currentMode.getScroll(), left: 0}; + + // Save current selection. + // If state selection is undefined, we have a legacy editor. Just ignore that part. const cm6editor = view.editor as EditorWithCM6; const stateSelection: EditorSelection = cm6editor.cm.state.selection; - if (stateSelection == undefined) { - // Legacy editor is in use, let's ignore - return; - } - const stateSelectionJSON = stateSelection.toJSON(); + const stateSelectionJSON = (stateSelection !== undefined) ? stateSelection.toJSON() : ""; + const stateData = {'scrollInfo': scrollInfo, 'selection': stateSelectionJSON}; var existingFile = this.data.rememberedFiles[file.path]; @@ -312,12 +313,18 @@ if (existingFile) { console.debug("RememberedFileState: restoring state for:", file.path, existingFile.stateData); const stateData = existingFile.stateData; - view.editor.scrollTo(stateData.scrollInfo.left, stateData.scrollInfo.top); - const cm6editor = view.editor as EditorWithCM6; - var transaction = cm6editor.cm.state.update({ - selection: EditorSelection.fromJSON(stateData.selection)}) - - cm6editor.cm.dispatch(transaction); + + // Restore scrolling position (Obsidian API only allows setting vertical position). + view.currentMode.applyScroll(stateData.scrollInfo.top); + + // Restore last known selection, if any. + if (stateData.selection != "") { + const cm6editor = view.editor as EditorWithCM6; + var transaction = cm6editor.cm.state.update({ + selection: EditorSelection.fromJSON(stateData.selection)}) + + cm6editor.cm.dispatch(transaction); + } } }