-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.ts
585 lines (541 loc) · 17.9 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
import {
App,
Modal,
Plugin,
PluginSettingTab,
Setting,
TAbstractFile,
TFile,
TFolder,
Vault,
} from "obsidian";
interface Translation {
MergeFolder: string;
MergedFilesuffix: string;
OverwriteFileQuestion: string;
Settings: string;
SettingSortMode: string;
SettingSortModeDescription: string;
SettingSortAlphabetically: string;
SettingSortDateCreated: string;
SettingSortLogical: string;
SettingIncludeNestedFolders: string;
SettingIncludeNestedFoldersDescription: string;
SettingIncludeFoldersAsSections: string;
SettingIncludeFoldersAsSectionsDescription: string;
Yes: string;
No: string;
}
const TRANSLATIONS: { [name: string]: Translation } = {
de: {
MergeFolder: "Ordner zusammenführen",
MergedFilesuffix: "zusammengeführt",
OverwriteFileQuestion: "Vorhandene Datei überschreiben",
Settings: "Einstellungen",
SettingIncludeNestedFolders: "Verschachtelte Ordner einbeziehen",
SettingIncludeNestedFoldersDescription:
"Wenn aktiviert, werden Dateien in verschachtelten Ordnern zusammengeführt. Andernfalls werden nur Dateien im ausgewählten Ordner zusammengeführt (Standardverhalten).",
SettingIncludeFoldersAsSections: "Ordner als Abschnitte einbeziehen",
SettingIncludeFoldersAsSectionsDescription:
"Ordner werden als benannte Abschnitte in die Ausgabedatei eingefügt.",
Yes: "Ja",
No: "Nein",
SettingSortMode: "Sortiermodus",
SettingSortModeDescription:
"Wählen Sie den Sortiermodus für das Zusammenführen von Notizen.",
SettingSortDateCreated: "Erstellungsdatum",
SettingSortLogical: "Logisch",
SettingSortAlphabetically: "Alphabetisch",
},
en: {
MergeFolder: "Merge folder",
MergedFilesuffix: "merged",
OverwriteFileQuestion: "Overwite exising file",
Settings: "Settings",
SettingIncludeNestedFolders: "Include nested folders",
SettingIncludeNestedFoldersDescription:
"If enabled, files in nested folders will be included in merge. Otherwise, only files in selected folder will be merged (default behaviour).",
SettingIncludeFoldersAsSections: "Include folders as sections",
SettingIncludeFoldersAsSectionsDescription:
"Folders will be included as named sections into output file.",
Yes: "Yes",
No: "No",
SettingSortMode: "Sort mode",
SettingSortModeDescription: "Pick the sorting mode for merging notes.",
SettingSortDateCreated: "Date created",
SettingSortLogical: "Logical",
SettingSortAlphabetically: "Alphabetical",
},
fi: {
MergeFolder: "Yhdistä kansio",
MergedFilesuffix: "yhdistetty",
OverwriteFileQuestion: "Korvaa olemassa oleva tiedosto",
Settings: "Asetukset",
SettingIncludeNestedFolders: "Sisällytä sisäkkäiset kansiot",
SettingIncludeNestedFoldersDescription:
"Jos käytössä, sisäkkäisten kansioiden tiedostot yhdistetään. Muussa tapauksessa vain valitun kansion tiedostot yhdistetään (oletustoiminto).",
SettingIncludeFoldersAsSections: "Sisällytä kansiot osioihin",
SettingIncludeFoldersAsSectionsDescription:
"Kansiot sisällytetään nimettyinä osina tulostiedostoon.",
Yes: "Kyllä",
No: "Ei",
SettingSortMode: "Lajittelu järjestys",
SettingSortModeDescription:
"Valitse lajittelutapa muistiinpanojen yhdistämistä varten.",
SettingSortDateCreated: "Luontipäivämäärä",
SettingSortLogical: "Looginen",
SettingSortAlphabetically: "Aakkosjärjestys",
},
fr: {
MergeFolder: "Fusionner le dossier",
MergedFilesuffix: "fusionné",
OverwriteFileQuestion: "Remplacer le fichier existant",
Settings: "Paramètres",
SettingIncludeNestedFolders: "Inclure les dossiers imbriqués",
SettingIncludeNestedFoldersDescription:
"Si activé, les fichiers des dossiers imbriqués seront inclus dans la fusion. Sinon, seuls les fichiers du dossier sélectionné seront fusionnés (comportement par défaut).",
SettingIncludeFoldersAsSections:
"Inclure les dossiers en tant que sections",
SettingIncludeFoldersAsSectionsDescription:
"Les dossiers seront inclus en tant que sections nommées dans le fichier de sortie.",
Yes: "Oui",
No: "Non",
SettingSortMode: "mode de tri",
SettingSortModeDescription:
"Choisissez le mode de tri pour la fusion des notes.",
SettingSortDateCreated: "Date de création",
SettingSortLogical: "Logique",
SettingSortAlphabetically: "Alphabétique",
},
ru: {
MergeFolder: "Объединить папку",
MergedFilesuffix: "совмещенный",
OverwriteFileQuestion: "Перезаписать существующий файл",
Settings: "Настройки",
SettingIncludeNestedFolders: "Влючать вложенные папки",
SettingIncludeNestedFoldersDescription:
"Если включено, файлы во вложенных папках будут включены в слияние. В противном случае будут объединены только файлы в выбранной папке (поведение по умолчанию).",
SettingIncludeFoldersAsSections: "Включать папки как разделы",
SettingIncludeFoldersAsSectionsDescription:
"Папки будут включены в выходной файл в качестве разделов.",
Yes: "Да",
No: "Нет",
SettingSortMode: "режим сортировки",
SettingSortModeDescription:
"Выберите режим сортировки при объединении заметок.",
SettingSortDateCreated: "Дата создания",
SettingSortLogical: "Логический",
SettingSortAlphabetically: "Алфавитный указатель",
},
ua: {
MergeFolder: "Об'єднати папку",
MergedFilesuffix: "об'єднані",
OverwriteFileQuestion: "Перезаписати існуючий файл",
Settings: "Налаштування",
SettingIncludeNestedFolders: "Включити вкладені папки",
SettingIncludeNestedFoldersDescription:
"Якщо ввімкнено, файли у вкладених папках будуть включені в об’єднання. В іншому випадку буде об’єднано лише файли у вибраній папці (поведінка за замовчуванням).",
SettingIncludeFoldersAsSections: "Включити папки як розділи",
SettingIncludeFoldersAsSectionsDescription:
"Папки будуть включені як іменовані розділи у вихідний файл.",
Yes: "Так",
No: "Ні",
SettingSortMode: "Логический",
SettingSortModeDescription:
"Виберіть режим сортування для об'єднання нотаток.",
SettingSortDateCreated: "Дата створення",
SettingSortLogical: "Логічний",
SettingSortAlphabetically: "За алфавітом",
},
};
/**
* Enum representing the available sorting options for merging notes.
* If you add a new option, make sure to add it to the settings in 'AdvancedMergeSettingTab.display'.
*/
interface AdvancedMergePluginSettings {
sortMode: "alphabetical" | "creationDate" | "logical";
includeNestedFolders: boolean;
includeFoldersAsSections: boolean;
}
const DEFAULT_SETTINGS: AdvancedMergePluginSettings = {
sortMode: "logical",
includeNestedFolders: false,
includeFoldersAsSections: false,
};
/** @constant
@type {string}
@default
*/
const ICON_NAME = "git-merge";
/** @constant
@type {string}
@default
*/
const PLUGIN_NAME = "Advanced Merger";
/** @constant
@type {string}
@default
*/
const DEFAULT_LANGUAGE = "en";
/** @constant
@type {string}
@default
*/
const HANDLER_LOCATION = "file-menu";
/** @constant
@type {string}
@default
*/
const NEW_LINE_CHAR = "\n";
/** @constant
@type {string}
@default
*/
const DOUBLE_NEW_LINE_CHAR = "\n\n";
/** @constant
@type {string}
@default
*/
const SECTION_CHAR = "#";
/** @constant
@type {string}
@default
*/
const MARKDOWN_FILE_EXTENSION = "md";
export default class AdvancedMerge extends Plugin {
public translation: AdvancedMergeTranslation;
public settings: AdvancedMergePluginSettings;
public async onload(): Promise<void> {
this.translation = new AdvancedMergeTranslation();
await this.loadSettings();
this.registerEvent(
this.app.workspace.on(HANDLER_LOCATION, (menu, file) => {
if (!(file instanceof TFolder)) {
return;
}
const folder = file;
menu.addItem((item) => {
item.setTitle(this.translation.get().MergeFolder)
.setIcon(ICON_NAME)
.onClick(
async (evt) =>
await this.onClickCallback(folder, evt),
);
});
}),
);
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new AdvancedMergeSettingTab(this.app, this));
}
private async onClickCallback(
folder: TFolder,
_evt: MouseEvent | KeyboardEvent,
): Promise<void> {
const { vault } = this.app;
const documentEntries: Array<TFile> = [];
Vault.recurseChildren(folder, (folderOrFile: TFile) => {
// For merging we are including only *.md files
if (
folderOrFile instanceof TFile &&
folderOrFile.extension == MARKDOWN_FILE_EXTENSION
) {
console.log(`Found a file: ${folderOrFile.name}`);
documentEntries.push(folderOrFile);
} else if (
folderOrFile instanceof TFolder &&
this.settings.includeFoldersAsSections
) {
console.log(`Found a folder: ${folderOrFile.name}`);
documentEntries.push(folderOrFile);
}
});
const entries = this.sortNotes(
documentEntries.filter((entry) => this.filterNotes(folder, entry)),
);
const outputFileName = `${folder.path}-${
this.translation.get().MergedFilesuffix
}.md`;
const fileExists = await vault.adapter.exists(outputFileName, false);
if (fileExists) {
new AdvancedMergeOverwriteFileModal(
this.app,
this.translation,
outputFileName,
async (deleteFile) => {
if (!deleteFile) {
console.info(
`file "${outputFileName}" already exists, but user cancelled deleting..`,
);
return;
}
console.info(
`file "${outputFileName}" already exists, deleting..`,
);
await vault.adapter.remove(outputFileName);
await this.mergeNotes(vault, entries, outputFileName);
},
).open();
return;
}
await this.mergeNotes(vault, entries, outputFileName);
}
/**
* Merges input notes to single output file.
* @param {Vault} vault - Current vault.
* @param {Array<TAbstractFile>} entries - Files and folders, to be included.
* @param {string} outputFileName - Output file name.
*/
private async mergeNotes(
vault: Vault,
entries: Array<TAbstractFile>,
outputFileName: string,
): Promise<void> {
const outputFile = await vault.create(outputFileName, "");
for (let index = 0; index < entries.length; index++) {
const folderOrFile: TAbstractFile = entries[index];
const sectionLevel = (folderOrFile.path.match(/\//g) || []).length;
let sectionContents = `${index === 0 ? "" : NEW_LINE_CHAR}`;
const lastEntry = index === entries.length - 1;
if (folderOrFile instanceof TFile) {
sectionContents += await vault.cachedRead(folderOrFile);
const fileSectionName = folderOrFile.name.replace(/\.md$/, "");
// For the first file in a row, we shouldnt add new line
sectionContents = `${SECTION_CHAR.repeat(
sectionLevel,
)} ${fileSectionName}${DOUBLE_NEW_LINE_CHAR}${sectionContents}${
lastEntry ? "" : DOUBLE_NEW_LINE_CHAR
}`;
console.info(
`Adding file "${folderOrFile.name}" as section "${fileSectionName}" into file "${outputFileName}"..`,
);
} else if (folderOrFile instanceof TFolder) {
sectionContents += `${SECTION_CHAR.repeat(sectionLevel)} ${
folderOrFile.name
}${DOUBLE_NEW_LINE_CHAR}`;
console.info(
`Adding folder "${folderOrFile.name}" as section "${sectionContents}" into file "${outputFileName}"..`,
);
}
vault.append(outputFile, sectionContents);
}
}
/**
* Applies filtering to input file.
* @param {TFolder} folder - Selected folder.
* @param {TFile} file - Files, to be included.
* @returns {boolean} Provided file passses folder check.
*/
private filterNotes(folder: TFolder, file: TAbstractFile): boolean {
return this.settings.includeNestedFolders
? !!file.parent?.path.startsWith(folder.path)
: file.parent?.path == folder.path;
}
/**
* Applies sorting to input files array.
* @param {Array<TFile>} files - The files array, to be sorted.
* @returns {Array<TFile>} Sorted files array.
*/
private sortNotes(files: Array<TFile>): Array<TFile> {
switch (this.settings.sortMode) {
case "alphabetical":
return files.sort((a, b) => a.name.localeCompare(b.name));
case "creationDate":
return files.sort((a, b) => a.stat.ctime - b.stat.ctime);
case "logical":
default:
return files.sort((a, b) =>
a.path.localeCompare(b.path, undefined, {
numeric: true,
sensitivity: "base",
usage: "sort",
}),
);
}
}
/**
* De-serializes settings from persistent storage.
*/
private async loadSettings(): Promise<void> {
const data = await this.loadData();
console.log("Loaded settings", data);
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData(),
);
}
/**
* Serializes settings into persistent storage.
*/
public async saveSettings(): Promise<void> {
console.log("Saving settings", this.settings);
await this.saveData(this.settings);
}
}
class AdvancedMergeSettingTab extends PluginSettingTab {
private plugin: AdvancedMerge;
private includeFolderAsSectionSetting: Setting;
/**
* Represents a settings tab.
* @constructor
* @param {App} app - The `Obsidian` application object.
* @param {AdvancedMerge} plugin - The `AdvancedMerge` plugin object.
*/
constructor(app: App, plugin: AdvancedMerge) {
super(app, plugin);
this.plugin = plugin;
}
public display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", {
text: `${PLUGIN_NAME} - ${this.plugin.translation.get().Settings}`,
});
// Add "sort mode" dropdown in settings
new Setting(containerEl)
.setName(this.plugin.translation.get().SettingSortMode)
.setDesc(this.plugin.translation.get().SettingSortModeDescription)
.addDropdown((dropdown) =>
dropdown
.addOptions({
alphabetical:
this.plugin.translation.get()
.SettingSortAlphabetically,
creationDate:
this.plugin.translation.get()
.SettingSortDateCreated,
logical:
this.plugin.translation.get().SettingSortLogical,
})
.onChange(async (value) => {
this.plugin.settings.sortMode = value as any;
await this.plugin.saveSettings();
})
.setValue(this.plugin.settings.sortMode),
);
// Add "include nested folders" toggle in settings
new Setting(containerEl)
.setName(this.plugin.translation.get().SettingIncludeNestedFolders)
.setDesc(
this.plugin.translation.get()
.SettingIncludeNestedFoldersDescription,
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.includeNestedFolders)
.onChange(async (value) => {
this.plugin.settings.includeNestedFolders = value;
this.plugin.settings.includeFoldersAsSections =
value === false
? value
: this.plugin.settings.includeFoldersAsSections;
await this.plugin.saveSettings();
this.showIncludeFolderAsSectionSetting(containerEl);
}),
);
this.showIncludeFolderAsSectionSetting(containerEl);
}
private showIncludeFolderAsSectionSetting(containerEl: HTMLElement): void {
if (!this.plugin.settings.includeNestedFolders) {
this.includeFolderAsSectionSetting?.settingEl?.remove();
return;
}
// Add "include folders as sections" toggle in settings
this.includeFolderAsSectionSetting = new Setting(containerEl)
.setName(
this.plugin.translation.get().SettingIncludeFoldersAsSections,
)
.setDesc(
this.plugin.translation.get()
.SettingIncludeFoldersAsSectionsDescription,
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.includeFoldersAsSections)
.onChange(async (value) => {
this.plugin.settings.includeFoldersAsSections = value;
await this.plugin.saveSettings();
}),
);
}
}
class AdvancedMergeOverwriteFileModal extends Modal {
private tranlation: AdvancedMergeTranslation;
private existingFileName: string;
private onSubmitHandler: (result: boolean) => void;
/**
* Represents an "Overwrite file?" dialog.
* @constructor
* @param {App} app - The `Obsidian` application object.
* @param {AdvancedMergeTranslation} translation - Plugin translation.
* @param {string} existingFileName - Existing file name.
* @param handler - Modal callback handler.
*/
constructor(
app: App,
translation: AdvancedMergeTranslation,
existingFileName: string,
handler: (result: boolean) => void,
) {
super(app);
this.tranlation = translation;
this.existingFileName = existingFileName;
this.onSubmitHandler = handler;
}
/**
* @inheritdoc
*/
public onOpen(): void {
const { contentEl } = this;
contentEl.createEl("h3", {
text: `${this.tranlation.get().OverwriteFileQuestion} "${
this.existingFileName
}"?`,
});
new Setting(contentEl)
.addButton((btn) =>
btn
.setButtonText(this.tranlation.get().No)
.setCta()
.onClick(() => {
this.close();
this.onSubmitHandler(false);
}),
)
.addButton((btn) =>
btn
.setButtonText(this.tranlation.get().Yes)
.setCta()
.onClick(() => {
this.close();
this.onSubmitHandler(true);
}),
);
}
/**
* @inheritdoc
*/
public onClose(): void {
const { contentEl } = this;
contentEl.empty();
}
}
class AdvancedMergeTranslation {
private language: string;
/**
* Represents a plugin translation.
* @constructor
*/
constructor() {
this.language = !Object.keys(TRANSLATIONS).contains(navigator.language)
? DEFAULT_LANGUAGE
: navigator.language;
}
/**
* Gets translation object for current language.
* @returns {Translation} Current translation object.
*/
public get(): Translation {
return TRANSLATIONS[this.language];
}
}