Develop functionality
This commit is contained in:
parent
af0d47c19c
commit
13aa4dd66d
|
@ -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),
|
||||
};
|
||||
}
|
||||
}
|
|
@ -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();
|
||||
}));
|
||||
}
|
||||
}
|
254
main.ts
254
main.ts
|
@ -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!
|
||||
|
||||
interface MyPluginSettings {
|
||||
mySetting: string;
|
||||
enum CountType {
|
||||
Word = "word",
|
||||
Page = "page",
|
||||
}
|
||||
|
||||
const DEFAULT_SETTINGS: MyPluginSettings = {
|
||||
mySetting: 'default'
|
||||
interface NovelWordCountSettings {
|
||||
countType: CountType;
|
||||
}
|
||||
|
||||
export default class MyPlugin extends Plugin {
|
||||
settings: MyPluginSettings;
|
||||
const DEFAULT_SETTINGS: NovelWordCountSettings = {
|
||||
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() {
|
||||
await this.loadSettings();
|
||||
this.addSettingTab(new NovelWordCountSettingTab(this.app, this));
|
||||
|
||||
// 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.handleEvents();
|
||||
|
||||
// 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();
|
||||
await this.refreshAllCounts();
|
||||
await this.updateDisplayedCounts();
|
||||
}
|
||||
|
||||
// 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));
|
||||
async onunload() {
|
||||
this.saveSettings();
|
||||
}
|
||||
|
||||
onunload() {
|
||||
|
||||
}
|
||||
// SETTINGS
|
||||
|
||||
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() {
|
||||
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 {
|
||||
constructor(app: App) {
|
||||
super(app);
|
||||
}
|
||||
class NovelWordCountSettingTab extends PluginSettingTab {
|
||||
plugin: NovelWordCountPlugin;
|
||||
|
||||
onOpen() {
|
||||
const {contentEl} = this;
|
||||
contentEl.setText('Woah!');
|
||||
}
|
||||
|
||||
onClose() {
|
||||
const {contentEl} = this;
|
||||
contentEl.empty();
|
||||
}
|
||||
}
|
||||
|
||||
class SampleSettingTab extends PluginSettingTab {
|
||||
plugin: MyPlugin;
|
||||
|
||||
constructor(app: App, plugin: MyPlugin) {
|
||||
constructor(app: App, plugin: NovelWordCountPlugin) {
|
||||
super(app, plugin);
|
||||
this.plugin = plugin;
|
||||
}
|
||||
|
||||
display(): void {
|
||||
const {containerEl} = this;
|
||||
const { containerEl } = this;
|
||||
|
||||
containerEl.empty();
|
||||
|
||||
containerEl.createEl('h2', {text: 'Settings for my awesome plugin.'});
|
||||
containerEl.createEl("h2", { text: "Novel word count settings" });
|
||||
|
||||
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;
|
||||
.setName("Type of count to show")
|
||||
.setDesc("Word count or page count")
|
||||
.addDropdown((drop) =>
|
||||
drop
|
||||
.addOption(CountType.Word, "Word Count")
|
||||
.addOption(CountType.Page, "Page Count")
|
||||
.setValue(this.plugin.settings.countType)
|
||||
.onChange(async (value: CountType) => {
|
||||
this.plugin.settings.countType = value;
|
||||
await this.plugin.saveSettings();
|
||||
}));
|
||||
await this.plugin.updateDisplayedCounts();
|
||||
})
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,10 +1,10 @@
|
|||
{
|
||||
"id": "obsidian-sample-plugin",
|
||||
"name": "Sample Plugin",
|
||||
"version": "1.0.1",
|
||||
"minAppVersion": "0.12.0",
|
||||
"description": "This is a sample plugin for Obsidian. This plugin demonstrates some of the capabilities of the Obsidian API.",
|
||||
"author": "Obsidian",
|
||||
"authorUrl": "https://obsidian.md",
|
||||
"id": "novel-word-count",
|
||||
"name": "Novel word count",
|
||||
"version": "1.0.0",
|
||||
"minAppVersion": "0.13.31",
|
||||
"description": "Displays a word or page count for each file, folder and vault in the file pane.",
|
||||
"author": "Isaac Lyman",
|
||||
"authorUrl": "https://isaaclyman.com",
|
||||
"isDesktopOnly": false
|
||||
}
|
||||
|
|
File diff suppressed because it is too large
Load Diff
|
@ -1,7 +1,7 @@
|
|||
{
|
||||
"name": "obsidian-sample-plugin",
|
||||
"version": "1.0.1",
|
||||
"description": "This is a sample plugin for Obsidian (https://obsidian.md)",
|
||||
"name": "novel-word-count",
|
||||
"version": "1.0.0",
|
||||
"description": "Displays a word or page count for each file, folder and vault in the file pane.",
|
||||
"main": "main.js",
|
||||
"scripts": {
|
||||
"dev": "node esbuild.config.mjs",
|
||||
|
@ -9,7 +9,7 @@
|
|||
"version": "node version-bump.mjs && git add manifest.json versions.json"
|
||||
},
|
||||
"keywords": [],
|
||||
"author": "",
|
||||
"author": "Isaac Lyman",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@types/node": "^16.11.6",
|
||||
|
|
13
styles.css
13
styles.css
|
@ -1,4 +1,11 @@
|
|||
/* Sets all the text color to red! */
|
||||
body {
|
||||
color: red;
|
||||
.nav-files-container .nav-folder-title::after, .nav-files-container .nav-file-title::after {
|
||||
align-items: center;
|
||||
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;
|
||||
}
|
Loading…
Reference in New Issue