import { Plugin, TFile } from 'obsidian'; import { VIEW_TYPE } from './constants'; import { DEFAULT_SETTINGS, YaotpSettings, YaotpSettingTab } from './settings'; import { TaskFileView } from './view/TaskFileView'; import { installFileIntercept, uninstallFileIntercept } from './file-intercept'; export default class YaotpPlugin extends Plugin { settings: YaotpSettings = { ...DEFAULT_SETTINGS }; private taskRegex: RegExp = new RegExp(DEFAULT_SETTINGS.taskFileRegex); async onload(): Promise { await this.loadSettings(); this.rebuildRegex(); // Register the custom view this.registerView( VIEW_TYPE, (leaf) => new TaskFileView(leaf, this.settings, () => this.getTaskFiles()) ); // Intercept file opens for task files installFileIntercept((path) => this.isTaskFile(path)); // Open existing task-file leaves in the custom view on startup this.app.workspace.onLayoutReady(() => { this.redirectExistingLeaves(); }); // Settings tab this.addSettingTab(new YaotpSettingTab(this.app, this)); // Command: open inbox this.addCommand({ id: 'open-inbox', name: 'Open Inbox', callback: () => this.openInbox(), }); } onunload(): void { uninstallFileIntercept(); } async loadSettings(): Promise { this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()); } async saveSettings(): Promise { await this.saveData(this.settings); this.rebuildRegex(); } isTaskFile(path: string): boolean { return this.taskRegex.test(path); } getTaskFiles(): TFile[] { return this.app.vault .getMarkdownFiles() .filter((f) => this.isTaskFile(f.path)); } private rebuildRegex(): void { try { this.taskRegex = new RegExp(this.settings.taskFileRegex); } catch { // Fall back to default if the setting is invalid this.taskRegex = new RegExp(DEFAULT_SETTINGS.taskFileRegex); } } private redirectExistingLeaves(): void { this.app.workspace.iterateAllLeaves((leaf) => { const state = leaf.getViewState(); if ( state.type === 'markdown' && state.state?.file && this.isTaskFile(state.state.file as string) ) { leaf.setViewState({ ...state, type: VIEW_TYPE }); } }); } private async openInbox(): Promise { const { inboxPath } = this.settings; let file = this.app.vault.getAbstractFileByPath(inboxPath) as TFile | null; if (!file) { file = await this.app.vault.create(inboxPath, ''); } const leaf = this.app.workspace.getLeaf(false); await leaf.openFile(file); } }