generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 16
/
main.ts
348 lines (306 loc) · 9.87 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
343
344
345
346
347
348
import {
App,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting,
Editor,
MarkdownView,
TextComponent,
RequestParam,
request,
} from "obsidian";
interface WikipediaExtract {
title: string;
text: string;
url: string;
}
interface WikipediaPluginSettings {
template: string;
shouldUseParagraphTemplate: boolean;
shouldBoldSearchTerm: boolean;
paragraphTemplate: string;
language: string;
}
const DEFAULT_SETTINGS: WikipediaPluginSettings = {
template: `{{text}}\n> [Wikipedia]({{url}})`,
shouldUseParagraphTemplate: true,
shouldBoldSearchTerm: true,
paragraphTemplate: `> {{paragraphText}}\n>\n`,
language: "en",
};
const extractApiUrl =
"wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=1&redirects&origin=*&titles=";
const disambiguationIdentifier = "may refer to:";
export default class WikipediaPlugin extends Plugin {
settings: WikipediaPluginSettings;
getLanguage(): string {
return this.settings.language ? this.settings.language : "en";
}
getUrl(title: string): string {
return `https://${this.getLanguage()}.wikipedia.org/wiki/${encodeURI(
title
)}`;
}
getApiUrl(): string {
return `https://${this.getLanguage()}.` + extractApiUrl;
}
formatExtractText(extract: WikipediaExtract, searchTerm: string): string {
const text = extract.text;
let formattedText: string = "";
if (this.settings.shouldUseParagraphTemplate) {
const split = text.split("==")[0].trim().split("\n");
formattedText = split
.map((paragraph) =>
this.settings.paragraphTemplate.replace(
"{{paragraphText}}",
paragraph
)
)
.join("")
.trim();
} else {
formattedText = text.split("==")[0].trim();
}
if (this.settings.shouldBoldSearchTerm) {
const pattern = new RegExp(searchTerm, "i");
formattedText = formattedText.replace(pattern, `**${searchTerm}**`);
}
return formattedText;
}
handleNotFound(searchTerm: string) {
new Notice(`${searchTerm} not found on Wikipedia.`);
}
handleCouldntResolveDisambiguation() {
new Notice(`Could not automatically resolve disambiguation.`);
}
hasDisambiguation(extract: WikipediaExtract) {
if (extract.text.includes(disambiguationIdentifier)) {
return true;
}
return false;
}
parseResponse(json: any): WikipediaExtract | undefined {
const pages = json.query.pages;
const pageKeys = Object.keys(pages);
if (pageKeys.includes("-1")) {
return undefined;
}
const extracts: WikipediaExtract[] = pageKeys.map((key) => {
const page = pages[key];
const extract: WikipediaExtract = {
title: page.title,
text: page.extract,
url: this.getUrl(page.title),
};
return extract;
});
return extracts[0];
}
formatExtractInsert(extract: WikipediaExtract, searchTerm: string): string {
const formattedText = this.formatExtractText(extract, searchTerm);
const template = this.settings.template;
const formattedTemplate = template
.replace("{{text}}", formattedText)
.replace("{{searchTerm}}", searchTerm)
.replace("{{url}}", extract.url);
return formattedTemplate;
}
async getWikipediaText(title: string): Promise<WikipediaExtract | undefined> {
const url = this.getApiUrl() + encodeURIComponent(title);
const requestParam: RequestParam = {
url: url,
};
const resp = await request(requestParam)
.then((r) => JSON.parse(r))
.catch(
() =>
new Notice(
"Failed to get Wikipedia. Check your internet connection or language prefix."
)
);
const extract = this.parseResponse(resp);
return extract;
}
async pasteIntoEditor(editor: Editor, searchTerm: string) {
let extract: WikipediaExtract = await this.getWikipediaText(searchTerm);
if (!extract) {
this.handleNotFound(searchTerm);
return;
}
if (this.hasDisambiguation(extract)) {
new Notice(
`Disambiguation found for ${searchTerm}. Choosing first result.`
);
const newSearchTerm = extract.text
.split(disambiguationIdentifier)[1]
.trim()
.split(",")[0]
.split("==")
.pop()
.trim();
extract = await this.getWikipediaText(newSearchTerm);
if (!extract) {
this.handleCouldntResolveDisambiguation();
return;
}
}
editor.replaceSelection(this.formatExtractInsert(extract, searchTerm));
}
async getWikipediaTextForActiveFile(editor: Editor) {
const activeFile = await this.app.workspace.getActiveFile();
if (activeFile) {
const searchTerm = activeFile.basename;
if (searchTerm) {
await this.pasteIntoEditor(editor, searchTerm);
}
}
}
async getWikipediaTextForSearchTerm(editor: Editor) {
new WikipediaSearchModal(this.app, this, editor).open();
}
async onload() {
await this.loadSettings();
this.addCommand({
id: "wikipedia-get-active-note-title",
name: "Get Wikipedia for Active Note Title",
editorCallback: (editor: Editor) =>
this.getWikipediaTextForActiveFile(editor),
});
this.addCommand({
id: "wikipedia-get-search-term",
name: "Get Wikipedia for Search Term",
editorCallback: (editor: Editor) =>
this.getWikipediaTextForSearchTerm(editor),
});
this.addSettingTab(new WikipediaSettingTab(this.app, this));
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class WikipediaSearchModal extends Modal {
searchTerm: string;
plugin: WikipediaPlugin;
editor: Editor;
constructor(app: App, plugin: WikipediaPlugin, editor: Editor) {
super(app);
this.plugin = plugin;
this.editor = editor;
}
onOpen() {
let { contentEl } = this;
contentEl.createEl("h2", { text: "Enter Search Term:" });
const inputs = contentEl.createDiv("inputs");
const searchInput = new TextComponent(inputs).onChange((searchTerm) => {
this.searchTerm = searchTerm;
});
searchInput.inputEl.focus();
searchInput.inputEl.addEventListener("keydown", (event) => {
if (event.key === "Enter") {
this.close();
}
});
const controls = contentEl.createDiv("controls");
const searchButton = controls.createEl("button", {
text: "Search",
cls: "mod-cta",
attr: {
autofocus: true,
},
});
searchButton.addEventListener("click", this.close.bind(this));
const cancelButton = controls.createEl("button", { text: "Cancel" });
cancelButton.addEventListener("click", this.close.bind(this));
}
async onClose() {
let { contentEl } = this;
contentEl.empty();
if (this.searchTerm) {
await this.plugin.pasteIntoEditor(this.editor, this.searchTerm);
}
}
}
class WikipediaSettingTab extends PluginSettingTab {
plugin: WikipediaPlugin;
constructor(app: App, plugin: WikipediaPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
let { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", { text: "Obsidian Wikipedia" });
new Setting(containerEl)
.setName("Wikipedia Language Prefix")
.setDesc(`Choose Wikipedia language prefix to use (ex. en for English)`)
.addText((textField) => {
textField
.setValue(this.plugin.settings.language)
.onChange(async (value) => {
this.plugin.settings.language = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Wikipedia Extract Template")
.setDesc(
`Set markdown template for extract to be inserted.\n
Available template variables are {{text}}, {{searchTerm}} and {{url}}.
`
)
.addTextArea((textarea) =>
textarea
.setValue(this.plugin.settings.template)
.onChange(async (value) => {
this.plugin.settings.template = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Bold Search Term?")
.setDesc(
"If set to true, the first instance of the search term will be **bolded**"
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.shouldBoldSearchTerm)
.onChange(async (value) => {
this.plugin.settings.shouldBoldSearchTerm = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Use paragraph template?")
.setDesc(
"If set to true, the paragraph template will be inserted for each paragraph of text for {{text}} in main template."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.shouldUseParagraphTemplate)
.onChange(async (value) => {
this.plugin.settings.shouldUseParagraphTemplate = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Paragraph Template")
.setDesc(
`Set markdown template for extract paragraphs to be inserted.\n
Available template variables are: {{paragraphText}}
`
)
.addTextArea((textarea) =>
textarea
.setValue(this.plugin.settings.paragraphTemplate)
.onChange(async (value) => {
this.plugin.settings.paragraphTemplate = value;
await this.plugin.saveSettings();
})
);
}
}