forked from akosbalasko/zoottelkeeper-obsidian-plugin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.ts
715 lines (623 loc) · 23.3 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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
import { App, Modal, debounce, Plugin, PluginSettingTab, Setting, TFile, TAbstractFile } from 'obsidian';
import { IndexItemStyle } from './interfaces/IndexItemStyle';
import { GeneralContentOptions, ZoottelkeeperPluginSettings } from './interfaces'
import { isInAllowedFolder, isInDisAllowedFolder, updateFrontmatter, updateIndexContent, removeFrontmatter, hasFrontmatter } from './utils'
import { DEFAULT_SETTINGS } from './defaultSettings';
import * as emoji from 'node-emoji';
import { SortOrder } from 'models';
export default class ZoottelkeeperPlugin extends Plugin {
settings: ZoottelkeeperPluginSettings;
lastVault: Set<string>;
triggerUpdateIndexFile = debounce(
(file: TAbstractFile, oldPath?: string) => {
this.keepTheZooClean(false, file, oldPath)
},
3000,
true
);
async onload(): Promise<void> {
await this.loadSettings();
this.app.workspace.onLayoutReady(async () => {
this.loadVault();
console.debug(
`Vault in files: ${JSON.stringify(
this.app.vault.getMarkdownFiles().map((f) => f.path)
)}`
);
});
this.registerEvent(
this.app.vault.on('create', this.triggerUpdateIndexFile)
);
this.registerEvent(
this.app.vault.on('delete', this.triggerUpdateIndexFile)
);
this.registerEvent(
this.app.vault.on('rename', this.triggerUpdateIndexFile)
);
this.addSettingTab(new ZoottelkeeperPluginSettingTab(this.app, this));
}
loadVault() {
this.lastVault = this.getVaultSet();
}
getVaultSet() {
return new Set(
this.app.vault.getMarkdownFiles().map((file) => file.path)
);
}
async keepTheZooClean(triggeredManually?: boolean, file?: TAbstractFile, oldPath?: string) {
console.debug('keeping the zoo clean...');
if (this.lastVault || triggeredManually) {
const vaultFilePathsSet = this.getVaultSet();
try {
const changedFiles = this.getCreatedAndDeletedFiles(vaultFilePathsSet)
console.debug(
`changedFiles: ${JSON.stringify(changedFiles)}`
);
const indexFileAndNewPath = this.getIndexFile2BRenamed(file, oldPath)
const indexFiles2BUpdated = this.getIndexFiles2BUpdated(changedFiles)
console.debug(
`Index files to be updated: ${JSON.stringify(
Array.from(indexFiles2BUpdated)
)}`
);
await this.renameIndexFile(indexFileAndNewPath)
await this.updateIndexFiles(indexFiles2BUpdated)
} catch (e) {}
}
this.lastVault = this.getVaultSet();
}
getCreatedAndDeletedFiles(vaultFilePathsSet: Set<string>) {
// getting the changed files using symmetric diff
const createdFiles = Array.from(vaultFilePathsSet).filter(
(currentFile) => !this.lastVault.has(currentFile)
)
const deletedFiles = Array.from(this.lastVault).filter(
(currentVaultFile) => !vaultFilePathsSet.has(currentVaultFile)
)
let changedFiles = Array.from(new Set([
...createdFiles,
...deletedFiles,
]));
return changedFiles
}
getIndexFile2BRenamed(file?: TAbstractFile, oldPath?: string): { file: TFile, newPath: string } | undefined {
if (!file || !oldPath) return undefined;
const createdFileSplit = file.path.split('/')
const deletedFileSplit = oldPath.split('/')
const createdFileName = file.name
const deletedFileName = deletedFileSplit.last()
// the file itself was renamed, not the folder
if (createdFileName !== deletedFileName) return undefined
// The file was moved to a shallower or deeper nested directory
if (createdFileSplit.length !== deletedFileSplit.length) return undefined
// Find the folder that was renamed
for (let i = 0; i < createdFileSplit.length; i++) {
const createdParentFolder = createdFileSplit[i];
const deletedParentFolder = deletedFileSplit[i];
// This folder has not changed
if (createdParentFolder === deletedParentFolder) continue
// Is the index file of the old folder still present in the new folder?
const indexFilePath = `${createdFileSplit.slice(0, i + 1).join('/')}/${this.settings.indexPrefix}${deletedParentFolder}.md`
const folderOrIndexFile = this.app.vault.getAbstractFileByPath(indexFilePath)
// The old index file is still there => folder has been renamed and the file can be deleted
if (folderOrIndexFile instanceof TFile) {
const newPath = this.getIndexFilePath(`${createdFileSplit.slice(0, i + 1).join('/')}/`)
return { file: folderOrIndexFile, newPath }
}
// If there is no such file, either that folder is excluded or the file was moved there.
// In both cases there is no action necessary
return undefined
}
}
getIndexFiles2BUpdated(changedFiles: string[]) {
const indexFiles2BUpdated = new Set<string>();
for (const changedFile of changedFiles) {
const indexFilePath = this.getIndexFilePath(changedFile);
if (indexFilePath
&& isInAllowedFolder(this.settings, indexFilePath)
&& !isInDisAllowedFolder(this.settings, indexFilePath)) {
indexFiles2BUpdated.add(indexFilePath);
}
// getting the parents' index notes of each changed file in order to update their links as well (hierarhical backlinks)
const parentIndexFilePath = this.getIndexFilePath(
this.getParentFolder(changedFile)
);
if (parentIndexFilePath) indexFiles2BUpdated.add(parentIndexFilePath);
}
return indexFiles2BUpdated
}
async renameIndexFile(indexFileAndNewPath: { file: TFile, newPath: string } | undefined) {
if (!indexFileAndNewPath) return
const { file, newPath } = indexFileAndNewPath
const newIndexFile = this.app.vault.getAbstractFileByPath(newPath)
const newIndexFileExists = newIndexFile instanceof TFile
if (newIndexFileExists) {
await this.app.vault.delete(newIndexFile)
}
await this.app.vault.rename(file, newPath)
}
async updateIndexFiles(indexFiles2BUpdated: Set<string>) {
await this.removeDisallowedFoldersIndexes(indexFiles2BUpdated);
// update index files
for (const indexFile of Array.from(indexFiles2BUpdated)) {
await this.generateIndexContents(indexFile);
}
await this.cleanDisallowedFolders();
}
onunload() {
console.debug('unloading plugin');
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
generateIndexContents = async (indexFile: string): Promise<void> => {
const templateFile = this.app.vault.getAbstractFileByPath(this.settings.templateFile);
let currentTemplateContent = '';
if (templateFile instanceof TFile){
currentTemplateContent = await this.app.vault.cachedRead(templateFile);
}
let indexTFile =
this.app.vault.getAbstractFileByPath(indexFile) ||
(await this.app.vault.create(indexFile, currentTemplateContent));
if (indexTFile && indexTFile instanceof TFile)
return this.generateIndexContent(indexTFile);
};
generateGeneralIndexContent = (options: GeneralContentOptions): Array<string> => {
return options.items
.reduce(
(acc, curr) => {
acc.push(options.func(curr.path, this.isFile(curr)));
return acc;
}, options.initValue);
}
generateIndexContent = async (indexTFile: TFile): Promise<void> => {
let indexContent;
// get subFolders
//const subFolders = indexTFile.parent.children.filter(item => !this.isFile(item));
//const files = indexTFile.parent.children.filter(item => this.isFile(item));
const splitItems = indexTFile.parent.children.reduce(
(acc,curr) => {
if (this.isFile(curr))
acc['files'].push(curr)
else acc['subFolders'].push(curr);
return acc;
}, {subFolders: [], files: []}
)
indexContent = this.generateGeneralIndexContent({
items: splitItems.subFolders,
func: this.generateIndexFolderItem,
initValue: [],
})
indexContent = this.generateGeneralIndexContent({
items: splitItems.files.filter(file => file.name !== indexTFile.name ),
func: this.generateIndexItem,
initValue: indexContent,
})
try {
if (indexTFile instanceof TFile){
let currentContent = await this.app.vault.cachedRead(indexTFile);
if (currentContent === ''){
const templateFile = this.app.vault.getAbstractFileByPath(this.settings.templateFile);
if (templateFile instanceof TFile){
currentContent = await this.app.vault.cachedRead(templateFile);
}
}
const updatedFrontmatter = hasFrontmatter(currentContent, this.settings.frontMatterSeparator)
? updateFrontmatter(this.settings, currentContent)
: '';
currentContent = removeFrontmatter(currentContent, this.settings.frontMatterSeparator);
const updatedIndexContent = updateIndexContent(this.settings.sortOrder, currentContent, indexContent);
await this.app.vault.modify(indexTFile, `${updatedFrontmatter}${updatedIndexContent}`);
} else {
throw new Error('Creation index as folder is not supported');
}
} catch (e) {
console.warn('Error during deletion/creation of index files', e);
}
};
setEmojiPrefix = (isFile: boolean): string => {
return this.settings.enableEmojis
? isFile
? emoji.get(this.settings.fileEmoji)
: emoji.get(this.settings.folderEmoji)
: '';
}
generateFormattedIndexItem = (path: string, isFile: boolean): string => {
const realFileName = `${path.split('|')[0]}.md`;
const fileAbstrPath = this.app.vault.getAbstractFileByPath(realFileName);
const embedSubIndexCharacter = this.settings.embedSubIndex && this.isIndexFile(fileAbstrPath) ? '!' : '';
switch (this.settings.indexItemStyle) {
case IndexItemStyle.PureLink:
return `${this.setEmojiPrefix(isFile)} ${embedSubIndexCharacter}[[${path}]]`;
case IndexItemStyle.List:
return `- ${this.setEmojiPrefix(isFile)} ${embedSubIndexCharacter}[[${path}]]`;
case IndexItemStyle.Checkbox:
return `- [ ] ${this.setEmojiPrefix(isFile)} ${embedSubIndexCharacter}[[${path}]]`
};
}
generateIndexItem = (path: string, isFile: boolean): string => {
let internalFormattedIndex;
if (this.settings.cleanPathBoolean) {
const cleanPath = ( path.endsWith(".md"))
? path.replace(/\.md$/,'')
: path;
const fileName = cleanPath.split("/").pop();
internalFormattedIndex = `${cleanPath}|${fileName}`;
}
else {
internalFormattedIndex = path;
}
return this.generateFormattedIndexItem(internalFormattedIndex, isFile);
}
generateIndexFolderItem = (path: string, isFile: boolean): string => {
return this.generateIndexItem(this.getInnerIndexFilePath(path), isFile);
}
getInnerIndexFilePath = (folderPath: string): string => {
const folderName = this.getFolderName(folderPath);
return this.createIndexFilePath(folderPath, folderName);
}
getIndexFilePath = (filePath: string): string => {
const fileAbstrPath = this.app.vault.getAbstractFileByPath(filePath);
if (this.isIndexFile(fileAbstrPath)) return null;
let parentPath = this.getParentFolder(filePath);
// if its parent does not exits, then its a moved subfolder, so it should not be updated
const parentTFolder = this.app.vault.getAbstractFileByPath(parentPath);
if (parentPath && parentPath !== '') {
if (!parentTFolder) return undefined;
parentPath = `${parentPath}/`;
}
const parentName = this.getParentFolderName(filePath);
return this.createIndexFilePath(parentPath, parentName);
}
createIndexFilePath = (folderPath: string, folderName: string) => {
if (!folderPath.endsWith('/') && folderPath !== '') {
folderPath += '/';
}
return `${folderPath}${this.settings.indexPrefix}${folderName}.md`;
}
removeDisallowedFoldersIndexes = async (indexFiles: Set<string>): Promise<void> => {
for (const folder of this.settings.foldersExcluded.split('\n').map(f=> f.trim())){
const innerIndex = this.getInnerIndexFilePath(folder);
indexFiles.delete(innerIndex);
}
}
cleanDisallowedFolders = async (): Promise<void> => {
for (const folder of this.settings.foldersExcluded.split('\n').map(f=> f.trim())){
const innerIndex = this.getInnerIndexFilePath(folder);
const indexTFile = this.app.vault.getAbstractFileByPath(innerIndex);
await this.app.vault.delete(indexTFile);
}
}
getParentFolder = (filePath: string): string => {
const fileFolderArray = filePath.split('/');
fileFolderArray.pop();
return fileFolderArray.join('/');
};
getParentFolderName = (filePath: string): string => {
const parentFolder = this.getParentFolder(filePath);
const fileFolderArray = parentFolder.split('/');
return fileFolderArray[0] !== ''
? fileFolderArray[fileFolderArray.length - 1]
: this.app.vault.getName();
};
getFolderName = (folderPath: string): string => {
const folderArray = folderPath.split('/');
return (folderArray[0] !== '') ? folderArray[folderArray.length - 1] : this.app.vault.getName();
}
isIndexFile = (item: TAbstractFile): boolean => {
return this.isFile(item)
&& item.name === `${this.settings.indexPrefix}${item.parent.name}`
}
isFile = (item: TAbstractFile): boolean => {
return item instanceof TFile;
}
}
class ZoottelkeeperPluginModal extends Modal {
constructor(app: App) {
super(app);
}
}
class ZoottelkeeperPluginSettingTab extends PluginSettingTab {
plugin: ZoottelkeeperPlugin;
constructor(app: App, plugin: ZoottelkeeperPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
let { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Zoottelkeeper Settings' });
containerEl.createEl('h3', { text: 'Folder Settings' });
new Setting(containerEl)
.setName('Folders included')
.setDesc(
'Specify the folders to be handled by Zoottelkeeper. They must be absolute paths starting from the root vault, one per line, example: Notes/ <enter> Articles/, which will include Notes and Articles folder in the root folder. Empty list means all of the vault will be handled except the excluded folders. \'*\' can be added to the end, to include the folder\'s subdirectories recursively, e.g. Notes/* <enter> Articles/'
)
.addTextArea((text) =>
text
.setPlaceholder('')
.setValue(this.plugin.settings.foldersIncluded)
.onChange(async (value) => {
this.plugin.settings.foldersIncluded = value
.replace(/,/g,'\n')
.split('\n')
.map(
folder=> {
const f = folder.trim();
return f.startsWith('/')
? f.substring(1)
: f
})
.join('\n');
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Folders excluded')
.setDesc(
'Specify the folders NOT to be handled by Zoottelkeeper. They must be absolute paths starting from the root vault, one per line, an empty line excluding the root folder itself. Example: "Notes/ <enter> Articles/ ", it will exclude Notes and Articles folder in the root folder. * can be added to the end, to exclude the folder\'s subdirectories recursively.'
)
.addTextArea((text) =>
text
.setPlaceholder('')
.setValue(this.plugin.settings.foldersExcluded)
.onChange(async (value) => {
this.plugin.settings.foldersExcluded = value
.replace(/,/g,'\n')
.split('\n')
.map(
folder=> {
const f = folder.trim();
return f.startsWith('/')
? f.substring(1)
: f
})
.join('\n');;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Trigger indexing')
.setDesc(
'By pushing this button you can trigger the indexing on folders match your include/exclude criterias currently set.'
)
.addButton((btn) => {
btn.setButtonText('Generate index now')
btn.onClick(async () => {
this.plugin.lastVault = new Set();
await this.plugin.keepTheZooClean(true);
})
}
);
containerEl.createEl('h3', { text: 'General Settings' });
new Setting(containerEl)
.setName("Clean Files")
.setDesc(
"This enables you to only show the files without path and '.md' ending in preview mode."
)
.addToggle((t) => {
t.setValue(this.plugin.settings.cleanPathBoolean);
t.onChange(async (v) => {
this.plugin.settings.cleanPathBoolean = v;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName('Index links Order')
.setDesc('Select the order of the links to be sorted in the index files.')
.addDropdown(async (dropdown) => {
dropdown.addOption(SortOrder.ASC, 'Ascending');
dropdown.addOption(SortOrder.DESC, 'Descending');
dropdown.setValue(this.plugin.settings.sortOrder);
dropdown.onChange(async (option) => {
this.plugin.settings.sortOrder = option as SortOrder;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName('List Style')
.setDesc('Select the style of the index-list.')
.addDropdown(async (dropdown) => {
dropdown.addOption(IndexItemStyle.PureLink, 'Pure Obsidian link');
dropdown.addOption(IndexItemStyle.List, 'Listed link');
dropdown.addOption(IndexItemStyle.Checkbox, 'Checkboxed link');
dropdown.setValue(this.plugin.settings.indexItemStyle);
dropdown.onChange(async (option) => {
console.debug('Chosen index item style: ' + option);
this.plugin.settings.indexItemStyle = option as IndexItemStyle;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName('Embed sub-index content in preview')
.setDesc(
"If you enable this, the plugin will embed the sub-index content in preview mode."
)
.addToggle((t) => {
t.setValue(this.plugin.settings.embedSubIndex);
t.onChange(async (v) => {
this.plugin.settings.embedSubIndex = v;
await this.plugin.saveSettings();
});
});
// index prefix
new Setting(containerEl)
.setName('Index Prefix')
.setDesc(
'Per default the file is named after your folder, but you can prefix it here.'
)
.addText((text) =>
text
.setPlaceholder('')
.setValue(this.plugin.settings.indexPrefix)
.onChange(async (value) => {
console.debug('Index prefix: ' + value);
this.plugin.settings.indexPrefix = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Template file')
.setDesc(
'Set your template file\'s absolute path like "templates/zoottel_template.md"'
)
.addText((text) =>
text
.setPlaceholder('')
.setValue(this.plugin.settings.templateFile)
.onChange(async (value) => {
console.debug('Template file: ' + value);
this.plugin.settings.templateFile = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Frontmatter separator')
.setDesc('It specifies the separator string generated before and after the frontmatter, by default its ---')
.addText((text) =>
text
.setPlaceholder('')
.setValue(this.plugin.settings.frontMatterSeparator)
.onChange(async (value) => {
this.plugin.settings.frontMatterSeparator = value;
await this.plugin.saveSettings();
})
);
containerEl.createEl('h4', { text: 'Meta Tags' });
// Enabling Meta Tags
new Setting(containerEl)
.setName('Enable Meta Tags')
.setDesc(
"You can add Meta Tags at the top of your index-file. This is useful when you're using the index files as MOCs."
)
.addToggle((t) => {
t.setValue(this.plugin.settings.indexTagBoolean);
t.onChange(async (v) => {
this.plugin.settings.indexTagBoolean = v;
await this.plugin.saveSettings();
});
});
// setting the meta tag value
const metaTagsSetting = new Setting(containerEl)
.setName('Set Meta Tags')
.setDesc(
'You can add one or multiple tags to your index-files! There is no need to use "#", just use the exact value of the tags\' separator specified below between the tags.'
)
.addText((text) =>
text
.setPlaceholder('moc')
.setValue(this.plugin.settings.indexTagValue)
.onChange(async (value) => {
this.plugin.settings.indexTagValue = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Set the tag\'s label in frontmatter')
.setDesc(
'Please specify the label of the tags in frontmatter (the text before the colon ):'
)
.addText((text) =>
text
.setPlaceholder('tags')
.setValue(this.plugin.settings.indexTagLabel)
.onChange(async (value) => {
this.plugin.settings.indexTagLabel = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Set the tag\'s separator in Frontmatter')
.setDesc(
'Please specify the separator characters that distinguish the tags in Frontmatter:'
)
.addText((text) =>
text
.setPlaceholder(', ')
.setValue(this.plugin.settings.indexTagSeparator)
.onChange(async (value) => {
this.plugin.settings.indexTagSeparator = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Add square brackets around each tags')
.setDesc(
"If you enable this, the plugin will put square brackets around the tags set."
)
.addToggle((t) => {
t.setValue(this.plugin.settings.addSquareBrackets);
t.onChange(async (v) => {
this.plugin.settings.addSquareBrackets = v;
await this.plugin.saveSettings();
});
});
containerEl.createEl('h4', { text: 'Emojis' });
// Enabling Meta Tags
new Setting(containerEl)
.setName('Enable Emojis')
.setDesc("You can set an emoji at the beginning of each index item depending on its type (file or folder). If multiple emojis matches, the first one will be stored."
)
.addToggle((t) => {
t.setValue(this.plugin.settings.enableEmojis);
t.onChange(async (v) => {
this.plugin.settings.enableEmojis = v;
await this.plugin.saveSettings();
});
});
let emojiFolderDesc = 'Set an emoji for folders:'
if (this.plugin.settings.folderEmoji){
const setFolderEmoji = emoji.search(this.plugin.settings.folderEmoji);
emojiFolderDesc = `Matching Options:${setFolderEmoji[0].emoji} (${setFolderEmoji[0].key})`;
}
const emojiForFoldersSetting = new Setting(containerEl)
.setName('Emojis')
.setDesc(emojiFolderDesc)
.addText((text) =>
text.setPlaceholder('card_index_dividers')
.setValue(this.plugin.settings.folderEmoji.replace(/:/g, ''))
.onChange(async (value) => {
if (value !== ''){
const emojiOptions = emoji.search(value);
emojiForFoldersSetting.setDesc(`Matching Options:${emojiOptions.map(emojOp => emojOp.emoji + "("+emojOp.key+")")}`)
if (emojiOptions.length > 0){
this.plugin.settings.folderEmoji = `:${emojiOptions[0].key}:`;
await this.plugin.saveSettings();
}
} else {
emojiForFoldersSetting.setDesc(
'Set an emoji for folders:'
)
}
}));
let emojiFileDesc = 'Set an emoji for files:'
if (this.plugin.settings.fileEmoji){
const setFileEmoji = emoji.search(this.plugin.settings.fileEmoji);
emojiFileDesc = `Matching Options:${setFileEmoji[0].emoji} (${setFileEmoji[0].key})`;
}
const emojiForFilesSetting = new Setting(containerEl)
.setName('Emojis')
.setDesc(emojiFileDesc)
.addText((text) =>
text.setPlaceholder('page_facing_up')
.setValue(this.plugin.settings.fileEmoji.replace(/:/g, ''))
.onChange(async (value) => {
if (value !== ''){
const emojiOptions = emoji.search(value);
emojiForFilesSetting.setDesc(`Matching Options:${emojiOptions.map(emojOp => emojOp.emoji + "("+emojOp.key+")")}`)
if (emojiOptions.length > 0){
this.plugin.settings.fileEmoji = `:${emojiOptions[0].key}:`;
await this.plugin.saveSettings();
}
} else {
emojiForFilesSetting.setDesc(
'Set an emoji for files:'
)
}
})
);
}
}