generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.ts
103 lines (82 loc) · 2.45 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
92
93
94
95
96
97
98
99
100
101
102
103
import { App, MarkdownView, Plugin, PluginSettingTab, Setting, loadMathJax } from 'obsidian';
import wypst from 'wypst';
import wasm from 'wypst/core/core_bg.wasm';
import 'katex/dist/katex.css';
import 'default.css';
interface WypstSettings {
fallbackToLatexOnError: boolean
}
const DEFAULT_SETTINGS: Partial<WypstSettings> = {
fallbackToLatexOnError: false,
};
export default class Wypst extends Plugin {
settings: WypstSettings
_tex2chtml: any;
async onload() {
await this.loadSettings();
this.addSettingTab(new WypstSettingTab(this.app, this));
await loadMathJax();
if (!globalThis.MathJax) {
throw new Error("MathJax failed to load.");
}
await wypst.init(wasm);
const parser = new DOMParser();
this._tex2chtml = globalThis.MathJax.tex2chtml;
globalThis.MathJax.tex2chtml = (e, r) => {
if (!hasLatexCommand(e)) {
const renderSettings = {
displayMode: r.display,
}
let renderedString = '';
try {
renderedString = wypst.renderToString(e, renderSettings);
} catch (error) {
if (this.settings.fallbackToLatexOnError) {
return this._tex2chtml(e, r);
}
renderedString = `<span style="color: red;">${error}</span>`;
}
return parser.parseFromString(renderedString, "text/html").body.firstChild;
} else {
return this._tex2chtml(e, r);
}
};
this.app.workspace.getActiveViewOfType(MarkdownView)?.previewMode.rerender(true);
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
onunload() {
globalThis.MathJax.tex2chtml = this._tex2chtml;
this.app.workspace.getActiveViewOfType(MarkdownView)?.previewMode.rerender(true);
}
}
export class WypstSettingTab extends PluginSettingTab {
plugin: Wypst;
constructor(app: App, plugin: Wypst) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName("Fallback to LaTeX on error")
.setDesc("Always fallback to LaTeX when Wypst fails to render an expression (experimental)")
.addToggle(toggle => {
toggle
.setValue(this.plugin.settings.fallbackToLatexOnError)
.onChange(async value => {
this.plugin.settings.fallbackToLatexOnError = value;
await this.plugin.saveSettings();
})
})
}
}
function hasLatexCommand(expr: string) {
const regex = /\\\S/;
return regex.test(expr);
}