generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 6
/
main.ts
36 lines (32 loc) · 1.02 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
import { App, Plugin, TFile } from "obsidian";
import { ulid } from "ulid";
function addID(app: App): (f: TFile) => Promise<void> {
return async function (f: TFile): Promise<void> {
const key = "id";
if (!app.metadataCache.getFileCache(f)?.frontmatter?.[key]) {
await app.fileManager.processFrontMatter(f, (data) => {
data[key] = ulid();
});
}
};
}
function addIDsToAllNotes(app: App) {
const _addID = addID(app);
return function () {
app.vault.getMarkdownFiles().forEach((f) => _addID(f));
};
}
export default class IDPlugin extends Plugin {
async onload() {
// Called when a file has been indexed, and its (updated) cache is now
// available.
this.registerEvent(
this.app.metadataCache.on("changed", addID(this.app))
);
this.addCommand({
id: "add-ids-to-all-notes",
name: "Add an ID to all notes",
callback: addIDsToAllNotes(this.app),
});
}
}