Skip to content

Commit

Permalink
Improve performance by only calling getViewState() when necessary
Browse files Browse the repository at this point in the history
  • Loading branch information
bwydoogh committed Aug 25, 2021
1 parent 5f6aff3 commit 41f5ed0
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 7 deletions.
1 change: 0 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,3 @@ obsidianUIMode: preview
... and this will always open the note in "preview" mode.

This plug-in also ensures that a note is always opened in the configured default mode (suppose the Obsidian setting has "preview" as default mode but the pane is currently in "source" mode, then opening a new note in that same pane will open in "preview" mode).

12 changes: 8 additions & 4 deletions main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,18 @@ export default class ViewModeByFrontmatterPlugin extends Plugin {
return;
}

let state = leaf.getViewState();

// ... get frontmatter data and search for a key indicating the desired view mode
// and when the given key is present ... set it to the declared mode
const fileCache = this.app.metadataCache.getFileCache(view.file);
const fileDeclaredUIMode = fileCache !== null && fileCache.frontmatter ? fileCache.frontmatter[this.OBSIDIAN_UI_MODE_KEY] : null;

if (null !== fileDeclaredUIMode) {
if (['source', 'preview', 'live'].includes(fileDeclaredUIMode)
&& state.state.mode !== fileDeclaredUIMode) {
&& view.getMode() !== fileDeclaredUIMode) {
let state = leaf.getViewState();

state.state.mode = fileDeclaredUIMode;

leaf.setViewState(state);
}

Expand All @@ -30,8 +31,11 @@ export default class ViewModeByFrontmatterPlugin extends Plugin {

const defaultViewMode = this.app.vault.config.defaultViewMode ? this.app.vault.config.defaultViewMode : 'source';

if (state.state.mode !== defaultViewMode) {
if (view.getMode() !== defaultViewMode) {
let state = leaf.getViewState();

state.state.mode = defaultViewMode;

leaf.setViewState(state);
}
};
Expand Down
4 changes: 2 additions & 2 deletions manifest.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
{
"id": "obsidian-view-mode-by-frontmatter",
"name": "Force note view mode (preview, source) using front matter",
"version": "1.0.0",
"version": "1.0.1",
"minAppVersion": "0.9.12",
"description": "This plugin allows to force the view mode for a note by using front matter: YAML block with 'obsidian_ui_mode' as key.",
"description": "This plugin allows to force the view mode for a note by using front matter",
"author": "Benny Wydooghe",
"authorUrl": "https://i-net.be",
"isDesktopOnly": false
Expand Down

0 comments on commit 41f5ed0

Please sign in to comment.