diff --git a/src/main.ts b/src/main.ts index a42d783..15118c3 100644 --- a/src/main.ts +++ b/src/main.ts @@ -1,4 +1,4 @@ -import { App, MarkdownView, Modal, Plugin, TFile } from "obsidian"; +import { MarkdownView, Plugin, TFile } from "obsidian"; import { StatusBar } from "./status-bar"; export default class BetterWordCount extends Plugin { @@ -19,6 +19,39 @@ export default class BetterWordCount extends Plugin { this.app.workspace.on("quick-preview", this.onQuickPreview, this) ); + this.registerInterval( + window.setInterval(async () => { + let activeLeaf = this.app.workspace.activeLeaf; + let files: TFile[] = this.app.vault.getMarkdownFiles(); + let currentFile: TFile; + + files.forEach((file) => { + if ((file.basename = activeLeaf.getDisplayText())) { + currentFile = file; + } + }); + if (!activeLeaf || !(activeLeaf.view instanceof MarkdownView)) { + return; + } + + let editor = activeLeaf.view.sourceMode.cmEditor; + if (editor.somethingSelected()) { + let content: string = editor.getSelection(); + this.updateWordCount(content); + this.recentlyTyped = false; + } else if ( + currentFile && + currentFile.extension === "md" && + !this.recentlyTyped + ) { + const contents = await this.app.vault.read(currentFile); + this.updateWordCount(contents); + } else if (!this.recentlyTyped) { + this.updateWordCount(""); + } + }, 500) + ); + let activeLeaf = this.app.workspace.activeLeaf; let files: TFile[] = this.app.vault.getMarkdownFiles(); @@ -32,32 +65,11 @@ export default class BetterWordCount extends Plugin { async onFileOpen(file: TFile) { if (file && file.extension === "md") { const contents = await this.app.vault.cachedRead(file); + this.recentlyTyped = true; this.updateWordCount(contents); } else { this.updateWordCount(""); } - - let activeLeaf = this.app.workspace.activeLeaf; - if (!activeLeaf || !(activeLeaf.view instanceof MarkdownView)) { - return; - } - - let editor = activeLeaf.view.sourceMode.cmEditor; - - activeLeaf.view.registerInterval( - window.setInterval(async () => { - if (editor.somethingSelected()) { - let content: string = editor.getSelection(); - this.updateWordCount(content); - this.recentlyTyped = false; - } else if (file && file.extension === "md" && !this.recentlyTyped) { - const contents = await this.app.vault.cachedRead(file); - this.updateWordCount(contents); - } else if (!this.recentlyTyped) { - this.updateWordCount(""); - } - }, 500) - ); } onQuickPreview(file: TFile, contents: string) {