Добавил обработчик открытия нового файла

This commit is contained in:
NoRFoLK 2025-01-25 16:18:50 +04:00
parent 464359f494
commit 71d2580918
2 changed files with 47 additions and 40 deletions

77
main.ts
View File

@ -1,12 +1,15 @@
import { App, MarkdownView, Notice, Plugin, PluginSettingTab, Setting, TFile } from 'obsidian'; import { App, MarkdownView, Notice, Plugin, PluginSettingTab, Setting, TFile } from 'obsidian';
import * as path from 'path';
interface PluginConfiguration { interface PluginConfiguration {
mySetting: string; mySetting: string;
rules?: any; // Add the rules property rules?: any; // Add the rules property
previousFile: TFile | null; // Add the previousFile property
} }
const DEFAULT_SETTINGS: PluginConfiguration = { const DEFAULT_SETTINGS: PluginConfiguration = {
mySetting: 'default' mySetting: 'default',
previousFile: null
} }
export default class MoveNotePlugin extends Plugin { export default class MoveNotePlugin extends Plugin {
@ -28,30 +31,16 @@ export default class MoveNotePlugin extends Plugin {
await this.loadSettings(); await this.loadSettings();
const rules = this.settings.rules; const rules = this.settings.rules;
// Создает иконку в левой боковой панели. // Создает иконку в левой боковой панели.
const ribbonIconEl = this.addRibbonIcon('dice', 'Move File', (evt: MouseEvent) => { const ribbonIconEl = this.addRibbonIcon('dice', 'Move File', (evt: MouseEvent) => {
// Вызывается при клике на иконку. const activeFile = this.app.workspace.getActiveFile();
rules.forEach((rule: any) => { if (activeFile) {
const includeTags = rule?.include?.tags||[]; this.applyRulesToFile(activeFile, rules);
const excludeTags = rule?.exclude?.tags||[]; } else {
new Notice('Не выбран активный файл.');
}
});
this.getTagsFromNote().then(tags => {
if (tags) {
const activeFile = this.app.workspace.getActiveFile();
if (activeFile) {
//вставить сюда код
if (includeTags.every((tag) => tags.includes(tag)) && !excludeTags.some((tag) => tags.includes(tag))) {//проверяем наличие всех тегов из списка в тегах файла
new Notice(`Удовлетворяет правилу ${rule.name}`);
this.moveFileToFolder(activeFile, rule.targetFolder);
}
} else {
new Notice('Не выбран активный файл.');
}
} else {
new Notice('Не удовлетворяет правилам для переноса');
}
});
});
});
// Добавляет дополнительные стили к иконке. // Добавляет дополнительные стили к иконке.
ribbonIconEl.addClass('my-plugin-ribbon-class'); ribbonIconEl.addClass('my-plugin-ribbon-class');
@ -62,17 +51,7 @@ export default class MoveNotePlugin extends Plugin {
callback: async () => { callback: async () => {
const fileList = await this.scanFolder(); const fileList = await this.scanFolder();
fileList.forEach((file) => { fileList.forEach((file) => {
this.settings.rules.forEach((rule: any) => { this.applyRulesToFile(file, rules);
const includeTags = rule?.include?.tags||[];
const excludeTags = rule?.exclude?.tags||[];
const tags = this.getTagsFromNote(file);
tags.then((tags)=>{//получаем теги из файла
if (includeTags.every((tag) => tags.includes(tag)) && !excludeTags.some((tag) => tags.includes(tag))) {//проверяем наличие всех тегов из списка в тегах файла
this.moveFileToFolder(file, rule.targetFolder)//перемещаем файл в папку
new Notice(` ${file.name} удовлетворяет правилу ${rule.name}`);
}
})
})
}); });
} }
}); });
@ -82,6 +61,14 @@ export default class MoveNotePlugin extends Plugin {
// При регистрации интервалов эта функция автоматически очистит интервал при отключении плагина. // При регистрации интервалов эта функция автоматически очистит интервал при отключении плагина.
this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000)); this.registerInterval(window.setInterval(() => console.log('setInterval'), 5 * 60 * 1000));
// Добавляем обработчик события для выполнения действия при открытии другого файла
this.app.workspace.on('file-open', (file: TFile|null) => {
if (this.settings.previousFile && this.settings.previousFile !== file) {
this.applyRulesToFile(this.settings.previousFile, rules);
}
this.settings.previousFile = file;
});
} }
onunload() { onunload() {
@ -177,6 +164,26 @@ export default class MoveNotePlugin extends Plugin {
} }
} }
async applyRulesToFile(file: TFile, rules: any) {
rules.forEach((rule: any) => {
const includeTags = rule?.include?.tags || [];
const excludeTags = rule?.exclude?.tags || [];
const newPath = path.normalize(`${rule.targetFolder}/${file.name}`);
if (path.normalize(file.path) === newPath) {
return false}
this.getTagsFromNote(file).then(tags => {
if (tags) {
if (includeTags.every((tag) => tags.includes(tag)) && !excludeTags.some((tag) => tags.includes(tag))) {
new Notice(`Удовлетворяет правилу ${rule.name}`);
new Notice(`Перемещаем файл ${file.name} в папку ${rule.targetFolder}`);
this.moveFileToFolder(file, rule.targetFolder);
return true;
} else { return false; }
}
});
});
}
} }

View File

@ -1,9 +1,9 @@
{ {
"id": "AAA-move-note-plugin", "id": "smart-note-mover",
"name": "AA Move Note Plugin", "name": "SmartNoteMover",
"version": "0.0.1a", "version": "0.0.2a",
"minAppVersion": "0.15.0", "minAppVersion": "0.15.0",
"description": "Demonstrates some of the capabilities of the Obsidian API.", "description": "Move notes based on rules",
"author": "NoRFoLK", "author": "NoRFoLK",
"authorUrl": "https://obsidian.md", "authorUrl": "https://obsidian.md",
"fundingUrl": "https://obsidian.md/pricing", "fundingUrl": "https://obsidian.md/pricing",