generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
283 lines (240 loc) · 7.51 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
import { Plugin, Notice, Modal, App, PluginSettingTab, TFile, MarkdownView, Setting } from 'obsidian';
interface BlogPluginSettings {
host: string;
slug: string;
saveLocation: string;
}
const DEFAULT_SETTINGS: BlogPluginSettings = {
host: '',
slug: '',
saveLocation: 'blog-posts',
};
export default class BlogPlugin extends Plugin {
settings: BlogPluginSettings;
async onload() {
await this.loadSettings();
// Add ribbon icon to fetch and save blog post
this.addRibbonIcon('book-down', 'Load a blog to local', async () => {
new FetchBlogModal(this.app, this).open();
});
// Add ribbon icon to show blog directory files with stars
this.addRibbonIcon('library-big', 'All local blogs', async () => {
await this.showAllBlogs();
});
this.addSettingTab(new BlogPluginSettingTab(this.app, this));
}
async fetchBlogPost(): Promise<string | null> {
const { host, slug } = this.settings;
const query = `
query Publication($host: String!, $slug: String!) {
publication(host: $host) {
post(slug: $slug) {
content {
markdown
}
}
}
}
`;
const variables = { host, slug };
try {
const response = await fetch('https://gql.hashnode.com', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables }),
});
const result = await response.json();
const markdownContent = result?.data?.publication?.post?.content?.markdown;
if (!markdownContent) {
new Notice('Could not fetch the blog post. Please check your host and slug.');
return null;
}
return markdownContent;
} catch (error) {
console.error('Error fetching blog:', error);
new Notice('Failed to fetch the blog post. Please try again.');
return null;
}
}
async saveFetchedBlog() {
const markdownContent = await this.fetchBlogPost();
if (markdownContent) {
const fileName = `${this.settings.slug}.md`;
const filePath = `${this.settings.saveLocation}/${fileName}`;
try {
await this.app.vault.create(filePath, markdownContent);
new Notice(`Blog saved as ${fileName} in ${this.settings.saveLocation}`);
} catch (error) {
console.error('Error saving blog:', error);
new Notice('Failed to save the blog. Please try again.');
}
}
}
async showAllBlogs() {
const { saveLocation } = this.settings;
const folder = this.app.vault.getAbstractFileByPath(saveLocation);
if (folder && folder instanceof TFile) {
new Notice(`${saveLocation} is a file, not a folder.`);
return;
}
const files = folder ? folder.children.filter(child => child instanceof TFile) : [];
if (files.length === 0) {
new Notice(`No files found in ${saveLocation}.`);
return;
}
new AllBlogsModal(this.app, this, files as TFile[]).open();
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class FetchBlogModal extends Modal {
plugin: BlogPlugin;
constructor(app: App, plugin: BlogPlugin) {
super(app);
this.plugin = plugin;
}
onOpen() {
const { contentEl } = this;
contentEl.createEl('h3', { text: 'Load a blog on local' });
contentEl.createEl('small', { text: 'Efie is home in Akan' });
// Neatly arrange input fields with labels
const formEl = contentEl.createEl('div', { cls: 'blog-fetch-form' });
formEl.createEl('label', { text: 'Publication Host:' });
const hostInput = formEl.createEl('input', {
type: 'text',
placeholder: 'Enter publication host. eg. username.hashnode.dev',
});
hostInput.value = this.plugin.settings.host;
formEl.createEl('label', { text: 'Blog Post Slug:' });
const slugInput = formEl.createEl('input', {
type: 'text',
placeholder: 'Enter blog post slug. eg. my-blog-post',
});
slugInput.value = this.plugin.settings.slug;
const fetchButton = contentEl.createEl('button', { text: 'Load Blog' });
fetchButton.onclick = async () => {
this.plugin.settings.host = hostInput.value.trim();
this.plugin.settings.slug = slugInput.value.trim();
await this.plugin.saveSettings();
await this.plugin.saveFetchedBlog();
this.close();
};
// Add some styling
contentEl.createEl('style').textContent = `
.blog-fetch-form {
display: grid;
gap: 10px;
margin-top: 10px;
}
.blog-fetch-form label {
font-weight: bold;
}
.blog-fetch-form input {
padding: 5px;
font-size: 1rem;
}
button {
margin-top: 15px;
padding: 5px 10px;
font-size: 1rem;
}
`;
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
class AllBlogsModal extends Modal {
plugin: BlogPlugin;
files: TFile[];
constructor(app: App, plugin: BlogPlugin, files: TFile[]) {
super(app);
this.plugin = plugin;
this.files = files;
}
onOpen() {
const { contentEl } = this;
contentEl.createEl('h3', { text: 'Local Blog Posts' });
this.files.forEach(file => {
const item = contentEl.createEl('div', { cls: 'blog-list-item' });
const starIcon = item.createEl('span', { text: '★', cls: 'star-icon' });
const fileNameEl = item.createEl('span', { text: file.name });
item.addEventListener('click', async () => {
const leaf = this.app.workspace.getLeaf(false);
await leaf.openFile(file);
this.close();
});
});
// Add styling for the blog list items
contentEl.createEl('style').textContent = `
.blog-list-item {
display: flex;
align-items: center;
cursor: pointer;
margin: 5px 0;
}
.star-icon {
color: gold;
margin-right: 8px;
}
.blog-list-item:hover {
background-color: #333;
border-radius: 4px;
}
.blog-list-item span {
padding: 5px;
}
`;
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
class BlogPluginSettingTab extends PluginSettingTab {
plugin: BlogPlugin;
constructor(app: App, plugin: BlogPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display() {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Blog Plugin Settings' });
new Setting(containerEl)
.setName('Publication Host')
.setDesc('The host of your blog publication (e.g., blog.hashnode.dev).')
.addText(text => text
.setValue(this.plugin.settings.host)
.onChange(async (value) => {
this.plugin.settings.host = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Blog Slug')
.setDesc('The slug of the blog post you want to fetch.')
.addText(text => text
.setValue(this.plugin.settings.slug)
.onChange(async (value) => {
this.plugin.settings.slug = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Save Location')
.setDesc('Location to save your fetched blog posts.')
.addText(text => text
.setValue(this.plugin.settings.saveLocation)
.onChange(async (value) => {
this.plugin.settings.saveLocation = value;
await this.plugin.saveSettings();
})
);
}
}