diff --git a/src/i18n/locales/en.json b/src/i18n/locales/en.json index eace6d85..58937390 100644 --- a/src/i18n/locales/en.json +++ b/src/i18n/locales/en.json @@ -226,7 +226,13 @@ }, "ghToken": { "desc": "A GitHub token with repository permission. You can generate it ", - "title": "Github Token" + "encrypted" : "The token will be encrypted and stored as it in your settings.", + "title": "GitHub Token", + "button" : { + "title" : "Regenerate encrypted token", + "notice" : "Token regenerated!", + "tooltip" : "Will regenerate public and private key and save the new encrypted token in your settings." + } }, "repoName": { "desc": "The name of the repository where you store your blog.", diff --git a/src/i18n/locales/fr.json b/src/i18n/locales/fr.json index dfa3408f..c5ccb499 100644 --- a/src/i18n/locales/fr.json +++ b/src/i18n/locales/fr.json @@ -1,435 +1,441 @@ { - "commands": { - "checkValidity": { - "inBranch": { - "error403": "Erreur 403: {{- repo.owner}}/{{- repo.repo}} a été déplacé de manière permanente (depuis {{- branchInfo}}", - "error404": "Erreur 404 : La branche {{- repo.branch}} est introuvable depuis {{- repo.owner}}/{{- repo.repo}}" - }, - "inRepo": { - "error301": "Erreur 301 : {{- repo.owner}}/{{- repo.repo}} a été déplacé de manière permanente", - "error403": "Erreur 403 : Cette action est interdite pour {{- repo.owner}}/{{- repo.repo}}", - "error404": "Erreur 404 : {{- repo.owner}}/{{- repo.repo}} est introuvable" - }, - "rateLimit": { - "command": "Vérifier la limite de requêtes de l'API GitHub", - "limited": "Vous avez atteint la limite de requêtes Github. La limite sera réinitialisée à {{- resetTime}}. minutes.", - "notLimited": "Vous n'êtes pas limité par Github. Vous pouvez encore faire {{- remaining}} requêtes, et la limite sera réinitialisée à {{- resetTime}}." - }, - "repoExistsTestBranch": "Le dépôt {{- repo.owner}}/{{- repo.repo}} existe. Maintenant, nous allons tester la branche {{- repo.branch}}", - "success": "{{- repo.owner}}/{{- repo.repo}} semble valide !", - "title": "Tester la connexion au dépôt configuré" - }, - "copyLink": { - "onActivation": "Lien copié dans le presse-papier !", - "title": "Créer un lien vers cette note" - }, - "publisherDeleteClean": "Purger les fichiers dépubliés et supprimés", - "runOtherRepo": { - "noFile": "Aucun fichier actif, ou le fichier n'est pas partagé.", - "title": "Lancer une commande pour un dépôt" - }, - "shareActiveFile": "Transférer la note active", - "shareViewFiles": "Transférer {{- viewFile}} avec Github Publisher", - "uploadAllEditedNote": "Rafraîchir toutes les notes publiées", - "uploadAllNewEditedNote": "Rafraîchir les notes publiées et transférer les nouvelles notes", - "uploadAllNotes": "Transférer toutes les notes", - "uploadNewNotes": "Transférer les nouvelles notes" - }, - "common": { - "add": "Ajouter {{- things}}", - "after": "Après", - "attachments": "pièces-jointes", - "before": "Avant", - "cancel": "Annuler", - "close": "Fermer", - "delete": "Supprimer {{- things}}", - "edit": "Éditer {{- things}}", - "error": "Erreur", - "files": "fichiers", - "ghToken": "Token GitHub", - "here": "ici", - "or": "ou", - "path": { - "file": "Nom du fichier", - "folder": "Chemin du dossier", - "full": "Chemin du fichier" - }, - "published": "publiés", - "regex": "regex", - "repository": "Dépôt", - "save": "Sauvegarder", - "shared": "partagés", - "text": "texte", - "warning": "Attention" - }, - "deletion": { - "defaultFolder": "Vous avez besoin d'un dossier par défaut dans les paramètres pour utiliser cette commande.", - "failed": "Échec de la suppression de {{- nb}} notes.", - "noFile": "Aucun fichier n'a été supprimé.", - "rootFolder": "Vous devez configurer un dossier racine dans les paramètres pour utiliser cette commande.", - "success": "Suppression réussie de {{- nb}} fichiers." - }, - "error": { - "dataview": "Impossible de convertir la requête Dataview. Veuillez mettre à jour le module Dataview à la dernière version;", - "errorConfig": "Erreur de configuration pour {{- repo.owner}}/{{- repo.repo}}:{{- repo.branch}}. Merci de vérifier vos paramètres.", - "errorPublish": "Erreur lors de la publication sur {{- repo.owner}}/{{- repo.repo}}:{{- repo.branch}}", - "isEmpty": "{{- what}} est vide.", - "mergeconflic": "La Pull-Request n'est pas fusionnale, vous avez besoin de le faire manuellement.", - "unablePublishMultiNotes": "Impossible de transférer plusieurs notes, quelque chose s'est mal passé.", - "unablePublishNote": "Impossible de transférer {{- file}}, le fichier a été ignoré.", - "whatEmpty": { - "branch": "Branch", - "owner": "Propriétaire" - } - }, - "informations": { - "foundNoteToSend": "Trouvé {{- nbNotes}} nouvelles notes à transférer.", - "migrating": { - "fileReplace": "Migration du remplacement du nom du fichier au nouveau format...", - "normalFormat": "Migration des paramètres...", - "oldSettings": "Migration des anciens paramètres au nouveau format...", - "subFolder": "Ajout du remplacement du sous-dossier au remplacement de chemin de fichier..." - }, - "noNewNote": "Aucune note à transférer.", - "scanningRepo": "Scan du dépôt, veuillez patienter...", - "sendMessage": "Transfert de {{- nbNotes}} notes vers {{- repo.owner}}/{{- repo.repo}}", - "startingClean": "Début du nettoyage de {{- repo.owner}}/{{- repo.repo}}", - "successfullPublish": "Transfert réussi de {{- nbNotes}} notes vers {{- repo.owner}}/{{- repo.repo}}", - "successPublishOneNote": "Transfert réussi de {{- file}} vers {{- repo.owner}}/{{- repo.repo}}", - "waitingWorkflow": "Maintenant, attente de la fin du workflow..." - }, - "modals": { - "export": { - "copy": "Copier vers le presse-papier", - "desc": "Exporter les paramètres vers un fichier ou dans le presse-papier.", - "download": "Télécharger", - "title": "Exporter les paramètres" - }, - "import": { - "desc": "Importer des paramètres depuis un fichier ou un texte. Cela écrasera vos paramètres actuels (sauf le nom du dépôt, le nom d'utilisateur et votre token)", - "error": { - "isEmpty": "la configuration est vide", - "span": "Erreur lors de l'importation de la configuration :" - }, - "importFromFile": "Import depuis le fichier", - "paste": "Coller la configuration ici...", - "title": "Importer des paramètres" - }, - "listChangedFiles": { - "added": "Ajouté", - "deleted": "Supprimé", - "edited": "Modifié", - "error": "Erreurs", - "notDeleted": "Impossible à supprimer", - "title": "Liste des fichiers édités sur le dépôt", - "unpublished": "Impossible à publier" - } - }, - "publish": { - "branch": { - "alreadyExists": "La branche {{- branchName}} sur {{- repo.owner}}/{{- repo.repo}} existe déjà - Utilisation de celle-ci.", - "error": "Erreur avec {{- repo.owner}}/{{- repo.repo}} : {{- error}}", - "prMessage": "Pull-Request [{{- branchName}}] depuis Obsidian", - "success": "La branche a été crée avec succès (status: {{- branchStatus}} sur {{- repo.owner}}/{{- repo.repo}})" - } - }, - "regex": { - "entry": "Valeur à remplacer", - "replace": "Remplacement" - }, - "settings": { - "conversion": { - "dataview": { - "desc": "Convertir les requêtes Dataview en markdown.", - "title": "Dataview" - }, - "desc": "Ces options ne changent pas le contenu du fichier dans votre coffre Obsidian, mais changeront le contenu du fichier publié sur GitHub.", - "hardBreak": { - "desc": "Ajoutez un retour à la ligne Markdown (double espace) après chaque ligne.", - "title": "Saut de ligne strict" - }, - "links": { - "desc": "Vous pouvez empêcher la conversion des liens et conserver le texte alt (ou le nom du fichier) en utilisant la clé frontmatter \"links\" avec la valeur \"false\".", - "folderNote": { - "desc": "Renommer les fichiers en un nom spécifique (défaut : \"index.md\") s'il porte le même nom que leur dossier/catégorie parent (fonctionne aussi si la note est à l'extérieur du dossier).", - "title": "Folder Note" - }, - "internals": { - "desc": "Convertir les liens internes pointant vers les notes publiées vers leur homologue dans le dépôt, sous forme de chemin relatif.", - "title": "Liens internes" - }, - "nonShared": { - "desc": "L'option précédente, mais appliquées aux liens internes pointant vers des notes non-publiées. Désactivé, seul le nom du fichier sera conservé.", - "title": "Conversion des liens internes pointant vers des notes non-publiées" - }, - "slugify": { - "desc": "Normaliser le lien (slug) des liens d'ancrage (pointant vers le titre de la rubrique). Transforme le texte en minuscules. Remplace l'espace par un tiret. Applicable uniquement aux liens d'ancrage dans la syntaxe de lien markdown.", - "title": "Slugifier l'ancre des liens markdown" - }, - "title": "Liens", - "wikilinks": { - "desc": "Conversion des liens wikilinks en liens Markdown, sans en modifier le contenu.", - "title": "Convertir [[WikiLinks]] en [liens](Markdown)" - } - }, - "sectionTitle": "Texte principal", - "tags": { - "desc": "Ceci convertira tous les champs du frontmatter/dataview en tags. Séparez les champs par une virgule.", - "exclude": { - "desc": "Exclusion de champs de la conversion. Séparer les valeurs par une virgule.", - "title": "Exclusion de tags" - }, - "inlineTags": { - "desc": "Ajoute vos inlines tags dans votre bloc frontmatter et converti les tags imbriqués en remplaçant \"/\" par \"_\".", - "title": "Inlines tags" - }, - "title": "Convertir des champs dataview ou frontmatter en tags" - }, - "title": "Conversion du contenu" - }, - "embed": { - "defaultImageFolder": { - "desc": "Pour utiliser un dossier différent de celui par défaut pour les pièces-jointes.", - "title": "Dossier de pièces-jointes par défaut" - }, - "title": "Embed", - "transferImage": { - "desc": "Transférer les pièces-jointes", - "title": "Envoyer les pièces-jointes intégrées dans un fichier dans le dépôt." - }, - "transferMetaFile": { - "desc": "Permet d'envoyer des fichiers en utilisant une clé frontmatter/dataview. Séparer les champs par une virgule.", - "title": "Envoyer des fichiers en utilisant une clé frontmatter/dataview" - }, - "transferNotes": { - "desc": "Envoyer les notes intégrées dans un fichier publié dans le dépôt. Seul les fichiers publiés seront envoyés !", - "title": "Transférer les notes intégrées" - } - }, - "github": { - "apiType": { - "desc": "Choisir entre l'API GitHub ou l'API pour GitHub Entreprise (uniquement pour les utilisateurs de GitHub Enterprise — Utilisateur avancé !).", - "dropdown": { - "enterprise": "Entreprise", - "free": "Free/Pro/Team (défaut)" - }, - "hostname": { - "desc": "Le nom de l'instance Github de votre entreprise.", - "title": "Instance Github Entreprise" - }, - "title": "Type d'API" - }, - "automaticallyMergePR": "Fusionner automatiquement les pull-request", - "branch": { - "desc": "Dans le cas où vous souhaitez utiliser une branche différente de \"main\".", - "title": "Branche principale" - }, - "ghToken": { - "desc": "Un token GitHub avec autorisation de dépôt. Vous pouvez le générer ", - "title": "Token Github" - }, - "repoName": { - "desc": "Le nom du dépôt dans lequel vos fichiers seront transférés.", - "placeholder": "mkdocs-template", - "title": "Nom du dépôt" - }, - "smartRepo": { - "button": "Gérer plus de dépôt", - "modals": { - "default": "Le nom \"default\" est réservé pour votre configuration principale.", - "desc": "Ces \"autres dépôts\" vous permettent d'utiliser toutes les commandes sur les dépôts ajoutés ci-dessous.", - "duplicate": "Les smartKey doivent être uniques !", - "frontmatterInfo": "L'utilisation de la clé frontmatter \"shortRepo\" avec la \"smartKey\" permet également d'utiliser ce dépôt dans un fichier sans avoir à écrire son chemin.", - "newRepo": "un nouveau dépôt", - "otherConfig": "Autres paramètres", - "shortcuts": { - "desc": "Ajoute toutes les commandes de ce dépôt dans la palette de commandes", - "title": "Raccourci" - }, - "title": "Gérer d'autres dépôts" - } - }, - "testConnection": "Tester la connexion", - "title": "Configuration GitHub", - "username": { - "desc": "Votre username sur GitHub.", - "title": "Nom d'utilisateur GitHub" - } - }, - "githubWorkflow": { - "autoCleanUp": { - "desc": "Si le plugin doit supprimer de votre dépôt les fichiers dépubliés (arrêt du partage ou suppression).", - "title": "Auto-nettoyage" - }, - "excludedFiles": { - "desc": "Si vous voulez exclure certains dossier ou fichier du nettoyage automatique, définissez leur chemin. Les regex sont acceptées en les encadrant par des slashs. Séparer les valeurs par une virgule.", - "title": "fichiers et dossier exclus" - }, - "githubAction": { - "desc": "Si vous souhaitez activer une action GitHub lorsque le plugin push les fichiers dans le dépôt, il vous faut indiquer le nom du fichier issus du dossier .github/workflows/. Seules les actions activées par un workflow_dispatch sont activées.", - "title": "Nom de l'action GitHub" - }, - "prRequest": { - "desc": "Le message envoyé lorsque la pull-request est fusionnée. Sera toujours suivi par le numéro de la pull-request.", - "error": "Vous ne pouvez pas utiliser une valeur vide pour le message de commit.", - "title": "Message de commit" - }, - "useMetadataExtractor": { - "desc": "Envoyer les fichiers générés par metadata-extractor dans ce dossier.", - "title": "Fichier de metadata-extractor" - } - }, - "help": { - "frontmatter": { - "attachment": { - "folder": "Change le dossier par défaut pour les pièces-jointes.", - "send": "Envoie toutes les pièces-jointes dans le dépôt GitHub." - }, - "autoclean": "Désactive ou active le nettoyage automatique du dépôt GitHub.", - "baselink": { - "desc": "Change le lien de base pour la commande de copie de lien. Désactive aussi la suppression de partie de lien. Peut être utilisée en tant qu'objet sous le nom de ", - "remove": "Supprime les parties de lien. À mettre sous forme de liste !" - }, - "convert": { - "enableOrDisable": "Active ou désactive la conversion des liens. En désactivant cette option, vous supprimez les", - "syntax": "syntaxes, tout en gardant le nom du fichier ou son text alternatif." - }, - "dataview": "Convertit les requêtes dataview en markdown.", - "desc": "Il existe quelques clés YAML qui peuvent vous êtes utile. Le code ci-dessous montre les paramètres par défaut, mais n'hésitez pas à le modifier selon vos besoins pour chaque note !", - "embed": { - "remove": "Supprime les notes intégrées du fichier partagés en ne laissant qu'une ligne vide.", - "send": "Envoie les notes intégrées de la note publiées dans le dépôt. Seules les notes partagées seront envoyées !" - }, - "hardBreak": "Convertit tous les sauts de lignes en \"hard break\" markdown.", - "internals": "Convertit les liens internes vers leur homologue du dépôt, sous forme de liens relatifs. Désactivés, les liens seront conservés tels quels.", - "mdlinks": "Convertir tous les liens [[wikilinks]] en [liens](Markdown)", - "nonShared": "Convertit les liens internes pointat vers une notes non publiées vers son futur homologue. Désactivé, le plugin conservera le nom du fichier ou son texte alternatif.", - "path": "Vous pouvez écraser tous les paramètres de chemins en utilisant cette clé. Le chemin sera créée à partir de la racine du dépôt.", - "repo": { - "branch": "Nom de la branche", - "desc": "Changer le dépôt GitHub pour cette note", - "owner": "Pseudo GitHub du propriétaire du dépôt" - }, - "share": { - "other": "Vous pouvez également utiliser une autre shareKey basée sur la clé définie dans « Gérer plus de dépôt ». Cela vous permet de séparer vos différents dépôts. Si vous utilisez les clés principales et secondaires, le dépôt principal sera utilisé.", - "title": "La clé utilisée pour partager une note" - }, - "shortRepo": "Autorise l'utilisation de l'un des dépôts définis dans les paramètres", - "title": "Aide-mémoire frontmatter", - "titleKey": "Change le titre de la note" - }, - "multiRepoHelp": { - "desc": "Si vous souhaitez envoyer vos notes dans plusieurs dépôt en même temps, vous pouvez utiliser la clé ", - "desc2": "dans votre frontmatter. La valeur de cette clé doit être une liste. Chaque dépôt doit avoir les clés suivantes :", - "exampleDesc": "Le code YAML ci-dessous montre un exemple basé sur vos paramètres.", - "title": "Envoie dans plusieurs dépôt" - }, - "title": "Aide", - "usefulLinks": { - "discussion": "Discussion", - "documentation": "Documentation (en anglais)", - "issue": "Issue", - "links": "https://obsidian-publisher.netlify.app", - "title": "Liens utiles" - } - }, - "plugin": { - "copyLink": { - "baselink": { - "desc": "Permet de créer un lien dans le presse-papier avec cette base. Par défaut : \"https://username.github.io/repo/\"", - "title": "Lien du dépôt/blog" - }, - "command": { - "desc": "Ajouter une commande permettant de copier le lien de la note publiée dans le presse-papier (nécessite de recharger le plugin pour prendre effet)" - }, - "desc": "Envoie d'un lien vers la note publiées dans votre presse-papier.", - "linkpathremover": { - "desc": "Supprimer cette partie des liens créés. Séparer par une virgule si plusieurs valeurs doivent être supprimées.", - "title": "Suppression d'une partie du lien" - }, - "title": "Copie de lien" - }, - "editorMenu": { - "desc": "Ajouter une commande de partage dans le menu du clic droit.", - "title": "Menu \"Edition\"" - }, - "embedEditRepo": { - "desc": "Permet d'afficher la liste des fichiers éditer, ajouté, supprimé... Du dépôt principal (dans un modal).", - "title": "Afficher les éditions sur le dépôt" - }, - "excludedFolder": { - "desc": "Les fichiers dans ses dossiers ne seront jamais publiés, quelle que soit l'état de la clé de partage. Séparez les noms de dossier par une virgule.", - "title": "Dossiers exclus" - }, - "fileMenu": { - "desc": "Ajouter une commande de partage dans le menu \"Fichier\"", - "title": "Menu \"Fichier\"" - }, - "logNoticeHeader": { - "desc": "Sur mobile, il peut être difficile de debug le module. Activer cette option pour notifier toutes les erreurs via une notification Obsidian.", - "title": "Notifier toutes les erreurs" - }, - "shareKey": { - "desc": "Clé de partage", - "otherRepo": "Vous pouvez également définir une clé de partage pour séparer avec des autres, sans utiliser la clé shortRepo.", - "title": "La clé frontmatter pour publier la note sur le dépôt." - }, - "title": "Paramètres du plugin" - }, - "regexReplacing": { - "empty": "Le remplacement peut être vide pour supprimer l'ensemble de la chaîne de caractère.", - "forbiddenValue": "Le {{- what}} ne peut contenir le caractère : {{- forbiddenChar}}.", - "modal": { - "desc": "Replace des textes dans le fichier par la valeur donnée. Vous pouvez encadrer le texte à remplacer avec \"//\" pour utiliser un regex.", - "title": { - "all": "Remplacement du nom ou du chemin du fichier", - "only": "Remplacement du titre uniquement", - "text": "Remplacement de texte" - } - }, - "momentReplaceRegex": "Éxécuter le remplacement {{- moment}} les autres conversions (dataview, liens internes...)", - "warningPath": "Attention ! Utiliser le caractère \"/\" modifiera le chemin du fichier. Veuillez faire attention avec cette option." - }, - "upload": { - "defaultFolder": { - "desc": "Définir le dossier de réception par défaut. Laisser vide pour utiliser la racine du dépôt.", - "placeholder": "docs", - "title": "Dossier par défaut" - }, - "folderBehavior": { - "desc": "Choisir la hierarchie des dossiers dans le dépôt, en se basant sur une clé frontmatter, un dossier fixe ou la hierarchie des dossiers dans Obsidian.", - "fixedFolder": "Dossier fixé", - "obsidianPath": "Chemin Obsidian", - "title": "Hierarchie des dossiers", - "yaml": "Valeur d'une clé frontmatter" - }, - "frontmatterKey": { - "desc": "Définir le nom de la clé où obtenir le dossier", - "placeholder": "category", - "title": "Clé frontmatter" - }, - "regexFilePathTitle": { - "desc": "Si le texte est entre \"//\", il sera interprété comme une expression régulière. Sinon, il sera interprété comme du texte brut.", - "title": { - "FolderPathTitle": "Éditer le titre et le chemin du dossier (automatiquement)", - "titleOnly": "Éditer le titre (automatiquement)" - } - }, - "rootFolder": { - "desc": "Ajouter ce chemin au dossier définit par la clé frontmatter.", - "title": "Dossier racine" - }, - "title": "Configuration du transfert", - "useFrontmatterTitle": { - "desc": "Utiliser un champ du frontmatter pour générer le nom du fichier. Par défaut, \"title\" est utilisé.", - "title": "Utiliser une clé frontmatter pour définir le titre" - } - } - }, - "statusBar": { - "counter": "{{- msg}} : {{- counter}}/{{- nb}}", - "markedForSharing": "{{- nb}} {{- type}} à partager", - "sharing": "⌛Partage de {{- type}}", - "success": "✅{{- action}} {{- type}}" - } + "commands": { + "checkValidity": { + "inBranch": { + "error403": "Erreur 403: {{- repo.owner}}/{{- repo.repo}} a été déplacé de manière permanente (depuis {{- branchInfo}}", + "error404": "Erreur 404 : La branche {{- repo.branch}} est introuvable depuis {{- repo.owner}}/{{- repo.repo}}" + }, + "inRepo": { + "error301": "Erreur 301 : {{- repo.owner}}/{{- repo.repo}} a été déplacé de manière permanente", + "error403": "Erreur 403 : Cette action est interdite pour {{- repo.owner}}/{{- repo.repo}}", + "error404": "Erreur 404 : {{- repo.owner}}/{{- repo.repo}} est introuvable" + }, + "rateLimit": { + "command": "Vérifier la limite de requêtes de l'API GitHub", + "limited": "Vous avez atteint la limite de requêtes Github. La limite sera réinitialisée à {{- resetTime}}. minutes.", + "notLimited": "Vous n'êtes pas limité par Github. Vous pouvez encore faire {{- remaining}} requêtes, et la limite sera réinitialisée à {{- resetTime}}." + }, + "repoExistsTestBranch": "Le dépôt {{- repo.owner}}/{{- repo.repo}} existe. Maintenant, nous allons tester la branche {{- repo.branch}}", + "success": "{{- repo.owner}}/{{- repo.repo}} semble valide !", + "title": "Tester la connexion au dépôt configuré" + }, + "copyLink": { + "onActivation": "Lien copié dans le presse-papier !", + "title": "Créer un lien vers cette note" + }, + "publisherDeleteClean": "Purger les fichiers dépubliés et supprimés", + "runOtherRepo": { + "noFile": "Aucun fichier actif, ou le fichier n'est pas partagé.", + "title": "Lancer une commande pour un dépôt" + }, + "shareActiveFile": "Transférer la note active", + "shareViewFiles": "Transférer {{- viewFile}} avec Github Publisher", + "uploadAllEditedNote": "Rafraîchir toutes les notes publiées", + "uploadAllNewEditedNote": "Rafraîchir les notes publiées et transférer les nouvelles notes", + "uploadAllNotes": "Transférer toutes les notes", + "uploadNewNotes": "Transférer les nouvelles notes" + }, + "common": { + "add": "Ajouter {{- things}}", + "after": "Après", + "attachments": "pièces-jointes", + "before": "Avant", + "cancel": "Annuler", + "close": "Fermer", + "delete": "Supprimer {{- things}}", + "edit": "Éditer {{- things}}", + "error": "Erreur", + "files": "fichiers", + "ghToken": "Token GitHub", + "here": "ici", + "or": "ou", + "path": { + "file": "Nom du fichier", + "folder": "Chemin du dossier", + "full": "Chemin du fichier" + }, + "published": "publiés", + "regex": "regex", + "repository": "Dépôt", + "save": "Sauvegarder", + "shared": "partagés", + "text": "texte", + "warning": "Attention" + }, + "deletion": { + "defaultFolder": "Vous avez besoin d'un dossier par défaut dans les paramètres pour utiliser cette commande.", + "failed": "Échec de la suppression de {{- nb}} notes.", + "noFile": "Aucun fichier n'a été supprimé.", + "rootFolder": "Vous devez configurer un dossier racine dans les paramètres pour utiliser cette commande.", + "success": "Suppression réussie de {{- nb}} fichiers." + }, + "error": { + "dataview": "Impossible de convertir la requête Dataview. Veuillez mettre à jour le module Dataview à la dernière version;", + "errorConfig": "Erreur de configuration pour {{- repo.owner}}/{{- repo.repo}}:{{- repo.branch}}. Merci de vérifier vos paramètres.", + "errorPublish": "Erreur lors de la publication sur {{- repo.owner}}/{{- repo.repo}}:{{- repo.branch}}", + "isEmpty": "{{- what}} est vide.", + "mergeconflic": "La Pull-Request n'est pas fusionnale, vous avez besoin de le faire manuellement.", + "unablePublishMultiNotes": "Impossible de transférer plusieurs notes, quelque chose s'est mal passé.", + "unablePublishNote": "Impossible de transférer {{- file}}, le fichier a été ignoré.", + "whatEmpty": { + "branch": "Branch", + "owner": "Propriétaire" + } + }, + "informations": { + "foundNoteToSend": "Trouvé {{- nbNotes}} nouvelles notes à transférer.", + "migrating": { + "fileReplace": "Migration du remplacement du nom du fichier au nouveau format...", + "normalFormat": "Migration des paramètres...", + "oldSettings": "Migration des anciens paramètres au nouveau format...", + "subFolder": "Ajout du remplacement du sous-dossier au remplacement de chemin de fichier..." + }, + "noNewNote": "Aucune note à transférer.", + "scanningRepo": "Scan du dépôt, veuillez patienter...", + "sendMessage": "Transfert de {{- nbNotes}} notes vers {{- repo.owner}}/{{- repo.repo}}", + "startingClean": "Début du nettoyage de {{- repo.owner}}/{{- repo.repo}}", + "successPublishOneNote": "Transfert réussi de {{- file}} vers {{- repo.owner}}/{{- repo.repo}}", + "successfullPublish": "Transfert réussi de {{- nbNotes}} notes vers {{- repo.owner}}/{{- repo.repo}}", + "waitingWorkflow": "Maintenant, attente de la fin du workflow..." + }, + "modals": { + "export": { + "copy": "Copier vers le presse-papier", + "desc": "Exporter les paramètres vers un fichier ou dans le presse-papier.", + "download": "Télécharger", + "title": "Exporter les paramètres" + }, + "import": { + "desc": "Importer des paramètres depuis un fichier ou un texte. Cela écrasera vos paramètres actuels (sauf le nom du dépôt, le nom d'utilisateur et votre token)", + "error": { + "isEmpty": "la configuration est vide", + "span": "Erreur lors de l'importation de la configuration :" + }, + "importFromFile": "Import depuis le fichier", + "paste": "Coller la configuration ici...", + "title": "Importer des paramètres" + }, + "listChangedFiles": { + "added": "Ajouté", + "deleted": "Supprimé", + "edited": "Modifié", + "error": "Erreurs", + "notDeleted": "Impossible à supprimer", + "title": "Liste des fichiers édités sur le dépôt", + "unpublished": "Impossible à publier" + } + }, + "publish": { + "branch": { + "alreadyExists": "La branche {{- branchName}} sur {{- repo.owner}}/{{- repo.repo}} existe déjà - Utilisation de celle-ci.", + "error": "Erreur avec {{- repo.owner}}/{{- repo.repo}} : {{- error}}", + "prMessage": "Pull-Request [{{- branchName}}] depuis Obsidian", + "success": "La branche a été crée avec succès (status: {{- branchStatus}} sur {{- repo.owner}}/{{- repo.repo}})" + } + }, + "regex": { + "entry": "Valeur à remplacer", + "replace": "Remplacement" + }, + "settings": { + "conversion": { + "dataview": { + "desc": "Convertir les requêtes Dataview en markdown.", + "title": "Dataview" + }, + "desc": "Ces options ne changent pas le contenu du fichier dans votre coffre Obsidian, mais changeront le contenu du fichier publié sur GitHub.", + "hardBreak": { + "desc": "Ajoutez un retour à la ligne Markdown (double espace) après chaque ligne.", + "title": "Saut de ligne strict" + }, + "links": { + "desc": "Vous pouvez empêcher la conversion des liens et conserver le texte alt (ou le nom du fichier) en utilisant la clé frontmatter \"links\" avec la valeur \"false\".", + "folderNote": { + "desc": "Renommer les fichiers en un nom spécifique (défaut : \"index.md\") s'il porte le même nom que leur dossier/catégorie parent (fonctionne aussi si la note est à l'extérieur du dossier).", + "title": "Folder Note" + }, + "internals": { + "desc": "Convertir les liens internes pointant vers les notes publiées vers leur homologue dans le dépôt, sous forme de chemin relatif.", + "title": "Liens internes" + }, + "nonShared": { + "desc": "L'option précédente, mais appliquées aux liens internes pointant vers des notes non-publiées. Désactivé, seul le nom du fichier sera conservé.", + "title": "Conversion des liens internes pointant vers des notes non-publiées" + }, + "slugify": { + "desc": "Normaliser le lien (slug) des liens d'ancrage (pointant vers le titre de la rubrique). Transforme le texte en minuscules. Remplace l'espace par un tiret. Applicable uniquement aux liens d'ancrage dans la syntaxe de lien markdown.", + "title": "Slugifier l'ancre des liens markdown" + }, + "title": "Liens", + "wikilinks": { + "desc": "Conversion des liens wikilinks en liens Markdown, sans en modifier le contenu.", + "title": "Convertir [[WikiLinks]] en [liens](Markdown)" + } + }, + "sectionTitle": "Texte principal", + "tags": { + "desc": "Ceci convertira tous les champs du frontmatter/dataview en tags. Séparez les champs par une virgule.", + "exclude": { + "desc": "Exclusion de champs de la conversion. Séparer les valeurs par une virgule.", + "title": "Exclusion de tags" + }, + "inlineTags": { + "desc": "Ajoute vos inlines tags dans votre bloc frontmatter et converti les tags imbriqués en remplaçant \"/\" par \"_\".", + "title": "Inlines tags" + }, + "title": "Convertir des champs dataview ou frontmatter en tags" + }, + "title": "Conversion du contenu" + }, + "embed": { + "defaultImageFolder": { + "desc": "Pour utiliser un dossier différent de celui par défaut pour les pièces-jointes.", + "title": "Dossier de pièces-jointes par défaut" + }, + "title": "Embed", + "transferImage": { + "desc": "Transférer les pièces-jointes", + "title": "Envoyer les pièces-jointes intégrées dans un fichier dans le dépôt." + }, + "transferMetaFile": { + "desc": "Permet d'envoyer des fichiers en utilisant une clé frontmatter/dataview. Séparer les champs par une virgule.", + "title": "Envoyer des fichiers en utilisant une clé frontmatter/dataview" + }, + "transferNotes": { + "desc": "Envoyer les notes intégrées dans un fichier publié dans le dépôt. Seul les fichiers publiés seront envoyés !", + "title": "Transférer les notes intégrées" + } + }, + "github": { + "apiType": { + "desc": "Choisir entre l'API GitHub ou l'API pour GitHub Entreprise (uniquement pour les utilisateurs de GitHub Enterprise — Utilisateur avancé !).", + "dropdown": { + "enterprise": "Entreprise", + "free": "Free/Pro/Team (défaut)" + }, + "hostname": { + "desc": "Le nom de l'instance Github de votre entreprise.", + "title": "Instance Github Entreprise" + }, + "title": "Type d'API" + }, + "automaticallyMergePR": "Fusionner automatiquement les pull-request", + "branch": { + "desc": "Dans le cas où vous souhaitez utiliser une branche différente de \"main\".", + "title": "Branche principale" + }, + "ghToken": { + "button": { + "notice": "Le token chiffré a été regénéré !", + "title": "Regénérer le token chiffré", + "tooltip": "Régénérera la clé publique et privée et enregistrera le nouveau jeton crypté dans vos paramètres." + }, + "desc": "Un token GitHub avec autorisation de dépôt. Vous pouvez le générer ", + "encrypted": "Le jeton sera enregistré crypté dans vos paramètres.", + "title": "Token Github" + }, + "repoName": { + "desc": "Le nom du dépôt dans lequel vos fichiers seront transférés.", + "placeholder": "mkdocs-template", + "title": "Nom du dépôt" + }, + "smartRepo": { + "button": "Gérer plus de dépôt", + "modals": { + "default": "Le nom \"default\" est réservé pour votre configuration principale.", + "desc": "Ces \"autres dépôts\" vous permettent d'utiliser toutes les commandes sur les dépôts ajoutés ci-dessous.", + "duplicate": "Les smartKey doivent être uniques !", + "frontmatterInfo": "L'utilisation de la clé frontmatter \"shortRepo\" avec la \"smartKey\" permet également d'utiliser ce dépôt dans un fichier sans avoir à écrire son chemin.", + "newRepo": "un nouveau dépôt", + "otherConfig": "Autres paramètres", + "shortcuts": { + "desc": "Ajoute toutes les commandes de ce dépôt dans la palette de commandes", + "title": "Raccourci" + }, + "title": "Gérer d'autres dépôts" + } + }, + "testConnection": "Tester la connexion", + "title": "Configuration GitHub", + "username": { + "desc": "Votre username sur GitHub.", + "title": "Nom d'utilisateur GitHub" + } + }, + "githubWorkflow": { + "autoCleanUp": { + "desc": "Si le plugin doit supprimer de votre dépôt les fichiers dépubliés (arrêt du partage ou suppression).", + "title": "Auto-nettoyage" + }, + "excludedFiles": { + "desc": "Si vous voulez exclure certains dossier ou fichier du nettoyage automatique, définissez leur chemin. Les regex sont acceptées en les encadrant par des slashs. Séparer les valeurs par une virgule.", + "title": "fichiers et dossier exclus" + }, + "githubAction": { + "desc": "Si vous souhaitez activer une action GitHub lorsque le plugin push les fichiers dans le dépôt, il vous faut indiquer le nom du fichier issus du dossier .github/workflows/. Seules les actions activées par un workflow_dispatch sont activées.", + "title": "Nom de l'action GitHub" + }, + "prRequest": { + "desc": "Le message envoyé lorsque la pull-request est fusionnée. Sera toujours suivi par le numéro de la pull-request.", + "error": "Vous ne pouvez pas utiliser une valeur vide pour le message de commit.", + "title": "Message de commit" + }, + "useMetadataExtractor": { + "desc": "Envoyer les fichiers générés par metadata-extractor dans ce dossier.", + "title": "Fichier de metadata-extractor" + } + }, + "help": { + "frontmatter": { + "attachment": { + "folder": "Change le dossier par défaut pour les pièces-jointes.", + "send": "Envoie toutes les pièces-jointes dans le dépôt GitHub." + }, + "autoclean": "Désactive ou active le nettoyage automatique du dépôt GitHub.", + "baselink": { + "desc": "Change le lien de base pour la commande de copie de lien. Désactive aussi la suppression de partie de lien. Peut être utilisée en tant qu'objet sous le nom de ", + "remove": "Supprime les parties de lien. À mettre sous forme de liste !" + }, + "convert": { + "enableOrDisable": "Active ou désactive la conversion des liens. En désactivant cette option, vous supprimez les", + "syntax": "syntaxes, tout en gardant le nom du fichier ou son text alternatif." + }, + "dataview": "Convertit les requêtes dataview en markdown.", + "desc": "Il existe quelques clés YAML qui peuvent vous êtes utile. Le code ci-dessous montre les paramètres par défaut, mais n'hésitez pas à le modifier selon vos besoins pour chaque note !", + "embed": { + "remove": "Supprime les notes intégrées du fichier partagés en ne laissant qu'une ligne vide.", + "send": "Envoie les notes intégrées de la note publiées dans le dépôt. Seules les notes partagées seront envoyées !" + }, + "hardBreak": "Convertit tous les sauts de lignes en \"hard break\" markdown.", + "internals": "Convertit les liens internes vers leur homologue du dépôt, sous forme de liens relatifs. Désactivés, les liens seront conservés tels quels.", + "mdlinks": "Convertir tous les liens [[wikilinks]] en [liens](Markdown)", + "nonShared": "Convertit les liens internes pointat vers une notes non publiées vers son futur homologue. Désactivé, le plugin conservera le nom du fichier ou son texte alternatif.", + "path": "Vous pouvez écraser tous les paramètres de chemins en utilisant cette clé. Le chemin sera créée à partir de la racine du dépôt.", + "repo": { + "branch": "Nom de la branche", + "desc": "Changer le dépôt GitHub pour cette note", + "owner": "Pseudo GitHub du propriétaire du dépôt" + }, + "share": { + "other": "Vous pouvez également utiliser une autre shareKey basée sur la clé définie dans « Gérer plus de dépôt ». Cela vous permet de séparer vos différents dépôts. Si vous utilisez les clés principales et secondaires, le dépôt principal sera utilisé.", + "title": "La clé utilisée pour partager une note" + }, + "shortRepo": "Autorise l'utilisation de l'un des dépôts définis dans les paramètres", + "title": "Aide-mémoire frontmatter", + "titleKey": "Change le titre de la note" + }, + "multiRepoHelp": { + "desc": "Si vous souhaitez envoyer vos notes dans plusieurs dépôt en même temps, vous pouvez utiliser la clé ", + "desc2": "dans votre frontmatter. La valeur de cette clé doit être une liste. Chaque dépôt doit avoir les clés suivantes :", + "exampleDesc": "Le code YAML ci-dessous montre un exemple basé sur vos paramètres.", + "title": "Envoie dans plusieurs dépôt" + }, + "title": "Aide", + "usefulLinks": { + "discussion": "Discussion", + "documentation": "Documentation (en anglais)", + "issue": "Issue", + "links": "https://obsidian-publisher.netlify.app", + "title": "Liens utiles" + } + }, + "plugin": { + "copyLink": { + "baselink": { + "desc": "Permet de créer un lien dans le presse-papier avec cette base. Par défaut : \"https://username.github.io/repo/\"", + "title": "Lien du dépôt/blog" + }, + "command": { + "desc": "Ajouter une commande permettant de copier le lien de la note publiée dans le presse-papier (nécessite de recharger le plugin pour prendre effet)" + }, + "desc": "Envoie d'un lien vers la note publiées dans votre presse-papier.", + "linkpathremover": { + "desc": "Supprimer cette partie des liens créés. Séparer par une virgule si plusieurs valeurs doivent être supprimées.", + "title": "Suppression d'une partie du lien" + }, + "title": "Copie de lien" + }, + "editorMenu": { + "desc": "Ajouter une commande de partage dans le menu du clic droit.", + "title": "Menu \"Edition\"" + }, + "embedEditRepo": { + "desc": "Permet d'afficher la liste des fichiers éditer, ajouté, supprimé... Du dépôt principal (dans un modal).", + "title": "Afficher les éditions sur le dépôt" + }, + "excludedFolder": { + "desc": "Les fichiers dans ses dossiers ne seront jamais publiés, quelle que soit l'état de la clé de partage. Séparez les noms de dossier par une virgule.", + "title": "Dossiers exclus" + }, + "fileMenu": { + "desc": "Ajouter une commande de partage dans le menu \"Fichier\"", + "title": "Menu \"Fichier\"" + }, + "logNoticeHeader": { + "desc": "Sur mobile, il peut être difficile de debug le module. Activer cette option pour notifier toutes les erreurs via une notification Obsidian.", + "title": "Notifier toutes les erreurs" + }, + "shareKey": { + "desc": "Clé de partage", + "otherRepo": "Vous pouvez également définir une clé de partage pour séparer avec des autres, sans utiliser la clé shortRepo.", + "title": "La clé frontmatter pour publier la note sur le dépôt." + }, + "title": "Paramètres du plugin" + }, + "regexReplacing": { + "empty": "Le remplacement peut être vide pour supprimer l'ensemble de la chaîne de caractère.", + "forbiddenValue": "Le {{- what}} ne peut contenir le caractère : {{- forbiddenChar}}.", + "modal": { + "desc": "Replace des textes dans le fichier par la valeur donnée. Vous pouvez encadrer le texte à remplacer avec \"//\" pour utiliser un regex.", + "title": { + "all": "Remplacement du nom ou du chemin du fichier", + "only": "Remplacement du titre uniquement", + "text": "Remplacement de texte" + } + }, + "momentReplaceRegex": "Éxécuter le remplacement {{- moment}} les autres conversions (dataview, liens internes...)", + "warningPath": "Attention ! Utiliser le caractère \"/\" modifiera le chemin du fichier. Veuillez faire attention avec cette option." + }, + "upload": { + "defaultFolder": { + "desc": "Définir le dossier de réception par défaut. Laisser vide pour utiliser la racine du dépôt.", + "placeholder": "docs", + "title": "Dossier par défaut" + }, + "folderBehavior": { + "desc": "Choisir la hierarchie des dossiers dans le dépôt, en se basant sur une clé frontmatter, un dossier fixe ou la hierarchie des dossiers dans Obsidian.", + "fixedFolder": "Dossier fixé", + "obsidianPath": "Chemin Obsidian", + "title": "Hierarchie des dossiers", + "yaml": "Valeur d'une clé frontmatter" + }, + "frontmatterKey": { + "desc": "Définir le nom de la clé où obtenir le dossier", + "placeholder": "category", + "title": "Clé frontmatter" + }, + "regexFilePathTitle": { + "desc": "Si le texte est entre \"//\", il sera interprété comme une expression régulière. Sinon, il sera interprété comme du texte brut.", + "title": { + "FolderPathTitle": "Éditer le titre et le chemin du dossier (automatiquement)", + "titleOnly": "Éditer le titre (automatiquement)" + } + }, + "rootFolder": { + "desc": "Ajouter ce chemin au dossier définit par la clé frontmatter.", + "title": "Dossier racine" + }, + "title": "Configuration du transfert", + "useFrontmatterTitle": { + "desc": "Utiliser un champ du frontmatter pour générer le nom du fichier. Par défaut, \"title\" est utilisé.", + "title": "Utiliser une clé frontmatter pour définir le titre" + } + } + }, + "statusBar": { + "counter": "{{- msg}} : {{- counter}}/{{- nb}}", + "markedForSharing": "{{- nb}} {{- type}} à partager", + "sharing": "⌛Partage de {{- type}}", + "success": "✅{{- action}} {{- type}}" + } } diff --git a/src/main.ts b/src/main.ts index 85b29ca5..7b1851ec 100644 --- a/src/main.ts +++ b/src/main.ts @@ -117,7 +117,7 @@ export default class GithubPublisher extends Plugin { async reloadOctokit() { let octokit: Octokit; const apiSettings = this.settings.github.api; - const token = await decrypt(this.settings.github.token, this.app, this.manifest, this.settings); + const token = await decrypt(this.settings.github.token, this); if (apiSettings.tiersForApi === GithubTiersVersion.entreprise && apiSettings.hostname.length > 0) { octokit = new Octokit( { diff --git a/src/settings.ts b/src/settings.ts index 51ec74df..573c6c0c 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -1,939 +1,953 @@ -import { App, Notice, PluginSettingTab, setIcon, Setting } from "obsidian"; -import GithubPublisherPlugin from "./main"; -import { ModalRegexFilePathName, ModalRegexOnContents } from "./settings/modals/regex_edition"; -import { - autoCleanCondition, - folderHideShowSettings, - autoCleanUpSettingsOnCondition, - shortcutsHideShow, showHideBasedOnFolder, -} from "./settings/style"; -import { - FolderSettings, GithubTiersVersion, Repository, -} from "./settings/interface"; -import { - help, - multipleRepoExplained, - supportMe, - usefullLinks, - KeyBasedOnSettings -} from "./settings/help"; -import "i18next"; -import { checkRepositoryValidity } from "./src/data_validation_test"; -import { ExportModal, ImportModal } from "./settings/modals/import_export"; -import i18next from "i18next"; -import { enumbSettingsTabId } from "./settings/interface"; -import {ModalAddingNewRepository} from "./settings/modals/manage_repo"; - - -export class GithubPublisherSettingsTab extends PluginSettingTab { - plugin: GithubPublisherPlugin; - settingsPage: HTMLElement; - branchName: string; - - constructor(app: App, plugin: GithubPublisherPlugin, branchName: string) { - super(app, plugin); - this.plugin = plugin; - this.branchName = branchName; - } - - display(): void { - const { containerEl } = this; - containerEl.empty(); - - const PUBLISHER_TABS = { - "github-configuration": { - name: i18next.t("settings.github.title"), - icon: "cloud", - }, - "upload-configuration": { - name: i18next.t("settings.upload.title"), - icon: "upload", - }, - "text-conversion": { - name: i18next.t("settings.conversion.title"), - icon: "file-text", - }, - "embed-configuration": { - name: i18next.t("settings.embed.title"), - icon: "link", - }, - "plugin-settings": { - name: i18next.t("settings.plugin.title"), - icon: "gear", - }, - "help": { - name: i18next.t("settings.help.title"), - icon: "info", - }, - }; - - new Setting(containerEl) - .setClass("github-publisher-export-import") - .addButton((button) => { - button.setButtonText(i18next.t("modals.export.title")) - .setClass("github-publisher-export") - .onClick(() => { - new ExportModal(this.app, this.plugin).open(); - }); - } - ) - .addButton((button) => { - button.setButtonText(i18next.t("modals.import.title")) - .setClass("github-publisher-import") - .onClick(() => { - new ImportModal(this.app, this.plugin, this.settingsPage, this).open(); - }); - }); - const tabBar = containerEl.createEl("nav", { - cls: "settings-tab-bar github-publisher", - }); - - - - for (const [tabID, tabInfo] of Object.entries(PUBLISHER_TABS)) { - const tabEl = tabBar.createEl("div", { - cls: "settings-tab github-publisher", - }); - const tabIcon = tabEl.createEl("div", { - cls: "settings-tab-icon github-publisher", - }); - setIcon(tabIcon, tabInfo.icon); - tabEl.createEl("div", { - cls: "settings-tab-name github-publisher", - text: tabInfo.name, - }); - if (tabID === "github-configuration") - tabEl.addClass("settings-tab-active"); - - tabEl.addEventListener("click", () => { - // @ts-ignore - for (const tabEl of tabBar.children) - tabEl.removeClass("settings-tab-active"); - - tabEl.addClass("settings-tab-active"); - this.renderSettingsPage(tabID); - }); - } - this.settingsPage = containerEl.createEl("div", { - cls: "settings-tab-page github-publisher", - }); - this.renderSettingsPage("github-configuration"); - } - - renderSettingsPage(tabId: string) { - this.settingsPage.empty(); - switch (tabId) { - case "github-configuration": - this.renderGithubConfiguration(); - break; - case "upload-configuration": - this.renderUploadConfiguration(); - break; - case "text-conversion": - this.renderTextConversion(); - break; - case "embed-configuration": - this.renderEmbedConfiguration(); - break; - case "plugin-settings": - this.renderPluginSettings(); - break; - case "help": - this.renderHelp(); - break; - } - } - - renderGithubConfiguration() { - const githubSettings = this.plugin.settings.github; - new Setting(this.settingsPage) - .setName(i18next.t("settings.github.apiType.title")) - .setDesc(i18next.t("settings.github.apiType.desc")) - .addDropdown((dropdown) => { - dropdown - .addOption(GithubTiersVersion.free, i18next.t("settings.github.apiType.dropdown.free")) - .addOption(GithubTiersVersion.entreprise, i18next.t("settings.github.apiType.dropdown.enterprise")) - .setValue(githubSettings.api.tiersForApi) - .onChange(async (value) => { - githubSettings.api.tiersForApi = value as GithubTiersVersion; - await this.plugin.saveSettings(); - this.renderSettingsPage(enumbSettingsTabId.github); - }); - }); - if (githubSettings.api.tiersForApi === GithubTiersVersion.entreprise) { - new Setting(this.settingsPage) - .setName(i18next.t("settings.github.apiType.hostname.title")) - .setDesc(i18next.t("settings.github.apiType.hostname.desc")) - .addText((text) => - text - .setPlaceholder("https://github.mycompany.com") - .setValue(githubSettings.api.hostname) - .onChange(async (value) => { - githubSettings.api.hostname = value.trim(); - await this.plugin.saveSettings(); - }) - ); - } - - new Setting(this.settingsPage) - .setName(i18next.t("settings.github.repoName.title")) - .setDesc(i18next.t("settings.github.repoName.desc")) - .addText((text) => - text - .setPlaceholder(i18next.t("settings.github.repoName.placeholder")) - .setValue(githubSettings.repo) - .onChange(async (value) => { - githubSettings.repo = value.trim(); - await this.plugin.saveSettings(); - }) - ); - new Setting(this.settingsPage) - .setName(i18next.t("settings.github.username.title")) - .setDesc(i18next.t("settings.github.username.desc")) - .addText((text) => - text - .setPlaceholder( - i18next.t("settings.github.username.title") - ) - .setValue(githubSettings.user) - .onChange(async (value) => { - githubSettings.user = value.trim(); - await this.plugin.saveSettings(); - }) - ); - const desc_ghToken = document.createDocumentFragment(); - desc_ghToken.createEl("span", null, (span) => { - span.innerText = i18next.t("settings.github.ghToken.desc") ; - span.createEl("a", null, (link) => { - link.innerText = i18next.t("common.here") ; - link.href = - "https://github.com/settings/tokens/new?scopes=repo,workflow"; - }); - }); - new Setting(this.settingsPage) - .setName(i18next.t("settings.github.ghToken.title")) - .setDesc(desc_ghToken) - .addText((text) => - text - .setPlaceholder("ghb-15457498545647987987112184") - .setValue(githubSettings.token) - .onChange(async (value) => { - githubSettings.token = value.trim(); - await this.plugin.saveSettings(); - }) - ); - - new Setting(this.settingsPage) - .setName(i18next.t("settings.github.branch.title")) - .setDesc(i18next.t("settings.github.branch.desc")) - .addText((text) => - text - .setPlaceholder("main") - .setValue(githubSettings.branch) - .onChange(async (value) => { - githubSettings.branch = value.trim(); - await this.plugin.saveSettings(); - }) - ); - - new Setting(this.settingsPage) - .setName(i18next.t("settings.github.automaticallyMergePR")) - .addToggle((toggle) => - toggle - .setValue(githubSettings.automaticallyMergePR) - .onChange(async (value) => { - githubSettings.automaticallyMergePR = value; - await this.plugin.saveSettings(); - }) - ); - - new Setting(this.settingsPage) - .setClass("github-publisher-no-display") - .addButton((button) => - button - .setButtonText(i18next.t("settings.github.testConnection")) - .setClass("github-publisher-connect-button") - .onClick(async () => { - await checkRepositoryValidity(this.branchName, this.plugin.reloadOctokit(), this.plugin.settings, null,null, this.app.metadataCache); - }) - ) - .addButton((button) => - button - .setButtonText(i18next.t("settings.github.smartRepo.button")) - .onClick(async () => { - const repository: Repository[] = this.plugin.settings.github.otherRepo ? this.plugin.settings.github.otherRepo : []; - new ModalAddingNewRepository(this.app, this.plugin.settings, this.branchName, this.plugin, repository, (result => { - this.plugin.settings.github.otherRepo = result; - this.plugin.saveSettings(); - this.plugin.reloadCommands(this.branchName); - }) - ).open(); - })); - this.settingsPage.createEl("h3", { text: "Github Workflow" }); - new Setting(this.settingsPage) - .setName(i18next.t("settings.githubWorkflow.prRequest.title")) - .setDesc(i18next.t("settings.githubWorkflow.prRequest.desc")) - .addText((text) => - text - .setPlaceholder("[PUBLISHER] MERGE") - .setValue(githubSettings.workflow.commitMessage) - .onChange(async (value) => { - if (value.trim().length === 0) { - value = "[PUBLISHER] MERGE"; - new Notice(i18next.t("settings.githubWorkflow.prRequest.error")); - } - githubSettings.workflow.commitMessage = value; - await this.plugin.saveSettings(); - }) - ); - - new Setting(this.settingsPage) - .setName(i18next.t("settings.githubWorkflow.githubAction.title")) - .setDesc( - i18next.t("settings.githubWorkflow.githubAction.desc") - ) - .addText((text) => { - text.setPlaceholder("ci") - .setValue(githubSettings.workflow.name) - .onChange(async (value) => { - if (value.length > 0) { - value = value.trim(); - const yamlEndings = [".yml", ".yaml"]; - if (! yamlEndings.some(ending => value.endsWith(ending))) { - value += yamlEndings[0]; - } - } - githubSettings.workflow.name = value; - await this.plugin.saveSettings(); - }); - }); - - - } - - renderUploadConfiguration() { - const uploadSettings = this.plugin.settings.upload; - new Setting(this.settingsPage) - .setName(i18next.t("settings.upload.folderBehavior.title")) - .setDesc(i18next.t("settings.upload.folderBehavior.desc")) - .addDropdown((dropDown) => { - dropDown - .addOptions({ - fixed: i18next.t( - "settings.upload.folderBehavior.fixedFolder") , - yaml: i18next.t("settings.upload.folderBehavior.yaml") , - obsidian: i18next.t( - "settings.upload.folderBehavior.obsidianPath") , - }) - .setValue(uploadSettings.behavior) - .onChange(async (value: string) => { - uploadSettings.behavior = value as FolderSettings; - await folderHideShowSettings( - frontmatterKeySettings, - rootFolderSettings, - autoCleanSetting, - value, - this.plugin); - await this.plugin.saveSettings(); - this.renderSettingsPage(enumbSettingsTabId.upload); - }); - }); - - new Setting(this.settingsPage) - .setName(i18next.t("settings.upload.defaultFolder.title")) - .setDesc(i18next.t("settings.upload.defaultFolder.desc")) - .addText((text) => { - text.setPlaceholder(i18next.t("settings.upload.defaultFolder.placeholder")) - .setValue(uploadSettings.defaultName) - .onChange(async (value) => { - uploadSettings.defaultName = value.replace( - /\/$/, - "" - ); - await autoCleanCondition( - value, - autoCleanSetting, - this.plugin - ); - await this.plugin.saveSettings(); - }); - }); - - const frontmatterKeySettings = new Setting(this.settingsPage) - .setName(i18next.t("settings.upload.frontmatterKey.title")) - .setClass("github-publisher") - .setDesc(i18next.t("settings.upload.frontmatterKey.desc")) - .addText((text) => { - text.setPlaceholder(i18next.t("settings.upload.frontmatterKey.placeholder")) - .setValue(uploadSettings.yamlFolderKey) - .onChange(async (value) => { - uploadSettings.yamlFolderKey = value.trim(); - await this.plugin.saveSettings(); - }); - }); - const rootFolderSettings = new Setting(this.settingsPage) - .setName(i18next.t("settings.upload.rootFolder.title")) - .setClass("github-publisher") - .setDesc(i18next.t("settings.upload.rootFolder.desc")) - .addText((text) => { - text.setPlaceholder("docs") - .setValue(uploadSettings.rootFolder) - .onChange(async (value) => { - uploadSettings.rootFolder = value.replace( - /\/$/, - "" - ); - await autoCleanCondition( - value, - autoCleanSetting, - this.plugin - ); - await this.plugin.saveSettings(); - }); - }); - const frontmatterTitleSet = new Setting(this.settingsPage) - .setName( - i18next.t("settings.upload.useFrontmatterTitle.title") - ) - .setDesc( - i18next.t("settings.upload.useFrontmatterTitle.desc") - ) - .setClass("github-publisher-title") - .addToggle((toggle) => { - toggle - .setValue(uploadSettings.frontmatterTitle.enable) - .onChange(async (value) => { - uploadSettings.frontmatterTitle.enable = value; - await this.plugin.saveSettings(); - this.renderSettingsPage(enumbSettingsTabId.upload); - }); - }); - if (uploadSettings.frontmatterTitle.enable) { - frontmatterTitleSet.addText((text) => { - text.setPlaceholder("title") - .setValue(uploadSettings.frontmatterTitle.key) - .onChange(async (value) => { - uploadSettings.frontmatterTitle.key = value.trim(); - await this.plugin.saveSettings(); - }); - }); - } - - let desc = i18next.t("settings.upload.regexFilePathTitle.title.FolderPathTitle") ; - if (uploadSettings.behavior === FolderSettings.fixed) { - desc = i18next.t("settings.upload.regexFilePathTitle.title.titleOnly"); - } - - new Setting(this.settingsPage) - .setName(desc) - .setDesc( - i18next.t("settings.upload.regexFilePathTitle.desc") - ) - .addButton((button) => { - button - .setIcon("pencil") - .onClick(async () => { - let allRegex = uploadSettings.replaceTitle; - if (uploadSettings.behavior !== FolderSettings.fixed) { - allRegex = allRegex.concat(uploadSettings.replacePath); - } - new ModalRegexFilePathName(this.app, this.plugin.settings, allRegex, (result => { - uploadSettings.replacePath = result.filter(title => {return title.type === "path";}); - uploadSettings.replaceTitle = result.filter(title => {return title.type === "title";}); - this.plugin.saveSettings(); - })).open(); - }); - }); - - const folderNoteSettings = new Setting(this.settingsPage) - .setName(i18next.t("settings.conversion.links.folderNote.title")) - .setClass("github-publisher-folderNote") - .setDesc( - i18next.t("settings.conversion.links.folderNote.desc") - ) - .addToggle((toggle) => { - toggle - .setValue(uploadSettings.folderNote.enable) - .onChange(async (value) => { - uploadSettings.folderNote.enable = value; - await this.plugin.saveSettings(); - this.renderSettingsPage("upload-configuration"); - }); - }); - - if (uploadSettings.folderNote.enable) { - folderNoteSettings.addText((text) => { - text.setPlaceholder("folderNote") - .setValue(uploadSettings.folderNote.rename) - .onChange(async (value) => { - uploadSettings.folderNote.rename = value; - await this.plugin.saveSettings(); - - }); - }); - } - - showHideBasedOnFolder(this.plugin.settings, frontmatterKeySettings, rootFolderSettings, folderNoteSettings); - - - //@ts-ignore - if (app.plugins.enabledPlugins.has("metadata-extractor")) { - new Setting(this.settingsPage) - .setName( - i18next.t("settings.githubWorkflow.useMetadataExtractor.title") - ) - .setDesc( - i18next.t("settings.githubWorkflow.useMetadataExtractor.desc") - ) - .addText((text) => { - text.setPlaceholder("docs/_assets/metadata") - .setValue(uploadSettings.metadataExtractorPath) - .onChange(async (value) => { - uploadSettings.metadataExtractorPath = - value.trim(); - await this.plugin.saveSettings(); - }); - }); - } - - const condition = - (uploadSettings.behavior === FolderSettings.yaml && - uploadSettings.rootFolder.length === 0) || - uploadSettings.defaultName.length === 0; - - const autoCleanSetting = new Setting(this.settingsPage) - .setName(i18next.t("settings.githubWorkflow.autoCleanUp.title")) - .setDesc(i18next.t("settings.githubWorkflow.autoCleanUp.desc")) - .setDisabled(condition) - .addToggle((toggle) => { - toggle - .setValue(uploadSettings.autoclean.enable) - .onChange(async (value) => { - uploadSettings.autoclean.enable = value; - await this.plugin.saveSettings(); - this.renderSettingsPage(enumbSettingsTabId.upload); - }); - }); - if (uploadSettings.autoclean.enable) { - new Setting(this.settingsPage) - .setName(i18next.t("settings.githubWorkflow.excludedFiles.title")) - .setDesc(i18next.t("settings.githubWorkflow.excludedFiles.desc")) - .setClass("github-publisher-textarea") - .addTextArea((textArea) => { - textArea - .setPlaceholder( - "docs/assets/js, docs/assets/logo, /\\.js$/" - ) - .setValue( - uploadSettings.autoclean.excluded.join(", ") - ) - .onChange(async (value) => { - uploadSettings.autoclean.excluded = value - .split(/[,\n]\W*/) - .map((item) => item.trim()) - .filter((item) => item.length > 0); - await this.plugin.saveSettings(); - }); - }); - } - autoCleanUpSettingsOnCondition( - condition, - autoCleanSetting, - this.plugin - ); - - folderHideShowSettings( - frontmatterKeySettings, - rootFolderSettings, - autoCleanSetting, - uploadSettings.behavior, - this.plugin, - ); - - } - - renderTextConversion() { - const textSettings = this.plugin.settings.conversion; - this.settingsPage.createEl("p", { - text: i18next.t("settings.conversion.desc") , - }); - this.settingsPage.createEl("h5", { - text: i18next.t("settings.conversion.sectionTitle") , - }); - new Setting(this.settingsPage) - .setName(i18next.t("settings.conversion.hardBreak.title")) - .setDesc(i18next.t("settings.conversion.hardBreak.desc")) - .addToggle((toggle) => { - toggle - .setValue(textSettings.hardbreak) - .onChange(async (value) => { - textSettings.hardbreak = value; - await this.plugin.saveSettings(); - }); - }); - new Setting(this.settingsPage) - .setName(i18next.t("settings.conversion.dataview.title")) - .setDesc(i18next.t("settings.conversion.dataview.desc")) - .addToggle((toggle) => { - toggle - .setValue(textSettings.dataview) - .onChange(async (value) => { - textSettings.dataview = value; - await this.plugin.saveSettings(); - }); - }); - - new Setting(this.settingsPage) - .setName(i18next.t("settings.regexReplacing.modal.title.text")) - .setDesc(i18next.t("settings.regexReplacing.modal.desc")) - .addButton((button) => { - button - .setIcon("pencil") - .onClick(async () => { - new ModalRegexOnContents(this.app, this.plugin.settings, (result => { - this.plugin.settings.conversion.censorText = result.conversion.censorText; - this.plugin.saveSettings(); - })).open(); - }); - }); - - this.settingsPage.createEl("h5", { text: "Tags" }); - new Setting(this.settingsPage) - .setName( - i18next.t("settings.conversion.tags.inlineTags.title") - ) - .setDesc( - i18next.t("settings.conversion.tags.inlineTags.desc") - ) - .addToggle((toggle) => { - toggle - .setValue(textSettings.tags.inline) - .onChange(async (value) => { - textSettings.tags.inline = value; - await this.plugin.saveSettings(); - }); - }); - - new Setting(this.settingsPage) - .setName(i18next.t("settings.conversion.tags.title")) - .setDesc(i18next.t("settings.conversion.tags.desc")) - .setClass("github-publisher-textarea") - .addTextArea((text) => { - text.inputEl.style.width = "50%"; - text.setPlaceholder("field_name") - .setValue(textSettings.tags.fields.join(",")) - .onChange(async (value) => { - textSettings.tags.fields = value - .split(/[,\n]\W*/) - .map((item) => item.trim()) - .filter((item) => item.length > 0); - await this.plugin.saveSettings(); - }); - }); - new Setting(this.settingsPage) - .setName(i18next.t("settings.conversion.tags.exclude.title")) - .setDesc(i18next.t("settings.conversion.tags.exclude.desc")) - .setClass("github-publisher-textarea") - .addTextArea((text) => { - text.setPlaceholder("field value") - .setValue( - textSettings.tags.exclude.join(",") - ) - .onChange(async (value) => { - textSettings.tags.exclude = value - .split(/[,\n]\W*/) - .map((item) => item.trim()) - .filter((item) => item.length > 0); - await this.plugin.saveSettings(); - }); - }); - - this.settingsPage.createEl("h5", { - text: i18next.t("settings.conversion.links.title") , - }); - this.settingsPage.createEl("p", { - text: i18next.t("settings.conversion.links.desc") , - }); - - new Setting(this.settingsPage) - .setName(i18next.t("settings.conversion.links.internals.title")) - .setDesc( - i18next.t("settings.conversion.links.internals.desc") - ) - .addToggle((toggle) => { - toggle - .setValue(textSettings.links.internal) - .onChange(async (value) => { - textSettings.links.internal = value; - await this.plugin.saveSettings(); - this.renderSettingsPage("text-conversion"); - }); - }); - - if (textSettings.links.internal) { - new Setting(this.settingsPage) - .setName( - i18next.t("settings.conversion.links.nonShared.title") - ) - .setDesc( - i18next.t("settings.conversion.links.nonShared.desc") - ) - .addToggle((toggle) => { - toggle - .setValue(textSettings.links.unshared) - .onChange(async (value) => { - textSettings.links.unshared = - value; - await this.plugin.saveSettings(); - }); - }); - } - - new Setting(this.settingsPage) - .setName(i18next.t("settings.conversion.links.wikilinks.title")) - .setDesc( - i18next.t("settings.conversion.links.wikilinks.desc") - ) - .addToggle((toggle) => { - toggle - .setValue(textSettings.links.wiki) - .onChange(async (value) => { - textSettings.links.wiki = value; - await this.plugin.saveSettings(); - this.renderSettingsPage("text-conversion"); - }); - }); - - if (textSettings.links.wiki || textSettings.links.internal) { - new Setting(this.settingsPage) - .setName(i18next.t("settings.conversion.links.slugify.title")) - .setDesc(i18next.t("settings.conversion.links.slugify.desc")) - .addToggle((toggle) => { - toggle - .setValue(textSettings.links.slugify) - .onChange(async (value) => { - textSettings.links.slugify = value; - await this.plugin.saveSettings(); - }); - }); - } - } - - renderEmbedConfiguration() { - const embedSettings = this.plugin.settings.embed; - new Setting(this.settingsPage) - .setName(i18next.t("settings.embed.transferImage.title")) - .setDesc(i18next.t("settings.embed.transferImage.desc")) - .addToggle((toggle) => { - toggle - .setValue(embedSettings.attachments) - .onChange(async (value) => { - embedSettings.attachments = value; - shortcutsHideShow(value, settingsDefaultImage); - await this.plugin.saveSettings(); - }); - }); - - const settingsDefaultImage = new Setting(this.settingsPage) - .setName(i18next.t("settings.embed.defaultImageFolder.title")) - .setDesc(i18next.t("settings.embed.defaultImageFolder.desc")) - .addText((text) => { - text.setPlaceholder("docs/images") - .setValue(embedSettings.folder) - .onChange(async (value) => { - embedSettings.folder = value.replace( - /\/$/, - "" - ); - await this.plugin.saveSettings(); - }); - }); - - new Setting(this.settingsPage) - .setName(i18next.t("settings.embed.transferMetaFile.title")) - .setDesc(i18next.t("settings.embed.transferMetaFile.desc")) - .setClass("github-publisher-textarea") - .addTextArea((text) => { - text.setPlaceholder("banner") - .setValue( - embedSettings.keySendFile.join(", ") - ) - .onChange(async (value) => { - embedSettings.keySendFile = value - .split(/[,\n]\W*/) - .map((item) => item.trim()) - .filter((item) => item.length > 0); - await this.plugin.saveSettings(); - }); - }); - - new Setting(this.settingsPage) - .setName(i18next.t("settings.embed.transferNotes.title")) - .setDesc(i18next.t("settings.embed.transferNotes.desc")) - .addToggle((toggle) => { - toggle - .setValue(embedSettings.notes) - .onChange(async (value) => { - embedSettings.notes = value; - await this.plugin.saveSettings(); - }); - }); - - - } - - renderPluginSettings() { - const pluginSettings = this.plugin.settings.plugin; - new Setting(this.settingsPage) - .setName(i18next.t("settings.plugin.shareKey.title")) - .setDesc(i18next.t("settings.plugin.shareKey.desc")) - .addText((text) => - text - .setPlaceholder("share") - .setValue(pluginSettings.shareKey) - .onChange(async (value) => { - pluginSettings.shareKey = value.trim(); - await this.plugin.saveSettings(); - }) - ); - new Setting(this.settingsPage) - .setName(i18next.t("settings.plugin.excludedFolder.title")) - .setDesc(i18next.t("settings.plugin.excludedFolder.desc")) - .setClass("github-publisher-textarea") - .addTextArea((textArea) => - textArea - .setPlaceholder("_assets, Archive, /^_(.*)/gi") - .setValue(pluginSettings.excludedFolder.join(", ")) - .onChange(async (value) => { - pluginSettings.excludedFolder = value - .split(/[,\n]\W*/) - .map((item) => item.trim()) - .filter((item) => item.length > 0); - await this.plugin.saveSettings(); - }) - ); - new Setting(this.settingsPage) - .setName(i18next.t("settings.plugin.fileMenu.title")) - .setDesc(i18next.t("settings.plugin.fileMenu.desc")) - .addToggle((toggle) => - toggle - .setValue(pluginSettings.fileMenu) - .onChange(async (value) => { - pluginSettings.fileMenu = value; - await this.plugin.saveSettings(); - }) - ); - new Setting(this.settingsPage) - .setName(i18next.t("settings.plugin.editorMenu.title")) - .setDesc(i18next.t("settings.plugin.editorMenu.desc")) - .addToggle((toggle) => - toggle - .setValue(pluginSettings.editorMenu) - .onChange(async (value) => { - pluginSettings.editorMenu = value; - await this.plugin.saveSettings(); - }) - ); - new Setting(this.settingsPage) - .setName(i18next.t("settings.plugin.copyLink.title")) - .setDesc(i18next.t("settings.plugin.copyLink.desc")) - .addToggle((toggle) => - toggle - .setValue(pluginSettings.copyLink.enable) - .onChange(async (value) => { - pluginSettings.copyLink.enable = value; - await this.plugin.saveSettings(); - this.renderSettingsPage(enumbSettingsTabId.plugin); - - }) - ); - if (pluginSettings.copyLink.enable) { - new Setting(this.settingsPage) - .setName(i18next.t("settings.plugin.copyLink.baselink.title")) - .setDesc(i18next.t("settings.plugin.copyLink.baselink.desc")) - .setClass("github-publisher") - .addText((text) => { - text.setPlaceholder("my_blog.com") - .setValue(pluginSettings.copyLink.links) - .onChange(async (value) => { - pluginSettings.copyLink.links = value; - await this.plugin.saveSettings(); - }); - }); - new Setting(this.settingsPage) - .setName(i18next.t("settings.plugin.copyLink.linkpathremover.title")) - .setDesc( - i18next.t("settings.plugin.copyLink.linkpathremover.desc") - ) - .setClass("github-publisher") - .addText((text) => { - text.setPlaceholder("docs") - .setValue(pluginSettings.copyLink.removePart.join(", ")) - .onChange(async (value) => { - pluginSettings.copyLink.removePart = value.split(/[,\n]\s*/).map((item) => item.trim()).filter((item) => item.length > 0); - await this.plugin.saveSettings(); - }); - }); - - new Setting(this.settingsPage) - .setName(i18next.t("settings.plugin.copyLink.command.desc")) - .addToggle((toggle) => - toggle - .setValue(pluginSettings.copyLink.addCmd) - .onChange(async (value) => { - pluginSettings.copyLink.addCmd = value; - await this.plugin.saveSettings(); - }) - ); - } - new Setting(this.settingsPage) - .setName(i18next.t("settings.plugin.logNoticeHeader.title")) - .setDesc(i18next.t("settings.plugin.logNoticeHeader.desc")) - .addToggle((toggle) => - toggle - .setValue(pluginSettings.noticeError) - .onChange(async (value) => { - pluginSettings.noticeError = value; - await this.plugin.saveSettings(); - }) - ); - new Setting(this.settingsPage) - .setName(i18next.t("settings.plugin.embedEditRepo.title")) - .setDesc(i18next.t("settings.plugin.embedEditRepo.desc")) - .addToggle((toggle) => - toggle - .setValue(pluginSettings.displayModalRepoEditing) - .onChange(async (value) => { - pluginSettings.displayModalRepoEditing = value; - await this.plugin.saveSettings(); - }) - ); - } - renderHelp() { - this.settingsPage.createEl("h2", { - text: i18next.t("settings.help.usefulLinks.title") , - }); - this.settingsPage.appendChild(usefullLinks()); - this.settingsPage.createEl("hr"); - this.settingsPage.createEl("h2", { - text: i18next.t("settings.help.frontmatter.title") , - }); - this.settingsPage.createEl("p", { - text: i18next.t("settings.help.frontmatter.desc") , - }); - this.settingsPage - .createEl("pre", { cls: "language-yaml" }) - .createEl("code", { - text: KeyBasedOnSettings(this.plugin.settings), - cls: "language-yaml", - }); - this.settingsPage.appendChild(help(this.plugin.settings)); - this.settingsPage.createEl("h2", { - text: i18next.t("settings.help.multiRepoHelp.title") , - }); - this.settingsPage.appendChild( - multipleRepoExplained(this.plugin.settings) - ); - this.settingsPage.appendChild(supportMe()); - } -} +import { App, Notice, PluginSettingTab, setIcon, Setting } from "obsidian"; +import GithubPublisherPlugin from "./main"; +import { ModalRegexFilePathName, ModalRegexOnContents } from "./settings/modals/regex_edition"; +import { + autoCleanCondition, + folderHideShowSettings, + autoCleanUpSettingsOnCondition, + shortcutsHideShow, showHideBasedOnFolder, +} from "./settings/style"; +import { + FolderSettings, GithubTiersVersion, Repository, +} from "./settings/interface"; +import { + help, + multipleRepoExplained, + supportMe, + usefullLinks, + KeyBasedOnSettings +} from "./settings/help"; +import "i18next"; +import { checkRepositoryValidity } from "./src/data_validation_test"; +import { ExportModal, ImportModal } from "./settings/modals/import_export"; +import i18next from "i18next"; +import { enumbSettingsTabId } from "./settings/interface"; +import {ModalAddingNewRepository} from "./settings/modals/manage_repo"; +import { encrypt, decrypt, isEncrypted, regenerateTokenKeyPair } from "./settings/crypto"; + + +export class GithubPublisherSettingsTab extends PluginSettingTab { + plugin: GithubPublisherPlugin; + settingsPage: HTMLElement; + branchName: string; + + constructor(app: App, plugin: GithubPublisherPlugin, branchName: string) { + super(app, plugin); + this.plugin = plugin; + this.branchName = branchName; + } + + display(): void{ + const { containerEl } = this; + containerEl.empty(); + + const PUBLISHER_TABS = { + "github-configuration": { + name: i18next.t("settings.github.title"), + icon: "cloud", + }, + "upload-configuration": { + name: i18next.t("settings.upload.title"), + icon: "upload", + }, + "text-conversion": { + name: i18next.t("settings.conversion.title"), + icon: "file-text", + }, + "embed-configuration": { + name: i18next.t("settings.embed.title"), + icon: "link", + }, + "plugin-settings": { + name: i18next.t("settings.plugin.title"), + icon: "gear", + }, + "help": { + name: i18next.t("settings.help.title"), + icon: "info", + }, + }; + + new Setting(containerEl) + .setClass("github-publisher-export-import") + .addButton((button) => { + button.setButtonText(i18next.t("modals.export.title")) + .setClass("github-publisher-export") + .onClick(() => { + new ExportModal(this.app, this.plugin).open(); + }); + } + ) + .addButton((button) => { + button.setButtonText(i18next.t("modals.import.title")) + .setClass("github-publisher-import") + .onClick(() => { + new ImportModal(this.app, this.plugin, this.settingsPage, this).open(); + }); + }); + const tabBar = containerEl.createEl("nav", { + cls: "settings-tab-bar github-publisher", + }); + + + + for (const [tabID, tabInfo] of Object.entries(PUBLISHER_TABS)) { + const tabEl = tabBar.createEl("div", { + cls: "settings-tab github-publisher", + }); + const tabIcon = tabEl.createEl("div", { + cls: "settings-tab-icon github-publisher", + }); + setIcon(tabIcon, tabInfo.icon); + tabEl.createEl("div", { + cls: "settings-tab-name github-publisher", + text: tabInfo.name, + }); + if (tabID === "github-configuration") + tabEl.addClass("settings-tab-active"); + + tabEl.addEventListener("click", async () => { + // @ts-ignore + for (const tabEl of tabBar.children) + tabEl.removeClass("settings-tab-active"); + + tabEl.addClass("settings-tab-active"); + this.renderSettingsPage(tabID); + }); + } + this.settingsPage = containerEl.createEl("div", { + cls: "settings-tab-page github-publisher", + }); + this.renderSettingsPage("github-configuration"); + } + + renderSettingsPage(tabId: string) { + this.settingsPage.empty(); + switch (tabId) { + case "github-configuration": + this.renderGithubConfiguration(); + break; + case "upload-configuration": + this.renderUploadConfiguration(); + break; + case "text-conversion": + this.renderTextConversion(); + break; + case "embed-configuration": + this.renderEmbedConfiguration(); + break; + case "plugin-settings": + this.renderPluginSettings(); + break; + case "help": + this.renderHelp(); + break; + } + } + + renderGithubConfiguration() { + const githubSettings = this.plugin.settings.github; + new Setting(this.settingsPage) + .setName(i18next.t("settings.github.apiType.title")) + .setDesc(i18next.t("settings.github.apiType.desc")) + .addDropdown((dropdown) => { + dropdown + .addOption(GithubTiersVersion.free, i18next.t("settings.github.apiType.dropdown.free")) + .addOption(GithubTiersVersion.entreprise, i18next.t("settings.github.apiType.dropdown.enterprise")) + .setValue(githubSettings.api.tiersForApi) + .onChange(async (value) => { + githubSettings.api.tiersForApi = value as GithubTiersVersion; + await this.plugin.saveSettings(); + this.renderSettingsPage(enumbSettingsTabId.github); + }); + }); + if (githubSettings.api.tiersForApi === GithubTiersVersion.entreprise) { + new Setting(this.settingsPage) + .setName(i18next.t("settings.github.apiType.hostname.title")) + .setDesc(i18next.t("settings.github.apiType.hostname.desc")) + .addText((text) => + text + .setPlaceholder("https://github.mycompany.com") + .setValue(githubSettings.api.hostname) + .onChange(async (value) => { + githubSettings.api.hostname = value.trim(); + await this.plugin.saveSettings(); + }) + ); + } + + new Setting(this.settingsPage) + .setName(i18next.t("settings.github.repoName.title")) + .setDesc(i18next.t("settings.github.repoName.desc")) + .addText((text) => + text + .setPlaceholder(i18next.t("settings.github.repoName.placeholder")) + .setValue(githubSettings.repo) + .onChange(async (value) => { + githubSettings.repo = value.trim(); + await this.plugin.saveSettings(); + }) + ); + new Setting(this.settingsPage) + .setName(i18next.t("settings.github.username.title")) + .setDesc(i18next.t("settings.github.username.desc")) + .addText((text) => + text + .setPlaceholder( + i18next.t("settings.github.username.title") + ) + .setValue(githubSettings.user) + .onChange(async (value) => { + githubSettings.user = value.trim(); + await this.plugin.saveSettings(); + }) + ); + const desc_ghToken = document.createDocumentFragment(); + desc_ghToken.createEl("span", null, (span) => { + span.innerText = i18next.t("settings.github.ghToken.desc") ; + span.createEl("a", null, (link) => { + link.innerText = i18next.t("common.here") + "." ; + link.href = + "https://github.com/settings/tokens/new?scopes=repo,workflow"; + }); + span.createEl("div", null, (p) => p.innerText = i18next.t("settings.github.ghToken.encrypted")); + }); + new Setting(this.settingsPage) + .setName(i18next.t("settings.github.ghToken.title")) + .setDesc(desc_ghToken) + .addText(async (text) => { + const decryptedToken = isEncrypted(this.plugin) ? await decrypt(githubSettings.token, this.plugin) : githubSettings.token; + text + .setPlaceholder("ghp_15457498545647987987112184") + .setValue(decryptedToken) + .onChange(async (value) => { + githubSettings.token = await encrypt(value.trim(), this.plugin); + await this.plugin.saveSettings(); + }); + }) + .addButton((button) => { + button + .setButtonText(i18next.t("settings.github.ghToken.button.title")) + .setTooltip(i18next.t("settings.github.ghToken.button.tooltip")) + .onClick(async () => { + await regenerateTokenKeyPair(this.plugin); + new Notice(i18next.t("settings.github.ghToken.button.notice")); + this.renderGithubConfiguration(); + }); + }); + + new Setting(this.settingsPage) + .setName(i18next.t("settings.github.branch.title")) + .setDesc(i18next.t("settings.github.branch.desc")) + .addText((text) => + text + .setPlaceholder("main") + .setValue(githubSettings.branch) + .onChange(async (value) => { + githubSettings.branch = value.trim(); + await this.plugin.saveSettings(); + }) + ); + + new Setting(this.settingsPage) + .setName(i18next.t("settings.github.automaticallyMergePR")) + .addToggle((toggle) => + toggle + .setValue(githubSettings.automaticallyMergePR) + .onChange(async (value) => { + githubSettings.automaticallyMergePR = value; + await this.plugin.saveSettings(); + }) + ); + + new Setting(this.settingsPage) + .setClass("github-publisher-no-display") + .addButton((button) => + button + .setButtonText(i18next.t("settings.github.testConnection")) + .setClass("github-publisher-connect-button") + .onClick(async () => { + const octokit = await this.plugin.reloadOctokit(); + await checkRepositoryValidity(this.branchName, octokit, this.plugin.settings, null,null, this.app.metadataCache); + }) + ) + .addButton((button) => + button + .setButtonText(i18next.t("settings.github.smartRepo.button")) + .onClick(async () => { + const repository: Repository[] = this.plugin.settings.github?.otherRepo ?? []; + new ModalAddingNewRepository(this.app, this.plugin.settings, this.branchName, this.plugin, repository, (result => { + this.plugin.settings.github.otherRepo = result; + this.plugin.saveSettings(); + this.plugin.reloadCommands(this.branchName); + }) + ).open(); + })); + this.settingsPage.createEl("h3", { text: "Github Workflow" }); + new Setting(this.settingsPage) + .setName(i18next.t("settings.githubWorkflow.prRequest.title")) + .setDesc(i18next.t("settings.githubWorkflow.prRequest.desc")) + .addText((text) => + text + .setPlaceholder("[PUBLISHER] MERGE") + .setValue(githubSettings.workflow.commitMessage) + .onChange(async (value) => { + if (value.trim().length === 0) { + value = "[PUBLISHER] MERGE"; + new Notice(i18next.t("settings.githubWorkflow.prRequest.error")); + } + githubSettings.workflow.commitMessage = value; + await this.plugin.saveSettings(); + }) + ); + + new Setting(this.settingsPage) + .setName(i18next.t("settings.githubWorkflow.githubAction.title")) + .setDesc( + i18next.t("settings.githubWorkflow.githubAction.desc") + ) + .addText((text) => { + text.setPlaceholder("ci") + .setValue(githubSettings.workflow.name) + .onChange(async (value) => { + if (value.length > 0) { + value = value.trim(); + const yamlEndings = [".yml", ".yaml"]; + if (! yamlEndings.some(ending => value.endsWith(ending))) { + value += yamlEndings[0]; + } + } + githubSettings.workflow.name = value; + await this.plugin.saveSettings(); + }); + }); + + + } + + renderUploadConfiguration() { + const uploadSettings = this.plugin.settings.upload; + new Setting(this.settingsPage) + .setName(i18next.t("settings.upload.folderBehavior.title")) + .setDesc(i18next.t("settings.upload.folderBehavior.desc")) + .addDropdown((dropDown) => { + dropDown + .addOptions({ + fixed: i18next.t( + "settings.upload.folderBehavior.fixedFolder") , + yaml: i18next.t("settings.upload.folderBehavior.yaml") , + obsidian: i18next.t( + "settings.upload.folderBehavior.obsidianPath") , + }) + .setValue(uploadSettings.behavior) + .onChange(async (value: string) => { + uploadSettings.behavior = value as FolderSettings; + await folderHideShowSettings( + frontmatterKeySettings, + rootFolderSettings, + autoCleanSetting, + value, + this.plugin); + await this.plugin.saveSettings(); + this.renderSettingsPage(enumbSettingsTabId.upload); + }); + }); + + new Setting(this.settingsPage) + .setName(i18next.t("settings.upload.defaultFolder.title")) + .setDesc(i18next.t("settings.upload.defaultFolder.desc")) + .addText((text) => { + text.setPlaceholder(i18next.t("settings.upload.defaultFolder.placeholder")) + .setValue(uploadSettings.defaultName) + .onChange(async (value) => { + uploadSettings.defaultName = value.replace( + /\/$/, + "" + ); + await autoCleanCondition( + value, + autoCleanSetting, + this.plugin + ); + await this.plugin.saveSettings(); + }); + }); + + const frontmatterKeySettings = new Setting(this.settingsPage) + .setName(i18next.t("settings.upload.frontmatterKey.title")) + .setClass("github-publisher") + .setDesc(i18next.t("settings.upload.frontmatterKey.desc")) + .addText((text) => { + text.setPlaceholder(i18next.t("settings.upload.frontmatterKey.placeholder")) + .setValue(uploadSettings.yamlFolderKey) + .onChange(async (value) => { + uploadSettings.yamlFolderKey = value.trim(); + await this.plugin.saveSettings(); + }); + }); + const rootFolderSettings = new Setting(this.settingsPage) + .setName(i18next.t("settings.upload.rootFolder.title")) + .setClass("github-publisher") + .setDesc(i18next.t("settings.upload.rootFolder.desc")) + .addText((text) => { + text.setPlaceholder("docs") + .setValue(uploadSettings.rootFolder) + .onChange(async (value) => { + uploadSettings.rootFolder = value.replace( + /\/$/, + "" + ); + await autoCleanCondition( + value, + autoCleanSetting, + this.plugin + ); + await this.plugin.saveSettings(); + }); + }); + const frontmatterTitleSet = new Setting(this.settingsPage) + .setName( + i18next.t("settings.upload.useFrontmatterTitle.title") + ) + .setDesc( + i18next.t("settings.upload.useFrontmatterTitle.desc") + ) + .setClass("github-publisher-title") + .addToggle((toggle) => { + toggle + .setValue(uploadSettings.frontmatterTitle.enable) + .onChange(async (value) => { + uploadSettings.frontmatterTitle.enable = value; + await this.plugin.saveSettings(); + this.renderSettingsPage(enumbSettingsTabId.upload); + }); + }); + if (uploadSettings.frontmatterTitle.enable) { + frontmatterTitleSet.addText((text) => { + text.setPlaceholder("title") + .setValue(uploadSettings.frontmatterTitle.key) + .onChange(async (value) => { + uploadSettings.frontmatterTitle.key = value.trim(); + await this.plugin.saveSettings(); + }); + }); + } + + let desc = i18next.t("settings.upload.regexFilePathTitle.title.FolderPathTitle") ; + if (uploadSettings.behavior === FolderSettings.fixed) { + desc = i18next.t("settings.upload.regexFilePathTitle.title.titleOnly"); + } + + new Setting(this.settingsPage) + .setName(desc) + .setDesc( + i18next.t("settings.upload.regexFilePathTitle.desc") + ) + .addButton((button) => { + button + .setIcon("pencil") + .onClick(async () => { + let allRegex = uploadSettings.replaceTitle; + if (uploadSettings.behavior !== FolderSettings.fixed) { + allRegex = allRegex.concat(uploadSettings.replacePath); + } + new ModalRegexFilePathName(this.app, this.plugin.settings, allRegex, (result => { + uploadSettings.replacePath = result.filter(title => {return title.type === "path";}); + uploadSettings.replaceTitle = result.filter(title => {return title.type === "title";}); + this.plugin.saveSettings(); + })).open(); + }); + }); + + const folderNoteSettings = new Setting(this.settingsPage) + .setName(i18next.t("settings.conversion.links.folderNote.title")) + .setClass("github-publisher-folderNote") + .setDesc( + i18next.t("settings.conversion.links.folderNote.desc") + ) + .addToggle((toggle) => { + toggle + .setValue(uploadSettings.folderNote.enable) + .onChange(async (value) => { + uploadSettings.folderNote.enable = value; + await this.plugin.saveSettings(); + this.renderSettingsPage("upload-configuration"); + }); + }); + + if (uploadSettings.folderNote.enable) { + folderNoteSettings.addText((text) => { + text.setPlaceholder("folderNote") + .setValue(uploadSettings.folderNote.rename) + .onChange(async (value) => { + uploadSettings.folderNote.rename = value; + await this.plugin.saveSettings(); + + }); + }); + } + + showHideBasedOnFolder(this.plugin.settings, frontmatterKeySettings, rootFolderSettings, folderNoteSettings); + + + //@ts-ignore + if (app.plugins.enabledPlugins.has("metadata-extractor")) { + new Setting(this.settingsPage) + .setName( + i18next.t("settings.githubWorkflow.useMetadataExtractor.title") + ) + .setDesc( + i18next.t("settings.githubWorkflow.useMetadataExtractor.desc") + ) + .addText((text) => { + text.setPlaceholder("docs/_assets/metadata") + .setValue(uploadSettings.metadataExtractorPath) + .onChange(async (value) => { + uploadSettings.metadataExtractorPath = + value.trim(); + await this.plugin.saveSettings(); + }); + }); + } + + const condition = + (uploadSettings.behavior === FolderSettings.yaml && + uploadSettings.rootFolder.length === 0) || + uploadSettings.defaultName.length === 0; + + const autoCleanSetting = new Setting(this.settingsPage) + .setName(i18next.t("settings.githubWorkflow.autoCleanUp.title")) + .setDesc(i18next.t("settings.githubWorkflow.autoCleanUp.desc")) + .setDisabled(condition) + .addToggle((toggle) => { + toggle + .setValue(uploadSettings.autoclean.enable) + .onChange(async (value) => { + uploadSettings.autoclean.enable = value; + await this.plugin.saveSettings(); + this.renderSettingsPage(enumbSettingsTabId.upload); + }); + }); + if (uploadSettings.autoclean.enable) { + new Setting(this.settingsPage) + .setName(i18next.t("settings.githubWorkflow.excludedFiles.title")) + .setDesc(i18next.t("settings.githubWorkflow.excludedFiles.desc")) + .setClass("github-publisher-textarea") + .addTextArea((textArea) => { + textArea + .setPlaceholder( + "docs/assets/js, docs/assets/logo, /\\.js$/" + ) + .setValue( + uploadSettings.autoclean.excluded.join(", ") + ) + .onChange(async (value) => { + uploadSettings.autoclean.excluded = value + .split(/[,\n]\W*/) + .map((item) => item.trim()) + .filter((item) => item.length > 0); + await this.plugin.saveSettings(); + }); + }); + } + autoCleanUpSettingsOnCondition( + condition, + autoCleanSetting, + this.plugin + ); + + folderHideShowSettings( + frontmatterKeySettings, + rootFolderSettings, + autoCleanSetting, + uploadSettings.behavior, + this.plugin, + ); + + } + + renderTextConversion() { + const textSettings = this.plugin.settings.conversion; + this.settingsPage.createEl("p", { + text: i18next.t("settings.conversion.desc") , + }); + this.settingsPage.createEl("h5", { + text: i18next.t("settings.conversion.sectionTitle") , + }); + new Setting(this.settingsPage) + .setName(i18next.t("settings.conversion.hardBreak.title")) + .setDesc(i18next.t("settings.conversion.hardBreak.desc")) + .addToggle((toggle) => { + toggle + .setValue(textSettings.hardbreak) + .onChange(async (value) => { + textSettings.hardbreak = value; + await this.plugin.saveSettings(); + }); + }); + new Setting(this.settingsPage) + .setName(i18next.t("settings.conversion.dataview.title")) + .setDesc(i18next.t("settings.conversion.dataview.desc")) + .addToggle((toggle) => { + toggle + .setValue(textSettings.dataview) + .onChange(async (value) => { + textSettings.dataview = value; + await this.plugin.saveSettings(); + }); + }); + + new Setting(this.settingsPage) + .setName(i18next.t("settings.regexReplacing.modal.title.text")) + .setDesc(i18next.t("settings.regexReplacing.modal.desc")) + .addButton((button) => { + button + .setIcon("pencil") + .onClick(async () => { + new ModalRegexOnContents(this.app, this.plugin.settings, (result => { + this.plugin.settings.conversion.censorText = result.conversion.censorText; + this.plugin.saveSettings(); + })).open(); + }); + }); + + this.settingsPage.createEl("h5", { text: "Tags" }); + new Setting(this.settingsPage) + .setName( + i18next.t("settings.conversion.tags.inlineTags.title") + ) + .setDesc( + i18next.t("settings.conversion.tags.inlineTags.desc") + ) + .addToggle((toggle) => { + toggle + .setValue(textSettings.tags.inline) + .onChange(async (value) => { + textSettings.tags.inline = value; + await this.plugin.saveSettings(); + }); + }); + + new Setting(this.settingsPage) + .setName(i18next.t("settings.conversion.tags.title")) + .setDesc(i18next.t("settings.conversion.tags.desc")) + .setClass("github-publisher-textarea") + .addTextArea((text) => { + text.inputEl.style.width = "50%"; + text.setPlaceholder("field_name") + .setValue(textSettings.tags.fields.join(",")) + .onChange(async (value) => { + textSettings.tags.fields = value + .split(/[,\n]\W*/) + .map((item) => item.trim()) + .filter((item) => item.length > 0); + await this.plugin.saveSettings(); + }); + }); + new Setting(this.settingsPage) + .setName(i18next.t("settings.conversion.tags.exclude.title")) + .setDesc(i18next.t("settings.conversion.tags.exclude.desc")) + .setClass("github-publisher-textarea") + .addTextArea((text) => { + text.setPlaceholder("field value") + .setValue( + textSettings.tags.exclude.join(",") + ) + .onChange(async (value) => { + textSettings.tags.exclude = value + .split(/[,\n]\W*/) + .map((item) => item.trim()) + .filter((item) => item.length > 0); + await this.plugin.saveSettings(); + }); + }); + + this.settingsPage.createEl("h5", { + text: i18next.t("settings.conversion.links.title") , + }); + this.settingsPage.createEl("p", { + text: i18next.t("settings.conversion.links.desc") , + }); + + new Setting(this.settingsPage) + .setName(i18next.t("settings.conversion.links.internals.title")) + .setDesc( + i18next.t("settings.conversion.links.internals.desc") + ) + .addToggle((toggle) => { + toggle + .setValue(textSettings.links.internal) + .onChange(async (value) => { + textSettings.links.internal = value; + await this.plugin.saveSettings(); + this.renderSettingsPage("text-conversion"); + }); + }); + + if (textSettings.links.internal) { + new Setting(this.settingsPage) + .setName( + i18next.t("settings.conversion.links.nonShared.title") + ) + .setDesc( + i18next.t("settings.conversion.links.nonShared.desc") + ) + .addToggle((toggle) => { + toggle + .setValue(textSettings.links.unshared) + .onChange(async (value) => { + textSettings.links.unshared = + value; + await this.plugin.saveSettings(); + }); + }); + } + + new Setting(this.settingsPage) + .setName(i18next.t("settings.conversion.links.wikilinks.title")) + .setDesc( + i18next.t("settings.conversion.links.wikilinks.desc") + ) + .addToggle((toggle) => { + toggle + .setValue(textSettings.links.wiki) + .onChange(async (value) => { + textSettings.links.wiki = value; + await this.plugin.saveSettings(); + this.renderSettingsPage("text-conversion"); + }); + }); + + if (textSettings.links.wiki || textSettings.links.internal) { + new Setting(this.settingsPage) + .setName(i18next.t("settings.conversion.links.slugify.title")) + .setDesc(i18next.t("settings.conversion.links.slugify.desc")) + .addToggle((toggle) => { + toggle + .setValue(textSettings.links.slugify) + .onChange(async (value) => { + textSettings.links.slugify = value; + await this.plugin.saveSettings(); + }); + }); + } + } + + renderEmbedConfiguration() { + const embedSettings = this.plugin.settings.embed; + new Setting(this.settingsPage) + .setName(i18next.t("settings.embed.transferImage.title")) + .setDesc(i18next.t("settings.embed.transferImage.desc")) + .addToggle((toggle) => { + toggle + .setValue(embedSettings.attachments) + .onChange(async (value) => { + embedSettings.attachments = value; + shortcutsHideShow(value, settingsDefaultImage); + await this.plugin.saveSettings(); + }); + }); + + const settingsDefaultImage = new Setting(this.settingsPage) + .setName(i18next.t("settings.embed.defaultImageFolder.title")) + .setDesc(i18next.t("settings.embed.defaultImageFolder.desc")) + .addText((text) => { + text.setPlaceholder("docs/images") + .setValue(embedSettings.folder) + .onChange(async (value) => { + embedSettings.folder = value.replace( + /\/$/, + "" + ); + await this.plugin.saveSettings(); + }); + }); + + new Setting(this.settingsPage) + .setName(i18next.t("settings.embed.transferMetaFile.title")) + .setDesc(i18next.t("settings.embed.transferMetaFile.desc")) + .setClass("github-publisher-textarea") + .addTextArea((text) => { + text.setPlaceholder("banner") + .setValue( + embedSettings.keySendFile.join(", ") + ) + .onChange(async (value) => { + embedSettings.keySendFile = value + .split(/[,\n]\W*/) + .map((item) => item.trim()) + .filter((item) => item.length > 0); + await this.plugin.saveSettings(); + }); + }); + + new Setting(this.settingsPage) + .setName(i18next.t("settings.embed.transferNotes.title")) + .setDesc(i18next.t("settings.embed.transferNotes.desc")) + .addToggle((toggle) => { + toggle + .setValue(embedSettings.notes) + .onChange(async (value) => { + embedSettings.notes = value; + await this.plugin.saveSettings(); + }); + }); + + + } + + renderPluginSettings() { + const pluginSettings = this.plugin.settings.plugin; + new Setting(this.settingsPage) + .setName(i18next.t("settings.plugin.shareKey.title")) + .setDesc(i18next.t("settings.plugin.shareKey.desc")) + .addText((text) => + text + .setPlaceholder("share") + .setValue(pluginSettings.shareKey) + .onChange(async (value) => { + pluginSettings.shareKey = value.trim(); + await this.plugin.saveSettings(); + }) + ); + new Setting(this.settingsPage) + .setName(i18next.t("settings.plugin.excludedFolder.title")) + .setDesc(i18next.t("settings.plugin.excludedFolder.desc")) + .setClass("github-publisher-textarea") + .addTextArea((textArea) => + textArea + .setPlaceholder("_assets, Archive, /^_(.*)/gi") + .setValue(pluginSettings.excludedFolder.join(", ")) + .onChange(async (value) => { + pluginSettings.excludedFolder = value + .split(/[,\n]\W*/) + .map((item) => item.trim()) + .filter((item) => item.length > 0); + await this.plugin.saveSettings(); + }) + ); + new Setting(this.settingsPage) + .setName(i18next.t("settings.plugin.fileMenu.title")) + .setDesc(i18next.t("settings.plugin.fileMenu.desc")) + .addToggle((toggle) => + toggle + .setValue(pluginSettings.fileMenu) + .onChange(async (value) => { + pluginSettings.fileMenu = value; + await this.plugin.saveSettings(); + }) + ); + new Setting(this.settingsPage) + .setName(i18next.t("settings.plugin.editorMenu.title")) + .setDesc(i18next.t("settings.plugin.editorMenu.desc")) + .addToggle((toggle) => + toggle + .setValue(pluginSettings.editorMenu) + .onChange(async (value) => { + pluginSettings.editorMenu = value; + await this.plugin.saveSettings(); + }) + ); + new Setting(this.settingsPage) + .setName(i18next.t("settings.plugin.copyLink.title")) + .setDesc(i18next.t("settings.plugin.copyLink.desc")) + .addToggle((toggle) => + toggle + .setValue(pluginSettings.copyLink.enable) + .onChange(async (value) => { + pluginSettings.copyLink.enable = value; + await this.plugin.saveSettings(); + this.renderSettingsPage(enumbSettingsTabId.plugin); + + }) + ); + if (pluginSettings.copyLink.enable) { + new Setting(this.settingsPage) + .setName(i18next.t("settings.plugin.copyLink.baselink.title")) + .setDesc(i18next.t("settings.plugin.copyLink.baselink.desc")) + .setClass("github-publisher") + .addText((text) => { + text.setPlaceholder("my_blog.com") + .setValue(pluginSettings.copyLink.links) + .onChange(async (value) => { + pluginSettings.copyLink.links = value; + await this.plugin.saveSettings(); + }); + }); + new Setting(this.settingsPage) + .setName(i18next.t("settings.plugin.copyLink.linkpathremover.title")) + .setDesc( + i18next.t("settings.plugin.copyLink.linkpathremover.desc") + ) + .setClass("github-publisher") + .addText((text) => { + text.setPlaceholder("docs") + .setValue(pluginSettings.copyLink.removePart.join(", ")) + .onChange(async (value) => { + pluginSettings.copyLink.removePart = value.split(/[,\n]\s*/).map((item) => item.trim()).filter((item) => item.length > 0); + await this.plugin.saveSettings(); + }); + }); + + new Setting(this.settingsPage) + .setName(i18next.t("settings.plugin.copyLink.command.desc")) + .addToggle((toggle) => + toggle + .setValue(pluginSettings.copyLink.addCmd) + .onChange(async (value) => { + pluginSettings.copyLink.addCmd = value; + await this.plugin.saveSettings(); + }) + ); + } + new Setting(this.settingsPage) + .setName(i18next.t("settings.plugin.logNoticeHeader.title")) + .setDesc(i18next.t("settings.plugin.logNoticeHeader.desc")) + .addToggle((toggle) => + toggle + .setValue(pluginSettings.noticeError) + .onChange(async (value) => { + pluginSettings.noticeError = value; + await this.plugin.saveSettings(); + }) + ); + new Setting(this.settingsPage) + .setName(i18next.t("settings.plugin.embedEditRepo.title")) + .setDesc(i18next.t("settings.plugin.embedEditRepo.desc")) + .addToggle((toggle) => + toggle + .setValue(pluginSettings.displayModalRepoEditing) + .onChange(async (value) => { + pluginSettings.displayModalRepoEditing = value; + await this.plugin.saveSettings(); + }) + ); + } + renderHelp() { + this.settingsPage.createEl("h2", { + text: i18next.t("settings.help.usefulLinks.title") , + }); + this.settingsPage.appendChild(usefullLinks()); + this.settingsPage.createEl("hr"); + this.settingsPage.createEl("h2", { + text: i18next.t("settings.help.frontmatter.title") , + }); + this.settingsPage.createEl("p", { + text: i18next.t("settings.help.frontmatter.desc") , + }); + this.settingsPage + .createEl("pre", { cls: "language-yaml" }) + .createEl("code", { + text: KeyBasedOnSettings(this.plugin.settings), + cls: "language-yaml", + }); + this.settingsPage.appendChild(help(this.plugin.settings)); + this.settingsPage.createEl("h2", { + text: i18next.t("settings.help.multiRepoHelp.title") , + }); + this.settingsPage.appendChild( + multipleRepoExplained(this.plugin.settings) + ); + this.settingsPage.appendChild(supportMe()); + } +} diff --git a/src/settings/crypto.ts b/src/settings/crypto.ts index db482768..f94e752b 100644 --- a/src/settings/crypto.ts +++ b/src/settings/crypto.ts @@ -1,5 +1,6 @@ -import { arrayBufferToBase64, base64ToArrayBuffer, App, PluginManifest } from "obsidian"; -import { GitHubPublisherSettings } from "./interface"; +import { arrayBufferToBase64, base64ToArrayBuffer} from "obsidian"; +import GithubPublisher from "src/main"; +import { noticeLog } from "src/src/utils"; interface KeyPair { publicKey: CryptoKey; @@ -19,7 +20,8 @@ async function generateKey(): Promise { ); } -export async function writeKeyPair(app: App, manifest: PluginManifest) { +export async function writeKeyPair(plugin: GithubPublisher) { + const manifest = plugin.manifest; const keyPair = await generateKey(); const exportedPublicKey = await window.crypto.subtle.exportKey("jwk", keyPair.publicKey); const exportedPrivateKey = await window.crypto.subtle.exportKey("jwk", keyPair.privateKey); @@ -30,11 +32,12 @@ export async function writeKeyPair(app: App, manifest: PluginManifest) { await app.vault.adapter.write(`${app.vault.configDir}/plugins/${manifest.id}/keyPair.json`, JSON.stringify(keyPairJson)); } -async function loadKeyPair(app: App, manifest: PluginManifest, settings: GitHubPublisherSettings): Promise { - const keyPairFile = await isEncrypted(app, manifest, settings); +async function loadKeyPair(plugin: GithubPublisher): Promise { + const keyPairFile = await isEncrypted(plugin); if (!keyPairFile) { - await writeKeyPair(app, manifest); + await writeKeyPair(plugin); } + const manifest = plugin.manifest; const keys = JSON.parse(await app.vault.adapter.read(`${app.vault.configDir}/plugins/${manifest.id}/keyPair.json`)); const publicKey = await window.crypto.subtle.importKey( "jwk", @@ -59,23 +62,29 @@ async function loadKeyPair(app: App, manifest: PluginManifest, settings: GitHubP } -export async function encrypt(data: string, app: App, manifest: PluginManifest, settings: GitHubPublisherSettings):Promise { - const enc = new TextEncoder(); - const keyPair = await loadKeyPair(app, manifest, settings); - const encodedData = enc.encode(data); - const {publicKey} = keyPair; - const encryptedText = await window.crypto.subtle.encrypt({ - name: "RSA-OAEP" - }, - publicKey, - encodedData - ); - return arrayBufferToBase64(encryptedText); +export async function encrypt(data: string, plugin: GithubPublisher):Promise { + if (data.length === 0) return data; + try { + const enc = new TextEncoder(); + const keyPair = await loadKeyPair(plugin); + const encodedData = enc.encode(data); + const {publicKey} = keyPair; + const encryptedText = await window.crypto.subtle.encrypt({ + name: "RSA-OAEP" + }, + publicKey, + encodedData + ); + return arrayBufferToBase64(encryptedText); + } catch (e) { + noticeLog(e, plugin.settings); + return ""; + } } -export async function decrypt(data: string, app: App, manifest: PluginManifest, settings: GitHubPublisherSettings): Promise { +export async function decrypt(data: string, plugin: GithubPublisher): Promise { const dec = new TextDecoder(); - const keyPair = await loadKeyPair(app, manifest, settings); + const keyPair = await loadKeyPair(plugin); const bufferData = base64ToArrayBuffer(data); const decryptData = await window.crypto.subtle.decrypt({ name: "RSA-OAEP" @@ -86,7 +95,19 @@ export async function decrypt(data: string, app: App, manifest: PluginManifest, return dec.decode(decryptData); } -export async function isEncrypted(app: App, manifest: PluginManifest, settings: GitHubPublisherSettings) { +export async function isEncrypted(plugin: GithubPublisher): Promise { + const {manifest, settings} = plugin; const isExist= await app.vault.adapter.exists(`${app.vault.configDir}/plugins/${manifest.id}/keyPair.json`) && settings.github.token.length > 0 && !settings.github.token.startsWith("ghp"); return isExist; +} + +export async function regenerateTokenKeyPair(plugin: GithubPublisher) { + noticeLog("Regenerating token key pair", plugin.settings); + const settings = plugin.settings; + const token = await decrypt(settings.github.token, plugin); + await writeKeyPair(plugin); + const encryptedToken = await encrypt(token, plugin); + settings.github.token = encryptedToken; + await plugin.saveSettings(); + noticeLog("Regenerated token key pair", plugin.settings); } \ No newline at end of file diff --git a/src/settings/help.ts b/src/settings/help.ts index 39e56c21..1cec55e1 100644 --- a/src/settings/help.ts +++ b/src/settings/help.ts @@ -1,340 +1,340 @@ -import {FolderSettings, GitHubPublisherSettings} from "./interface"; -import i18next from "i18next"; - - -/** - * Export the YAML help to create an example of yaml with the value based on the Settings - * @param {GitHubPublisherSettings} settings - * @return {string} - */ - -export function KeyBasedOnSettings(settings: GitHubPublisherSettings) { - let category = ""; - if (settings.upload.behavior === FolderSettings.yaml) { - category = `${settings.upload.yamlFolderKey}: ${settings.upload.defaultName}\n`; - } - const shortRepo = settings.github.otherRepo.length > 0 ? "shortRepo: " + settings.github.otherRepo[0].smartKey +"\n" : ""; - return `${settings.plugin.shareKey}: true\n` + category + - "links:\n" + - ` mdlinks: ${settings.conversion.links.wiki}\n` + - " convert: true\n" + - ` internals: ${settings.conversion.links.internal}\n` + - ` nonShared: ${settings.conversion.links.unshared}\n` + - "embed:\n" + - ` send: ${settings.embed.notes}\n` + - " remove: false\n" + - "attachment:\n" + - ` send: ${settings.embed.attachments}\n` + - ` folder: ${settings.embed.folder}\n` + - `dataview: ${settings.conversion.dataview}\n` + - `hardBreak: ${settings.conversion.hardbreak}\n` + - shortRepo + - "repo:\n" + - ` owner: ${settings.github.user}\n` + - ` repo: ${settings.github.repo}\n` + - ` branch: ${settings.github.branch}\n` + - ` autoclean: ${settings.upload.autoclean.enable}\n` + - "copylink:\n" + - ` base: ${settings.plugin.copyLink.links}\n` + - ` remove: [${settings.plugin.copyLink.removePart.map(val => `"${val}"`).join(", ")}]\n`; -} - -/** - * Create the contents of the help settings tab - * @param {GitHubPublisherSettings} settings - * @return {DocumentFragment} - */ -export function help(settings: GitHubPublisherSettings) { - const explanation = document.createDocumentFragment(); - explanation.createEl("ul", null, (span) => { - span.createEl("li", null, (span) => { - span.createEl("code", { - text: `${settings.plugin.shareKey}:`, - cls: "code-title", - }); - span.createEl("span", { - text: `${i18next.t("settings.help.frontmatter.share.title")}`, - }); - span.createEl("ul", null, (l) => { - l.createEl("span", {text: i18next.t("settings.help.frontmatter.share.other")}); - }); - }); - span.createEl("li", null, (span) => { - span.createEl("code", { - text: "path:", - cls: "code-title", - }); - span.createEl("span", { - text: ` ${i18next.t("settings.help.frontmatter.path")}`, - }); - }); - span.createEl("li", null, (span) => { - span.createEl("code", { text: "links:", cls: "code-title" }); - }); - span.createEl("ul", null, (l) => { - l.createEl("li", null, (p) => { - p.createEl("code", { text: "mdlinks" }); - p.createEl("span", { - text: `: ${ - i18next.t("settings.help.frontmatter.mdlinks") - }`, - }); - }); - l.createEl("li", null, (p) => { - p.createEl("code", { text: "convert" }); - p.createEl("span", null, (span) => { - span.createEl("span", { - text: `: ${ - i18next.t( - "settings.help.frontmatter.convert.enableOrDisable" - ) - } `, - }); - span.createEl("code", { text: " [[link]] " }); - span.createEl("span", { - text: i18next.t("common.or") - }); - span.createEl("code", { text: " [](link) " }); - span.createEl("span", { - text: i18next.t("settings.help.frontmatter.convert.syntax") - }); - }); - }); - l.createEl("li", null, (p) => { - p.createEl("code", {text: "internals"}); - p.createEl("span", { - text: `: ${i18next.t("settings.help.frontmatter.internals")}` - }); - }); - l.createEl("li", null, (p) => { - p.createEl("code", { text: "nonShared" }); - p.createEl("span", { text: `: ${i18next.t("settings.help.frontmatter.nonShared")}` }); - }); - }); - span.createEl("li", { text: "embed:", cls: "code code-title" }); - span.createEl("ul", null, (l) => { - l.createEl("li", null, (p) => { - p.createEl("code", { text: "send" }); - p.createEl("span", { - text: `: ${ - i18next.t("settings.help.frontmatter.embed.send") - }`, - }); - }); - l.createEl("li", null, (p) => { - p.createEl("code", { text: "remove" }); - p.createEl("span", { - text: `: ${ - i18next.t("settings.help.frontmatter.embed.remove") - }`, - }); - }); - }); - span.createEl("li", { text: "attachment:", cls: "code code-title" }); - span.createEl("ul", null, (l) => { - l.createEl("li", null, (span) => { - span.createEl("code", { text: "send" }); - span.createEl("span", { - text: `: ${ - i18next.t( - "settings.help.frontmatter.attachment.send" - ) - }`, - }); - }); - l.createEl("li", null, (p) => { - p.createEl("code", { text: "folder" }); - p.createEl("span", { - text: `: ${ - i18next.t( - "settings.help.frontmatter.attachment.folder" - ) - }`, - }); - }); - }); - span.createEl("li", null, (span) => { - span.createEl("code", { text: "dataview", cls: "code-title" }); - span.createEl("span", { - text: `: ${i18next.t("settings.help.frontmatter.dataview")}`, - }); - }); - span.createEl("li", null, (span) => { - span.createEl("code", { text: "hardbreak", cls: "code-title" }); - span.createEl("span", { - text: `: ${ - i18next.t("settings.help.frontmatter.hardBreak") - }`, - }); - }); - span.createEl("li", null, (span) => { - span.createEl("code", { text: "shortRepo", cls: "code-title" }); - span.createEl("span", { - text: `: ${i18next.t("settings.help.frontmatter.shortRepo")}`, - }); - }); - span.createEl("li", null, (span) => { - span.createEl("code", { text: "repo", cls: "code-title" }); - span.createEl("span", { - text: `: ${i18next.t("settings.help.frontmatter.repo.desc")}`, - }); - span.createEl("ul", null, (ul) => { - ul.createEl("li", null, (li) => { - li.createEl("code", { text: "owner" }); - li.createEl("span", { - text: `: ${i18next.t("settings.help.frontmatter.repo.owner")}`, - }); - }); - ul.createEl("li", null, (li) => { - li.createEl("code", { text: "repo" }); - li.createEl("span", { - text: `: ${i18next.t("settings.github.repoName.title")}`, - }); - }); - ul.createEl("li", null, (li) => { - li.createEl("code", { text: "branch" }); - li.createEl("span", { - text: `: ${i18next.t( - "settings.help.frontmatter.repo.branch" - )}`, - }); - }); - ul.createEl("li", null, (li) => { - li.createEl("code", { text: "autoclean"}); - li.createEl("span", { - text: `: ${i18next.t("settings.help.frontmatter.autoclean")}`, - }); - }); - }); - }); - span.createEl("li", null, (span) => { - span.createEl("code", { - text: `${settings.upload.frontmatterTitle.key}`, - cls: "code-title", - }); - span.createEl("span", { - text: `: ${i18next.t("settings.help.frontmatter.titleKey")}`, - }); - }); - span.createEl("li", null, (span) => { - span.createEl("code", { text: "baseLink", cls: "code-title" }); - span.createEl("span", { - text: `: ${i18next.t("settings.help.frontmatter.baselink.desc")}`, - }); - span.createEl("code", {text: "copylink:", cls: "code-title"}); - span.createEl("ul", null, (ul) => { - ul.createEl("li", null, (li) => { - li.createEl("code", { text: "base"}); - li.createEl("span", { - text: `: ${i18next.t("settings.plugin.copyLink.baselink.title")}`, - }); - }); - ul.createEl("li", null, (li) => { - li.createEl("code", { text: "remove"}); - li.createEl("span", { - text: `: ${i18next.t("settings.help.frontmatter.baselink.remove")}`, - }); - }); - }); - }); - }); - return explanation; -} - -/** - * Create the useful links section in the settings help tab - * @return {DocumentFragment} - */ -export function usefullLinks(): DocumentFragment { - const usefullLinks = document.createDocumentFragment(); - usefullLinks.createEl("ul", null, (el) => { - el.createEl("li", null, (el) => { - el.createEl("a", { - text: i18next.t("settings.help.usefulLinks.documentation"), - href: i18next.t("settings.help.usefulLinks.links"), - }); - }); - el.createEl("li", null, (el) => { - el.createEl("a", { - text: i18next.t("common.repository"), - href: "https://github.com/ObsidianPublisher/obsidian-github-publisher", - }); - }); - el.createEl("li", null, (el) => { - el.createEl("a", { - text: i18next.t("settings.help.usefulLinks.issue"), - href: "https://github.com/ObsidianPublisher/obsidian-github-publisher/issues", - }); - }); - el.createEl("li", null, (el) => { - el.createEl("a", { - text: i18next.t("settings.help.usefulLinks.discussion"), - href: "https://github.com/ObsidianPublisher/obsidian-github-publisher/discussions", - }); - }); - }); - return usefullLinks; -} - -/** - * Create the explanation of multiple repo for the help tab - * @param {GitHubPublisherSettings} settings - * @return {DocumentFragment} - */ -export function multipleRepoExplained( - settings: GitHubPublisherSettings -): DocumentFragment { - const multipleRepoExplained = document.createDocumentFragment(); - multipleRepoExplained.createEl("p", null, (el) => { - el.createEl("span", { - text: i18next.t("settings.help.multiRepoHelp.desc"), - }); - el.createEl("code", { text: "multipleRepo" }); - el.createEl("span", { - text: ` ${i18next.t("settings.help.multiRepoHelp.desc2")}:`, - }); - el.createEl("ul", null, (el) => { - el.createEl("li", { text: "owner" }).addClass("code"); - el.createEl("li", { text: "repo" }).addClass("code"); - el.createEl("li", { text: "branch" }).addClass("code"); - el.createEl("li", { text: "autoclean" }).addClass("code"); - }); - el.createEl("span", { - text: i18next.t("settings.help.multiRepoHelp.exampleDesc"), - }); - }); - multipleRepoExplained - .createEl("pre", { cls: "language-yaml" }) - .createEl("code", { - text: `multipleRepo:\n - owner: ${settings.github.user}\n repo: ${settings.github.repo}\n branch: ${settings.github.branch}\n autoclean: false\n - owner: ${settings.github.user}\n repo: my_second_brain\n branch: master\n autoclean: false`, - cls: "language-yaml", - }); - return multipleRepoExplained; -} - -/** - * Add the link for kofi in the help tab - * @return {DocumentFragment} - */ - -export function supportMe(): DocumentFragment { - const supportMe = document.createDocumentFragment(); - supportMe.createEl("p", null, (el) => { - el.createEl("a", null, (el) => { - el.createEl("img", null, (img) => { - img.setAttr( - "src", - "https://storage.ko-fi.com/cdn/kofi2.png?v=3" - ); - img.setAttr("alt", "Buy Me A Coffee"); - img.setAttr( - "style", - "height: 60px !important;width: 217px !important;" - ); - }); - el.setAttr("href", "https://ko-fi.com/lisandra_dev"); - }); - el.setAttr("style", "text-align: center;"); - }); - return supportMe; -} +import {FolderSettings, GitHubPublisherSettings} from "./interface"; +import i18next from "i18next"; + + +/** + * Export the YAML help to create an example of yaml with the value based on the Settings + * @param {GitHubPublisherSettings} settings + * @return {string} + */ + +export function KeyBasedOnSettings(settings: GitHubPublisherSettings) { + let category = ""; + if (settings.upload.behavior === FolderSettings.yaml) { + category = `${settings.upload.yamlFolderKey}: ${settings.upload.defaultName}\n`; + } + const shortRepo = settings.github.otherRepo.length > 0 ? "shortRepo: " + settings.github.otherRepo[0].smartKey +"\n" : ""; + return `${settings.plugin.shareKey}: true\n` + category + + "links:\n" + + ` mdlinks: ${settings.conversion.links.wiki}\n` + + " convert: true\n" + + ` internals: ${settings.conversion.links.internal}\n` + + ` nonShared: ${settings.conversion.links.unshared}\n` + + "embed:\n" + + ` send: ${settings.embed.notes}\n` + + " remove: false\n" + + "attachment:\n" + + ` send: ${settings.embed.attachments}\n` + + ` folder: ${settings.embed.folder}\n` + + `dataview: ${settings.conversion.dataview}\n` + + `hardBreak: ${settings.conversion.hardbreak}\n` + + shortRepo + + "repo:\n" + + ` owner: ${settings.github.user}\n` + + ` repo: ${settings.github.repo}\n` + + ` branch: ${settings.github.branch}\n` + + ` autoclean: ${settings.upload.autoclean.enable}\n` + + "copylink:\n" + + ` base: ${settings.plugin.copyLink.links}\n` + + ` remove: [${settings.plugin.copyLink.removePart.map(val => `"${val}"`).join(", ")}]\n`; +} + +/** + * Create the contents of the help settings tab + * @param {GitHubPublisherSettings} settings + * @return {DocumentFragment} + */ +export function help(settings: GitHubPublisherSettings) { + const explanation = document.createDocumentFragment(); + explanation.createEl("ul", null, (span) => { + span.createEl("li", null, (span) => { + span.createEl("code", { + text: `${settings.plugin.shareKey}:`, + cls: "code-title", + }); + span.createEl("span", { + text: `${i18next.t("settings.help.frontmatter.share.title")}`, + }); + span.createEl("ul", null, (l) => { + l.createEl("span", {text: i18next.t("settings.help.frontmatter.share.other")}); + }); + }); + span.createEl("li", null, (span) => { + span.createEl("code", { + text: "path:", + cls: "code-title", + }); + span.createEl("span", { + text: ` ${i18next.t("settings.help.frontmatter.path")}`, + }); + }); + span.createEl("li", null, (span) => { + span.createEl("code", { text: "links:", cls: "code-title" }); + }); + span.createEl("ul", null, (l) => { + l.createEl("li", null, (p) => { + p.createEl("code", { text: "mdlinks" }); + p.createEl("span", { + text: `: ${ + i18next.t("settings.help.frontmatter.mdlinks") + }`, + }); + }); + l.createEl("li", null, (p) => { + p.createEl("code", { text: "convert" }); + p.createEl("span", null, (span) => { + span.createEl("span", { + text: `: ${ + i18next.t( + "settings.help.frontmatter.convert.enableOrDisable" + ) + } `, + }); + span.createEl("code", { text: " [[link]] " }); + span.createEl("span", { + text: i18next.t("common.or") + }); + span.createEl("code", { text: " [](link) " }); + span.createEl("span", { + text: i18next.t("settings.help.frontmatter.convert.syntax") + }); + }); + }); + l.createEl("li", null, (p) => { + p.createEl("code", {text: "internals"}); + p.createEl("span", { + text: `: ${i18next.t("settings.help.frontmatter.internals")}` + }); + }); + l.createEl("li", null, (p) => { + p.createEl("code", { text: "nonShared" }); + p.createEl("span", { text: `: ${i18next.t("settings.help.frontmatter.nonShared")}` }); + }); + }); + span.createEl("li", { text: "embed:", cls: "code code-title" }); + span.createEl("ul", null, (l) => { + l.createEl("li", null, (p) => { + p.createEl("code", { text: "send" }); + p.createEl("span", { + text: `: ${ + i18next.t("settings.help.frontmatter.embed.send") + }`, + }); + }); + l.createEl("li", null, (p) => { + p.createEl("code", { text: "remove" }); + p.createEl("span", { + text: `: ${ + i18next.t("settings.help.frontmatter.embed.remove") + }`, + }); + }); + }); + span.createEl("li", { text: "attachment:", cls: "code code-title" }); + span.createEl("ul", null, (l) => { + l.createEl("li", null, (span) => { + span.createEl("code", { text: "send" }); + span.createEl("span", { + text: `: ${ + i18next.t( + "settings.help.frontmatter.attachment.send" + ) + }`, + }); + }); + l.createEl("li", null, (p) => { + p.createEl("code", { text: "folder" }); + p.createEl("span", { + text: `: ${ + i18next.t( + "settings.help.frontmatter.attachment.folder" + ) + }`, + }); + }); + }); + span.createEl("li", null, (span) => { + span.createEl("code", { text: "dataview", cls: "code-title" }); + span.createEl("span", { + text: `: ${i18next.t("settings.help.frontmatter.dataview")}`, + }); + }); + span.createEl("li", null, (span) => { + span.createEl("code", { text: "hardbreak", cls: "code-title" }); + span.createEl("span", { + text: `: ${ + i18next.t("settings.help.frontmatter.hardBreak") + }`, + }); + }); + span.createEl("li", null, (span) => { + span.createEl("code", { text: "shortRepo", cls: "code-title" }); + span.createEl("span", { + text: `: ${i18next.t("settings.help.frontmatter.shortRepo")}`, + }); + }); + span.createEl("li", null, (span) => { + span.createEl("code", { text: "repo", cls: "code-title" }); + span.createEl("span", { + text: `: ${i18next.t("settings.help.frontmatter.repo.desc")}`, + }); + span.createEl("ul", null, (ul) => { + ul.createEl("li", null, (li) => { + li.createEl("code", { text: "owner" }); + li.createEl("span", { + text: `: ${i18next.t("settings.help.frontmatter.repo.owner")}`, + }); + }); + ul.createEl("li", null, (li) => { + li.createEl("code", { text: "repo" }); + li.createEl("span", { + text: `: ${i18next.t("settings.github.repoName.title")}`, + }); + }); + ul.createEl("li", null, (li) => { + li.createEl("code", { text: "branch" }); + li.createEl("span", { + text: `: ${i18next.t( + "settings.help.frontmatter.repo.branch" + )}`, + }); + }); + ul.createEl("li", null, (li) => { + li.createEl("code", { text: "autoclean"}); + li.createEl("span", { + text: `: ${i18next.t("settings.help.frontmatter.autoclean")}`, + }); + }); + }); + }); + span.createEl("li", null, (span) => { + span.createEl("code", { + text: `${settings.upload.frontmatterTitle.key}`, + cls: "code-title", + }); + span.createEl("span", { + text: `: ${i18next.t("settings.help.frontmatter.titleKey")}`, + }); + }); + span.createEl("li", null, (span) => { + span.createEl("code", { text: "baseLink", cls: "code-title" }); + span.createEl("span", { + text: `: ${i18next.t("settings.help.frontmatter.baselink.desc")}`, + }); + span.createEl("code", {text: "copylink:", cls: "code-title"}); + span.createEl("ul", null, (ul) => { + ul.createEl("li", null, (li) => { + li.createEl("code", { text: "base"}); + li.createEl("span", { + text: `: ${i18next.t("settings.plugin.copyLink.baselink.title")}`, + }); + }); + ul.createEl("li", null, (li) => { + li.createEl("code", { text: "remove"}); + li.createEl("span", { + text: `: ${i18next.t("settings.help.frontmatter.baselink.remove")}`, + }); + }); + }); + }); + }); + return explanation; +} + +/** + * Create the useful links section in the settings help tab + * @return {DocumentFragment} + */ +export function usefullLinks(): DocumentFragment { + const usefullLinks = document.createDocumentFragment(); + usefullLinks.createEl("ul", null, (el) => { + el.createEl("li", null, (el) => { + el.createEl("a", { + text: i18next.t("settings.help.usefulLinks.documentation"), + href: i18next.t("settings.help.usefulLinks.links"), + }); + }); + el.createEl("li", null, (el) => { + el.createEl("a", { + text: i18next.t("common.repository"), + href: "https://github.com/ObsidianPublisher/obsidian-github-publisher", + }); + }); + el.createEl("li", null, (el) => { + el.createEl("a", { + text: i18next.t("settings.help.usefulLinks.issue"), + href: "https://github.com/ObsidianPublisher/obsidian-github-publisher/issues", + }); + }); + el.createEl("li", null, (el) => { + el.createEl("a", { + text: i18next.t("settings.help.usefulLinks.discussion"), + href: "https://github.com/ObsidianPublisher/obsidian-github-publisher/discussions", + }); + }); + }); + return usefullLinks; +} + +/** + * Create the explanation of multiple repo for the help tab + * @param {GitHubPublisherSettings} settings + * @return {DocumentFragment} + */ +export function multipleRepoExplained( + settings: GitHubPublisherSettings +): DocumentFragment { + const multipleRepoExplained = document.createDocumentFragment(); + multipleRepoExplained.createEl("p", null, (el) => { + el.createEl("span", { + text: i18next.t("settings.help.multiRepoHelp.desc"), + }); + el.createEl("code", { text: "multipleRepo" }); + el.createEl("span", { + text: ` ${i18next.t("settings.help.multiRepoHelp.desc2")}:`, + }); + el.createEl("ul", null, (el) => { + el.createEl("li", { text: "owner" }).addClass("code"); + el.createEl("li", { text: "repo" }).addClass("code"); + el.createEl("li", { text: "branch" }).addClass("code"); + el.createEl("li", { text: "autoclean" }).addClass("code"); + }); + el.createEl("span", { + text: i18next.t("settings.help.multiRepoHelp.exampleDesc"), + }); + }); + multipleRepoExplained + .createEl("pre", { cls: "language-yaml" }) + .createEl("code", { + text: `multipleRepo:\n - owner: ${settings.github.user}\n repo: ${settings.github.repo}\n branch: ${settings.github.branch}\n autoclean: false\n - owner: ${settings.github.user}\n repo: my_second_brain\n branch: master\n autoclean: false`, + cls: "language-yaml", + }); + return multipleRepoExplained; +} + +/** + * Add the link for kofi in the help tab + * @return {DocumentFragment} + */ + +export function supportMe(): DocumentFragment { + const supportMe = document.createDocumentFragment(); + supportMe.createEl("p", null, (el) => { + el.createEl("a", null, (el) => { + el.createEl("img", null, (img) => { + img.setAttr( + "src", + "https://storage.ko-fi.com/cdn/kofi2.png?v=3" + ); + img.setAttr("alt", "Buy Me A Coffee"); + img.setAttr( + "style", + "height: 60px !important;width: 217px !important;" + ); + }); + el.setAttr("href", "https://ko-fi.com/lisandra_dev"); + }); + el.setAttr("style", "text-align: center;"); + }); + return supportMe; +} diff --git a/src/settings/migrate.ts b/src/settings/migrate.ts index 3948c22b..d5de76ba 100644 --- a/src/settings/migrate.ts +++ b/src/settings/migrate.ts @@ -122,10 +122,10 @@ async function migrateWorFlow(plugin: GithubPublisher) { } async function migrateEncryptToken(plugin: GithubPublisher) { - const encrypted = await isEncrypted(plugin.app, plugin.manifest, plugin.settings); + const encrypted = await isEncrypted(plugin); if (!encrypted) { noticeLog("Encrypting token", plugin.settings); - const encryptedToken = await encrypt(plugin.settings.github.token, plugin.app, plugin.manifest, plugin.settings); + const encryptedToken = await encrypt(plugin.settings.github.token, plugin); plugin.settings.github.token = encryptedToken; } await plugin.saveSettings(); diff --git a/src/settings/modals/import_export.ts b/src/settings/modals/import_export.ts index b5bdfcf7..3fd3b83a 100644 --- a/src/settings/modals/import_export.ts +++ b/src/settings/modals/import_export.ts @@ -1,272 +1,272 @@ -import GithubPublisher from "../../main"; -import { App, Modal, Setting, TextAreaComponent, ButtonComponent, Platform } from "obsidian"; -import {GithubPublisherSettingsTab} from "../../settings"; -import i18next from "i18next"; -import {GitHubPublisherSettings} from "../interface"; -import { OldSettings } from "../migrate"; -import { noticeLog } from "../../src/utils"; -import {migrateSettings} from "../migrate"; - -export type SettingValue = number | string | boolean | unknown; - -function clone(obj: GitHubPublisherSettings): GitHubPublisherSettings { - return JSON.parse(JSON.stringify(obj)); -} -/** - * - * Credit : Style Settings Plugin - * URL : https://github.com/mgmeyers/obsidian-github-publisher - **/ - -export class ImportModal extends Modal { - plugin: GithubPublisher; - settingsPage: HTMLElement; - settingsTab: GithubPublisherSettingsTab; - constructor(app: App, plugin: GithubPublisher, settingsPage: HTMLElement, settingsTab: GithubPublisherSettingsTab) { - super(app); - this.plugin = plugin; - this.settingsPage = settingsPage; - this.settingsTab = settingsTab; - } - - async censoreRepositoryData(actualSettings: GitHubPublisherSettings) { - this.plugin.settings.plugin = actualSettings.plugin; - this.plugin.settings.github.repo = actualSettings.github.repo; - this.plugin.settings.github.token = actualSettings.github.token; - this.plugin.settings.github.user = actualSettings.github.user; - for (const repo of actualSettings.github.otherRepo) { - //search the same repo in this.settings.github.otherRepo - const index = this.plugin.settings.github.otherRepo.findIndex((r) => r.smartKey === repo.smartKey); - if (index !== -1) { - const found = this.plugin.settings.github.otherRepo[index]; - found.repo = repo.repo; - found.user = repo.user; - } else { - repo.repo = ""; - repo.user = ""; - } - } - await this.plugin.saveSettings(); - - } - - onOpen() { - const {contentEl} = this; - - new Setting(contentEl) - .setName(i18next.t("modals.import.title") ) - .setDesc(i18next.t("modals.import.desc") ); - - new Setting(contentEl).then((setting) => { - // Build an error message container - const errorSpan = createSpan({ - cls: "github-publisher-import-error", - text: i18next.t("modals.import.error.span") , - }); - setting.nameEl.appendChild(errorSpan); - const importAndClose = async (str: string) => { - if (str) { - try { - let importedSettings = JSON.parse(str); - if (Object.keys(importedSettings).includes("editorMenu")) { - //need to convert old settings to new settings - const oldSettings = importedSettings as unknown as OldSettings; - await migrateSettings(oldSettings, this.plugin); - noticeLog(i18next.t("informations.migrating.oldSettings"), this.plugin.settings); - } else { - noticeLog(i18next.t("informations.migrating.normalFormat"), this.plugin.settings); - importedSettings = importedSettings as unknown as GitHubPublisherSettings; - //create a copy of actual settings - const actualSettings = clone(this.plugin.settings); - if (!(importedSettings.upload.replaceTitle instanceof Array)) { - importedSettings.upload.replaceTitle = [importedSettings.upload.replaceTitle]; - } - - for (const [key, value] of Object.entries(importedSettings)) { - // @ts-ignore - this.plugin.settings[key] = value; - } - await this.censoreRepositoryData(actualSettings); - await this.plugin.saveSettings(); - } - this.close(); - } catch (e) { - errorSpan.addClass("active"); - errorSpan.setText(`${i18next.t("modals.import.error.span")}${e}`); - } - } else { - errorSpan.addClass("active"); - errorSpan.setText(`${i18next.t("modals.import.error.span")}: ${i18next.t("modals.import.error.isEmpty")}`); - } - }; - setting.controlEl.createEl( - "input", - { - cls: "github-publisher-import-input", - attr: { - id: "github-publisher-import-input", - name: "github-publisher-import-input", - type: "file", - accept: ".json", - }, - }, - (importInput) => { - // Set up a FileReader so we can parse the file contents - importInput.addEventListener("change", (e) => { - const reader = new FileReader(); - - reader.onload = async (e: ProgressEvent) => { - await importAndClose(e.target.result.toString().trim()); - }; - - reader.readAsText((e.target as HTMLInputElement).files[0]); - }); - } - ); - - // Build a label we will style as a link - setting.controlEl.createEl("label", { - cls: "github-publisher-import-label", - text: i18next.t("modals.import.importFromFile") , - attr: { - for: "github-publisher-import-input", - }, - }); - - const textArea = new TextAreaComponent(contentEl) - .setPlaceholder(i18next.t("modals.import.paste") ).then((ta) => { - const saveButton = new ButtonComponent(contentEl).setButtonText(i18next.t("common.save") ).onClick(async () => { - await importAndClose(ta.getValue().trim()); - }); - saveButton.buttonEl.addClass("github-publisher-import-save-button"); - }); - textArea.inputEl.addClass("github-publisher-import-textarea"); - }); - } - - onClose() { - const { contentEl } = this; - contentEl.empty(); - this.settingsPage.empty(); - // @ts-ignore - let openedTab = document.querySelector(".settings-tab-active.github-publisher") ? document.querySelector(".settings-tab-active.github-publisher").innerText : i18next.t("settings.github.title") ; - openedTab = openedTab.trim(); - switch (openedTab) { - case i18next.t("settings.github.title") : - this.settingsTab.renderGithubConfiguration(); - break; - case i18next.t("settings.upload.title"): - this.settingsTab.renderUploadConfiguration(); - break; - case i18next.t("settings.conversion.title") : - this.settingsTab.renderTextConversion(); - break; - case i18next.t("settings.embed.title") : - this.settingsTab.renderEmbedConfiguration(); - break; - case i18next.t("settings.plugin.title") : - this.settingsTab.renderPluginSettings(); - break; - case i18next.t("settings.help.title") : - this.settingsTab.renderHelp(); - break; - } - - } -} - - -export class ExportModal extends Modal { - plugin: GithubPublisher; - - constructor(app: App, plugin: GithubPublisher) { - super(app); - this.plugin = plugin; - } - - censoreGithubSettingsData(censuredSettings: GitHubPublisherSettings) { - delete censuredSettings.github.repo; - delete censuredSettings.github.token; - delete censuredSettings.github.user; - delete censuredSettings.plugin; - for (const repo of censuredSettings.github.otherRepo) { - delete repo.repo; - delete repo.user; - } - return censuredSettings; - } - - onOpen() { - const {contentEl, modalEl} = this; - modalEl.addClass("modal-github-publisher"); - new Setting(contentEl) - .setName(i18next.t("modals.export.title") ) - .setDesc(i18next.t("modals.export.desc") ) - .then((setting) => { - //create a copy of the settings object - const censuredSettings = this.censoreGithubSettingsData(clone(this.plugin.settings)); - const output = JSON.stringify(censuredSettings, null, 2); - setting.controlEl.createEl("a", - { - cls: "github-publisher-copy", - text: i18next.t("modals.export.copy") , - href: "#", - }, - (copyButton) => { - const textArea = new TextAreaComponent(contentEl).setValue(output).then((textarea) => { - copyButton.addEventListener("click", (e) => { - e.preventDefault(); - - // Select the textarea contents and copy them to the clipboard - textarea.inputEl.select(); - textarea.inputEl.setSelectionRange(0, 99999); - document.execCommand("copy"); - - copyButton.addClass("success"); - - setTimeout(() => { - // If the button is still in the dom, remove the success class - if (copyButton.parentNode) { - copyButton.removeClass("success"); - } - }, 2000); - }); - }); - textArea.inputEl.addClass("github-publisher-export-textarea"); - }); - - if (Platform.isDesktop) { - setting.controlEl.createEl("a", { - cls: "github-publisher-download", - text: i18next.t("modals.export.download") , - attr: { - download: "github-publisher.json", - href: `data:application/json;charset=utf-8,${encodeURIComponent(output)}`, - }, - }); - } else if (Platform.isMobile) { - setting.addButton((b) => - b - .setButtonText(i18next.t("modals.export.download") ) - .onClick(() => { - // Can't use the method above on mobile, so we'll just open a new tab - //create a temporary file - this.app.vault.adapter.write(`${app.vault.configDir}/plugins/obsidian-mkdocs-publisher/._tempSettings.json`, output); - //open the file with default application - //eslint-disable-next-line +import GithubPublisher from "../../main"; +import { App, Modal, Setting, TextAreaComponent, ButtonComponent, Platform } from "obsidian"; +import {GithubPublisherSettingsTab} from "../../settings"; +import i18next from "i18next"; +import {GitHubPublisherSettings} from "../interface"; +import { OldSettings } from "../migrate"; +import { noticeLog } from "../../src/utils"; +import {migrateSettings} from "../migrate"; + +export type SettingValue = number | string | boolean | unknown; + +function clone(obj: GitHubPublisherSettings): GitHubPublisherSettings { + return JSON.parse(JSON.stringify(obj)); +} +/** + * + * Credit : Style Settings Plugin + * URL : https://github.com/mgmeyers/obsidian-github-publisher + **/ + +export class ImportModal extends Modal { + plugin: GithubPublisher; + settingsPage: HTMLElement; + settingsTab: GithubPublisherSettingsTab; + constructor(app: App, plugin: GithubPublisher, settingsPage: HTMLElement, settingsTab: GithubPublisherSettingsTab) { + super(app); + this.plugin = plugin; + this.settingsPage = settingsPage; + this.settingsTab = settingsTab; + } + + async censoreRepositoryData(actualSettings: GitHubPublisherSettings) { + this.plugin.settings.plugin = actualSettings.plugin; + this.plugin.settings.github.repo = actualSettings.github.repo; + this.plugin.settings.github.token = actualSettings.github.token; + this.plugin.settings.github.user = actualSettings.github.user; + for (const repo of actualSettings.github.otherRepo) { + //search the same repo in this.settings.github.otherRepo + const index = this.plugin.settings.github.otherRepo.findIndex((r) => r.smartKey === repo.smartKey); + if (index !== -1) { + const found = this.plugin.settings.github.otherRepo[index]; + found.repo = repo.repo; + found.user = repo.user; + } else { + repo.repo = ""; + repo.user = ""; + } + } + await this.plugin.saveSettings(); + + } + + onOpen() { + const {contentEl} = this; + + new Setting(contentEl) + .setName(i18next.t("modals.import.title") ) + .setDesc(i18next.t("modals.import.desc") ); + + new Setting(contentEl).then((setting) => { + // Build an error message container + const errorSpan = createSpan({ + cls: "github-publisher-import-error", + text: i18next.t("modals.import.error.span") , + }); + setting.nameEl.appendChild(errorSpan); + const importAndClose = async (str: string) => { + if (str) { + try { + let importedSettings = JSON.parse(str); + if (Object.keys(importedSettings).includes("editorMenu")) { + //need to convert old settings to new settings + const oldSettings = importedSettings as unknown as OldSettings; + await migrateSettings(oldSettings, this.plugin); + noticeLog(i18next.t("informations.migrating.oldSettings"), this.plugin.settings); + } else { + noticeLog(i18next.t("informations.migrating.normalFormat"), this.plugin.settings); + importedSettings = importedSettings as unknown as GitHubPublisherSettings; + //create a copy of actual settings + const actualSettings = clone(this.plugin.settings); + if (!(importedSettings.upload.replaceTitle instanceof Array)) { + importedSettings.upload.replaceTitle = [importedSettings.upload.replaceTitle]; + } + + for (const [key, value] of Object.entries(importedSettings)) { + // @ts-ignore + this.plugin.settings[key] = value; + } + await this.censoreRepositoryData(actualSettings); + await this.plugin.saveSettings(); + } + this.close(); + } catch (e) { + errorSpan.addClass("active"); + errorSpan.setText(`${i18next.t("modals.import.error.span")}${e}`); + } + } else { + errorSpan.addClass("active"); + errorSpan.setText(`${i18next.t("modals.import.error.span")}: ${i18next.t("modals.import.error.isEmpty")}`); + } + }; + setting.controlEl.createEl( + "input", + { + cls: "github-publisher-import-input", + attr: { + id: "github-publisher-import-input", + name: "github-publisher-import-input", + type: "file", + accept: ".json", + }, + }, + (importInput) => { + // Set up a FileReader so we can parse the file contents + importInput.addEventListener("change", (e) => { + const reader = new FileReader(); + + reader.onload = async (e: ProgressEvent) => { + await importAndClose(e.target.result.toString().trim()); + }; + + reader.readAsText((e.target as HTMLInputElement).files[0]); + }); + } + ); + + // Build a label we will style as a link + setting.controlEl.createEl("label", { + cls: "github-publisher-import-label", + text: i18next.t("modals.import.importFromFile") , + attr: { + for: "github-publisher-import-input", + }, + }); + + const textArea = new TextAreaComponent(contentEl) + .setPlaceholder(i18next.t("modals.import.paste") ).then((ta) => { + const saveButton = new ButtonComponent(contentEl).setButtonText(i18next.t("common.save") ).onClick(async () => { + await importAndClose(ta.getValue().trim()); + }); + saveButton.buttonEl.addClass("github-publisher-import-save-button"); + }); + textArea.inputEl.addClass("github-publisher-import-textarea"); + }); + } + + onClose() { + const { contentEl } = this; + contentEl.empty(); + this.settingsPage.empty(); + // @ts-ignore + let openedTab = document.querySelector(".settings-tab-active.github-publisher") ? document.querySelector(".settings-tab-active.github-publisher").innerText : i18next.t("settings.github.title") ; + openedTab = openedTab.trim(); + switch (openedTab) { + case i18next.t("settings.github.title") : + this.settingsTab.renderGithubConfiguration(); + break; + case i18next.t("settings.upload.title"): + this.settingsTab.renderUploadConfiguration(); + break; + case i18next.t("settings.conversion.title") : + this.settingsTab.renderTextConversion(); + break; + case i18next.t("settings.embed.title") : + this.settingsTab.renderEmbedConfiguration(); + break; + case i18next.t("settings.plugin.title") : + this.settingsTab.renderPluginSettings(); + break; + case i18next.t("settings.help.title") : + this.settingsTab.renderHelp(); + break; + } + + } +} + + +export class ExportModal extends Modal { + plugin: GithubPublisher; + + constructor(app: App, plugin: GithubPublisher) { + super(app); + this.plugin = plugin; + } + + censoreGithubSettingsData(censuredSettings: GitHubPublisherSettings) { + delete censuredSettings.github.repo; + delete censuredSettings.github.token; + delete censuredSettings.github.user; + delete censuredSettings.plugin; + for (const repo of censuredSettings.github.otherRepo) { + delete repo.repo; + delete repo.user; + } + return censuredSettings; + } + + onOpen() { + const {contentEl, modalEl} = this; + modalEl.addClass("modal-github-publisher"); + new Setting(contentEl) + .setName(i18next.t("modals.export.title") ) + .setDesc(i18next.t("modals.export.desc") ) + .then((setting) => { + //create a copy of the settings object + const censuredSettings = this.censoreGithubSettingsData(clone(this.plugin.settings)); + const output = JSON.stringify(censuredSettings, null, 2); + setting.controlEl.createEl("a", + { + cls: "github-publisher-copy", + text: i18next.t("modals.export.copy") , + href: "#", + }, + (copyButton) => { + const textArea = new TextAreaComponent(contentEl).setValue(output).then((textarea) => { + copyButton.addEventListener("click", (e) => { + e.preventDefault(); + + // Select the textarea contents and copy them to the clipboard + textarea.inputEl.select(); + textarea.inputEl.setSelectionRange(0, 99999); + document.execCommand("copy"); + + copyButton.addClass("success"); + + setTimeout(() => { + // If the button is still in the dom, remove the success class + if (copyButton.parentNode) { + copyButton.removeClass("success"); + } + }, 2000); + }); + }); + textArea.inputEl.addClass("github-publisher-export-textarea"); + }); + + if (Platform.isDesktop) { + setting.controlEl.createEl("a", { + cls: "github-publisher-download", + text: i18next.t("modals.export.download") , + attr: { + download: "github-publisher.json", + href: `data:application/json;charset=utf-8,${encodeURIComponent(output)}`, + }, + }); + } else if (Platform.isMobile) { + setting.addButton((b) => + b + .setButtonText(i18next.t("modals.export.download") ) + .onClick(() => { + // Can't use the method above on mobile, so we'll just open a new tab + //create a temporary file + this.app.vault.adapter.write(`${app.vault.configDir}/plugins/obsidian-mkdocs-publisher/._tempSettings.json`, output); + //open the file with default application + //eslint-disable-next-line (this.app as any).openWithDefaultApp(`${app.vault.configDir}/plugins/obsidian-mkdocs-publisher/._tempSettings.json`); - })); - } - }); - } - - onClose() { - try{ - this.app.vault.adapter.trashSystem(`${app.vault.configDir}/plugins/obsidian-mkdocs-publisher/._tempSettings.json`); - }catch(e){ - //do nothing if file doesn't exist - } - const {contentEl} = this; - contentEl.empty(); - } -} + })); + } + }); + } + + onClose() { + try{ + this.app.vault.adapter.trashSystem(`${app.vault.configDir}/plugins/obsidian-mkdocs-publisher/._tempSettings.json`); + }catch(e){ + //do nothing if file doesn't exist + } + const {contentEl} = this; + contentEl.empty(); + } +} diff --git a/src/settings/modals/list_changed.ts b/src/settings/modals/list_changed.ts index 9d82f507..12ac2d45 100644 --- a/src/settings/modals/list_changed.ts +++ b/src/settings/modals/list_changed.ts @@ -1,75 +1,75 @@ -import { Modal, App } from "obsidian"; -import { Deleted, ListeEditedFiles } from "../interface"; -import i18next from "i18next"; - - -export class ListChangedFiles extends Modal { - listChanged: ListeEditedFiles | Deleted; - constructor(app: App, listChanged: ListeEditedFiles | Deleted) { - super(app); - this.listChanged = listChanged ; - } - - displayListOfFile(toDisplay: string[], contentEl: HTMLElement) { - if (!toDisplay.length) return; - const ul = contentEl.createEl("ul"); - toDisplay.forEach((file) => { - let emoji = "❓"; - const ext = file.split(".").pop(); - if (["md"].includes(ext)) { - emoji = "🗒️"; - } else if ([".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"].includes(`.${ext}`)) { - emoji = "🖼️"; - } else if ([".mp3", ".wav", ".ogg", ".flac", ".aac"].includes(`.${ext}`)) { - emoji = "🎵"; - } else if ([".mp4", ".avi", ".mov", ".mkv", ".webm"].includes(`.${ext}`)) { - emoji = "🎥"; - } else if ([".pdf"].includes(`.${ext}`)) { - emoji = "📄"; - } - const li = ul.createEl("li"); - li.createEl("span", { text: emoji, cls: "github-publisher emoji" }); - li.createEl("code", { text: file, cls: "code-title github-publisher list-changed"}); - }); - } - - onOpen() { - /** - * a modal is open and the user can read what files was : - * - added - * - modified - * - deleted - * - Not uploaded - */ - const { contentEl } = this; - contentEl.empty(); - contentEl.createEl("h2", { text: i18next.t("modals.listChangedFiles.title"), cls: "github-publisher title"}); - if (Object.keys(this.listChanged).contains("edited")) { - this.listChanged = this.listChanged as ListeEditedFiles; - contentEl.createEl("h3", { text: `📤 ${i18next.t("modals.listChangedFiles.added")}`}); - this.displayListOfFile(this.listChanged.added, contentEl); - contentEl.createEl("h3", { text: `✒️ ${i18next.t("modals.listChangedFiles.edited")}`}); - this.displayListOfFile(this.listChanged.edited, contentEl); - contentEl.createEl("h3", { text: `🗑️ ${i18next.t("modals.listChangedFiles.deleted")}`}); - this.displayListOfFile(this.listChanged.deleted, contentEl); - contentEl.createEl("h2", { text: `❌ ${i18next.t("modals.listChangedFiles.error")}`, cls: "github-publisher title error"}); - contentEl.createEl("h3", { text: `📤 ${i18next.t("modals.listChangedFiles.unpublished")}`}); - this.displayListOfFile(this.listChanged.unpublished, contentEl); - contentEl.createEl("h3", { text: `♻️ ${i18next.t("modals.listChangedFiles.notDeleted")}`}); - this.displayListOfFile(this.listChanged.notDeleted, contentEl); - } else { - this.listChanged = this.listChanged as Deleted; - contentEl.createEl("h3", { text: `🗑️ ${i18next.t("modals.listChangedFiles.deleted")}`}); - this.displayListOfFile(this.listChanged.deleted, contentEl); - contentEl.createEl("h3", { text: `❌ ${i18next.t("modals.listChangedFiles.error")}`, cls: "github-publisher error"}); - contentEl.createEl("h3", { text: `♻️ ${i18next.t("modals.listChangedFiles.notDeleted")}`}); - this.displayListOfFile(this.listChanged.undeleted, contentEl); - } - } - - onClose() { - const { contentEl } = this; - contentEl.empty(); - } - -} +import { Modal, App } from "obsidian"; +import { Deleted, ListeEditedFiles } from "../interface"; +import i18next from "i18next"; + + +export class ListChangedFiles extends Modal { + listChanged: ListeEditedFiles | Deleted; + constructor(app: App, listChanged: ListeEditedFiles | Deleted) { + super(app); + this.listChanged = listChanged ; + } + + displayListOfFile(toDisplay: string[], contentEl: HTMLElement) { + if (!toDisplay.length) return; + const ul = contentEl.createEl("ul"); + toDisplay.forEach((file) => { + let emoji = "❓"; + const ext = file.split(".").pop(); + if (["md"].includes(ext)) { + emoji = "🗒️"; + } else if ([".png", ".jpg", ".jpeg", ".gif", ".svg", ".webp"].includes(`.${ext}`)) { + emoji = "🖼️"; + } else if ([".mp3", ".wav", ".ogg", ".flac", ".aac"].includes(`.${ext}`)) { + emoji = "🎵"; + } else if ([".mp4", ".avi", ".mov", ".mkv", ".webm"].includes(`.${ext}`)) { + emoji = "🎥"; + } else if ([".pdf"].includes(`.${ext}`)) { + emoji = "📄"; + } + const li = ul.createEl("li"); + li.createEl("span", { text: emoji, cls: "github-publisher emoji" }); + li.createEl("code", { text: file, cls: "code-title github-publisher list-changed"}); + }); + } + + onOpen() { + /** + * a modal is open and the user can read what files was : + * - added + * - modified + * - deleted + * - Not uploaded + */ + const { contentEl } = this; + contentEl.empty(); + contentEl.createEl("h2", { text: i18next.t("modals.listChangedFiles.title"), cls: "github-publisher title"}); + if (Object.keys(this.listChanged).contains("edited")) { + this.listChanged = this.listChanged as ListeEditedFiles; + contentEl.createEl("h3", { text: `📤 ${i18next.t("modals.listChangedFiles.added")}`}); + this.displayListOfFile(this.listChanged.added, contentEl); + contentEl.createEl("h3", { text: `✒️ ${i18next.t("modals.listChangedFiles.edited")}`}); + this.displayListOfFile(this.listChanged.edited, contentEl); + contentEl.createEl("h3", { text: `🗑️ ${i18next.t("modals.listChangedFiles.deleted")}`}); + this.displayListOfFile(this.listChanged.deleted, contentEl); + contentEl.createEl("h2", { text: `❌ ${i18next.t("modals.listChangedFiles.error")}`, cls: "github-publisher title error"}); + contentEl.createEl("h3", { text: `📤 ${i18next.t("modals.listChangedFiles.unpublished")}`}); + this.displayListOfFile(this.listChanged.unpublished, contentEl); + contentEl.createEl("h3", { text: `♻️ ${i18next.t("modals.listChangedFiles.notDeleted")}`}); + this.displayListOfFile(this.listChanged.notDeleted, contentEl); + } else { + this.listChanged = this.listChanged as Deleted; + contentEl.createEl("h3", { text: `🗑️ ${i18next.t("modals.listChangedFiles.deleted")}`}); + this.displayListOfFile(this.listChanged.deleted, contentEl); + contentEl.createEl("h3", { text: `❌ ${i18next.t("modals.listChangedFiles.error")}`, cls: "github-publisher error"}); + contentEl.createEl("h3", { text: `♻️ ${i18next.t("modals.listChangedFiles.notDeleted")}`}); + this.displayListOfFile(this.listChanged.undeleted, contentEl); + } + } + + onClose() { + const { contentEl } = this; + contentEl.empty(); + } + +} diff --git a/src/settings/modals/manage_repo.ts b/src/settings/modals/manage_repo.ts index 5547e95e..8a8f9331 100644 --- a/src/settings/modals/manage_repo.ts +++ b/src/settings/modals/manage_repo.ts @@ -1,366 +1,366 @@ -import i18next from "i18next"; -import {App, Modal, Notice, Setting} from "obsidian"; -import {GitHubPublisherSettings, GithubTiersVersion, Repository} from "../interface"; -import {checkRepositoryValidity} from "../../src/data_validation_test"; -import GithubPublisherPlugin from "../../main"; - -/** - * @description This class is used to add a new repo to the settings in the "otherRepo" in the github setting section - * It will list all the repo in the settings and allow the user to add a new one, edit or delete an existing one - * @extends Modal - * @param {App} app - the Obsidian App - * @param {GitHubPublisherSettings} settings - the plugin settings - * @param {string} branchName - the branch name - * @param {GithubPublisherPlugin} plugin - the plugin - * @param {Repository[]} repository - the list of repo in the settings - * @param {(result: Repository[]) => void} onSubmit - the function to call when the modal is submitted - */ - -export class ModalAddingNewRepository extends Modal { - settings: GitHubPublisherSettings; - plugin: GithubPublisherPlugin; - branchName: string; - repository: Repository[]; - onSubmit: (result: Repository[]) => void; - - constructor( - app: App, - settings: GitHubPublisherSettings, - branchName: string, - plugin: GithubPublisherPlugin, - repository: Repository[], - onSubmit: (result: Repository[]) => void) { - super(app); - this.settings = settings; - this.repository = repository; - this.plugin = plugin; - this.onSubmit = onSubmit; - this.branchName = branchName; - } - - onOpen() { - const {contentEl} = this; - contentEl.empty(); - contentEl.createEl("h2", {text: i18next.t("settings.github.smartRepo.modals.title")}); - contentEl.createEl("p", {text: i18next.t("settings.github.smartRepo.modals.desc")}); - contentEl.createEl("p", {text: i18next.t("settings.github.smartRepo.modals.frontmatterInfo")}); - contentEl.createEl("p", {text: i18next.t("settings.plugin.shareKey.otherRepo")}); - - - const defaultRepository: Repository = { - smartKey: "", - user: this.settings.github.user, - repo: this.settings.github.repo, - branch: this.settings.github.branch, - automaticallyMergePR: this.settings.github.automaticallyMergePR, - api: { - tiersForApi: this.settings.github.api.tiersForApi, - hostname: this.settings.github.api.hostname, - }, - workflow: { - commitMessage: this.settings.github.workflow.commitMessage, - name: "", - }, - createShortcuts: false, - shareKey: this.settings.plugin.shareKey, - copyLink: { - links: this.settings.plugin.copyLink.links, - removePart: [] - } - }; - - new Setting(contentEl) - .addButton((button) => { - button - - .setButtonText(i18next.t("common.add", {things: i18next.t("settings.github.smartRepo.modals.newRepo").toLowerCase()})) - .onClick(() => { - this.repository.push(defaultRepository); - this.onOpen(); - }) - .buttonEl.style.width = "100%"; - }) - .infoEl.style.display = "none"; - - for (const repo of this.repository) { - new Setting(contentEl) - .addText((text) => { - text - .setPlaceholder("smartKey") - .setValue(repo.smartKey) - .onChange((value) => { - repo.smartKey = value.toLowerCase(); - if (this.plugin.settings.github.otherRepo.filter((r) => r.smartKey === repo.smartKey).length > 1) { - new Notice(i18next.t("settings.github.smartRepo.modals.duplicate")); - text.inputEl.style.border = "1px solid red"; - repo.smartKey = ""; - } else if (repo.smartKey === "default") { - text.inputEl.style.border = "1px solid red"; - repo.smartKey = ""; - new Notice(i18next.t("settings.github.smartRepo.modals.default") as string); - } else { - text.inputEl.style.border = "0"; - } - }) - .inputEl.style.width = "100%"; - - }) - - .addExtraButton((btn) => { - btn - .setIcon("trash") - .onClick(() => { - this.repository.splice(this.repository.indexOf(repo), 1); - this.onOpen(); - }); - }) - .addExtraButton((btn) => { - btn - .setIcon("pencil") - .onClick(() => { - new ModalEditingRepository(this.app, repo, this.plugin, this.branchName, (result) => { - this.repository[this.repository.indexOf(repo)] = result; - }).open(); - }); - }) - .infoEl.style.display = "none"; - - } - new Setting(contentEl) - .addButton((button) => { - button - .setButtonText(i18next.t("common.save")) - .onClick(() => { - this.onSubmit(this.repository); - this.close(); - }); - }); - } - onClose() { - const {contentEl} = this; - contentEl.empty(); - this.onSubmit(this.repository); - } -} - -/** - * @description Called by the ModalAddingNewRepository class, this class is used to edit an existing repo - * @extends Modal - * @param {App} app - The Obsidian App instance - * @param {Repository} repository - The repository to edit - * @param {GithubPublisherPlugin} GithubPublisherPlugin - The GithubPublisherPlugin instance - * @param {string} brancheName - The name of the branch (for validation) - * @param {function} onSubmit - The function to call when the modal is closed (to save the changes) - */ - -class ModalEditingRepository extends Modal { - repository: Repository; - branchName: string; - plugin: GithubPublisherPlugin; - onSubmit: (result: Repository) => void; - - constructor( - app: App, - repository: Repository, - GithubPublisherPlugin: GithubPublisherPlugin, - brancheName: string, - onSubmit: (result: Repository) => void) { - super(app); - this.repository = repository; - this.onSubmit = onSubmit; - this.branchName = brancheName; - this.plugin = GithubPublisherPlugin; - } - - onOpen() { - const {contentEl} = this; - contentEl.empty(); - contentEl.createEl("h2", {text: i18next.t("common.edit", {things: this.repository.smartKey})}); - - new Setting(contentEl) - .setName(i18next.t("settings.github.apiType.title")) - .setDesc(i18next.t("settings.github.apiType.desc")) - .addDropdown((dropdown) => { - dropdown - .addOption(GithubTiersVersion.free, i18next.t("settings.github.apiType.dropdown.free")) - .addOption(GithubTiersVersion.entreprise, i18next.t("settings.github.apiType.dropdown.enterprise")) - .setValue(this.repository.api.tiersForApi) - .onChange((value) => { - this.repository.api.tiersForApi = value as GithubTiersVersion; - this.onOpen(); - }); - }); - if (this.repository.api.tiersForApi === GithubTiersVersion.entreprise) { - new Setting(contentEl) - .setName(i18next.t("settings.github.apiType.hostname.title")) - .setDesc(i18next.t("settings.github.apiType.hostname.desc")) - .addText((text) => - text - .setPlaceholder("https://github.mycompany.com") - .setValue(this.repository.api.hostname) - .onChange(async (value) => { - this.repository.api.hostname = value.trim(); - }) - ); - } - new Setting(contentEl) - .setName(i18next.t("settings.github.repoName.title")) - .setDesc(i18next.t("settings.github.repoName.desc")) - .addText((text) => - text - .setPlaceholder(i18next.t("settings.github.repoName.placeholder")) - .setValue(this.repository.repo) - .onChange(async (value) => { - this.repository.repo = value.trim(); - }) - ); - new Setting(contentEl) - .setName(i18next.t("settings.github.username.title")) - .setDesc(i18next.t("settings.github.username.desc")) - .addText((text) => - text - .setPlaceholder( - i18next.t("settings.github.username.title") - ) - .setValue(this.repository.user) - .onChange(async (value) => { - this.repository.user = value.trim(); - }) - ); - new Setting(contentEl) - .setName(i18next.t("settings.github.branch.title")) - .setDesc(i18next.t("settings.github.branch.desc")) - .addText((text) => - text - .setPlaceholder("main") - .setValue(this.repository.branch) - .onChange(async (value) => { - this.repository.branch = value.trim(); - }) - ); - new Setting(contentEl) - .setName(i18next.t("settings.github.automaticallyMergePR")) - .addToggle((toggle) => - toggle - .setValue(this.repository.automaticallyMergePR) - .onChange(async (value) => { - this.repository.automaticallyMergePR = value; - }) - ); - new Setting(contentEl) - .setClass("github-publisher-no-display") - .addButton((button) => - button - .setButtonText(i18next.t("settings.github.testConnection")) - .setClass("github-publisher-connect-button") - .onClick(async () => { - await checkRepositoryValidity(this.branchName, this.plugin.reloadOctokit(), this.plugin.settings, this.repository, null, this.app.metadataCache); - }) - ); - new Setting(contentEl) - .setName(i18next.t("settings.github.smartRepo.modals.shortcuts.title")) - .setDesc(i18next.t("settings.github.smartRepo.modals.shortcuts.desc")) - .addToggle((toggle) => - toggle - .setValue(this.repository.createShortcuts) - .onChange(async (value) => { - this.repository.createShortcuts = value; - }) - ); - - contentEl.createEl("h3", { text: "Github Workflow" }); - new Setting(contentEl) - .setName(i18next.t("settings.githubWorkflow.prRequest.title")) - .setDesc(i18next.t("settings.githubWorkflow.prRequest.desc")) - .addText((text) => - text - .setPlaceholder("[PUBLISHER] MERGE") - .setValue(this.repository.workflow.commitMessage) - .onChange(async (value) => { - if (value.trim().length === 0) { - value = "[PUBLISHER] MERGE"; - new Notice(i18next.t("settings.githubWorkflow.prRequest.error")); - } - this.repository.workflow.commitMessage = value; - }) - ); - new Setting(contentEl) - .setName(i18next.t("settings.githubWorkflow.githubAction.title")) - .setDesc( - i18next.t("settings.githubWorkflow.githubAction.desc") - ) - .addText((text) => { - text.setPlaceholder("ci") - .setValue(this.repository.workflow.name) - .onChange(async (value) => { - if (value.length > 0) { - value = value.trim(); - const yamlEndings = [".yml", ".yaml"]; - if (! yamlEndings.some(ending => value.endsWith(ending))) { - value += yamlEndings[0]; - } - } - this.repository.workflow.name = value; - }); - }); - - contentEl.createEl("h3", { text: i18next.t("settings.github.smartRepo.modals.otherConfig") }); - - new Setting(contentEl) - .setName(i18next.t("settings.plugin.shareKey.title")) - .setDesc(i18next.t("settings.plugin.shareKey.desc")) - .addText((text) => - text - .setPlaceholder("share") - .setValue(this.repository.shareKey) - .onChange(async (value) => { - this.repository.shareKey = value.trim(); - await this.plugin.saveSettings(); - }) - ); - if (this.plugin.settings.plugin.copyLink.enable) { - new Setting(contentEl) - .setName(i18next.t("settings.plugin.copyLink.baselink.title")) - .setDesc(i18next.t("settings.plugin.copyLink.baselink.desc")) - .setClass("github-publisher") - .addText((text) => - text - .setPlaceholder(this.plugin.settings.plugin.copyLink.links) - .setValue(this.repository.copyLink.links) - .onChange(async (value) => { - this.repository.copyLink.links = value.trim(); - }) - ); - - new Setting(contentEl) - .setName(i18next.t("settings.plugin.copyLink.linkpathremover.title")) - .setDesc( - i18next.t("settings.plugin.copyLink.linkpathremover.desc") - ) - .setClass("github-publisher") - .addText((text) => { - text.setPlaceholder("docs") - .setValue(this.repository.copyLink.removePart.join(", ")) - .onChange(async (value) => { - this.repository.copyLink.removePart = value.split(/[,\n]\s*/).map((item) => item.trim()).filter((item) => item.length > 0); - await this.plugin.saveSettings(); - }); - }); - } - - new Setting(contentEl) - .addButton((button) => - button - .setButtonText(i18next.t("common.save")) - .onClick(async () => { - this.onSubmit(this.repository); - this.close(); - }) - ); - } - onClose() { - const {contentEl} = this; - contentEl.empty(); - this.onSubmit(this.repository); - } -} +import i18next from "i18next"; +import {App, Modal, Notice, Setting} from "obsidian"; +import {GitHubPublisherSettings, GithubTiersVersion, Repository} from "../interface"; +import {checkRepositoryValidity} from "../../src/data_validation_test"; +import GithubPublisherPlugin from "../../main"; + +/** + * @description This class is used to add a new repo to the settings in the "otherRepo" in the github setting section + * It will list all the repo in the settings and allow the user to add a new one, edit or delete an existing one + * @extends Modal + * @param {App} app - the Obsidian App + * @param {GitHubPublisherSettings} settings - the plugin settings + * @param {string} branchName - the branch name + * @param {GithubPublisherPlugin} plugin - the plugin + * @param {Repository[]} repository - the list of repo in the settings + * @param {(result: Repository[]) => void} onSubmit - the function to call when the modal is submitted + */ + +export class ModalAddingNewRepository extends Modal { + settings: GitHubPublisherSettings; + plugin: GithubPublisherPlugin; + branchName: string; + repository: Repository[]; + onSubmit: (result: Repository[]) => void; + + constructor( + app: App, + settings: GitHubPublisherSettings, + branchName: string, + plugin: GithubPublisherPlugin, + repository: Repository[], + onSubmit: (result: Repository[]) => void) { + super(app); + this.settings = settings; + this.repository = repository; + this.plugin = plugin; + this.onSubmit = onSubmit; + this.branchName = branchName; + } + + onOpen() { + const {contentEl} = this; + contentEl.empty(); + contentEl.createEl("h2", {text: i18next.t("settings.github.smartRepo.modals.title")}); + contentEl.createEl("p", {text: i18next.t("settings.github.smartRepo.modals.desc")}); + contentEl.createEl("p", {text: i18next.t("settings.github.smartRepo.modals.frontmatterInfo")}); + contentEl.createEl("p", {text: i18next.t("settings.plugin.shareKey.otherRepo")}); + + + const defaultRepository: Repository = { + smartKey: "", + user: this.settings.github.user, + repo: this.settings.github.repo, + branch: this.settings.github.branch, + automaticallyMergePR: this.settings.github.automaticallyMergePR, + api: { + tiersForApi: this.settings.github.api.tiersForApi, + hostname: this.settings.github.api.hostname, + }, + workflow: { + commitMessage: this.settings.github.workflow.commitMessage, + name: "", + }, + createShortcuts: false, + shareKey: this.settings.plugin.shareKey, + copyLink: { + links: this.settings.plugin.copyLink.links, + removePart: [] + } + }; + + new Setting(contentEl) + .addButton((button) => { + button + + .setButtonText(i18next.t("common.add", {things: i18next.t("settings.github.smartRepo.modals.newRepo").toLowerCase()})) + .onClick(() => { + this.repository.push(defaultRepository); + this.onOpen(); + }) + .buttonEl.style.width = "100%"; + }) + .infoEl.style.display = "none"; + + for (const repo of this.repository) { + new Setting(contentEl) + .addText((text) => { + text + .setPlaceholder("smartKey") + .setValue(repo.smartKey) + .onChange((value) => { + repo.smartKey = value.toLowerCase(); + if (this.plugin.settings.github.otherRepo.filter((r) => r.smartKey === repo.smartKey).length > 1) { + new Notice(i18next.t("settings.github.smartRepo.modals.duplicate")); + text.inputEl.style.border = "1px solid red"; + repo.smartKey = ""; + } else if (repo.smartKey === "default") { + text.inputEl.style.border = "1px solid red"; + repo.smartKey = ""; + new Notice(i18next.t("settings.github.smartRepo.modals.default") as string); + } else { + text.inputEl.style.border = "0"; + } + }) + .inputEl.style.width = "100%"; + + }) + + .addExtraButton((btn) => { + btn + .setIcon("trash") + .onClick(() => { + this.repository.splice(this.repository.indexOf(repo), 1); + this.onOpen(); + }); + }) + .addExtraButton((btn) => { + btn + .setIcon("pencil") + .onClick(() => { + new ModalEditingRepository(this.app, repo, this.plugin, this.branchName, (result) => { + this.repository[this.repository.indexOf(repo)] = result; + }).open(); + }); + }) + .infoEl.style.display = "none"; + + } + new Setting(contentEl) + .addButton((button) => { + button + .setButtonText(i18next.t("common.save")) + .onClick(() => { + this.onSubmit(this.repository); + this.close(); + }); + }); + } + onClose() { + const {contentEl} = this; + contentEl.empty(); + this.onSubmit(this.repository); + } +} + +/** + * @description Called by the ModalAddingNewRepository class, this class is used to edit an existing repo + * @extends Modal + * @param {App} app - The Obsidian App instance + * @param {Repository} repository - The repository to edit + * @param {GithubPublisherPlugin} GithubPublisherPlugin - The GithubPublisherPlugin instance + * @param {string} brancheName - The name of the branch (for validation) + * @param {function} onSubmit - The function to call when the modal is closed (to save the changes) + */ + +class ModalEditingRepository extends Modal { + repository: Repository; + branchName: string; + plugin: GithubPublisherPlugin; + onSubmit: (result: Repository) => void; + + constructor( + app: App, + repository: Repository, + GithubPublisherPlugin: GithubPublisherPlugin, + brancheName: string, + onSubmit: (result: Repository) => void) { + super(app); + this.repository = repository; + this.onSubmit = onSubmit; + this.branchName = brancheName; + this.plugin = GithubPublisherPlugin; + } + + onOpen() { + const {contentEl} = this; + contentEl.empty(); + contentEl.createEl("h2", {text: i18next.t("common.edit", {things: this.repository.smartKey})}); + + new Setting(contentEl) + .setName(i18next.t("settings.github.apiType.title")) + .setDesc(i18next.t("settings.github.apiType.desc")) + .addDropdown((dropdown) => { + dropdown + .addOption(GithubTiersVersion.free, i18next.t("settings.github.apiType.dropdown.free")) + .addOption(GithubTiersVersion.entreprise, i18next.t("settings.github.apiType.dropdown.enterprise")) + .setValue(this.repository.api.tiersForApi) + .onChange((value) => { + this.repository.api.tiersForApi = value as GithubTiersVersion; + this.onOpen(); + }); + }); + if (this.repository.api.tiersForApi === GithubTiersVersion.entreprise) { + new Setting(contentEl) + .setName(i18next.t("settings.github.apiType.hostname.title")) + .setDesc(i18next.t("settings.github.apiType.hostname.desc")) + .addText((text) => + text + .setPlaceholder("https://github.mycompany.com") + .setValue(this.repository.api.hostname) + .onChange(async (value) => { + this.repository.api.hostname = value.trim(); + }) + ); + } + new Setting(contentEl) + .setName(i18next.t("settings.github.repoName.title")) + .setDesc(i18next.t("settings.github.repoName.desc")) + .addText((text) => + text + .setPlaceholder(i18next.t("settings.github.repoName.placeholder")) + .setValue(this.repository.repo) + .onChange(async (value) => { + this.repository.repo = value.trim(); + }) + ); + new Setting(contentEl) + .setName(i18next.t("settings.github.username.title")) + .setDesc(i18next.t("settings.github.username.desc")) + .addText((text) => + text + .setPlaceholder( + i18next.t("settings.github.username.title") + ) + .setValue(this.repository.user) + .onChange(async (value) => { + this.repository.user = value.trim(); + }) + ); + new Setting(contentEl) + .setName(i18next.t("settings.github.branch.title")) + .setDesc(i18next.t("settings.github.branch.desc")) + .addText((text) => + text + .setPlaceholder("main") + .setValue(this.repository.branch) + .onChange(async (value) => { + this.repository.branch = value.trim(); + }) + ); + new Setting(contentEl) + .setName(i18next.t("settings.github.automaticallyMergePR")) + .addToggle((toggle) => + toggle + .setValue(this.repository.automaticallyMergePR) + .onChange(async (value) => { + this.repository.automaticallyMergePR = value; + }) + ); + new Setting(contentEl) + .setClass("github-publisher-no-display") + .addButton((button) => + button + .setButtonText(i18next.t("settings.github.testConnection")) + .setClass("github-publisher-connect-button") + .onClick(async () => { + await checkRepositoryValidity(this.branchName, this.plugin.reloadOctokit(), this.plugin.settings, this.repository, null, this.app.metadataCache); + }) + ); + new Setting(contentEl) + .setName(i18next.t("settings.github.smartRepo.modals.shortcuts.title")) + .setDesc(i18next.t("settings.github.smartRepo.modals.shortcuts.desc")) + .addToggle((toggle) => + toggle + .setValue(this.repository.createShortcuts) + .onChange(async (value) => { + this.repository.createShortcuts = value; + }) + ); + + contentEl.createEl("h3", { text: "Github Workflow" }); + new Setting(contentEl) + .setName(i18next.t("settings.githubWorkflow.prRequest.title")) + .setDesc(i18next.t("settings.githubWorkflow.prRequest.desc")) + .addText((text) => + text + .setPlaceholder("[PUBLISHER] MERGE") + .setValue(this.repository.workflow.commitMessage) + .onChange(async (value) => { + if (value.trim().length === 0) { + value = "[PUBLISHER] MERGE"; + new Notice(i18next.t("settings.githubWorkflow.prRequest.error")); + } + this.repository.workflow.commitMessage = value; + }) + ); + new Setting(contentEl) + .setName(i18next.t("settings.githubWorkflow.githubAction.title")) + .setDesc( + i18next.t("settings.githubWorkflow.githubAction.desc") + ) + .addText((text) => { + text.setPlaceholder("ci") + .setValue(this.repository.workflow.name) + .onChange(async (value) => { + if (value.length > 0) { + value = value.trim(); + const yamlEndings = [".yml", ".yaml"]; + if (! yamlEndings.some(ending => value.endsWith(ending))) { + value += yamlEndings[0]; + } + } + this.repository.workflow.name = value; + }); + }); + + contentEl.createEl("h3", { text: i18next.t("settings.github.smartRepo.modals.otherConfig") }); + + new Setting(contentEl) + .setName(i18next.t("settings.plugin.shareKey.title")) + .setDesc(i18next.t("settings.plugin.shareKey.desc")) + .addText((text) => + text + .setPlaceholder("share") + .setValue(this.repository.shareKey) + .onChange(async (value) => { + this.repository.shareKey = value.trim(); + await this.plugin.saveSettings(); + }) + ); + if (this.plugin.settings.plugin.copyLink.enable) { + new Setting(contentEl) + .setName(i18next.t("settings.plugin.copyLink.baselink.title")) + .setDesc(i18next.t("settings.plugin.copyLink.baselink.desc")) + .setClass("github-publisher") + .addText((text) => + text + .setPlaceholder(this.plugin.settings.plugin.copyLink.links) + .setValue(this.repository.copyLink.links) + .onChange(async (value) => { + this.repository.copyLink.links = value.trim(); + }) + ); + + new Setting(contentEl) + .setName(i18next.t("settings.plugin.copyLink.linkpathremover.title")) + .setDesc( + i18next.t("settings.plugin.copyLink.linkpathremover.desc") + ) + .setClass("github-publisher") + .addText((text) => { + text.setPlaceholder("docs") + .setValue(this.repository.copyLink.removePart.join(", ")) + .onChange(async (value) => { + this.repository.copyLink.removePart = value.split(/[,\n]\s*/).map((item) => item.trim()).filter((item) => item.length > 0); + await this.plugin.saveSettings(); + }); + }); + } + + new Setting(contentEl) + .addButton((button) => + button + .setButtonText(i18next.t("common.save")) + .onClick(async () => { + this.onSubmit(this.repository); + this.close(); + }) + ); + } + onClose() { + const {contentEl} = this; + contentEl.empty(); + this.onSubmit(this.repository); + } +} diff --git a/src/settings/modals/regex_edition.ts b/src/settings/modals/regex_edition.ts index 1437cef0..d981fa3c 100644 --- a/src/settings/modals/regex_edition.ts +++ b/src/settings/modals/regex_edition.ts @@ -1,279 +1,279 @@ -import {App, Notice, Modal, Setting} from "obsidian"; -import { FolderSettings, GitHubPublisherSettings, RegexReplace, TextCleaner, TypeOfEditRegex } from "../interface"; -import i18next from "i18next"; - -export class ModalRegexFilePathName extends Modal { - settings: GitHubPublisherSettings; - allRegex: RegexReplace[]; - onSubmit: (result: RegexReplace[]) => void; - constructor( - app: App, - settings: GitHubPublisherSettings, - allRegex : RegexReplace[], - onSubmit: (result: RegexReplace[]) => void) { - super(app); - this.allRegex = allRegex; - this.settings = settings; - this.onSubmit = onSubmit; - } - - classValue(allRegex: RegexReplace[]) { - this.settings.upload.replacePath = allRegex.filter((regex) => { - return regex.type === TypeOfEditRegex.path; - }); - this.settings.upload.replaceTitle = allRegex.filter((regex) => { - return regex.type === TypeOfEditRegex.title; - } - ); - } - - forbiddenValue(value: string, type: TypeOfEditRegex): (string|boolean)[] { - let onWhat = type === TypeOfEditRegex.path ? i18next.t("common.path.folder") : i18next.t("common.path.file"); - onWhat = onWhat.toLowerCase(); - let isForbidden = false; - if (value == "/") { - new Notice(i18next.t("settings.regexReplacing.forbiddenValue", {what: onWhat, forbiddenChar: value})); - value = ""; - isForbidden = true; - } - else if ( - (value.match(/[><:"|?*]|(\\\/)|(^\w+\/\w+)|(\\)/)) && (type === TypeOfEditRegex.title) - ) { - new Notice(i18next.t("settings.regexReplacing.forbiddenValue", {what: onWhat, forbiddenChar: value.match(/[><:"|?*]|(\\\/)|(^\w+\/\w+)|(\\)/)[0]})); - value = ""; - isForbidden = true; - } else if (type === TypeOfEditRegex.path) { - if (value.match(/[\\><:"|?*]/)){ - new Notice(i18next.t("settings.regexReplacing.forbiddenValue", { what: onWhat, forbiddenChar: value.match(/[\\><:"|?*]/)[0]})); - value = ""; - isForbidden = true; - } else if (value.match(/(^\w+\/\w+)|(\\\/)/)) { - new Notice(i18next.t("settings.regexReplacing.warningPath")); - } - } - return [value, isForbidden]; - } - - onOpen() { - const {contentEl} = this; - contentEl.empty(); - if (this.settings.upload.behavior === FolderSettings.fixed) { - contentEl.createEl("h2", { text: i18next.t("settings.regexReplacing.modal.title.only")}); - } else { - contentEl.createEl("h2", { text: i18next.t("settings.regexReplacing.modal.title.all")}); - } - if (!this.settings.upload.replacePath) { - this.settings.upload.replacePath = []; - } - else if (!this.settings.upload.replaceTitle) { - this.settings.upload.replaceTitle = []; - } - this.settings.upload.replacePath.forEach((title) => { - if (!title.type) { - title.type = TypeOfEditRegex.path; - } - }); - this.settings.upload.replaceTitle.forEach((title) => { - if (!title.type) { - title.type = TypeOfEditRegex.title; - } - }); - - for (const title of this.allRegex) { - const sett = new Setting(contentEl) - .setClass("github-publisher-censor-entry") - .addText((text) => { - text.inputEl.style.width = "100%"; - text.setPlaceholder(i18next.t("regex.entry")) - .setValue(title.regex) - .onChange((value) => { - title.regex = value; - }); - }) - .addText((text) => { - text.inputEl.style.width = "100%"; - text.setPlaceholder(i18next.t("regex.replace")) - .setValue(title.replacement) - .onChange((value) => { - title.replacement = value; - }); - }); - - if (this.settings.upload.behavior !== FolderSettings.fixed) { - sett.addDropdown((dropdown) => { - dropdown - .addOption("path", i18next.t("common.path.folder")) - .addOption("title", i18next.t("common.path.file")) - .setValue(title.type) - .onChange((value) => { - title.type = value as TypeOfEditRegex; - - }); - }); - } else { - sett - .addButton((button) => { - button.buttonEl.classList.add("github-publisher-disabled-button"); - button.setButtonText(i18next.t("common.path.file")); - }); - } - sett.addExtraButton((button) => { - button - .setIcon("trash") - .onClick(() => { - //remove replace - this.allRegex.splice(this.allRegex.indexOf(title), 1); - this.onOpen(); - }); - }); - } - new Setting(contentEl) - .setClass("github-publisher-modals") - .addButton((button) => { - button - .setIcon("plus") - .onClick(() => { - this.allRegex.push({ - regex: "", - replacement: "", - type: TypeOfEditRegex.title - }); - this.onOpen(); - }); - }) - .addButton((button) => { - button - .setButtonText(i18next.t("common.save")) - .onClick(() => { - const canBeValidated: boolean[] = []; - this.allRegex.forEach((title) => { - const isForbiddenEntry = this.forbiddenValue(title.regex, title.type); - const isForbiddenReplace = this.forbiddenValue(title.replacement, title.type); - canBeValidated.push(isForbiddenEntry[1] as boolean); - canBeValidated.push(isForbiddenReplace[1] as boolean); - if (isForbiddenEntry[1] || isForbiddenReplace[1]) { - title.regex = isForbiddenEntry[0] as string; - title.replacement = isForbiddenReplace[0] as string; - } - }); - if (!canBeValidated.includes(true)) { - this.onSubmit(this.allRegex); - this.close(); - } - }); - }); - } - - onClose() { - const {contentEl} = this; - contentEl.empty(); - } -} - -export class ModalRegexOnContents extends Modal { - settings: GitHubPublisherSettings; - onSubmit: (settings: GitHubPublisherSettings) => void; - constructor( - app: App, - settings: GitHubPublisherSettings, - onSubmit: (settings: GitHubPublisherSettings) => void) { - super(app); - this.settings = settings; - this.onSubmit = onSubmit; - } - - onOpen() { - const {contentEl} = this; - contentEl.empty(); - contentEl - .createEl("p", { - text: i18next.t("settings.regexReplacing.modal.title.text") , - }) - .createEl("p", { - text: i18next.t("settings.regexReplacing.modal.desc") , - }) - .createEl("p", { - text: i18next.t("settings.regexReplacing.empty")}); - for (const censorText of this.settings.conversion.censorText) { - const afterIcon = censorText.after ? "arrow-down" : "arrow-up"; - const moment = censorText.after ? i18next.t("common.after").toLowerCase() : i18next.t("common.before").toLowerCase(); - const desc = i18next.t("settings.regexReplacing.momentReplaceRegex", {moment: moment}); - new Setting(contentEl) - .setClass("github-publisher-censor-entry") - .addText((text) => { - text.inputEl.style.width = "100%"; - text.setPlaceholder(i18next.t( - "regex.entry") - ) - .setValue(censorText.entry) - .onChange(async (value) => { - censorText.entry = value; - }); - }) - .addText((text) => { - text.inputEl.style.width="100%"; - text.setPlaceholder(i18next.t("regex.replace")) - .setValue(censorText.replace) - .onChange(async (value) => { - censorText.replace = value; - }); - - }) - - .addExtraButton((btn) => { - btn.setIcon("trash") - .setTooltip(i18next.t("common.delete", {things: "Regex"})) - .onClick(async () => { - this.settings.conversion.censorText.splice( - this.settings.conversion.censorText.indexOf( - censorText - ), - 1 - ); - this.onOpen(); - }); - }) - .addExtraButton((btn) => { - btn - .setTooltip(desc) - .setIcon(afterIcon) - .onClick(async () => { - censorText.after = !censorText.after; - this.onOpen(); - }); - }); - - } - new Setting(contentEl) - .addButton((btn) => { - btn - .setIcon("plus") - .setTooltip(i18next.t("common.add", {things: "Regex"})) - - .onClick(async () => { - const censorText: TextCleaner = { - entry: "", - replace: "", - after: false, - }; - this.settings.conversion.censorText.push(censorText); - this.onOpen(); - }); - }) - .addButton((button) => { - button - .setButtonText(i18next.t("common.save")) - .onClick(() => { - this.onSubmit(this.settings); - this.close(); - }); - }); - } - - onClose() { - const {contentEl} = this; - contentEl.empty(); - } -} - - +import {App, Notice, Modal, Setting} from "obsidian"; +import { FolderSettings, GitHubPublisherSettings, RegexReplace, TextCleaner, TypeOfEditRegex } from "../interface"; +import i18next from "i18next"; + +export class ModalRegexFilePathName extends Modal { + settings: GitHubPublisherSettings; + allRegex: RegexReplace[]; + onSubmit: (result: RegexReplace[]) => void; + constructor( + app: App, + settings: GitHubPublisherSettings, + allRegex : RegexReplace[], + onSubmit: (result: RegexReplace[]) => void) { + super(app); + this.allRegex = allRegex; + this.settings = settings; + this.onSubmit = onSubmit; + } + + classValue(allRegex: RegexReplace[]) { + this.settings.upload.replacePath = allRegex.filter((regex) => { + return regex.type === TypeOfEditRegex.path; + }); + this.settings.upload.replaceTitle = allRegex.filter((regex) => { + return regex.type === TypeOfEditRegex.title; + } + ); + } + + forbiddenValue(value: string, type: TypeOfEditRegex): (string|boolean)[] { + let onWhat = type === TypeOfEditRegex.path ? i18next.t("common.path.folder") : i18next.t("common.path.file"); + onWhat = onWhat.toLowerCase(); + let isForbidden = false; + if (value == "/") { + new Notice(i18next.t("settings.regexReplacing.forbiddenValue", {what: onWhat, forbiddenChar: value})); + value = ""; + isForbidden = true; + } + else if ( + (value.match(/[><:"|?*]|(\\\/)|(^\w+\/\w+)|(\\)/)) && (type === TypeOfEditRegex.title) + ) { + new Notice(i18next.t("settings.regexReplacing.forbiddenValue", {what: onWhat, forbiddenChar: value.match(/[><:"|?*]|(\\\/)|(^\w+\/\w+)|(\\)/)[0]})); + value = ""; + isForbidden = true; + } else if (type === TypeOfEditRegex.path) { + if (value.match(/[\\><:"|?*]/)){ + new Notice(i18next.t("settings.regexReplacing.forbiddenValue", { what: onWhat, forbiddenChar: value.match(/[\\><:"|?*]/)[0]})); + value = ""; + isForbidden = true; + } else if (value.match(/(^\w+\/\w+)|(\\\/)/)) { + new Notice(i18next.t("settings.regexReplacing.warningPath")); + } + } + return [value, isForbidden]; + } + + onOpen() { + const {contentEl} = this; + contentEl.empty(); + if (this.settings.upload.behavior === FolderSettings.fixed) { + contentEl.createEl("h2", { text: i18next.t("settings.regexReplacing.modal.title.only")}); + } else { + contentEl.createEl("h2", { text: i18next.t("settings.regexReplacing.modal.title.all")}); + } + if (!this.settings.upload.replacePath) { + this.settings.upload.replacePath = []; + } + else if (!this.settings.upload.replaceTitle) { + this.settings.upload.replaceTitle = []; + } + this.settings.upload.replacePath.forEach((title) => { + if (!title.type) { + title.type = TypeOfEditRegex.path; + } + }); + this.settings.upload.replaceTitle.forEach((title) => { + if (!title.type) { + title.type = TypeOfEditRegex.title; + } + }); + + for (const title of this.allRegex) { + const sett = new Setting(contentEl) + .setClass("github-publisher-censor-entry") + .addText((text) => { + text.inputEl.style.width = "100%"; + text.setPlaceholder(i18next.t("regex.entry")) + .setValue(title.regex) + .onChange((value) => { + title.regex = value; + }); + }) + .addText((text) => { + text.inputEl.style.width = "100%"; + text.setPlaceholder(i18next.t("regex.replace")) + .setValue(title.replacement) + .onChange((value) => { + title.replacement = value; + }); + }); + + if (this.settings.upload.behavior !== FolderSettings.fixed) { + sett.addDropdown((dropdown) => { + dropdown + .addOption("path", i18next.t("common.path.folder")) + .addOption("title", i18next.t("common.path.file")) + .setValue(title.type) + .onChange((value) => { + title.type = value as TypeOfEditRegex; + + }); + }); + } else { + sett + .addButton((button) => { + button.buttonEl.classList.add("github-publisher-disabled-button"); + button.setButtonText(i18next.t("common.path.file")); + }); + } + sett.addExtraButton((button) => { + button + .setIcon("trash") + .onClick(() => { + //remove replace + this.allRegex.splice(this.allRegex.indexOf(title), 1); + this.onOpen(); + }); + }); + } + new Setting(contentEl) + .setClass("github-publisher-modals") + .addButton((button) => { + button + .setIcon("plus") + .onClick(() => { + this.allRegex.push({ + regex: "", + replacement: "", + type: TypeOfEditRegex.title + }); + this.onOpen(); + }); + }) + .addButton((button) => { + button + .setButtonText(i18next.t("common.save")) + .onClick(() => { + const canBeValidated: boolean[] = []; + this.allRegex.forEach((title) => { + const isForbiddenEntry = this.forbiddenValue(title.regex, title.type); + const isForbiddenReplace = this.forbiddenValue(title.replacement, title.type); + canBeValidated.push(isForbiddenEntry[1] as boolean); + canBeValidated.push(isForbiddenReplace[1] as boolean); + if (isForbiddenEntry[1] || isForbiddenReplace[1]) { + title.regex = isForbiddenEntry[0] as string; + title.replacement = isForbiddenReplace[0] as string; + } + }); + if (!canBeValidated.includes(true)) { + this.onSubmit(this.allRegex); + this.close(); + } + }); + }); + } + + onClose() { + const {contentEl} = this; + contentEl.empty(); + } +} + +export class ModalRegexOnContents extends Modal { + settings: GitHubPublisherSettings; + onSubmit: (settings: GitHubPublisherSettings) => void; + constructor( + app: App, + settings: GitHubPublisherSettings, + onSubmit: (settings: GitHubPublisherSettings) => void) { + super(app); + this.settings = settings; + this.onSubmit = onSubmit; + } + + onOpen() { + const {contentEl} = this; + contentEl.empty(); + contentEl + .createEl("p", { + text: i18next.t("settings.regexReplacing.modal.title.text") , + }) + .createEl("p", { + text: i18next.t("settings.regexReplacing.modal.desc") , + }) + .createEl("p", { + text: i18next.t("settings.regexReplacing.empty")}); + for (const censorText of this.settings.conversion.censorText) { + const afterIcon = censorText.after ? "arrow-down" : "arrow-up"; + const moment = censorText.after ? i18next.t("common.after").toLowerCase() : i18next.t("common.before").toLowerCase(); + const desc = i18next.t("settings.regexReplacing.momentReplaceRegex", {moment: moment}); + new Setting(contentEl) + .setClass("github-publisher-censor-entry") + .addText((text) => { + text.inputEl.style.width = "100%"; + text.setPlaceholder(i18next.t( + "regex.entry") + ) + .setValue(censorText.entry) + .onChange(async (value) => { + censorText.entry = value; + }); + }) + .addText((text) => { + text.inputEl.style.width="100%"; + text.setPlaceholder(i18next.t("regex.replace")) + .setValue(censorText.replace) + .onChange(async (value) => { + censorText.replace = value; + }); + + }) + + .addExtraButton((btn) => { + btn.setIcon("trash") + .setTooltip(i18next.t("common.delete", {things: "Regex"})) + .onClick(async () => { + this.settings.conversion.censorText.splice( + this.settings.conversion.censorText.indexOf( + censorText + ), + 1 + ); + this.onOpen(); + }); + }) + .addExtraButton((btn) => { + btn + .setTooltip(desc) + .setIcon(afterIcon) + .onClick(async () => { + censorText.after = !censorText.after; + this.onOpen(); + }); + }); + + } + new Setting(contentEl) + .addButton((btn) => { + btn + .setIcon("plus") + .setTooltip(i18next.t("common.add", {things: "Regex"})) + + .onClick(async () => { + const censorText: TextCleaner = { + entry: "", + replace: "", + after: false, + }; + this.settings.conversion.censorText.push(censorText); + this.onOpen(); + }); + }) + .addButton((button) => { + button + .setButtonText(i18next.t("common.save")) + .onClick(() => { + this.onSubmit(this.settings); + this.close(); + }); + }); + } + + onClose() { + const {contentEl} = this; + contentEl.empty(); + } +} + + diff --git a/src/settings/style.ts b/src/settings/style.ts index 5c4ccbdb..04835b7b 100644 --- a/src/settings/style.ts +++ b/src/settings/style.ts @@ -1,179 +1,179 @@ -import { Setting } from "obsidian"; -import GithubPublisherPlugin from "../main"; -import {FolderSettings, GitHubPublisherSettings} from "./interface"; -/** - * show a settings - * @param {Setting} containerEl setting to show - */ - -export function showSettings(containerEl: Setting) { - for (const [type, elem] of Object.entries(containerEl)) { - if (type != "components") { - elem.show(); - } - } -} - - -/** - * Hide a settings - * @param {Setting} containerEl settings to hide - */ - -export function hideSettings(containerEl: Setting) { - for (const [type, elem] of Object.entries(containerEl)) { - if (type != "components") { - elem.hide(); - } - } -} - - -export function showHideBasedOnFolder(settings: GitHubPublisherSettings, frontmatterKeySettings: Setting, rootFolderSettings: Setting, folderNoteSettings: Setting) { - const upload = settings.upload; - if (upload.behavior === FolderSettings.yaml) { - showSettings(frontmatterKeySettings); - showSettings(rootFolderSettings); - showSettings(folderNoteSettings); - } else { - hideSettings(frontmatterKeySettings); - hideSettings(rootFolderSettings); - if ( - upload.behavior === - FolderSettings.obsidian - ) { - showSettings(folderNoteSettings); - } else { - hideSettings(folderNoteSettings); - } - } -} - - -/** - * Show or hide the autoclean settings - * @param {string} value - * @param {Setting} autoCleanSetting - * @param {GithubPublisher} plugin - * @return {Promise} - */ - -export async function autoCleanCondition( - value: string, - autoCleanSetting: Setting, - plugin: GithubPublisherPlugin -) { - const settings = plugin.settings.upload; - if (value.length === 0 && settings.defaultName) { - settings.autoclean.enable = false; - await plugin.saveSettings(); - autoCleanSetting.setDisabled(true); - // @ts-ignore - autoCleanSetting.components[0].toggleEl.classList.remove("is-enabled"); - } else if ( - value.length === 0 && - settings.behavior !== FolderSettings.yaml - ) { - settings.autoclean.enable = false; - autoCleanSetting.setDisabled(true); - // @ts-ignore - autoCleanSetting.components[0].toggleEl.classList.remove("is-enabled"); - } else { - autoCleanSetting.setDisabled(false); - if (settings.autoclean.enable) { - // @ts-ignore - autoCleanSetting.components[0].toggleEl.classList.add("is-enabled"); - } - } -} - -/** - * Show or hide settings based on the value of the folder settings - * Will : - * @example - * If the settings is set to YAML: - * - Show the frontmatterKey setting (to set the category key) - * - Show the rootFolder settings - * - Check the condition to show or hide the autoClean settings (with checking the length of the defaultFolder) - * - * @example - * - If obsidian path or fixed folder : hide the frontmatterKey setting and the rootFolder settings - * @param {Setting} frontmatterKeySettings - * @param {Setting} rootFolderSettings - * @param {Setting} autoCleanSetting - * @param {string} value - * @param {GithubPublisher} plugin - * @return {Promise} - */ - -export async function folderHideShowSettings( - frontmatterKeySettings: Setting, - rootFolderSettings: Setting, - autoCleanSetting: Setting, - value: string, - plugin: GithubPublisherPlugin, -) { - const settings = plugin.settings.upload; - if (value === FolderSettings.yaml) { - showSettings(frontmatterKeySettings); - showSettings(rootFolderSettings); - autoCleanCondition( - settings.rootFolder, - autoCleanSetting, - plugin - ).then(); - } else { - if (settings.defaultName.length > 0) { - autoCleanSetting.setDisabled(false); - if (settings.autoclean.enable) { - // @ts-ignore - autoCleanSetting.components[0].toggleEl.classList.add( - "is-enabled" - ); - } - } - hideSettings(frontmatterKeySettings); - hideSettings(rootFolderSettings); - } -} - -/** - * show or hide with disabling the autoclean settings based on the condition - * @param {boolean} condition - * @param {Setting} autoCleanSetting - * @param {GithubPublisher} plugin - */ - -export function autoCleanUpSettingsOnCondition( - condition: boolean, - autoCleanSetting: Setting, - plugin: GithubPublisherPlugin -) { - const settings = plugin.settings.upload; - if (condition) { - autoCleanSetting.setDisabled(true); - // @ts-ignore - autoCleanSetting.components[0].toggleEl.classList.remove("is-enabled"); - settings.autoclean.enable = false; - plugin.saveSettings().then(); - } else { - autoCleanSetting.setDisabled(false); - if (settings.autoclean.enable) { - // @ts-ignore - autoCleanSetting.components[0].toggleEl.classList.add("is-enabled"); - } - } -} - -/** - * Show or hide the settings based on the condition - * @param {string | boolean} condition - * @param {Setting} toDisplay the Settings to display - */ - -export function shortcutsHideShow( - condition: string | boolean, - toDisplay: Setting -) { - condition ? showSettings(toDisplay) : hideSettings(toDisplay); -} +import { Setting } from "obsidian"; +import GithubPublisherPlugin from "../main"; +import {FolderSettings, GitHubPublisherSettings} from "./interface"; +/** + * show a settings + * @param {Setting} containerEl setting to show + */ + +export function showSettings(containerEl: Setting) { + for (const [type, elem] of Object.entries(containerEl)) { + if (type != "components") { + elem.show(); + } + } +} + + +/** + * Hide a settings + * @param {Setting} containerEl settings to hide + */ + +export function hideSettings(containerEl: Setting) { + for (const [type, elem] of Object.entries(containerEl)) { + if (type != "components") { + elem.hide(); + } + } +} + + +export function showHideBasedOnFolder(settings: GitHubPublisherSettings, frontmatterKeySettings: Setting, rootFolderSettings: Setting, folderNoteSettings: Setting) { + const upload = settings.upload; + if (upload.behavior === FolderSettings.yaml) { + showSettings(frontmatterKeySettings); + showSettings(rootFolderSettings); + showSettings(folderNoteSettings); + } else { + hideSettings(frontmatterKeySettings); + hideSettings(rootFolderSettings); + if ( + upload.behavior === + FolderSettings.obsidian + ) { + showSettings(folderNoteSettings); + } else { + hideSettings(folderNoteSettings); + } + } +} + + +/** + * Show or hide the autoclean settings + * @param {string} value + * @param {Setting} autoCleanSetting + * @param {GithubPublisher} plugin + * @return {Promise} + */ + +export async function autoCleanCondition( + value: string, + autoCleanSetting: Setting, + plugin: GithubPublisherPlugin +) { + const settings = plugin.settings.upload; + if (value.length === 0 && settings.defaultName) { + settings.autoclean.enable = false; + await plugin.saveSettings(); + autoCleanSetting.setDisabled(true); + // @ts-ignore + autoCleanSetting.components[0].toggleEl.classList.remove("is-enabled"); + } else if ( + value.length === 0 && + settings.behavior !== FolderSettings.yaml + ) { + settings.autoclean.enable = false; + autoCleanSetting.setDisabled(true); + // @ts-ignore + autoCleanSetting.components[0].toggleEl.classList.remove("is-enabled"); + } else { + autoCleanSetting.setDisabled(false); + if (settings.autoclean.enable) { + // @ts-ignore + autoCleanSetting.components[0].toggleEl.classList.add("is-enabled"); + } + } +} + +/** + * Show or hide settings based on the value of the folder settings + * Will : + * @example + * If the settings is set to YAML: + * - Show the frontmatterKey setting (to set the category key) + * - Show the rootFolder settings + * - Check the condition to show or hide the autoClean settings (with checking the length of the defaultFolder) + * + * @example + * - If obsidian path or fixed folder : hide the frontmatterKey setting and the rootFolder settings + * @param {Setting} frontmatterKeySettings + * @param {Setting} rootFolderSettings + * @param {Setting} autoCleanSetting + * @param {string} value + * @param {GithubPublisher} plugin + * @return {Promise} + */ + +export async function folderHideShowSettings( + frontmatterKeySettings: Setting, + rootFolderSettings: Setting, + autoCleanSetting: Setting, + value: string, + plugin: GithubPublisherPlugin, +) { + const settings = plugin.settings.upload; + if (value === FolderSettings.yaml) { + showSettings(frontmatterKeySettings); + showSettings(rootFolderSettings); + autoCleanCondition( + settings.rootFolder, + autoCleanSetting, + plugin + ).then(); + } else { + if (settings.defaultName.length > 0) { + autoCleanSetting.setDisabled(false); + if (settings.autoclean.enable) { + // @ts-ignore + autoCleanSetting.components[0].toggleEl.classList.add( + "is-enabled" + ); + } + } + hideSettings(frontmatterKeySettings); + hideSettings(rootFolderSettings); + } +} + +/** + * show or hide with disabling the autoclean settings based on the condition + * @param {boolean} condition + * @param {Setting} autoCleanSetting + * @param {GithubPublisher} plugin + */ + +export function autoCleanUpSettingsOnCondition( + condition: boolean, + autoCleanSetting: Setting, + plugin: GithubPublisherPlugin +) { + const settings = plugin.settings.upload; + if (condition) { + autoCleanSetting.setDisabled(true); + // @ts-ignore + autoCleanSetting.components[0].toggleEl.classList.remove("is-enabled"); + settings.autoclean.enable = false; + plugin.saveSettings().then(); + } else { + autoCleanSetting.setDisabled(false); + if (settings.autoclean.enable) { + // @ts-ignore + autoCleanSetting.components[0].toggleEl.classList.add("is-enabled"); + } + } +} + +/** + * Show or hide the settings based on the condition + * @param {string | boolean} condition + * @param {Setting} toDisplay the Settings to display + */ + +export function shortcutsHideShow( + condition: string | boolean, + toDisplay: Setting +) { + condition ? showSettings(toDisplay) : hideSettings(toDisplay); +}