-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
280 lines (237 loc) · 8.78 KB
/
main.ts
File metadata and controls
280 lines (237 loc) · 8.78 KB
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
import { Plugin, MarkdownView, MarkdownPostProcessorContext, TFile, setIcon } from 'obsidian';
import { LinkdingSettingsTab } from './src/settings';
import { LinkdingService } from './src/linkding-service';
import { LinkdingSettings, DEFAULT_SETTINGS, LinkdingBookmark, CALLOUT_TYPES } from './src/types';
export default class LinkdingPlugin extends Plugin {
settings: LinkdingSettings;
linkdingService: LinkdingService;
async onload() {
await this.loadSettings();
this.linkdingService = new LinkdingService(this.settings);
this.addSettingTab(new LinkdingSettingsTab(this.app, this));
this.registerMarkdownCodeBlockProcessor('linkding', (source, el, ctx) => {
void this.renderLinkdingBlock(source, el, ctx);
});
this.registerMarkdownPostProcessor((element, context) => {
void this.processLinkdingFrontmatter(element, context);
});
}
async loadSettings() {
const loadedData = await this.loadData();
this.settings = Object.assign({}, DEFAULT_SETTINGS, loadedData);
// Validate callout type in case of corrupted/old settings
if (CALLOUT_TYPES.indexOf(this.settings.calloutType) === -1) {
this.settings.calloutType = DEFAULT_SETTINGS.calloutType;
}
}
async saveSettings() {
await this.saveData(this.settings);
this.linkdingService.updateSettings(this.settings);
}
private renderError(container: HTMLElement, message: string) {
container.createEl('p', {
text: `Error loading bookmarks: ${message}`,
cls: 'linkding-error'
});
}
private async renderLinkdingBlock(source: string, el: HTMLElement, ctx: MarkdownPostProcessorContext) {
const input = source.trim();
if (!input) {
// Empty block: use frontmatter tags and note title
const file = this.app.vault.getAbstractFileByPath(ctx.sourcePath);
if (!file || !(file instanceof TFile)) {
el.createEl('p', { text: 'Could not access file metadata' });
return;
}
const cache = this.app.metadataCache.getFileCache(file);
const frontmatterTags = cache?.frontmatter?.tags;
// Normalize tags to array (can be empty if no tags)
const tagArray = frontmatterTags
? (Array.isArray(frontmatterTags) ? frontmatterTags : [frontmatterTags])
.filter(tag => typeof tag === 'string' || typeof tag === 'number')
.map(tag => String(tag).trim())
.filter(tag => tag.length > 0)
: [];
// Get note title (filename without extension)
const noteTitle = file.basename;
// Need at least tags or a title to search
if (tagArray.length === 0 && !noteTitle) {
el.createEl('p', { text: 'No tags or title found to search with' });
return;
}
try {
const bookmarks = await this.linkdingService.searchBookmarksByTags(
tagArray,
noteTitle,
this.settings.maxResults
);
this.renderBookmarks(bookmarks, el, true); // preserve relevance ranking
} catch (error) {
this.renderError(el, error.message);
}
return;
}
try {
const bookmarks = await this.linkdingService.searchBookmarks(input);
this.renderBookmarks(bookmarks, el);
} catch (error) {
this.renderError(el, error.message);
}
}
private async processLinkdingFrontmatter(element: HTMLElement, context: MarkdownPostProcessorContext) {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view) return;
const cache = this.app.metadataCache.getFileCache(view.file);
if (!cache?.frontmatter?.linkding_tags) return;
const tags = cache.frontmatter.linkding_tags;
const tagArray = Array.isArray(tags) ? tags : [tags];
for (const tag of tagArray) {
try {
const query = `#${tag}`;
const bookmarks = await this.linkdingService.searchBookmarks(query);
const container = element.createEl('div', { cls: 'linkding-bookmarks-container' });
container.createEl('h3', { text: `Linkding bookmarks: ${tag}` });
this.renderBookmarks(bookmarks, container);
} catch (error) {
this.renderError(element, `for tag "${tag}": ${error.message}`);
}
}
}
private renderBookmarks(bookmarks: LinkdingBookmark[], container: HTMLElement, preserveOrder: boolean = false) {
if (bookmarks.length === 0) {
container.createEl('p', { text: 'No matching bookmarks found' });
return;
}
// Sort bookmarks alphabetically by title (unless preserveOrder is true)
const sortedBookmarks = preserveOrder ? bookmarks : [...bookmarks].sort((a, b) => {
const titleA = (a.title || a.url).toLowerCase();
const titleB = (b.title || b.url).toLowerCase();
return titleA.localeCompare(titleB);
});
// Determine the content container (either direct or inside a callout)
let contentContainer: HTMLElement;
if (this.settings.useCallout) {
// Generate unique ID for accessibility
const contentId = `linkding-callout-content-${Date.now()}`;
const isCollapsed = this.settings.calloutCollapsed;
// Create callout structure with accessibility attributes
const callout = container.createEl('div', {
cls: `callout linkding-callout`,
attr: {
'data-callout': this.settings.calloutType,
'role': 'region',
'aria-label': 'Linkding Bookmarks'
}
});
// Add collapsed class and fold attribute
if (isCollapsed) {
callout.addClass('is-collapsed');
}
callout.setAttribute('data-callout-fold', isCollapsed ? '-' : '+');
// Callout title with accessibility attributes
const calloutTitle = callout.createEl('div', {
cls: 'callout-title',
attr: {
'role': 'button',
'aria-expanded': isCollapsed ? 'false' : 'true',
'aria-controls': contentId,
'tabindex': '0'
}
});
// Callout icon
const iconEl = calloutTitle.createEl('div', { cls: 'callout-icon' });
setIcon(iconEl, this.getCalloutIcon(this.settings.calloutType));
// Callout title text
calloutTitle.createEl('div', { cls: 'callout-title-inner', text: 'Linkding Bookmarks' });
// Fold icon using Obsidian's setIcon helper (avoids innerHTML XSS risk)
const foldIcon = calloutTitle.createEl('div', { cls: 'callout-fold' });
setIcon(foldIcon, 'chevron-down');
// Toggle function for collapse/expand
const toggleCallout = () => {
const currentlyCollapsed = callout.hasClass('is-collapsed');
callout.toggleClass('is-collapsed', !currentlyCollapsed);
calloutTitle.setAttribute('aria-expanded', currentlyCollapsed ? 'true' : 'false');
};
// Event delegation: use registerDomEvent for automatic cleanup
this.registerDomEvent(calloutTitle, 'click', toggleCallout);
// Keyboard accessibility: Enter and Space to toggle
this.registerDomEvent(calloutTitle, 'keydown', (e: KeyboardEvent) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
toggleCallout();
}
});
// Callout content with ID for aria-controls
contentContainer = callout.createEl('div', {
cls: 'callout-content',
attr: { 'id': contentId }
});
} else {
contentContainer = container;
}
const listContainer = contentContainer.createEl('div', { cls: 'linkding-bookmarks-list' });
sortedBookmarks.forEach(bookmark => {
const item = listContainer.createEl('div', { cls: 'linkding-bookmark-item' });
const link = item.createEl('a', {
href: bookmark.url,
text: bookmark.title || bookmark.url,
cls: 'linkding-bookmark-link'
});
link.setAttr('target', '_blank');
// Create description
if (bookmark.description && bookmark.description.trim()) {
// Use configurable description length
let truncatedDescription = bookmark.description;
if (this.settings.descriptionLength > 0 && bookmark.description.length > this.settings.descriptionLength) {
truncatedDescription = bookmark.description.substring(0, this.settings.descriptionLength) + '...';
}
item.createEl('div', {
text: truncatedDescription,
cls: 'linkding-bookmark-description'
});
}
// Add tag labels on a new line
if (bookmark.tag_names && bookmark.tag_names.length > 0) {
const tagsContainer = item.createEl('div', { cls: 'linkding-bookmark-tags' });
bookmark.tag_names.forEach((tag: string) => {
tagsContainer.createEl('span', {
text: tag,
cls: 'linkding-bookmark-tag'
});
});
}
});
}
private getCalloutIcon(type: string): string {
const iconMap: Record<string, string> = {
'note': 'pencil',
'abstract': 'clipboard-list',
'summary': 'clipboard-list',
'tldr': 'clipboard-list',
'info': 'info',
'todo': 'check-circle-2',
'tip': 'flame',
'hint': 'flame',
'important': 'flame',
'success': 'check',
'check': 'check',
'done': 'check',
'question': 'help-circle',
'help': 'help-circle',
'faq': 'help-circle',
'warning': 'alert-triangle',
'caution': 'alert-triangle',
'attention': 'alert-triangle',
'failure': 'x',
'fail': 'x',
'missing': 'x',
'danger': 'zap',
'error': 'zap',
'bug': 'bug',
'example': 'list',
'quote': 'quote',
'cite': 'quote'
};
return iconMap[type] || 'info';
}
}