generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
566 lines (486 loc) · 15.6 KB
/
main.ts
File metadata and controls
566 lines (486 loc) · 15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
import { TFile, CachedMetadata, TFolder, SuggestModal } from 'obsidian';
// Remember to rename these classes and interfaces!
interface FolderRule {
sourceFolder: string;
destinationFolder: string;
conditions: {
field: string;
operator: 'equals' | 'contains' | 'regex';
value: string;
}[];
id: string; // Add unique identifier for each rule
matchType: 'all' | 'any'; // Add match type setting
}
interface FolderRulesSettings {
rules: FolderRule[];
enabled: boolean;
debug: boolean;
}
const DEFAULT_SETTINGS: FolderRulesSettings = {
rules: [],
enabled: true,
debug: false
}
export default class FolderRulesPlugin extends Plugin {
settings: FolderRulesSettings;
lastMetadataCache: { [path: string]: any } = {};
appliedRulesCache: { [path: string]: Set<string> } = {}; // Track which rules have been applied to each file
async onload() {
await this.loadSettings();
// Add a ribbon icon for toggling the plugin
const ribbonIconEl = this.addRibbonIcon('folder-plus', 'Folder Rules', (evt: MouseEvent) => {
// Toggle the plugin
this.settings.enabled = !this.settings.enabled;
this.saveSettings();
new Notice(`Folder Rules ${this.settings.enabled ? 'enabled' : 'disabled'}`);
});
// Register for metadata changes instead of file changes
this.registerEvent(
this.app.metadataCache.on('changed', (file) => {
if (this.settings.enabled && file instanceof TFile) {
this.handleMetadataChange(file);
}
})
);
// Add settings tab
this.addSettingTab(new FolderRulesSettingTab(this.app, this));
}
async handleMetadataChange(file: TFile) {
if (!this.settings.enabled) return;
const filePath = file.path;
const metadata = this.app.metadataCache.getFileCache(file);
const oldMetadata = this.lastMetadataCache[filePath];
if (!metadata) return;
if (this.settings.debug) {
console.group(`Processing metadata change for: ${filePath}`);
console.log('Current metadata:', metadata.frontmatter);
console.log('Previous metadata:', oldMetadata);
}
// Store current metadata for future comparison
this.lastMetadataCache[filePath] = metadata.frontmatter || {};
// Reset applied rules cache if the file has been manually moved
if (!this.appliedRulesCache[filePath]) {
this.appliedRulesCache[filePath] = new Set();
}
// Find matching rules for the file's current folder
const matchingRules = this.settings.rules.filter(rule =>
filePath.startsWith(rule.sourceFolder) &&
!this.appliedRulesCache[filePath].has(rule.id) // Only consider rules that haven't been applied yet
);
if (this.settings.debug) {
console.log(`Found ${matchingRules.length} potential rules for source folder`);
console.log('Previously applied rules:', Array.from(this.appliedRulesCache[filePath]));
matchingRules.forEach((rule, index) => {
console.log(`Rule ${index + 1}:`, {
id: rule.id,
sourceFolder: rule.sourceFolder,
destinationFolder: rule.destinationFolder,
conditions: rule.conditions
});
});
}
for (const rule of matchingRules) {
if (this.settings.debug) {
console.group(`Evaluating rule: ${rule.sourceFolder} → ${rule.destinationFolder}`);
}
const matchesNow = await this.checkRuleConditions(rule, metadata);
const matchedBefore = oldMetadata && await this.checkRuleConditions(rule, { frontmatter: oldMetadata });
if (this.settings.debug) {
console.log('Rule evaluation results:', {
matchesNow,
matchedBefore,
willMove: matchesNow && !matchedBefore
});
console.groupEnd();
}
// Only move if the file newly matches the conditions
if (matchesNow && !matchedBefore) {
await this.moveFile(file, rule.destinationFolder);
// Mark this rule as applied to this file
this.appliedRulesCache[filePath].add(rule.id);
if (this.settings.debug) {
console.log(`Marked rule ${rule.id} as applied to ${filePath}`);
}
break; // Stop after first matching rule
}
}
if (this.settings.debug) {
console.groupEnd();
}
}
async checkRuleConditions(rule: FolderRule, metadata: CachedMetadata): Promise<boolean> {
if (!metadata.frontmatter) {
if (this.settings.debug) {
console.log('No frontmatter found in metadata');
}
return false;
}
const conditionResults = [];
for (const condition of rule.conditions) {
const value = this.getMetadataValue(metadata, condition.field);
if (this.settings.debug) {
console.log(`Checking condition:`, {
field: condition.field,
operator: condition.operator,
expectedValue: condition.value,
actualValue: value
});
}
if (!value) {
if (this.settings.debug) {
console.log(`Field "${condition.field}" not found in metadata`);
}
conditionResults.push(false);
continue;
}
let matches = false;
switch (condition.operator) {
case 'equals':
matches = value === condition.value;
break;
case 'contains':
matches = value.includes(condition.value);
break;
case 'regex':
try {
const regex = new RegExp(condition.value);
matches = regex.test(value);
} catch (e) {
if (this.settings.debug) {
console.error('Invalid regex:', condition.value, e);
}
conditionResults.push(false);
continue;
}
break;
}
if (this.settings.debug) {
console.log(`Condition result: ${matches ? 'matched' : 'did not match'}`);
}
conditionResults.push(matches);
}
// If no conditions, return false
if (conditionResults.length === 0) return false;
// Apply match type logic
const result = rule.matchType === 'all'
? conditionResults.every(result => result)
: conditionResults.some(result => result);
if (this.settings.debug) {
console.log(`Final rule result (${rule.matchType}): ${result}`);
}
return result;
}
getMetadataValue(metadata: CachedMetadata, field: string): string | undefined {
if (!metadata.frontmatter) return undefined;
return metadata.frontmatter[field];
}
async moveFile(file: TFile, destinationFolder: string) {
try {
const newPath = `${destinationFolder}/${file.name}`;
if (this.settings.debug) {
console.log(`Attempting to move file:`, {
from: file.path,
to: newPath
});
}
await this.app.fileManager.renameFile(file, newPath);
// Update the applied rules cache for the new path
if (this.appliedRulesCache[file.path]) {
this.appliedRulesCache[newPath] = this.appliedRulesCache[file.path];
delete this.appliedRulesCache[file.path];
}
if (this.settings.debug) {
console.log(`Successfully moved ${file.path} to ${newPath}`);
}
} catch (e) {
if (this.settings.debug) {
console.error(`Failed to move ${file.path}:`, e);
}
}
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class FolderSuggestModal extends SuggestModal<TFolder> {
onSelect: (folder: TFolder) => void;
constructor(app: App, onSelect: (folder: TFolder) => void) {
super(app);
this.onSelect = onSelect;
}
getSuggestions(query: string): TFolder[] {
const folders = this.getAllFolders();
return folders.filter(folder =>
folder.path.toLowerCase().includes(query.toLowerCase())
);
}
renderSuggestion(folder: TFolder, el: HTMLElement) {
el.createEl("div", { text: folder.path });
}
onChooseSuggestion(folder: TFolder, evt: MouseEvent | KeyboardEvent) {
this.onSelect(folder);
}
private getAllFolders(): TFolder[] {
const folders: TFolder[] = [];
const files = this.app.vault.getAllLoadedFiles();
for (const file of files) {
if (file instanceof TFolder) {
folders.push(file);
}
}
return folders.sort((a, b) => a.path.localeCompare(b.path));
}
}
class DeleteRuleModal extends Modal {
onConfirm: () => void;
rule: FolderRule;
constructor(app: App, rule: FolderRule, onConfirm: () => void) {
super(app);
this.onConfirm = onConfirm;
this.rule = rule;
}
onOpen() {
const {contentEl} = this;
contentEl.empty();
contentEl.createEl('h2', {text: 'Delete Rule'});
contentEl.createEl('p', {text: 'Are you sure you want to delete this rule?'});
const ruleDetails = contentEl.createEl('div', {cls: 'rule-details'});
ruleDetails.createEl('p', {text: `Source Folder: ${this.rule.sourceFolder || 'None'}`});
ruleDetails.createEl('p', {text: `Destination Folder: ${this.rule.destinationFolder || 'None'}`});
ruleDetails.createEl('p', {text: `Conditions: ${this.rule.conditions.length}`});
// Add confirmation buttons
const buttonContainer = contentEl.createEl('div', {cls: 'modal-button-container'});
const confirmButton = buttonContainer.createEl('button', {
text: 'Delete',
cls: 'mod-warning'
});
confirmButton.onclick = () => {
this.onConfirm();
this.close();
};
const cancelButton = buttonContainer.createEl('button', {
text: 'Cancel'
});
cancelButton.onclick = () => {
this.close();
};
}
onClose() {
const {contentEl} = this;
contentEl.empty();
}
}
class FolderRulesSettingTab extends PluginSettingTab {
plugin: FolderRulesPlugin;
constructor(app: App, plugin: FolderRulesPlugin) {
super(app, plugin);
this.plugin = plugin;
}
private hasRuleContent(rule: FolderRule): boolean {
return rule.sourceFolder !== '' ||
rule.destinationFolder !== '' ||
rule.conditions.length > 0;
}
display(): void {
const {containerEl} = this;
containerEl.empty();
new Setting(containerEl)
.setName('Enable Folder Rules')
.setDesc('Toggle automatic note movement based on rules')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.enabled)
.onChange(async (value) => {
this.plugin.settings.enabled = value;
await this.plugin.saveSettings();
}));
new Setting(containerEl)
.setName('Debug Mode')
.setDesc('Enable detailed logging in the Developer Console (View > Toggle Developer Tools > Console)')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.debug)
.onChange(async (value) => {
this.plugin.settings.debug = value;
await this.plugin.saveSettings();
}));
containerEl.createEl('h2', {text: 'Folder Rules'});
this.plugin.settings.rules.forEach((rule, index) => {
// Ensure each rule has a unique ID and match type
if (!rule.id) {
rule.id = `rule-${Date.now()}-${index}`;
}
if (!rule.matchType) {
rule.matchType = 'all'; // Default to requiring all conditions to match
}
const ruleContainer = containerEl.createEl('div', {
cls: 'folder-rule-container'
});
const sourceFolderSetting = new Setting(ruleContainer)
.setName(`Rule ${index + 1}`)
.setDesc('Source folder')
.addText(text => {
text.setPlaceholder('Source folder path')
.setValue(rule.sourceFolder)
.onChange(async (value) => {
rule.sourceFolder = value;
await this.plugin.saveSettings();
});
// Add a button to open folder suggestion
text.inputEl.style.width = "calc(100% - 40px)";
const browseButton = createEl('button', {
text: '📁',
cls: 'folder-browse-button',
attr: {
'aria-label': 'Browse folders',
'style': 'margin-left: 4px;'
}
});
const parent = text.inputEl.parentElement;
if (parent) {
parent.appendChild(browseButton);
}
browseButton.onclick = () => {
new FolderSuggestModal(this.app, (folder) => {
text.setValue(folder.path);
rule.sourceFolder = folder.path;
this.plugin.saveSettings();
}).open();
};
return text;
});
const destFolderSetting = new Setting(ruleContainer)
.setName('Destination')
.setDesc('Destination folder')
.addText(text => {
text.setPlaceholder('Destination folder path')
.setValue(rule.destinationFolder)
.onChange(async (value) => {
rule.destinationFolder = value;
await this.plugin.saveSettings();
});
// Add a button to open folder suggestion
text.inputEl.style.width = "calc(100% - 40px)";
const browseButton = createEl('button', {
text: '📁',
cls: 'folder-browse-button',
attr: {
'aria-label': 'Browse folders',
'style': 'margin-left: 4px;'
}
});
const parent = text.inputEl.parentElement;
if (parent) {
parent.appendChild(browseButton);
}
browseButton.onclick = () => {
new FolderSuggestModal(this.app, (folder) => {
text.setValue(folder.path);
rule.destinationFolder = folder.path;
this.plugin.saveSettings();
}).open();
};
return text;
});
// Add match type setting before conditions
new Setting(ruleContainer)
.setName('Match Type')
.setDesc('Choose whether all conditions must match or if any condition can match')
.addDropdown(dropdown => dropdown
.addOption('all', 'All conditions must match')
.addOption('any', 'Any condition can match')
.setValue(rule.matchType)
.onChange(async (value: 'all' | 'any') => {
rule.matchType = value;
await this.plugin.saveSettings();
}));
rule.conditions.forEach((condition, condIndex) => {
const condContainer = ruleContainer.createEl('div', {
cls: 'condition-container'
});
new Setting(condContainer)
.setName(`Condition ${condIndex + 1}`)
.addText(text => text
.setPlaceholder('Metadata field')
.setValue(condition.field)
.onChange(async (value) => {
condition.field = value;
await this.plugin.saveSettings();
}))
.addDropdown(dropdown => dropdown
.addOption('equals', 'Equals')
.addOption('contains', 'Contains')
.addOption('regex', 'Regex')
.setValue(condition.operator)
.onChange(async (value: 'equals' | 'contains' | 'regex') => {
condition.operator = value;
await this.plugin.saveSettings();
}))
.addText(text => text
.setPlaceholder('Value')
.setValue(condition.value)
.onChange(async (value) => {
condition.value = value;
await this.plugin.saveSettings();
}))
.addButton(button => button
.setButtonText('Delete Condition')
.onClick(async () => {
rule.conditions.splice(condIndex, 1);
await this.plugin.saveSettings();
this.display();
}));
});
new Setting(ruleContainer)
.addButton(button => button
.setButtonText('Add Condition')
.onClick(async () => {
rule.conditions.push({
field: '',
operator: 'equals',
value: ''
});
await this.plugin.saveSettings();
this.display();
}));
// Add delete rule button in its own setting
new Setting(ruleContainer)
.addButton(button => button
.setButtonText('Delete Rule')
.setClass('delete-rule-button')
.onClick(async () => {
const rule = this.plugin.settings.rules[index];
if (this.hasRuleContent(rule)) {
new DeleteRuleModal(this.app, rule, async () => {
this.plugin.settings.rules.splice(index, 1);
await this.plugin.saveSettings();
this.display();
}).open();
} else {
// If rule is empty, delete without confirmation
this.plugin.settings.rules.splice(index, 1);
await this.plugin.saveSettings();
this.display();
}
}));
});
new Setting(containerEl)
.addButton(button => button
.setButtonText('Add Rule')
.onClick(async () => {
this.plugin.settings.rules.push({
id: `rule-${Date.now()}-${this.plugin.settings.rules.length}`,
sourceFolder: '',
destinationFolder: '',
conditions: [],
matchType: 'all'
});
await this.plugin.saveSettings();
this.display();
}));
}
}