generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
91 lines (84 loc) · 2.31 KB
/
main.ts
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
import { Notice, Plugin, TAbstractFile, TFile } from "obsidian";
import {
createDailyNote,
getAllDailyNotes,
getDailyNote,
} from "obsidian-daily-notes-interface";
export default class DailyNoteCollectorPlugin extends Plugin {
async onload() {
// Rename event handler is not needed as long as files auto-update all links when renamed.
this.registerEvent(
this.app.vault.on("delete", this.onDeleteFile.bind(this))
);
this.app.workspace.onLayoutReady(() => {
this.registerEvent(
this.app.vault.on("create", this.onCreateFile.bind(this))
);
});
}
onunload() {}
onCreateFile(file: TAbstractFile) {
if (!(file instanceof TFile)) return;
const link = this.app.fileManager.generateMarkdownLink(file, "");
const { dailyNote } = this.getDailyNote();
const promise = !dailyNote
? createDailyNote(window.moment())
: Promise.resolve(dailyNote);
promise
.then((dailyNote) => {
if (file.path === dailyNote.path) {
return;
}
return this.app.vault.process(dailyNote, (content) => {
if (content.includes(link)) {
return content;
}
// if we are at the top of the page, do not add a newline
if (!content) {
return `- ${link}`;
}
return `${content}\n- ${link}`;
});
})
.catch((error) => {
new Notice("Daily Note Collector Error: " + error);
});
}
onDeleteFile(file: TAbstractFile) {
if (!(file instanceof TFile)) return;
const { dailyNote } = this.getDailyNote();
if (!dailyNote) {
return;
}
const link = this.app.fileManager.generateMarkdownLink(file, "");
this.app.vault
.process(dailyNote, (content) => {
if (!content.includes(link)) {
return content;
}
if (content.includes(`\n- ${link}`)) {
const newContent = content.replace(`\n- ${link}`, "");
return newContent;
}
if (content.includes(`- ${link}\n`)) {
const newContent = content.replace(`- ${link}\n`, "");
return newContent;
}
if (content.includes(`- ${link}`)) {
const newContent = content.replace(`- ${link}`, "");
return newContent;
}
return content;
})
.catch((error) => {
new Notice("Daily Note Collector Error: " + error);
});
}
getDailyNote() {
const allNotes = getAllDailyNotes();
const dailyNote = getDailyNote(window.moment(), allNotes);
return {
dailyNote,
};
}
}