generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
77 lines (65 loc) · 2.56 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
import { MarkdownView, Plugin } from 'obsidian';
import { Compartment } from '@codemirror/state';
import { InlineAdmonitionSettingTab } from "./src/settings/inlineAdmonitionSettingTab";
import { InlineAdmonitionSettings, InlineAdmonitionSettingsIO } from "./src/settings/inlineAdmonitionSettings";
import { InlineAdmonitionsPostProcessor } from "./src/InlineAdmonitions/inlineAdmonitionsPostProcessor";
import { inlineAdmonitionPlugin } from "./src/InlineAdmonitions/InlineAdmonitionExtension";
import { setCssForClass, wipeCss } from "./src/io/inlineAdmonitionCss";
export default class InlineAdmonitionPlugin extends Plugin {
settings: InlineAdmonitionSettings;
private inlineAdmonitionCompartment: Compartment;
async onload() {
console.log("Loading Inline Admonitions.");
this.inlineAdmonitionCompartment = new Compartment();
await this.loadSettings();
const extension = this.inlineAdmonitionCompartment.of(
inlineAdmonitionPlugin(Array.from(this.settings.inlineAdmonitions.values()))
);
this.registerEditorExtension(extension);
this.registerMarkdownPostProcessor((element, context) => {
new InlineAdmonitionsPostProcessor(this.settings).postProcess(element, context);
});
this.addSettingTab(new InlineAdmonitionSettingTab(this.app, this));
}
onunload() {
// Unload any resources if necessary
}
async loadSettings() {
const settingData = await this.loadData();
const [settings, dataMigrated] = InlineAdmonitionSettingsIO.unmarshalAndMigrate(settingData);
this.settings = settings;
if (dataMigrated) {
await this.saveSettings();
}
await this.refreshCss();
}
async saveSettings() {
const settingData = InlineAdmonitionSettingsIO.marshal(this.settings);
await this.saveData(settingData);
await this.refreshCss();
this.rerenderMarkdownViews();
this.updateEditorExtensions();
}
async refreshCss() {
await wipeCss(this.app);
for (const iad of this.settings.inlineAdmonitions.values()) {
await setCssForClass(this.app, iad.cssClasses().last(), iad.simpleStyle());
}
}
private rerenderMarkdownViews() {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
view?.previewMode.rerender(true);
}
private updateEditorExtensions() {
const newExtension = inlineAdmonitionPlugin(Array.from(this.settings.inlineAdmonitions.values()));
this.app.workspace.iterateAllLeaves(leaf => {
if (leaf.view instanceof MarkdownView && leaf.view.editor) {
const editor = leaf.view.editor;
const cm = editor.cm;
cm.dispatch({
effects: this.inlineAdmonitionCompartment.reconfigure(newExtension)
});
}
});
}
}