generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.ts
96 lines (82 loc) · 2.37 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
import { App, Modal, Plugin } from "obsidian";
import { Etymo } from "./lib/etymo-js";
import { displayEntries } from "./util/displayEntries";
import { ellipsis } from "./util/ellipsis";
const etymo = new Etymo();
class EtymologyLookupModal extends Modal {
data: any;
constructor(app: App, data: any) {
super(app);
this.data = data;
}
async onOpen() {
const { contentEl } = this;
contentEl.setText("Searching...");
contentEl.className = "etymol-modal-content";
// scenario: word selected
if (this.data) {
try {
const entries = await etymo.search(this.data);
displayEntries(entries, contentEl);
} catch (_e) {
contentEl.setText("Search failed. Are you connected to the internet?");
}
}
// scenario: no word selected
else {
contentEl.setText(
"Highlight a word in your notes to search its etymology!"
);
}
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
export default class EtymologyLookupPlugin extends Plugin {
async onload() {
console.log("loading Etymology Lookup plugin");
// Creates an icon in the left ribbon.
this.addRibbonIcon("sprout", "Etymology Lookup", (event: MouseEvent) => {
this.lookup(getCurrentSelectedText(this.app));
});
// Adds a command to command palette
this.addCommand({
id: "search",
name: "Search",
callback: () => {
this.lookup(getCurrentSelectedText(this.app));
},
});
// Adds to right click menu
this.registerEvent(
this.app.workspace.on("editor-menu", (menu) => {
const selection = getCurrentSelectedText(this.app);
menu.addItem((item) => {
item
.setTitle(`Get etymology of "${ellipsis(selection, 18)}"`)
.onClick(() => {
this.lookup(selection);
});
});
})
);
}
onunload() {}
// Looks up the currently selected text
async lookup(selection: string | undefined) {
const modal = new EtymologyLookupModal(this.app, selection);
modal.open();
}
}
function getCurrentSelectedText(app: App): string {
const editor = app.workspace.activeEditor?.editor;
if (editor && document.getSelection()) {
const selection = document.getSelection();
if (selection && selection.toString()) {
return selection.toString();
}
}
return "";
}