generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmain.ts
342 lines (284 loc) · 9.77 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
import { MathfieldElement } from 'mathlive';
import { App, Editor, MarkdownView, Modal, Notice, Plugin } from 'obsidian';
import { MarkdownFileInfo } from 'obsidian';
import { PluginSettingTab, Setting } from "obsidian";
interface PluginSettings {
apiKey: string;
useLocalInference: boolean;
}
const DEFAULT_SETTINGS = {
apiKey: null,
selfHosted: false
}
export default class MathLivePlugin extends Plugin {
settings: PluginSettings;
async onload() {
if (customElements.get("math-field") === undefined)
customElements.define("math-field", MathfieldElement);
this.addCommand({
id: 'open-modal',
name: 'Add full-line math',
editorCallback: (editor: Editor, ctx: MarkdownFileInfo) => {
new MathLiveModal(this.app, editor, this).open();
}
});
this.addCommand({
id: 'open-modal-inline',
name: 'Add inline math',
editorCallback: (editor: Editor, ctx: MarkdownFileInfo) => {
new MathLiveModal(this.app, editor, this, true).open();
}
});
await this.loadSettings();
this.addSettingTab(new MathliveSettingTab(this.app, this))
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
export class MathliveSettingTab extends PluginSettingTab {
plugin: MathLivePlugin;
constructor(app: App, plugin: MathLivePlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
let { containerEl } = this;
containerEl.empty();
const title = document.createElement('h2')
title.textContent = 'Obsidian Mathlive'
title.setCssStyles({
fontSize: '28px'
})
containerEl.appendChild(title);
const intro = `This plugins currently has 2 main features, visual formula editor, and image to MathJax scanner.
The MathJax image scanner is available for free when self hosting.
In addition, there is a cloud option that requires no setup.
* Self hosting the image scanner may require technical knowledge of docker and requires background processing resources. For most people, the cloud options is better.`
const introEl = document.createElement('p');
introEl.textContent = intro;
introEl.style.whiteSpace = 'pre-wrap'
containerEl.appendChild(introEl);
new Setting(containerEl);
const cloudTitle = document.createElement('h2')
cloudTitle.textContent = 'Cloud Settings'
cloudTitle.setCssStyles({
fontSize: '24px'
})
containerEl.appendChild(cloudTitle);
new Setting(containerEl)
.setName('API key')
.addText(tc => tc.setValue(this.plugin.settings.apiKey).onChange(async val => {
this.plugin.settings.apiKey = val;
await this.plugin.saveSettings()
}))
const homepageLink = document.createElement('a')
homepageLink.href = 'https://mathlive.danz.blog'
homepageLink.text = 'Create an API key here'
containerEl.appendChild(homepageLink)
new Setting(containerEl);
const selfHostTitle = document.createElement('h2')
selfHostTitle.textContent = 'Self Hosting Settings'
selfHostTitle.setCssStyles({
fontSize: '24px'
})
containerEl.appendChild(selfHostTitle);
new Setting(containerEl)
.setName('Self hosted')
.addToggle(toggle => toggle.setValue(this.plugin.settings.useLocalInference).onChange(async val => {
this.plugin.settings.useLocalInference = val;
await this.plugin.saveSettings()
}))
}
}
class MathLiveModal extends Modal {
renderedResult?: string
editor: Editor
plugin: MathLivePlugin
mfe?: MathfieldElement
inline: boolean
resultRenderTemplate: (res: string) => string
constructor(app: App, editor: Editor, plugin: MathLivePlugin, inline=false) {
super(app);
this.editor = editor
this.plugin = plugin
this.inline = inline;
}
parseSelection(selectionText: string) : { resultRenderTemplate: (result: string) => string, initialLatex: string } | null {
if (selectionText.length === 0) {
const wrapper = this.inline ? "$" : "$$";
return {
resultRenderTemplate: result => result.length > 0 ? wrapper + result + wrapper : "",
initialLatex: ""
}
}
const mathPreviewStartIndex = selectionText.indexOf("$$");
if (mathPreviewStartIndex >= 0) {
const mathPreviewEndIndex = selectionText.indexOf("$$", mathPreviewStartIndex + 2);
if (mathPreviewEndIndex >= 0) {
return {
resultRenderTemplate: result =>
selectionText.substring(0, mathPreviewStartIndex)
+ "$$"
+ result
+ "$$"
+ selectionText.substring(mathPreviewEndIndex + 2, selectionText.length),
initialLatex: selectionText.substring(mathPreviewStartIndex + 2, mathPreviewEndIndex),
}
}
}
const mathInlineStartIndex = selectionText.indexOf("$");
if (mathInlineStartIndex >= 0) {
const mathInlineEndIndex = selectionText.indexOf("$", mathInlineStartIndex + 1);
return {
resultRenderTemplate: result =>
selectionText.substring(0, mathInlineStartIndex)
+ "$"
+ result
+ "$"
+ selectionText.substring(mathInlineEndIndex + 1, selectionText.length),
initialLatex: selectionText.substring(mathInlineStartIndex + 1, mathInlineEndIndex),
}
}
return {
resultRenderTemplate: result => result,
initialLatex: selectionText
}
}
onOpen() {
const modalContent = this.containerEl.querySelector('.modal-content')!;
const header = this.initHeader(modalContent)
this.initMadeByButton(header)
this.initSupportButton(header)
this.initMathlive(modalContent)
this.initSubmitButton(modalContent)
this.initImageScanner(modalContent)
}
initMathlive(modalContent: Element) {
const mathliveModalRoot = modalContent.parentElement?.parentElement
mathliveModalRoot?.addClass("mathlive-modal-root")
const keyboardContainer = window.createEl('div')
keyboardContainer.addClass("virt-keyboard")
mathliveModalRoot?.append(keyboardContainer)
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
const selectionText = markdownView?.editor.getSelection();
const parseResult = this.parseSelection(selectionText ?? "");
if (!parseResult) {
new Notice("MathLive: Failed to parse the selected text");
this.close();
return;
}
const {initialLatex, resultRenderTemplate} = parseResult;
this.resultRenderTemplate = resultRenderTemplate
this.renderedResult = resultRenderTemplate(initialLatex);
this.mfe = document.createElement("math-field") as MathfieldElement;
this.mfe.id = "mathfield"
this.mfe.value = initialLatex;
this.mfe.addEventListener('input', () => {
this.renderedResult = resultRenderTemplate(this.mfe?.value ?? '');
});
window.mathVirtualKeyboard.container = keyboardContainer
modalContent.addClass("mathlive-modal-content");
modalContent.appendChild(this.mfe);
this.mfe.focus();
setTimeout(() => document.getElementById("mathfield")!.focus(), 10)
}
initHeader(modalContent: Element) {
const header = document.createElement('div')
header.addClass('header')
modalContent.appendChild(header)
return header;
}
initMadeByButton(modalContent: Element) {
const link = document.createElement('a')
link.innerText = '👱♂️ Made by Dan Zilberman'
link.addClass('badge')
link.setAttr('href', 'https://danzilberdan.github.io/')
link.setAttr('target', '_blank')
link.addClass('external-link')
modalContent.appendChild(link)
}
initSupportButton(modalContent: Element) {
const link = document.createElement('a')
link.innerText = '☕ Support'
link.addClass('badge')
link.setAttr('href', 'https://www.buymeacoffee.com/danzilberdan')
link.setAttr('target', '_blank')
link.addClass('external-link')
modalContent.appendChild(link)
}
initSubmitButton(modalContent: Element) {
const submitButton = document.createElement('button')
submitButton.innerText = 'Insert'
submitButton.addClass('submit')
submitButton.addEventListener('click', this.close.bind(this))
modalContent.appendChild(submitButton)
}
initImageScanner(modalContent: Element) {
const scan = document.createElement('button')
scan.innerText = 'Scan MathJax from Clipboard'
scan.addClass('scan-button')
scan.onclick = this.onImageScanRequest.bind(this)
modalContent.appendChild(scan)
}
async onImageScanRequest() {
if (!this.plugin.settings.apiKey) {
new Notice('Please open plugin settings to create API key.')
return
}
try {
const clipboardItems = await navigator.clipboard.read();
for (const item of clipboardItems) {
for (const type of item.types) {
if (item.types.includes('image/png')) {
const blob = await item.getType(type)
new Notice('Scanning MathJax image')
const mathjax = await this.scanImage(blob);
this.mfe!.value += mathjax;
this.renderedResult = this.resultRenderTemplate(this.mfe?.value ?? '');
new Notice(`Got scan result for MathJax`)
return
}
}
}
new Notice('No image found in clipboard.');
} catch (error) {
console.error('Error reading clipboard or uploading image:', error);
new Notice(`Failed to scan image. See console for details.`)
}
}
async scanImage(imageData: Blob) {
let address = 'https://mathlive-ocr.danz.blog'
if (this.plugin.settings.useLocalInference) {
address = 'http://localhost:8502'
}
const formData = new FormData();
formData.append('file', imageData);
const res = await fetch(address + '/predict/', {
headers: {
'Api-key': this.plugin.settings.apiKey
},
method: 'POST',
body: formData
});
return await res.json()
}
async convertToJPEG(imageData: string) {
const img = new Image();
img.src = imageData;
await new Promise((resolve) => { img.onload = resolve; });
const canvas = document.createElement('canvas');
canvas.width = img.width;
canvas.height = img.height;
const ctx = canvas.getContext('2d');
ctx!.drawImage(img, 0, 0);
return canvas.toDataURL('image/jpeg', 0.8);
}
onClose() {
if (!!this.renderedResult)
this.editor.replaceSelection(this.renderedResult);
}
}