From 5f2436bd8240e2f4313d041c15907aa5975c61e9 Mon Sep 17 00:00:00 2001 From: EndarValuk Date: Thu, 11 May 2023 06:12:19 +0000 Subject: [PATCH 1/5] [*] Safer translation fallback. --- main.ts | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/main.ts b/main.ts index 42c115b..f5c8cd5 100644 --- a/main.ts +++ b/main.ts @@ -143,10 +143,9 @@ export default class AdvancedMerge extends Plugin { public settings: AdvancedMergePluginSettings; public async onload(): Promise { - this.language = - TRANSLATIONS[navigator.language] == null - ? DEFAULT_LANGUAGE - : navigator.language; + this.language = !Object.keys(TRANSLATIONS).contains(navigator.language) + ? DEFAULT_LANGUAGE + : navigator.language; await this.loadSettings(); @@ -270,7 +269,7 @@ export default class AdvancedMerge extends Plugin { return 1; } return 0; - }) + }) : files.reverse(); } From 3bef4a87656876cae430938897b220667386a618 Mon Sep 17 00:00:00 2001 From: EndarValuk Date: Thu, 11 May 2023 06:40:14 +0000 Subject: [PATCH 2/5] [+] New option to use nested folders as sections. --- main.ts | 135 +++++++++++++++++++++++++++++++++++++------------- manifest.json | 2 +- 2 files changed, 102 insertions(+), 35 deletions(-) diff --git a/main.ts b/main.ts index f5c8cd5..4c9571d 100644 --- a/main.ts +++ b/main.ts @@ -4,6 +4,7 @@ import { Plugin, PluginSettingTab, Setting, + TAbstractFile, TFile, TFolder, Vault, @@ -21,6 +22,8 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { 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", }, @@ -35,6 +38,8 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { 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", }, @@ -49,6 +54,8 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { 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", }, @@ -63,6 +70,8 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { 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", }, @@ -77,6 +86,8 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { SettingIncludeNestedFolders: "Влючать вложенные папки", SettingIncludeNestedFoldersDescription: "Если включено, файлы во вложенных папках будут включены в слияние. В противном случае будут объединены только файлы в выбранной папке (поведение по умолчанию).", + SettingIncludeFoldersAsSections: "Включать папки как разделы", + SettingIncludeFoldersAsSectionsDescription: "Папки будут включены в выходной файл в качестве разделов.", Yes: "Да", No: "Нет", }, @@ -91,6 +102,8 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { SettingIncludeNestedFolders: "Включити вкладені папки", SettingIncludeNestedFoldersDescription: "Якщо ввімкнено, файли у вкладених папках будуть включені в об’єднання. В іншому випадку буде об’єднано лише файли у вибраній папці (поведінка за замовчуванням).", + SettingIncludeFoldersAsSections: "Включити папки як розділи", + SettingIncludeFoldersAsSectionsDescription: "Папки будуть включені як іменовані розділи у вихідний файл.", Yes: "Так", No: "Ні", }, @@ -99,11 +112,13 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { interface AdvancedMergePluginSettings { sortAlphabetically: boolean; includeNestedFolders: boolean; + includeFoldersAsSections: boolean; } const DEFAULT_SETTINGS: AdvancedMergePluginSettings = { sortAlphabetically: false, includeNestedFolders: false, + includeFoldersAsSections: false, }; /** @constant @@ -136,6 +151,16 @@ const NEW_LINE_CHAR = "\n"; @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 language: string; @@ -177,67 +202,91 @@ export default class AdvancedMerge extends Plugin { ): Promise { const { vault } = this.app; - const files = this.fileSort( - vault - .getMarkdownFiles() - .filter((file) => this.fileFilter(folder, file)) + const documentEntries: Array = []; + Vault.recurseChildren(folder, (folderOrFile: TAbstractFile) => + { + // 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 mergedFileName = `${folder.path}-${ + const outputFileName = `${folder.path}-${ TRANSLATIONS[this.language].MergedFilesuffix }.md`; - const fileExists = await vault.adapter.exists(mergedFileName, false); + const fileExists = await vault.adapter.exists(outputFileName, false); if (fileExists) { new AdvancedMergeOverwriteFileModal( this.app, this.language, - mergedFileName, + outputFileName, async (deleteFile) => { if (!deleteFile) { console.info( - `file "${mergedFileName}" already exists, but user cancelled deleting..` + `file "${outputFileName}" already exists, but user cancelled deleting..` ); return; } console.info( - `file "${mergedFileName}" already exists, deleting..` + `file "${outputFileName}" already exists, deleting..` ); - await vault.adapter.remove(mergedFileName); + await vault.adapter.remove(outputFileName); - await this.mergeFiles(vault, files, mergedFileName); + await this.mergeNotes(vault, entries, outputFileName); } ).open(); return; } - await this.mergeFiles(vault, files, mergedFileName); + await this.mergeNotes(vault, entries, outputFileName); } /** - * Merges input files to single output file. + * Merges input notes to single output file. * @param {Vault} vault - Current vault. - * @param {Array} files - Files, to be included. - * @param {string} mergedFileName - Output file name. + * @param {Array} entries - Files and folders, to be included. + * @param {string} outputFileName - Output file name. */ - private async mergeFiles( + private async mergeNotes( vault: Vault, - files: Array, - mergedFileName: string + entries: Array, + outputFileName: string ): Promise { - const destination = await vault.create(mergedFileName, ""); - - files.forEach(async (file: TFile, index: number) => { - let contents = await vault.read(file); - const fileSectionName = file.name.replace(/\.md$/, ""); - // For the first file in a row, we shouldnt add new line - contents = `${ - index === 0 ? "" : NEW_LINE_CHAR - }# ${fileSectionName}${DOUBLE_NEW_LINE_CHAR}${contents}${NEW_LINE_CHAR}`; - console.info( - `Adding file "${file.name}" as section "${fileSectionName}" into file "${mergedFileName}"..` - ); - vault.append(destination, contents); - }); + 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); + } } /** @@ -246,7 +295,7 @@ export default class AdvancedMerge extends Plugin { * @param {TFile} file - Files, to be included. * @returns {boolean} Provided file passses folder check. */ - private fileFilter(folder: TFolder, file: TFile): boolean { + private filterNotes(folder: TFolder, file: TAbstractFile): boolean { return this.settings.includeNestedFolders ? !!file.parent?.path.startsWith(folder.path) : file.parent?.path == folder.path; @@ -257,7 +306,7 @@ export default class AdvancedMerge extends Plugin { * @param {Array} files - The files array, to be sorted. * @returns {Array} Sorted files array. */ - private fileSort(files: Array): Array { + private sortNotes(files: Array): Array { return this.settings.sortAlphabetically ? files.sort((a, b) => { const x = a.path.toLowerCase(); @@ -352,6 +401,24 @@ class AdvancedMergeSettingTab extends PluginSettingTab { await this.plugin.saveSettings(); }) ); + + // Add "include folders as sections" toggle in settings + new Setting(containerEl) + .setName( + TRANSLATIONS[this.plugin.language].SettingIncludeFoldersAsSections + ) + .setDesc( + TRANSLATIONS[this.plugin.language] + .SettingIncludeFoldersAsSectionsDescription + ) + .addToggle((toggle) => + toggle + .setValue(this.plugin.settings.includeFoldersAsSections) + .onChange(async (value) => { + this.plugin.settings.includeFoldersAsSections = value; + await this.plugin.saveSettings(); + }) + ); } } diff --git a/manifest.json b/manifest.json index 0932e58..df241a4 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "advanced-merger", "name": "Advanced Merger", - "version": "1.3.0", + "version": "1.4.0", "minAppVersion": "0.15.0", "description": "Merge a folder of notes for easier export.", "author": "Anto Keinänen", From 536822a916b26ce23a5e61e2e891b19fb7682f9b Mon Sep 17 00:00:00 2001 From: EndarValuk Date: Thu, 11 May 2023 07:48:23 +0000 Subject: [PATCH 3/5] [*] "folders as sections" depend on "nested folders" --- main.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/main.ts b/main.ts index 4c9571d..565aabc 100644 --- a/main.ts +++ b/main.ts @@ -343,6 +343,7 @@ export default class AdvancedMerge extends Plugin { class AdvancedMergeSettingTab extends PluginSettingTab { private plugin: AdvancedMerge; + private includeFolderAsSectionSetting: Setting; /** * Represents a settings tab. @@ -398,12 +399,23 @@ class AdvancedMergeSettingTab extends PluginSettingTab { .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 - new Setting(containerEl) + this.includeFolderAsSectionSetting = new Setting(containerEl) .setName( TRANSLATIONS[this.plugin.language].SettingIncludeFoldersAsSections ) From 02cc838228cff89356b5b4275908506070d4b932 Mon Sep 17 00:00:00 2001 From: EndarValuk Date: Thu, 11 May 2023 08:20:02 +0000 Subject: [PATCH 4/5] [*] Typesafe translations. --- CHANGELOG.md | 35 +++++++++--- main.ts | 154 ++++++++++++++++++++++++++++++++++----------------- 2 files changed, 129 insertions(+), 60 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6cf67b..45a49b3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,23 +1,40 @@ +## obsidian-advanced-merger 1.4.0 + +### Additions and Changes + +- Added new option to include "nested folders as sections" (depends on "nested folders" setting) +- Type-safe plugin translations + ## obsidian-advanced-merger 1.3.0 + ### Additions and Changes -- Added "Overwrite existing file" dialog + +- Added "Overwrite existing file" dialog ## obsidian-advanced-merger 1.2.0 + ### Additions and Changes -- Translations support added (starter: English, Ukranian, Finnish, French, Russian, German) -- Added support and configuration for merging files in nested folders -- Added configuration for sorting mode (default/alphabetically) + +- Translations support added (starter: English, Ukranian, Finnish, French, Russian, German) +- Added support and configuration for merging files in nested folders +- Added configuration for sorting mode (default/alphabetically) ## obsidian-advanced-merger 1.1.0 + ### Additions and Changes -- Fix issue where the created file will still be collected and merged -- Remove not needed await Promise.All + +- Fix issue where the created file will still be collected and merged +- Remove not needed await Promise.All ## obsidian-advanced-merger 1.0.2 + ### Additions and Changes -- Added sorting alphabetically by file path + +- Added sorting alphabetically by file path ## obsidian-advanced-merger 1.0.1 + ### Additions and Changes -- Remove unused onunload event -- Remove redundant file check + +- Remove unused onunload event +- Remove redundant file check diff --git a/main.ts b/main.ts index 565aabc..20a062e 100644 --- a/main.ts +++ b/main.ts @@ -10,7 +10,22 @@ import { Vault, } from "obsidian"; -const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { +interface Translation { + MergeFolder: string; + MergedFilesuffix: string; + OverwriteFileQuestion: string; + Settings: string; + SettingSortAlphabetically: string; + SettingSortAlphabeticallyDescription: 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", @@ -23,7 +38,8 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { 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.", + SettingIncludeFoldersAsSectionsDescription: + "Ordner werden als benannte Abschnitte in die Ausgabedatei eingefügt.", Yes: "Ja", No: "Nein", }, @@ -39,7 +55,8 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { 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.", + SettingIncludeFoldersAsSectionsDescription: + "Folders will be included as named sections into output file.", Yes: "Yes", No: "No", }, @@ -55,7 +72,8 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { 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.", + SettingIncludeFoldersAsSectionsDescription: + "Kansiot sisällytetään nimettyinä osina tulostiedostoon.", Yes: "Kyllä", No: "Ei", }, @@ -70,8 +88,10 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { 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.", + 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", }, @@ -87,7 +107,8 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { SettingIncludeNestedFoldersDescription: "Если включено, файлы во вложенных папках будут включены в слияние. В противном случае будут объединены только файлы в выбранной папке (поведение по умолчанию).", SettingIncludeFoldersAsSections: "Включать папки как разделы", - SettingIncludeFoldersAsSectionsDescription: "Папки будут включены в выходной файл в качестве разделов.", + SettingIncludeFoldersAsSectionsDescription: + "Папки будут включены в выходной файл в качестве разделов.", Yes: "Да", No: "Нет", }, @@ -103,7 +124,8 @@ const TRANSLATIONS: { [name: string]: { [name: string]: string } } = { SettingIncludeNestedFoldersDescription: "Якщо ввімкнено, файли у вкладених папках будуть включені в об’єднання. В іншому випадку буде об’єднано лише файли у вибраній папці (поведінка за замовчуванням).", SettingIncludeFoldersAsSections: "Включити папки як розділи", - SettingIncludeFoldersAsSectionsDescription: "Папки будуть включені як іменовані розділи у вихідний файл.", + SettingIncludeFoldersAsSectionsDescription: + "Папки будуть включені як іменовані розділи у вихідний файл.", Yes: "Так", No: "Ні", }, @@ -163,15 +185,11 @@ const SECTION_CHAR = "#"; const MARKDOWN_FILE_EXTENSION = "md"; export default class AdvancedMerge extends Plugin { - public language: string; - + public translation: AdvancedMergeTranslation; public settings: AdvancedMergePluginSettings; public async onload(): Promise { - this.language = !Object.keys(TRANSLATIONS).contains(navigator.language) - ? DEFAULT_LANGUAGE - : navigator.language; - + this.translation = new AdvancedMergeTranslation(); await this.loadSettings(); this.registerEvent( @@ -182,7 +200,7 @@ export default class AdvancedMerge extends Plugin { const folder = file; menu.addItem((item) => { - item.setTitle(TRANSLATIONS[this.language].MergeFolder) + item.setTitle(this.translation.get().MergeFolder) .setIcon(ICON_NAME) .onClick( async (evt) => @@ -203,31 +221,35 @@ export default class AdvancedMerge extends Plugin { const { vault } = this.app; const documentEntries: Array = []; - Vault.recurseChildren(folder, (folderOrFile: TAbstractFile) => - { + Vault.recurseChildren(folder, (folderOrFile: TAbstractFile) => { // For merging we are including only *.md files - if (folderOrFile instanceof TFile && folderOrFile.extension == MARKDOWN_FILE_EXTENSION) { + 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) { + } 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)) + documentEntries.filter((entry) => this.filterNotes(folder, entry)) ); const outputFileName = `${folder.path}-${ - TRANSLATIONS[this.language].MergedFilesuffix + this.translation.get().MergedFilesuffix }.md`; const fileExists = await vault.adapter.exists(outputFileName, false); if (fileExists) { new AdvancedMergeOverwriteFileModal( this.app, - this.language, + this.translation, outputFileName, async (deleteFile) => { if (!deleteFile) { @@ -265,22 +287,27 @@ export default class AdvancedMerge extends Plugin { for (let index = 0; index < entries.length; index++) { const folderOrFile: TAbstractFile = entries[index]; - const sectionLevel = (folderOrFile.path.match(/\//g)||[]).length; + const sectionLevel = (folderOrFile.path.match(/\//g) || []).length; - let sectionContents = `${ index === 0 ? "" : NEW_LINE_CHAR }`; + 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}`; + 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}`; + sectionContents += `${SECTION_CHAR.repeat(sectionLevel)} ${ + folderOrFile.name + }${DOUBLE_NEW_LINE_CHAR}`; console.info( `Adding folder "${folderOrFile.name}" as section "${sectionContents}" into file "${outputFileName}"..` ); @@ -362,18 +389,14 @@ class AdvancedMergeSettingTab extends PluginSettingTab { containerEl.empty(); containerEl.createEl("h2", { - text: `${PLUGIN_NAME} - ${ - TRANSLATIONS[this.plugin.language].Settings - }`, + text: `${PLUGIN_NAME} - ${this.plugin.translation.get().Settings}`, }); // Add "sort alphabetically" toggle in settings new Setting(containerEl) - .setName( - TRANSLATIONS[this.plugin.language].SettingSortAlphabetically - ) + .setName(this.plugin.translation.get().SettingSortAlphabetically) .setDesc( - TRANSLATIONS[this.plugin.language] + this.plugin.translation.get() .SettingSortAlphabeticallyDescription ) .addToggle((toggle) => @@ -387,11 +410,9 @@ class AdvancedMergeSettingTab extends PluginSettingTab { // Add "include nested folders" toggle in settings new Setting(containerEl) - .setName( - TRANSLATIONS[this.plugin.language].SettingIncludeNestedFolders - ) + .setName(this.plugin.translation.get().SettingIncludeNestedFolders) .setDesc( - TRANSLATIONS[this.plugin.language] + this.plugin.translation.get() .SettingIncludeNestedFoldersDescription ) .addToggle((toggle) => @@ -399,7 +420,10 @@ class AdvancedMergeSettingTab extends PluginSettingTab { .setValue(this.plugin.settings.includeNestedFolders) .onChange(async (value) => { this.plugin.settings.includeNestedFolders = value; - this.plugin.settings.includeFoldersAsSections = value === false ? value : this.plugin.settings.includeFoldersAsSections; + this.plugin.settings.includeFoldersAsSections = + value === false + ? value + : this.plugin.settings.includeFoldersAsSections; await this.plugin.saveSettings(); this.showIncludeFolderAsSectionSetting(containerEl); }) @@ -417,10 +441,10 @@ class AdvancedMergeSettingTab extends PluginSettingTab { // Add "include folders as sections" toggle in settings this.includeFolderAsSectionSetting = new Setting(containerEl) .setName( - TRANSLATIONS[this.plugin.language].SettingIncludeFoldersAsSections + this.plugin.translation.get().SettingIncludeFoldersAsSections ) .setDesc( - TRANSLATIONS[this.plugin.language] + this.plugin.translation.get() .SettingIncludeFoldersAsSectionsDescription ) .addToggle((toggle) => @@ -435,7 +459,7 @@ class AdvancedMergeSettingTab extends PluginSettingTab { } class AdvancedMergeOverwriteFileModal extends Modal { - private language: string; + private tranlation: AdvancedMergeTranslation; private existingFileName: string; private onSubmitHandler: (result: boolean) => void; @@ -443,27 +467,30 @@ class AdvancedMergeOverwriteFileModal extends Modal { * Represents an "Overwrite file?" dialog. * @constructor * @param {App} app - The `Obsidian` application object. - * @param {string} language - Application language. + * @param {AdvancedMergeTranslation} translation - Plugin translation. * @param {string} existingFileName - Existing file name. * @param handler - Modal callback handler. */ constructor( app: App, - language: string, + translation: AdvancedMergeTranslation, existingFileName: string, handler: (result: boolean) => void ) { super(app); - this.language = language; + this.tranlation = translation; this.existingFileName = existingFileName; this.onSubmitHandler = handler; } - public onOpen() { + /** + * @inheritdoc + */ + public onOpen(): void { const { contentEl } = this; contentEl.createEl("h3", { - text: `${TRANSLATIONS[this.language].OverwriteFileQuestion} "${ + text: `${this.tranlation.get().OverwriteFileQuestion} "${ this.existingFileName }"?`, }); @@ -471,7 +498,7 @@ class AdvancedMergeOverwriteFileModal extends Modal { new Setting(contentEl) .addButton((btn) => btn - .setButtonText(TRANSLATIONS[this.language].No) + .setButtonText(this.tranlation.get().No) .setCta() .onClick(() => { this.close(); @@ -480,7 +507,7 @@ class AdvancedMergeOverwriteFileModal extends Modal { ) .addButton((btn) => btn - .setButtonText(TRANSLATIONS[this.language].Yes) + .setButtonText(this.tranlation.get().Yes) .setCta() .onClick(() => { this.close(); @@ -489,8 +516,33 @@ class AdvancedMergeOverwriteFileModal extends Modal { ); } - public onClose() { + /** + * @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]; + } +} From e8fc6d54ad23517e169268eea1dccda093643f70 Mon Sep 17 00:00:00 2001 From: EndarValuk Date: Thu, 11 May 2023 08:29:20 +0000 Subject: [PATCH 5/5] [*] Pkg bump. --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index e10af10..b506620 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "obsidian-advanced-merger", - "version": "1.3.0", + "version": "1.4.0", "description": "Merge a folder of notes for easier export. This plugin is designed for Obsidian (https://obsidian.md).", "homepage": "https://github.com/antoKeinanen/obsidian-advanced-merger", "contributors": [