Develop functionality

This commit is contained in:
Isaac Lyman 2022-03-09 13:15:14 -07:00
parent af0d47c19c
commit 13aa4dd66d
7 changed files with 3763 additions and 118 deletions

79
logic/file.ts Normal file
View File

@ -0,0 +1,79 @@
import { TAbstractFile, TFile, TFolder, Vault } from "obsidian";
export interface CountData {
pageCount: number;
wordCount: number;
}
export type CountsByFile = {
[path: string]: CountData;
};
export class FileHelper {
constructor(private vault: Vault) {}
public async getAllFileCounts(): Promise<CountsByFile> {
const files = this.vault.getMarkdownFiles();
const counts: CountsByFile = {};
for (const file of files) {
const contents = await this.vault.cachedRead(file);
const wordCount = this.countWords(contents);
this.setCounts(counts, file.path, wordCount);
}
return counts;
}
public getCountDataForPath(counts: CountsByFile, path: string): CountData {
if (counts.hasOwnProperty(path)) {
return counts[path];
}
const childPaths = Object.keys(counts).filter(
(countPath) => path === "/" || countPath.startsWith(path + "/")
);
return childPaths.reduce(
(total, childPath) => {
const childCount = this.getCountDataForPath(counts, childPath);
total.wordCount += childCount.wordCount;
total.pageCount += childCount.pageCount;
return total;
},
{
wordCount: 0,
pageCount: 0,
} as CountData
);
}
public async updateFileCounts(
abstractFile: TAbstractFile,
counts: CountsByFile
): Promise<void> {
if ((abstractFile as TFolder).children) {
Object.assign(counts, this.getAllFileCounts());
return;
}
const file = abstractFile as TFile;
const contents = await this.vault.cachedRead(file);
const wordCount = this.countWords(contents);
this.setCounts(counts, file.path, wordCount);
}
private countWords(content: string): number {
return (content.match(/[^\s]+/g) || []).length;
}
private setCounts(
counts: CountsByFile,
path: string,
wordCount: number
): void {
counts[path] = {
wordCount: wordCount,
pageCount: Math.ceil(wordCount / 300),
};
}
}

137
main.example.ts Normal file
View File

@ -0,0 +1,137 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
// Remember to rename these classes and interfaces!
interface MyPluginSettings {
mySetting: string;
}
const DEFAULT_SETTINGS: MyPluginSettings = {
mySetting: 'default'
}
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
async onload() {
await this.loadSettings();
// This creates an icon in the left ribbon.
const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (evt: MouseEvent) => {
// Called when the user clicks the icon.
new Notice('This is a notice!');
});
// Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class');
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
const statusBarItemEl = this.addStatusBarItem();
statusBarItemEl.setText('Status Bar Text');
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: 'open-sample-modal-simple',
name: 'Open sample modal (simple)',
callback: () => {
new SampleModal(this.app).open();
}
});
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: 'sample-editor-command',
name: 'Sample editor command',
editorCallback: (editor: Editor, view: MarkdownView) => {
console.log(editor.getSelection());
editor.replaceSelection('Sample Editor Command');
}
});
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-sample-modal-complex',
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView) {
// If checking is true, we're simply "checking" if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
new SampleModal(this.app).open();
}
// This command will only show up in Command Palette when the check function returns true
return true;
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this));
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', (evt: MouseEvent) => {
console.log('click', evt);
});
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class SampleModal extends Modal {
constructor(app: App) {
super(app);
}
onOpen() {
const {contentEl} = this;
contentEl.setText('Woah!');
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
containerEl.createEl('h2', {text: 'Settings for my awesome plugin.'});
new Setting(containerEl)
.setName('Setting #1')
.setDesc('It\'s a secret')
.addText(text => text
.setPlaceholder('Enter your secret')
.setValue(this.plugin.settings.mySetting)
.onChange(async (value) => {
console.log('Secret: ' + value);
this.plugin.settings.mySetting = value;
await this.plugin.saveSettings();
}));
}
}

258
main.ts
View File

@ -1,137 +1,189 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian'; import { CountData, CountsByFile, FileHelper } from "logic/file";
import {
App,
Plugin,
PluginSettingTab,
Setting,
PluginManifest,
WorkspaceLeaf,
} from "obsidian";
// Remember to rename these classes and interfaces! enum CountType {
Word = "word",
interface MyPluginSettings { Page = "page",
mySetting: string;
} }
const DEFAULT_SETTINGS: MyPluginSettings = { interface NovelWordCountSettings {
mySetting: 'default' countType: CountType;
} }
export default class MyPlugin extends Plugin { const DEFAULT_SETTINGS: NovelWordCountSettings = {
settings: MyPluginSettings; countType: CountType.Word,
};
interface NovelWordCountSavedData {
cachedCounts: CountsByFile;
settings: NovelWordCountSettings;
}
interface FileItem {
titleEl: HTMLElement;
}
export default class NovelWordCountPlugin extends Plugin {
savedData: NovelWordCountSavedData;
settings: NovelWordCountSettings;
fileHelper: FileHelper;
constructor(app: App, manifest: PluginManifest) {
super(app, manifest);
this.fileHelper = new FileHelper(this.app.vault);
}
// LIFECYCLE
async onload() { async onload() {
await this.loadSettings(); await this.loadSettings();
this.addSettingTab(new NovelWordCountSettingTab(this.app, this));
// This creates an icon in the left ribbon. this.handleEvents();
const ribbonIconEl = this.addRibbonIcon('dice', 'Sample Plugin', (evt: MouseEvent) => {
// Called when the user clicks the icon.
new Notice('This is a notice!');
});
// Perform additional things with the ribbon
ribbonIconEl.addClass('my-plugin-ribbon-class');
// This adds a status bar item to the bottom of the app. Does not work on mobile apps. await this.refreshAllCounts();
const statusBarItemEl = this.addStatusBarItem(); await this.updateDisplayedCounts();
statusBarItemEl.setText('Status Bar Text');
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: 'open-sample-modal-simple',
name: 'Open sample modal (simple)',
callback: () => {
new SampleModal(this.app).open();
}
});
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: 'sample-editor-command',
name: 'Sample editor command',
editorCallback: (editor: Editor, view: MarkdownView) => {
console.log(editor.getSelection());
editor.replaceSelection('Sample Editor Command');
}
});
// This adds a complex command that can check whether the current state of the app allows execution of the command
this.addCommand({
id: 'open-sample-modal-complex',
name: 'Open sample modal (complex)',
checkCallback: (checking: boolean) => {
// Conditions to check
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (markdownView) {
// If checking is true, we're simply "checking" if the command can be run.
// If checking is false, then we want to actually perform the operation.
if (!checking) {
new SampleModal(this.app).open();
}
// This command will only show up in Command Palette when the check function returns true
return true;
}
}
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this));
// If the plugin hooks up any global DOM events (on parts of the app that doesn't belong to this plugin)
// Using this function will automatically remove the event listener when this plugin is disabled.
this.registerDomEvent(document, 'click', (evt: MouseEvent) => {
console.log('click', evt);
});
// When registering intervals, this function will automatically clear the interval when the plugin is disabled.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
} }
onunload() { async onunload() {
this.saveSettings();
} }
// SETTINGS
async loadSettings() { async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); this.savedData = Object.assign(
{},
await this.loadData()
) as NovelWordCountSavedData;
const settings: NovelWordCountSettings | null = this.savedData
? this.savedData.settings
: null;
this.settings = Object.assign({}, DEFAULT_SETTINGS, settings);
} }
async saveSettings() { async saveSettings() {
await this.saveData(this.settings); await this.saveData(this.savedData);
}
// PUBLIC
public async updateDisplayedCounts() {
const fileExplorerLeaf = await this.getFileExplorerLeaf();
const fileItems: { [path: string]: FileItem } = (
fileExplorerLeaf.view as any
).fileItems;
for (const path in fileItems) {
const counts = this.fileHelper.getCountDataForPath(
this.savedData.cachedCounts,
path
);
const item = fileItems[path];
item.titleEl.setAttribute(
"data-novel-word-count-plugin",
this.getNodeLabel(counts)
);
}
}
// FUNCTIONALITY
private async getFileExplorerLeaf(): Promise<WorkspaceLeaf> {
return new Promise((resolve) => {
let foundLeaf: WorkspaceLeaf | null = null;
this.app.workspace.iterateAllLeaves((leaf) => {
if (foundLeaf) {
return;
}
const view = leaf.view as any;
if (!view || !view.fileItems) {
return;
}
foundLeaf = leaf;
resolve(foundLeaf);
});
if (!foundLeaf) {
throw new Error("Could not find file explorer leaf.");
}
});
}
private getNodeLabel(counts: CountData): string | undefined {
if (!counts || typeof counts.wordCount !== "number") {
return "";
}
switch (this.settings.countType) {
case CountType.Word:
return `${counts.wordCount.toLocaleString()} words`;
case CountType.Page:
return `${counts.pageCount.toLocaleString()} pages`;
}
}
private handleEvents(): void {
this.registerEvent(
this.app.vault.on("modify", async (file) => {
await this.fileHelper.updateFileCounts(
file,
this.savedData.cachedCounts
);
await this.updateDisplayedCounts();
})
);
this.registerEvent(
this.app.vault.on("rename", async () => {
await this.refreshAllCounts();
await this.updateDisplayedCounts();
})
);
}
private async refreshAllCounts() {
this.savedData.cachedCounts = await this.fileHelper.getAllFileCounts();
} }
} }
class SampleModal extends Modal { class NovelWordCountSettingTab extends PluginSettingTab {
constructor(app: App) { plugin: NovelWordCountPlugin;
super(app);
}
onOpen() { constructor(app: App, plugin: NovelWordCountPlugin) {
const {contentEl} = this;
contentEl.setText('Woah!');
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
constructor(app: App, plugin: MyPlugin) {
super(app, plugin); super(app, plugin);
this.plugin = plugin; this.plugin = plugin;
} }
display(): void { display(): void {
const {containerEl} = this; const { containerEl } = this;
containerEl.empty(); containerEl.empty();
containerEl.createEl('h2', {text: 'Settings for my awesome plugin.'}); containerEl.createEl("h2", { text: "Novel word count settings" });
new Setting(containerEl) new Setting(containerEl)
.setName('Setting #1') .setName("Type of count to show")
.setDesc('It\'s a secret') .setDesc("Word count or page count")
.addText(text => text .addDropdown((drop) =>
.setPlaceholder('Enter your secret') drop
.setValue(this.plugin.settings.mySetting) .addOption(CountType.Word, "Word Count")
.onChange(async (value) => { .addOption(CountType.Page, "Page Count")
console.log('Secret: ' + value); .setValue(this.plugin.settings.countType)
this.plugin.settings.mySetting = value; .onChange(async (value: CountType) => {
await this.plugin.saveSettings(); this.plugin.settings.countType = value;
})); await this.plugin.saveSettings();
await this.plugin.updateDisplayedCounts();
})
);
} }
} }

View File

@ -1,10 +1,10 @@
{ {
"id": "obsidian-sample-plugin", "id": "novel-word-count",
"name": "Sample Plugin", "name": "Novel word count",
"version": "1.0.1", "version": "1.0.0",
"minAppVersion": "0.12.0", "minAppVersion": "0.13.31",
"description": "This is a sample plugin for Obsidian. This plugin demonstrates some of the capabilities of the Obsidian API.", "description": "Displays a word or page count for each file, folder and vault in the file pane.",
"author": "Obsidian", "author": "Isaac Lyman",
"authorUrl": "https://obsidian.md", "authorUrl": "https://isaaclyman.com",
"isDesktopOnly": false "isDesktopOnly": false
} }

3370
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,7 @@
{ {
"name": "obsidian-sample-plugin", "name": "novel-word-count",
"version": "1.0.1", "version": "1.0.0",
"description": "This is a sample plugin for Obsidian (https://obsidian.md)", "description": "Displays a word or page count for each file, folder and vault in the file pane.",
"main": "main.js", "main": "main.js",
"scripts": { "scripts": {
"dev": "node esbuild.config.mjs", "dev": "node esbuild.config.mjs",
@ -9,7 +9,7 @@
"version": "node version-bump.mjs && git add manifest.json versions.json" "version": "node version-bump.mjs && git add manifest.json versions.json"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "Isaac Lyman",
"license": "MIT", "license": "MIT",
"devDependencies": { "devDependencies": {
"@types/node": "^16.11.6", "@types/node": "^16.11.6",

View File

@ -1,4 +1,11 @@
/* Sets all the text color to red! */ .nav-files-container .nav-folder-title::after, .nav-files-container .nav-file-title::after {
body { align-items: center;
color: red; content: attr(data-novel-word-count-plugin);
} display: flex;
flex-direction: row;
font-size: 0.8em;
opacity: 0.75;
padding-left: 3px;
text-overflow: ellipsis;
white-space: nowrap;
}