-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
421 lines (354 loc) · 11.7 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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import {Plugin, Notice, Modal, App, MarkdownRenderer} from "obsidian";
interface Snippet {
id: string;
name: string;
author: string;
description: string;
repo: string;
folder: string;
}
export default class CssSnippetStore extends Plugin {
private snippets: Snippet[] = [];
observer: MutationObserver;
async onload() {
// Start the mutation observer when the plugin is loaded.
this.injectBrowseButton();
// fetching list of snippets
const url = "https://raw.githubusercontent.com/xavwe/obsidian-css-snippet-store/main/snippets.json"
try {
if (await isOnline()) {
const response = await fetchWithTimeout(url);
if (!response.ok) {
new Notice(`Network response was not ok: ${response.statusText}`);
return;
}
/*
if (!response.headers.get('content-type')?.includes('application/json')) {
throw new Error("Unexpected content type");
}*/
this.snippets = await response.json();
} else {
new Notice(`No Internet connection...`);
return;
}
} catch (error) {
console.error(error);
new Notice(`Error: ${error.message}`);
}
}
injectBrowseButton() {
this.observer = new MutationObserver(() => {
const settingItems = Array.from(document.querySelectorAll('.setting-item'));
for (const item of settingItems) {
const titleElement = item.querySelector('.setting-item-name');
if (
titleElement &&
titleElement.textContent &&
titleElement.textContent.trim().toLowerCase().includes("css snippets")
) {
const controlElement = item.querySelector('.setting-item-control');
// Check if our button is already injected
if (controlElement && !controlElement.querySelector('.my-custom-button')) {
const customButton = document.createElement("button");
customButton.onclick = () => {
new CssSnippetStoreModal(this.app, this.snippets, this).open();
};
controlElement.appendChild(customButton);
customButton.textContent = 'Browse';
customButton.className = "mod-cta my-custom-button injected-button";
}
}
}
});
this.observer.observe(document.body, {
childList: true,
subtree: true,
});
}
onunload() {
// Clean up the mutation observer on plugin unload.
if (this.observer) {
this.observer.disconnect();
}
}
}
class CssSnippetStoreModal extends Modal {
constructor(app: App, private snippets: Snippet[], private plugin: Plugin) {
super(app);
this.modalEl.addClass('mod-snippet-store');
}
async install(name: string, code: string) {
const vault = this.app.vault;
const adapter = vault.adapter;
const snippetFolderPath = this.app.vault.configDir + '/snippets';
const fileName = name + '.css';
const fullPath = `${snippetFolderPath}/${fileName}`;
try {
// Ensure the folder exists
if (!(await adapter.exists(snippetFolderPath))) {
await adapter.mkdir(snippetFolderPath);
}
// Check if file already exists
if (await adapter.exists(fullPath)) {
new Notice(`Snippet with id "${fileName}" already exists.`);
return;
}
// Write default content to the CSS snippet
await vault.create(fullPath, code);
new Notice(`Snippet "${fileName}" installed`);
} catch (err) {
console.error('Failed to create snippet:', err);
new Notice('Failed to create snippet. See console for details.');
}
}
async uninstall(name: string) {
const vault = this.app.vault;
const snippetFolderPath = this.app.vault.configDir + '/snippets';
const fileName = name + '.css';
const fullPath = `${snippetFolderPath}/${fileName}`;
try {
// Check if the file exists
if (await vault.adapter.exists(fullPath)) {
await vault.adapter.remove(fullPath);
new Notice(`Snippet "${fileName}" deleted.`);
} else {
new Notice(`Snippet "${fileName}" does not exist.`);
}
} catch (err) {
console.error('Failed to delete snippet:', err);
new Notice('Failed to delete snippet. See console for details.');
}
}
async checkSnippetExists(name: string): Promise<boolean> {
const vault = this.app.vault;
const snippetFolderPath = this.app.vault.configDir + '/snippets';
const fileName = name + '.css';
const fullPath = `${snippetFolderPath}/${fileName}`;
return await vault.adapter.exists(fullPath);
}
private updateSnippetCard(snippet: Snippet) {
const card = this.contentEl.querySelector(`.community-item[data-snippet-id="${snippet.id}"]`) as HTMLDivElement;
if (!card) return;
const buttonWrapper = card.querySelector('.snippet-store-button-wrapper') as HTMLDivElement;
if (!buttonWrapper) return;
// Clear any existing button
buttonWrapper.empty();
const button = buttonWrapper.createEl('button');
button.classList.add('mod-cta'); // default, will be overridden
this.checkSnippetExists(snippet.id).then((exists) => {
if (exists) {
button.textContent = 'Delete';
button.className = 'mod-danger';
button.addEventListener('click', async () => {
await this.uninstall(snippet.id);
this.updateSnippetCard(snippet);
});
} else {
button.textContent = 'Install';
button.className = 'mod-cta';
button.addEventListener('click', async () => {
const url = `https://raw.githubusercontent.com/${snippet.repo}/refs/heads/main/${snippet.folder}/snippet.css`;
try {
if (await isOnline()) {
const response = await fetchWithTimeout(url);
if (!response.ok) {
new Notice(`Network response was not ok: ${response.statusText}`);
return;
}
const code = await response.text();
await this.install(snippet.id, code);
this.updateSnippetCard(snippet);
} else {
new Notice(`No Internet connection...`);
}
} catch (error) {
console.error(error);
new Notice(`Error: ${error.message}`);
}
});
}
});
}
private renderSnippetsUI(filter: string = "") {
const { contentEl } = this;
const grid = contentEl.querySelector('.community-items-container') as HTMLDivElement;
const messageEl = contentEl.querySelector('.snippet-status-message') as HTMLDivElement;
if (!grid || !messageEl) return;
grid.empty();
messageEl.empty();
const lowerFilter = filter.toLowerCase();
const filteredSnippets = this.snippets.filter(snippet =>
!filter ||
snippet.name.toLowerCase().includes(lowerFilter) ||
snippet.author.toLowerCase().includes(lowerFilter) ||
snippet.description.toLowerCase().includes(lowerFilter)
);
if (filteredSnippets.length === 0) {
messageEl.setText(
this.snippets.length === 0
? "No Internet connection"
: "No snippets match your search."
);
return;
}
filteredSnippets.forEach(snippet => {
const card = grid.createDiv({ cls: 'community-item' });
card.setAttr("data-snippet-id", snippet.id);
card.createEl('div', { text: snippet.name, cls: 'community-item-name' });
card.createEl('div', { text: `By ${snippet.author}`, cls: 'community-item-author' });
card.createEl('div', { text: snippet.description, cls: 'community-desc' });
card.createDiv({ cls: 'snippet-store-button-wrapper' });
card.addEventListener('click', async (event) => {
// Prevent click events on buttons inside the card from triggering README modal
if ((event.target as HTMLElement).tagName.toLowerCase() === 'button') return;
// Create and open modal first with loading indicator
const readmeModal = new SnippetReadmeModal(this.app, snippet, "", this.plugin);
readmeModal.open();
const readmeUrl = `https://raw.githubusercontent.com/${snippet.repo}/refs/heads/main/${snippet.folder}/README.md`;
try {
if (await isOnline()) {
const response = await fetchWithTimeout(readmeUrl);
if (!response.ok) {
new Notice(`Could not fetch README: ${response.statusText}`);
readmeModal.close();
return;
}
const readme = await response.text();
// Update the modal with content
readmeModal.updateReadmeContent(readme);
} else {
new Notice("No Internet connection...");
readmeModal.close();
}
} catch (error) {
console.error(error);
new Notice(`Error fetching README: ${error.message}`);
readmeModal.close();
}
});
// Now update just the button based on snippet state
this.updateSnippetCard(snippet);
});
}
onOpen() {
const { contentEl } = this;
contentEl.addClass('snippet-store-modal');
this.modalEl.addClass('snippet-store-modal-element');
contentEl.createEl('h1', { text: 'CSS Snippet Store' });
const topContainer = contentEl.createDiv();
topContainer.addClass('snippet-store-top-container');
const searchInput = topContainer.createEl('input', {
type: 'text',
placeholder: 'Search snippets...',
});
searchInput.classList.add('snippet-search-input');
// Message container
const messageEl = topContainer.createEl('div');
messageEl.classList.add('snippet-status-message');
// Snippet container
contentEl.createEl('div', { cls: 'community-items-container' });
// Initial rendering
this.renderSnippetsUI();
// Live search
searchInput.addEventListener('input', () => {
const value = searchInput.value.trim();
this.renderSnippetsUI(value);
});
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
function fetchWithTimeout(resource: RequestInfo, timeout = 10000): Promise<Response> {
return Promise.race([
this.app.request.requestUrl(resource),
new Promise<Response>((_, reject) => setTimeout(() => reject(new Error("Request timed out")), timeout))
]);
}
export async function isOnline(timeout = 3000): Promise<boolean> {
try {
const controller = new AbortController();
const id = setTimeout(() => controller.abort(), timeout);
await this.app.request.requestUrl({
url: "https://ping.archlinux.org",
method: "GET",
cache: "no-cache"
});
clearTimeout(id);
return true;
} catch (e) {
return false;
}
}
class SnippetReadmeModal extends Modal {
constructor(
app: App,
private snippet: Snippet,
private readmeContent: string,
private plugin: Plugin
) {
super(app);
}
updateReadmeContent(content: string) {
this.readmeContent = content;
this.renderContent();
}
async onOpen() {
const { contentEl } = this;
contentEl.empty();
contentEl.addClass("snippet-readme-modal");
this.modalEl.addClass("snippet-readme-modal-element");
// Show loading indicator if no content yet
if (!this.readmeContent) {
contentEl.createEl('div', {
text: 'Loading README...',
cls: 'snippet-readme-loading'
});
return;
}
await this.renderContent();
}
async renderContent() {
if (!this.readmeContent) return;
const { contentEl } = this;
contentEl.empty();
try {
// Rewrite relative image paths to absolute GitHub raw URLs
const adjustedContent = this.rewriteRelativeMediaPaths(this.readmeContent);
// Markdown container
const markdownContainer = contentEl.createDiv();
// Render Markdown using Obsidian's renderer
await MarkdownRenderer.render(
this.app,
adjustedContent,
markdownContainer,
"",
this.plugin
);
// Optimize image loading
markdownContainer.querySelectorAll("img").forEach((img) => {
img.setAttribute("loading", "lazy");
img.addClass("snippet-readme-image");
});
} catch (error) {
console.error("Error rendering README:", error);
contentEl.empty();
contentEl.createEl('div', {
text: `Error rendering README: ${error.message}`,
cls: 'snippet-readme-error'
});
}
}
onClose() {
this.contentEl.empty();
}
private rewriteRelativeMediaPaths(content: string): string {
const base = `https://raw.githubusercontent.com/${this.snippet.repo}/refs/heads/main/${this.snippet.folder}/`;
// Regex to match image/video markdown with relative path
return content.replace(/!\[([^\]]*)]\((\.\/[^)]+)\)/g, (match, alt, relPath) => {
const url = base + relPath.replace("./", "");
return ``;
});
}
}