-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.ts
349 lines (312 loc) · 8.64 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
import {
App,
MarkdownView,
Modal,
normalizePath,
Plugin,
PluginSettingTab,
Setting,
TFile,
} from 'obsidian';
import { fetchTagData, getIsWildCard } from './src/utils/tagSearch';
import {
extractFrontMatterTagValue,
generateFilename,
generateTagPageContent,
swapPageContent,
} from './src/utils/pageContent';
import { PluginSettings } from './src/types';
import { isTagPage } from './src/utils/obsidianApi';
const DEFAULT_SETTINGS: PluginSettings = {
tagPageDir: 'Tags/',
frontmatterQueryProperty: 'tag-page-query',
nestedSeparator: '_',
bulletedSubItems: true,
includeLines: true,
autoRefresh: true,
fullLinkName: false,
};
export default class TagPagePlugin extends Plugin {
settings: PluginSettings;
ribbonIcon: HTMLElement;
async onload() {
await this.loadSettings();
this.addSettingTab(new TagPageSettingTab(this.app, this));
this.ribbonIcon = this.addRibbonIcon(
'tag-glyph',
'Refresh tag page',
() => {
this.refreshTagPageContent();
},
);
this.ribbonIcon.style.display = 'none';
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: 'create-tag-page',
name: 'Create tag page',
callback: () => {
new CreateTagPageModal(this.app, this).open();
},
});
this.registerEvent(
this.app.workspace.on('layout-change', () => {
this.updateRibbonIconVisibility();
this.autoRefreshTagPage();
}),
);
this.registerEvent(
this.app.workspace.on('file-open', () => {
this.updateRibbonIconVisibility();
this.autoRefreshTagPage();
}),
);
this.updateRibbonIconVisibility();
await this.autoRefreshTagPage();
}
updateRibbonIconVisibility() {
this.ribbonIcon.style.display = isTagPage(
this.app,
this.settings.frontmatterQueryProperty,
)
? 'block'
: 'none';
}
async autoRefreshTagPage() {
if (
this.settings.autoRefresh &&
isTagPage(this.app, this.settings.frontmatterQueryProperty)
) {
await this.refreshTagPageContent();
}
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData(),
);
}
async saveSettings() {
await this.saveData(this.settings);
}
/**
* Refreshes the content of the active tag page based on the current settings.
*
* @returns {Promise<void>} - A promise that resolves when the operation is complete.
*/
async refreshTagPageContent(): Promise<void> {
const activeLeaf = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!activeLeaf) return;
const tagOfInterest = extractFrontMatterTagValue(
this.app,
activeLeaf,
this.settings.frontmatterQueryProperty,
);
if (!tagOfInterest) return;
const tagsInfo = await fetchTagData(
this.app,
this.settings,
tagOfInterest,
);
const tagPageContentString = await generateTagPageContent(
this.app,
this.settings,
tagsInfo,
tagOfInterest,
);
swapPageContent(activeLeaf, tagPageContentString);
}
/**
* Creates a new tag page or navigates to an existing one.
*
* @param {string} tag - The tag for which to create or navigate to a page.
* @returns {Promise<void>} - A promise that resolves when the operation is complete.
*/
async createTagPage(tag: string): Promise<void> {
// Append # to tag if it doesn't exist
const tagOfInterest = tag.startsWith('#') ? tag : `#${tag}`;
const { isWildCard, cleanedTag } = getIsWildCard(tagOfInterest);
const filename = generateFilename(
cleanedTag,
isWildCard,
this.settings.nestedSeparator,
);
// Create tag page if it doesn't exist
const tagPage = this.app.vault.getAbstractFileByPath(
`${this.settings.tagPageDir}${filename}`,
);
if (!tagPage) {
const tagsInfo = await fetchTagData(
this.app,
this.settings,
tagOfInterest,
);
const tagPageContentString = await generateTagPageContent(
this.app,
this.settings,
tagsInfo,
tagOfInterest,
);
// if tag page doesn't exist, create it and continue
const exists = await this.app.vault.adapter.exists(
normalizePath(this.settings.tagPageDir),
);
if (!exists) {
await this.app.vault.createFolder(this.settings.tagPageDir);
}
const createdPage = await this.app.vault.create(
`${this.settings.tagPageDir}${filename}`,
tagPageContentString,
);
await this.app.workspace.getLeaf().openFile(createdPage as TFile);
} else {
// navigate to tag page
await this.app.workspace.getLeaf().openFile(tagPage as TFile);
}
}
}
class CreateTagPageModal extends Modal {
plugin: TagPagePlugin;
constructor(app: App, plugin: TagPagePlugin) {
super(app);
this.plugin = plugin;
}
onOpen() {
const { contentEl } = this;
contentEl.setText('Tag to create page for:');
const tagForm = contentEl.createEl('form');
contentEl.addClass('create-page-modal');
// Input Element
const input = tagForm.createEl('input', { type: 'text' });
input.placeholder = '#tag';
input.value = '#';
input.addEventListener('keydown', (e) => {
const cursorPosition = input.selectionStart;
if (
cursorPosition === 1 &&
(e.key === 'Backspace' || e.key === 'Delete')
) {
e.preventDefault();
}
});
// Submit Button
const submitButton = tagForm.createEl('button', { type: 'submit' });
submitButton.innerText = 'Create Tag Page';
// Form submit listener
tagForm.addEventListener('submit', async (e) => {
e.preventDefault();
const tag = input.value;
this.contentEl.empty();
this.contentEl.setText(`Creating tag page for ${tag}...`);
await this.plugin.createTagPage(tag);
this.close();
});
}
onClose() {
const { contentEl } = this;
contentEl.empty();
}
}
class TagPageSettingTab extends PluginSettingTab {
plugin: TagPagePlugin;
constructor(app: App, plugin: TagPagePlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName('Tag page directory')
.setDesc('The directory in which to create tag pages.')
.addText((text) =>
text
.setValue(this.plugin.settings.tagPageDir)
.onChange(async (value) => {
// add trailing slash if it doesn't exist
if (!value.endsWith('/')) {
value = `${value}/`;
}
this.plugin.settings.tagPageDir = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Frontmatter query property')
.setDesc(
'The frontmatter property to use storing the query tag within the tag page. Required for page refresh.',
)
.addText((text) =>
text
.setValue(this.plugin.settings.frontmatterQueryProperty)
.onChange(async (value) => {
this.plugin.settings.frontmatterQueryProperty = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Nested page separator')
.setDesc(
"Text used to separate levels for nested tags. Avoid \\/<>:\"|?* and other characters that aren't file-safe, or you won't be able to make pages for nested tags.",
)
.addText((text) =>
text
.setValue(this.plugin.settings.nestedSeparator)
.onChange(async (value) => {
this.plugin.settings.nestedSeparator = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Include lines')
.setDesc('Include lines containing the tag in the tag page.')
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.includeLines)
.onChange(async (value) => {
this.plugin.settings.includeLines = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Bulleted sub-items')
.setDesc(
'Include bulleted sub-items containing the tag in the tag page.',
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.bulletedSubItems)
.onChange(async (value) => {
this.plugin.settings.bulletedSubItems = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Auto refresh')
.setDesc(
'Automatically refresh tag pages when they are opened or become active.',
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.autoRefresh)
.onChange(async (value) => {
this.plugin.settings.autoRefresh = value;
await this.plugin.saveSettings();
}),
);
new Setting(containerEl)
.setName('Display full link name as reference')
.setDesc(
'Each bit of pulled content will display the full link title as a reference as an end of line. Displays * when false.',
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.fullLinkName)
.onChange(async (value) => {
this.plugin.settings.fullLinkName = value;
await this.plugin.saveSettings();
}),
);
}
}