generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoperations.ts
84 lines (70 loc) · 2.32 KB
/
operations.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
import { Editor, MarkdownView, type TFile } from "obsidian";
import { Replacer, UnsafeApp } from "./types";
import { createReplacerFromContent } from "./dataview-publisher";
import { DataviewApi } from "obsidian-dataview";
import { getDataviewAPI } from "./dataview-utils";
export class Operator {
app: UnsafeApp;
dv: DataviewApi;
constructor(app: UnsafeApp) {
this.app = app;
this.dv = getDataviewAPI(app);
}
async updateActiveFile() {
const editor = this.getEditor();
const cursor = editor.getCursor();
const content = editor.getValue();
const replacer = await createReplacerFromContent(content);
const updatedContent = this.updateContnet(content, replacer);
editor.setValue(updatedContent);
editor.setCursor(cursor);
}
private getEditor(): Editor {
const activeLeaf = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!activeLeaf) {
throw new Error("No active leaf found");
}
return activeLeaf.editor;
}
updateFromSource(source: string) {
const targetTfiles = this.retrieveTfilesFromSource(source);
targetTfiles.forEach(async (tfile) => {
await this.updateDataviewPublisherOutput(tfile);
});
}
private retrievePathsFromSource(source: string): Array<string> {
const paths =
this.dv
.pagePaths(source)
.map((path) => this.dv.io.normalize(path))
.array() ?? [];
return paths;
}
private retrieveTfilesFromSource(source: string): Array<TFile> {
const paths = this.retrievePathsFromSource(source);
const tfiles = paths
.map((path) => this.app.vault.getFileByPath(path))
.filter((tfile): tfile is TFile => tfile !== null);
return tfiles;
}
private async updateDataviewPublisherOutput(tfile: TFile) {
const content = await this.app.vault.cachedRead(tfile);
const replacer = await createReplacerFromContent(content);
const updatedContent = this.updateContnet(content, replacer);
this.app.vault.process(tfile, () => updatedContent);
}
private updateContnet(content: string, replacer: Replacer[]) {
return replacer.reduce(
(
c: string,
{
searchValue,
replaceValue,
}: { searchValue: string; replaceValue: string }
) => {
return c.replace(searchValue, replaceValue);
},
content
);
}
}