feat: add main code

This commit is contained in:
lowit 2025-04-13 19:12:21 +03:00
parent 3b6e1ed268
commit cc9f88844d
No known key found for this signature in database
GPG key ID: CA635F9EC3D8EF42
3 changed files with 2576 additions and 95 deletions

261
main.ts
View file

@ -1,89 +1,119 @@
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
import {
App,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting,
TFile,
} from "obsidian";
// Remember to rename these classes and interfaces!
interface MyPluginSettings {
mySetting: string;
interface TasksCleanerSettings {
daysThreshold: number;
taskPattern: string;
filenamePattern: string;
}
const DEFAULT_SETTINGS: MyPluginSettings = {
mySetting: 'default'
}
const DEFAULT_SETTINGS: TasksCleanerSettings = {
daysThreshold: 7,
taskPattern: "- \\[x\\].*?✅\\s*(\\d{4}-\\d{2}-\\d{2})",
filenamePattern: "TODO",
};
export default class MyPlugin extends Plugin {
settings: MyPluginSettings;
export default class TasksCleanerPlugin extends Plugin {
settings: TasksCleanerSettings;
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.addRibbonIcon("trash", "Clean old tasks", async () => {
await this.cleanOldTasks();
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new SampleSettingTab(this.app, this));
this.addSettingTab(new TasksCleanerSettingTab(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));
new Notice("Tasks Cleaner plugin loaded.");
}
onunload() {
async cleanOldTasks() {
const files = this.app.vault.getMarkdownFiles();
const now = new Date();
const thresholdDate = new Date(
now.getTime() - this.settings.daysThreshold * 24 * 60 * 60 * 1000,
);
const taskRegex = new RegExp(this.settings.taskPattern);
const results: {
file: TFile;
linesToDelete: number[];
taskCount: number;
content: string;
}[] = [];
for (const file of files) {
if (
this.settings.filenamePattern &&
!file.name.includes(this.settings.filenamePattern)
)
continue;
const content = await this.app.vault.read(file);
const lines = content.split("\n");
const linesToDelete: number[] = [];
let taskCount = 0;
let i = 0;
while (i < lines.length) {
const line = lines[i];
const match = line.match(taskRegex);
if (match) {
const doneDate = new Date(match[1]);
if (doneDate < thresholdDate) {
linesToDelete.push(i);
taskCount++;
let j = i + 1;
while (j < lines.length && lines[j].match(/^\s+/)) {
linesToDelete.push(j);
j++;
}
i = j;
continue;
}
}
i++;
}
if (linesToDelete.length > 0) {
results.push({ file, linesToDelete, taskCount, content });
}
}
if (results.length === 0) {
new Notice("There are no tasks to delete.");
return;
}
new ConfirmModal(this.app, results, async () => {
for (const result of results) {
const newLines = result.content
.split("\n")
.filter((_, idx) => !result.linesToDelete.includes(idx));
await this.app.vault.modify(result.file, newLines.join("\n"));
}
new Notice("Outdated tasks have been deleted.");
}).open();
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData(),
);
}
async saveSettings() {
@ -91,44 +121,99 @@ export default class MyPlugin extends Plugin {
}
}
class SampleModal extends Modal {
constructor(app: App) {
class ConfirmModal extends Modal {
constructor(
app: App,
private results: { file: TFile; taskCount: number }[],
private onConfirm: () => void,
) {
super(app);
}
onOpen() {
const {contentEl} = this;
contentEl.setText('Woah!');
const { contentEl } = this;
contentEl.createEl("h2", { text: "Confirmation of deletion" });
const ul = contentEl.createEl("ul");
for (const { file, taskCount } of this.results) {
ul.createEl("li", {
text: `${file.path}: ${taskCount} tasks will be deleted`,
});
}
const button = contentEl.createEl("button", { text: "Clear" });
button.style.marginTop = "1em";
button.onclick = () => {
this.onConfirm();
this.close();
};
}
onClose() {
const {contentEl} = this;
contentEl.empty();
this.contentEl.empty();
}
}
class SampleSettingTab extends PluginSettingTab {
plugin: MyPlugin;
class TasksCleanerSettingTab extends PluginSettingTab {
plugin: TasksCleanerPlugin;
constructor(app: App, plugin: MyPlugin) {
constructor(app: App, plugin: TasksCleanerPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const {containerEl} = this;
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "Tasks Cleaner Cleaner" });
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) => {
this.plugin.settings.mySetting = value;
await this.plugin.saveSettings();
}));
.setName("Delete issues older than (days)")
.setDesc(
"Completed tasks older than this number of days will be deleted.",
)
.addText((text) =>
text
.setPlaceholder("for example, 7")
.setValue(this.plugin.settings.daysThreshold.toString())
.onChange(async (value) => {
const num = parseInt(value);
if (!isNaN(num)) {
this.plugin.settings.daysThreshold = num;
await this.plugin.saveSettings();
}
}),
);
new Setting(containerEl)
.setName("Task template")
.setDesc(
"A regular expression for searching for completed tasks. It must contain the completion date.",
)
.addText((text) =>
text
.setPlaceholder("- [x] ... ✅ yyyy-mm-dd")
.setValue(this.plugin.settings.taskPattern)
.onChange(async (value) => {
this.plugin.settings.taskPattern = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName("Filter by file name")
.setDesc(
"If specified, tasks will be cleared only in files containing this line in the name.",
)
.addText((text) =>
text
.setPlaceholder("TODO")
.setValue(this.plugin.settings.filenamePattern)
.onChange(async (value) => {
this.plugin.settings.filenamePattern = value;
await this.plugin.saveSettings();
}),
);
}
}

View file

@ -1,11 +1,10 @@
{
"id": "sample-plugin",
"name": "Sample Plugin",
"version": "1.0.0",
"id": "tasks-cleaner",
"name": "Tasks Cleaner",
"version": "0.1.0",
"minAppVersion": "0.15.0",
"description": "Demonstrates some of the capabilities of the Obsidian API.",
"author": "Obsidian",
"authorUrl": "https://obsidian.md",
"fundingUrl": "https://obsidian.md/pricing",
"description": "Task Cleaner for completed tasks.",
"author": "lowit",
"authorUrl": "https://github.com/lowitea/",
"isDesktopOnly": false
}

2397
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff