diff --git a/src/commands/Article.ts b/src/commands/Article.ts index c9acb4de..f0c34dce 100644 --- a/src/commands/Article.ts +++ b/src/commands/Article.ts @@ -109,7 +109,6 @@ export class Article { * Sets the article lastmod date */ public static async setLastModifiedDate() { - const config = Settings.getConfig(); const editor = vscode.window.activeTextEditor; if (!editor) { return; @@ -121,7 +120,7 @@ export class Article { } const cloneArticle = Object.assign({}, article); - const dateField = config.get(SETTING_MODIFIED_FIELD) as string || DefaultFields.LastModified; + const dateField = Settings.get(SETTING_MODIFIED_FIELD) as string || DefaultFields.LastModified; try { cloneArticle.data[dateField] = Article.formatDate(new Date()); @@ -135,11 +134,10 @@ export class Article { * Generate the slug based on the article title */ public static async generateSlug() { - const config = Settings.getConfig(); - const prefix = config.get(SETTING_SLUG_PREFIX) as string; - const suffix = config.get(SETTING_SLUG_SUFFIX) as string; - const updateFileName = config.get(SETTING_SLUG_UPDATE_FILE_NAME) as string; - const filePrefix = config.get(SETTING_TEMPLATES_PREFIX); + const prefix = Settings.get(SETTING_SLUG_PREFIX) as string; + const suffix = Settings.get(SETTING_SLUG_SUFFIX) as string; + const updateFileName = Settings.get(SETTING_SLUG_UPDATE_FILE_NAME) as string; + const filePrefix = Settings.get(SETTING_TEMPLATES_PREFIX); const editor = vscode.window.activeTextEditor; if (!editor) { @@ -217,8 +215,7 @@ export class Article { const editor = vscode.window.activeTextEditor; if (txtChanges.length > 0 && editor && ArticleHelper.isMarkdownFile()) { - const config = Settings.getConfig(); - const autoUpdate = config.get(SETTING_AUTO_UPDATE_DATE); + const autoUpdate = Settings.get(SETTING_AUTO_UPDATE_DATE); if (autoUpdate) { const article = ArticleHelper.getFrontMatter(editor); @@ -241,8 +238,7 @@ export class Article { * Format the date to the defined format */ public static formatDate(dateValue: Date) { - const config = Settings.getConfig(); - const dateFormat = config.get(SETTING_DATE_FORMAT) as string; + const dateFormat = Settings.get(SETTING_DATE_FORMAT) as string; if (dateFormat && typeof dateFormat === "string") { return format(dateValue, dateFormat); diff --git a/src/commands/Dashboard.ts b/src/commands/Dashboard.ts index 21bc4898..d0674449 100644 --- a/src/commands/Dashboard.ts +++ b/src/commands/Dashboard.ts @@ -40,8 +40,7 @@ export class Dashboard { * Init the dashboard */ public static async init() { - const config = SettingsHelper.getConfig(); - const openOnStartup = config.get(SETTINGS_DASHBOARD_OPENONSTART); + const openOnStartup = SettingsHelper.get(SETTINGS_DASHBOARD_OPENONSTART); if (openOnStartup) { Dashboard.open(); } @@ -116,16 +115,10 @@ export class Dashboard { panel.getMediaSelection(); }); - workspace.onDidChangeConfiguration(() => { + SettingsHelper.onConfigChange((global?: any) => { Dashboard.getSettings(); }); - workspace.onDidChangeTextDocument((e) => { - if (e.document.fileName === "frontmatter.json") { - console.log("frontmatter.json changed"); - } - }); - Dashboard.webview.webview.onDidReceiveMessage(async (msg) => { switch(msg.command) { case DashboardMessage.getViewType: @@ -195,7 +188,6 @@ export class Dashboard { */ private static async getSettings() { const ext = Extension.getInstance(); - const config = SettingsHelper.getConfig(); const wsFolder = Folders.getWorkspaceFolder(); Dashboard.postWebviewMessage({ @@ -203,12 +195,12 @@ export class Dashboard { data: { beta: ext.isBetaVersion(), wsFolder: wsFolder ? wsFolder.fsPath : '', - staticFolder: config.get(SETTINGS_CONTENT_STATIC_FOLDERS), + staticFolder: SettingsHelper.get(SETTINGS_CONTENT_STATIC_FOLDERS), folders: Folders.get(), initialized: await Template.isInitialized(), tags: SettingsHelper.getTaxonomy(TaxonomyType.Tag), categories: SettingsHelper.getTaxonomy(TaxonomyType.Category), - openOnStart: config.get(SETTINGS_DASHBOARD_OPENONSTART), + openOnStart: SettingsHelper.get(SETTINGS_DASHBOARD_OPENONSTART), versionInfo: ext.getVersion(), pageViewType: await ext.getState(EXTENSION_STATE_PAGES_VIEW) } as Settings @@ -219,7 +211,7 @@ export class Dashboard { * Update a setting from the dashboard */ private static async updateSetting(data: { name: string, value: any }) { - await SettingsHelper.updateSetting(data.name, data.value); + await SettingsHelper.update(data.name, data.value); Dashboard.getSettings(); } @@ -228,8 +220,7 @@ export class Dashboard { */ private static async getMedia(page: number = 0, folder: string = '') { const wsFolder = Folders.getWorkspaceFolder(); - const config = SettingsHelper.getConfig(); - const staticFolder = config.get(SETTINGS_CONTENT_STATIC_FOLDERS); + const staticFolder = SettingsHelper.get(SETTINGS_CONTENT_STATIC_FOLDERS); if (Dashboard.media.length === 0) { const contentFolder = Folders.get(); @@ -313,12 +304,11 @@ export class Dashboard { * Retrieve all the markdown pages */ private static async getPages() { - const config = SettingsHelper.getConfig(); const wsFolder = Folders.getWorkspaceFolder(); - const descriptionField = config.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description; - const dateField = config.get(SETTING_DATE_FIELD) as string || DefaultFields.PublishingDate; - const staticFolder = config.get(SETTINGS_CONTENT_STATIC_FOLDERS); + const descriptionField = SettingsHelper.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description; + const dateField = SettingsHelper.get(SETTING_DATE_FIELD) as string || DefaultFields.PublishingDate; + const staticFolder = SettingsHelper.get(SETTINGS_CONTENT_STATIC_FOLDERS); const folderInfo = await Folders.getInfo(); const pages: Page[] = []; @@ -404,8 +394,7 @@ export class Dashboard { private static async saveFile({fileName, contents, folder}: { fileName: string; contents: string; folder: string | null }) { if (fileName && contents) { const wsFolder = Folders.getWorkspaceFolder(); - const config = SettingsHelper.getConfig(); - const staticFolder = config.get(SETTINGS_CONTENT_STATIC_FOLDERS); + const staticFolder = SettingsHelper.get(SETTINGS_CONTENT_STATIC_FOLDERS); const wsPath = wsFolder ? wsFolder.fsPath : ""; let absFolderPath = join(wsPath, staticFolder || "", folder || ""); diff --git a/src/commands/Folders.ts b/src/commands/Folders.ts index e89f394a..61f7ca15 100644 --- a/src/commands/Folders.ts +++ b/src/commands/Folders.ts @@ -197,9 +197,8 @@ export class Folders { * @returns */ public static get(): ContentFolder[] { - const config = Settings.getConfig(); const wsFolder = Folders.getWorkspaceFolder(); - const folders: ContentFolder[] = config.get(SETTINGS_CONTENT_PAGE_FOLDERS) as ContentFolder[]; + const folders: ContentFolder[] = Settings.get(SETTINGS_CONTENT_PAGE_FOLDERS) as ContentFolder[]; return folders.map(folder => ({ title: folder.title, @@ -212,9 +211,8 @@ export class Folders { * @param folders */ private static async update(folders: ContentFolder[]) { - const config = Settings.getConfig(); const wsFolder = Folders.getWorkspaceFolder(); - await config.update(SETTINGS_CONTENT_PAGE_FOLDERS, folders.map(folder => ({ title: folder.title, path: Folders.relWsFolder(folder, wsFolder) }))); + await Settings.update(SETTINGS_CONTENT_PAGE_FOLDERS, folders.map(folder => ({ title: folder.title, path: Folders.relWsFolder(folder, wsFolder) }))); } /** diff --git a/src/commands/Preview.ts b/src/commands/Preview.ts index 36a7d3d3..298078ac 100644 --- a/src/commands/Preview.ts +++ b/src/commands/Preview.ts @@ -124,10 +124,8 @@ export class Preview { * Retrieve all settings related to the preview command */ public static getSettings(): PreviewSettings { - - const config = Settings.getConfig(); - const host = config.get(SETTING_PREVIEW_HOST); - const pathname = config.get(SETTING_PREVIEW_PATHNAME); + const host = Settings.get(SETTING_PREVIEW_HOST); + const pathname = Settings.get(SETTING_PREVIEW_PATHNAME); return { host, diff --git a/src/commands/Settings.ts b/src/commands/Settings.ts index 5995267e..e6e51e62 100644 --- a/src/commands/Settings.ts +++ b/src/commands/Settings.ts @@ -22,9 +22,8 @@ export class Settings { }); if (newOption) { - const config = SettingsHelper.getConfig(); const configSetting = type === TaxonomyType.Tag ? SETTING_TAXONOMY_TAGS : SETTING_TAXONOMY_CATEGORIES; - let options = config.get(configSetting) as string[]; + let options = SettingsHelper.get(configSetting) as string[]; if (!options) { options = []; } @@ -35,7 +34,7 @@ export class Settings { } options.push(newOption); - await SettingsHelper.update(type, options); + await SettingsHelper.updateTaxonomy(type, options); // Ask if the new term needs to be added to the page const addToPage = await vscode.window.showQuickPick(["yes", "no"], { canPickMany: false, placeHolder: `Do you want to add the new ${type === TaxonomyType.Tag ? "tag" : "category"} to the page?` }); @@ -72,8 +71,6 @@ export class Settings { * Export the tags/categories front matter to the user settings */ public static async export() { - const config = SettingsHelper.getConfig(); - // Retrieve all the Markdown files const allMdFiles = await FilesHelper.getMdFiles(); if (!allMdFiles) { @@ -128,22 +125,22 @@ export class Settings { } // Retrieve the currently known tags, and add the new ones - let crntTags: string[] = config.get(SETTING_TAXONOMY_TAGS) as string[]; + let crntTags: string[] = SettingsHelper.get(SETTING_TAXONOMY_TAGS) as string[]; if (!crntTags) { crntTags = []; } crntTags = [...crntTags, ...tags]; // Update the tags and filter out the duplicates crntTags = [...new Set(crntTags)]; crntTags = crntTags.sort().filter(t => !!t); - await config.update(SETTING_TAXONOMY_TAGS, crntTags); + await SettingsHelper.update(SETTING_TAXONOMY_TAGS, crntTags); // Retrieve the currently known tags, and add the new ones - let crntCategories: string[] = config.get(SETTING_TAXONOMY_CATEGORIES) as string[]; + let crntCategories: string[] = SettingsHelper.get(SETTING_TAXONOMY_CATEGORIES) as string[]; if (!crntCategories) { crntCategories = []; } crntCategories = [...crntCategories, ...categories]; // Update the categories and filter out the duplicates crntCategories = [...new Set(crntCategories)]; crntCategories = crntCategories.sort().filter(c => !!c); - await config.update(SETTING_TAXONOMY_CATEGORIES, crntCategories); + await SettingsHelper.update(SETTING_TAXONOMY_CATEGORIES, crntCategories); // Done Notifications.info(`Export completed. Tags: ${crntTags.length} - Categories: ${crntCategories.length}.`); @@ -269,7 +266,7 @@ export class Settings { // Remove the selected option options = options.filter(o => o !== selectedOption); } - await SettingsHelper.update(type, options); + await SettingsHelper.updateTaxonomy(type, options); Notifications.info(`${newOptionValue ? "Remapping" : "Deleation"} of the ${selectedOption} ${type === TaxonomyType.Tag ? "tag" : "category"} completed.`); }); diff --git a/src/commands/StatusListener.ts b/src/commands/StatusListener.ts index aaa1e670..00ed1b6f 100644 --- a/src/commands/StatusListener.ts +++ b/src/commands/StatusListener.ts @@ -37,10 +37,9 @@ export class StatusListener { collection.clear(); // Retrieve the SEO config properties - const config = Settings.getConfig(); - const titleLength = config.get(SETTING_SEO_TITLE_LENGTH) as number || -1; - const descLength = config.get(SETTING_SEO_DESCRIPTION_LENGTH) as number || -1; - const fieldName = config.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description; + const titleLength = Settings.get(SETTING_SEO_TITLE_LENGTH) as number || -1; + const descLength = Settings.get(SETTING_SEO_DESCRIPTION_LENGTH) as number || -1; + const fieldName = Settings.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description; if (article.data.title && titleLength > -1) { SeoHelper.checkLength(editor, collection, article, "title", titleLength); diff --git a/src/commands/Template.ts b/src/commands/Template.ts index a0597c69..7c205a60 100644 --- a/src/commands/Template.ts +++ b/src/commands/Template.ts @@ -93,9 +93,8 @@ export class Template { * Create from a template */ public static async create(folderPath: string) { - const config = Settings.getConfig(); - const folder = config.get(SETTING_TEMPLATES_FOLDER); - const prefix = config.get(SETTING_TEMPLATES_PREFIX); + const folder = Settings.get(SETTING_TEMPLATES_FOLDER); + const prefix = Settings.get(SETTING_TEMPLATES_PREFIX); if (!folderPath) { Notifications.warning(`Incorrect project folder path retrieved.`); @@ -188,8 +187,7 @@ export class Template { * Get the folder settings */ public static getSettings() { - const config = Settings.getConfig(); - const folder = config.get(SETTING_TEMPLATES_FOLDER); + const folder = Settings.get(SETTING_TEMPLATES_FOLDER); return folder; } } \ No newline at end of file diff --git a/src/explorerView/ExplorerView.ts b/src/explorerView/ExplorerView.ts index 796ffab2..596bf3fb 100644 --- a/src/explorerView/ExplorerView.ts +++ b/src/explorerView/ExplorerView.ts @@ -204,16 +204,9 @@ export class ExplorerView implements WebviewViewProvider, Disposable { } }, this); - workspace.onDidChangeConfiguration(() => { + Settings.onConfigChange((global?: any) => { this.getSettings(); }); - - workspace.onDidChangeTextDocument((e) => { - console.log(e.document.fileName); - if (e.document.fileName === "frontmatter.json") { - console.log("frontmatter.json changed"); - } - }); } /** @@ -223,10 +216,9 @@ export class ExplorerView implements WebviewViewProvider, Disposable { public pushMetadata(metadata: any) { const wsFolder = Folders.getWorkspaceFolder(); const filePath = window.activeTextEditor?.document.uri.fsPath; - const config = Settings.getConfig(); - const commaSeparated = config.get(SETTING_COMMA_SEPARATED_FIELDS); - const staticFolder = config.get(SETTINGS_CONTENT_STATIC_FOLDERS); - const contentTypes = config.get(SETTING_TAXONOMY_CONTENT_TYPES); + const commaSeparated = Settings.get(SETTING_COMMA_SEPARATED_FIELDS); + const staticFolder = Settings.get(SETTINGS_CONTENT_STATIC_FOLDERS); + const contentTypes = Settings.get(SETTING_TAXONOMY_CONTENT_TYPES); const articleDetails = this.getArticleDetails(); @@ -338,8 +330,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable { * @param msg */ private runCustomScript(msg: { command: string, data: any}) { - const config = Settings.getConfig(); - const scripts: CustomScript[] | undefined = config.get(SETTING_CUSTOM_SCRIPTS); + const scripts: CustomScript[] | undefined = Settings.get(SETTING_CUSTOM_SCRIPTS); if (msg?.data?.title && msg?.data?.script && scripts) { const customScript = scripts.find((s: CustomScript) => s.title === msg.data.title); @@ -389,36 +380,34 @@ export class ExplorerView implements WebviewViewProvider, Disposable { * Retrieve the extension settings */ public async getSettings() { - const config = Settings.getConfig(); - this.postWebviewMessage({ command: Command.settings, data: { seo: { - title: config.get(SETTING_SEO_TITLE_LENGTH) as number || -1, - description: config.get(SETTING_SEO_DESCRIPTION_LENGTH) as number || -1, - content: config.get(SETTING_SEO_CONTENT_MIN_LENGTH) as number || -1, - descriptionField: config.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description + title: Settings.get(SETTING_SEO_TITLE_LENGTH) as number || -1, + description: Settings.get(SETTING_SEO_DESCRIPTION_LENGTH) as number || -1, + content: Settings.get(SETTING_SEO_CONTENT_MIN_LENGTH) as number || -1, + descriptionField: Settings.get(SETTING_SEO_DESCRIPTION_FIELD) as string || DefaultFields.Description }, slug: { - prefix: config.get(SETTING_SLUG_PREFIX) || "", - suffix: config.get(SETTING_SLUG_SUFFIX) || "", - updateFileName: !!config.get(SETTING_SLUG_UPDATE_FILE_NAME), + prefix: Settings.get(SETTING_SLUG_PREFIX) || "", + suffix: Settings.get(SETTING_SLUG_SUFFIX) || "", + updateFileName: !!Settings.get(SETTING_SLUG_UPDATE_FILE_NAME), }, date: { - format: config.get(SETTING_DATE_FORMAT) + format: Settings.get(SETTING_DATE_FORMAT) }, - tags: config.get(SETTING_TAXONOMY_TAGS) || [], - categories: config.get(SETTING_TAXONOMY_CATEGORIES) || [], - freeform: config.get(SETTING_PANEL_FREEFORM), - scripts: config.get(SETTING_CUSTOM_SCRIPTS), + tags: Settings.get(SETTING_TAXONOMY_TAGS) || [], + categories: Settings.get(SETTING_TAXONOMY_CATEGORIES) || [], + freeform: Settings.get(SETTING_PANEL_FREEFORM), + scripts: Settings.get(SETTING_CUSTOM_SCRIPTS), isInitialized: await Template.isInitialized(), - modifiedDateUpdate: config.get(SETTING_AUTO_UPDATE_DATE) || false, + modifiedDateUpdate: Settings.get(SETTING_AUTO_UPDATE_DATE) || false, writingSettingsEnabled: this.isWritingSettingsEnabled() || false, - fmHighlighting: config.get(SETTINGS_CONTENT_FRONTMATTER_HIGHLIGHT), + fmHighlighting: Settings.get(SETTINGS_CONTENT_FRONTMATTER_HIGHLIGHT), preview: Preview.getSettings(), - commaSeparatedFields: config.get(SETTING_COMMA_SEPARATED_FIELDS) || [], - contentTypes: config.get(SETTING_TAXONOMY_CONTENT_TYPES) || [], + commaSeparatedFields: Settings.get(SETTING_COMMA_SEPARATED_FIELDS) || [], + contentTypes: Settings.get(SETTING_TAXONOMY_CONTENT_TYPES) || [], dashboardViewData: Dashboard.viewData } as PanelSettings }); @@ -473,8 +462,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable { */ private async addTags(tagType: TagType, value: string) { if (value) { - const config = Settings.getConfig(); - let options = tagType === TagType.tags ? config.get(SETTING_TAXONOMY_TAGS) : config.get(SETTING_TAXONOMY_CATEGORIES); + let options = tagType === TagType.tags ? Settings.get(SETTING_TAXONOMY_TAGS) : Settings.get(SETTING_TAXONOMY_CATEGORIES); if (!options) { options = []; @@ -482,7 +470,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable { options.push(value); const taxType = tagType === TagType.tags ? TaxonomyType.Tag : TaxonomyType.Category; - await Settings.update(taxType, options); + await Settings.updateTaxonomy(taxType, options); } } @@ -581,8 +569,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable { * Update the preview URL */ private async updatePreviewUrl(previewUrl: string) { - const config = Settings.getConfig(); - await config.update(SETTING_PREVIEW_HOST, previewUrl); + await Settings.update(SETTING_PREVIEW_HOST, previewUrl); this.getSettings(); } @@ -590,8 +577,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable { * Toggle the Front Matter highlighting */ private async updateFmHighlight(autoUpdate: boolean) { - const config = Settings.getConfig(); - await config.update(SETTINGS_CONTENT_FRONTMATTER_HIGHLIGHT, autoUpdate); + await Settings.update(SETTINGS_CONTENT_FRONTMATTER_HIGHLIGHT, autoUpdate); this.getSettings(); } @@ -599,8 +585,7 @@ export class ExplorerView implements WebviewViewProvider, Disposable { * Toggle the modified auto-update setting */ private async updateModifiedUpdating(autoUpdate: boolean) { - const config = Settings.getConfig(); - await config.update(SETTING_AUTO_UPDATE_DATE, autoUpdate); + await Settings.update(SETTING_AUTO_UPDATE_DATE, autoUpdate); this.getSettings(); } diff --git a/src/extension.ts b/src/extension.ts index 1ade4a62..8986dbdc 100644 --- a/src/extension.ts +++ b/src/extension.ts @@ -12,6 +12,7 @@ import { TagType } from './panelWebView/TagType'; import { ExplorerView } from './explorerView/ExplorerView'; import { Extension } from './helpers/Extension'; import { DashboardData } from './models/DashboardData'; +import { Settings as SettingsHelper } from './helpers'; let frontMatterStatusBar: vscode.StatusBarItem; let statusDebouncer: { (fnc: any, time: number): void; }; @@ -23,6 +24,7 @@ const mdSelector: vscode.DocumentSelector = { language: 'markdown', scheme: 'fil export async function activate(context: vscode.ExtensionContext) { const { subscriptions, extensionUri, extensionPath } = context; + SettingsHelper.init(); const extension = Extension.getInstance(context); if (!extension.checkIfExtensionCanRun()) { @@ -120,7 +122,7 @@ export async function activate(context: vscode.ExtensionContext) { }); // Things to do when configuration changes - vscode.workspace.onDidChangeConfiguration(() => { + SettingsHelper.onConfigChange((global?: any) => { Template.init(); Preview.init(); diff --git a/src/helpers/ArticleHelper.ts b/src/helpers/ArticleHelper.ts index eb8e9dcf..83a1fcde 100644 --- a/src/helpers/ArticleHelper.ts +++ b/src/helpers/ArticleHelper.ts @@ -39,9 +39,8 @@ export class ArticleHelper { * @param article */ public static async update(editor: vscode.TextEditor, article: matter.GrayMatterFile) { - const config = Settings.getConfig(); - const removeQuotes = config.get(SETTING_REMOVE_QUOTES) as string[]; - const commaSeparated = config.get(SETTING_COMMA_SEPARATED_FIELDS); + const removeQuotes = Settings.get(SETTING_REMOVE_QUOTES) as string[]; + const commaSeparated = Settings.get(SETTING_COMMA_SEPARATED_FIELDS); let newMarkdown = this.stringifyFrontMatter(article.content, Object.assign({}, article.data)); @@ -72,9 +71,8 @@ export class ArticleHelper { * @param data */ public static stringifyFrontMatter(content: string, data: any) { - const config = Settings.getConfig(); - const indentArray = config.get(SETTING_INDENT_ARRAY) as boolean; - const commaSeparated = config.get(SETTING_COMMA_SEPARATED_FIELDS); + const indentArray = Settings.get(SETTING_INDENT_ARRAY) as boolean; + const commaSeparated = Settings.get(SETTING_COMMA_SEPARATED_FIELDS); const language = getFmLanguage(); const langOpts = getFormatOpts(language); @@ -114,9 +112,8 @@ export class ArticleHelper { return; } - const config = Settings.getConfig(); - const dateFormat = config.get(SETTING_DATE_FORMAT) as string; - const dateField = config.get(SETTING_DATE_FIELD) as string || DefaultFields.PublishingDate; + const dateFormat = Settings.get(SETTING_DATE_FORMAT) as string; + const dateField = Settings.get(SETTING_DATE_FIELD) as string || DefaultFields.PublishingDate; if (typeof article.data[dateField] !== "undefined") { if (dateFormat && typeof dateFormat === "string") { @@ -135,8 +132,7 @@ export class ArticleHelper { * @param updatedMetadata */ public static getContentType(metadata: { [field: string]: string; }): ContentType { - const config = Settings.getConfig(); - const contentTypes = config.get(SETTING_TAXONOMY_CONTENT_TYPES); + const contentTypes = Settings.get(SETTING_TAXONOMY_CONTENT_TYPES); if (!contentTypes || !metadata) { return DEFAULT_CONTENT_TYPE; @@ -173,8 +169,7 @@ export class ArticleHelper { */ private static parseFile(fileContents: string): matter.GrayMatterFile | null { try { - const config = Settings.getConfig(); - const commaSeparated = config.get(SETTING_COMMA_SEPARATED_FIELDS); + const commaSeparated = Settings.get(SETTING_COMMA_SEPARATED_FIELDS); if (fileContents) { const language: string = getFmLanguage(); diff --git a/src/helpers/Extension.ts b/src/helpers/Extension.ts index 1c6837d7..321cafa9 100644 --- a/src/helpers/Extension.ts +++ b/src/helpers/Extension.ts @@ -66,10 +66,8 @@ export class Extension { * Migrate old settings to new settings */ public async migrateSettings(): Promise { - const config = Settings.getConfig(); - // Migration to version 3.1.0 - const folders = config.get(SETTINGS_CONTENT_FOLDERS); + const folders = Settings.get(SETTINGS_CONTENT_FOLDERS); if (folders && folders.length > 0) { const workspace = Folders.getWorkspaceFolder(); const projectFolder = basename(workspace?.fsPath || ""); @@ -79,14 +77,14 @@ export class Extension { path: `${WORKSPACE_PLACEHOLDER}${folder.fsPath.split(projectFolder).slice(1).join('')}`.split('\\').join('/') })); - await config.update(`${SETTINGS_CONTENT_PAGE_FOLDERS}`, paths); + await Settings.update(SETTINGS_CONTENT_PAGE_FOLDERS, paths); } // Migration to version 3.2.0 - const dateField = config.get(SETTING_DATE_FIELD); - const lastModField = config.get(SETTING_MODIFIED_FIELD); - const description = config.get(SETTING_SEO_DESCRIPTION_FIELD); - const contentTypes = config.get(SETTING_TAXONOMY_CONTENT_TYPES); + const dateField = Settings.get(SETTING_DATE_FIELD); + const lastModField = Settings.get(SETTING_MODIFIED_FIELD); + const description = Settings.get(SETTING_SEO_DESCRIPTION_FIELD); + const contentTypes = Settings.get(SETTING_TAXONOMY_CONTENT_TYPES); if (contentTypes) { let needsUpdate = false; @@ -121,7 +119,7 @@ export class Extension { } if (needsUpdate) { - await config.update(SETTING_TAXONOMY_CONTENT_TYPES, contentTypes); + await Settings.update(SETTING_TAXONOMY_CONTENT_TYPES, contentTypes); } } } diff --git a/src/helpers/SettingsHelper.ts b/src/helpers/SettingsHelper.ts index 4a55336c..ce718746 100644 --- a/src/helpers/SettingsHelper.ts +++ b/src/helpers/SettingsHelper.ts @@ -3,30 +3,31 @@ import * as vscode from 'vscode'; import { TaxonomyType } from '../models'; import { SETTING_TAXONOMY_TAGS, SETTING_TAXONOMY_CATEGORIES, CONFIG_KEY } from '../constants'; import { Folders } from '../commands/Folders'; -import { join } from 'path'; -import { existsSync, readFileSync } from 'fs'; +import { join, basename } from 'path'; +import { existsSync, readFileSync, writeFileSync } from 'fs'; export class Settings { private static config: vscode.WorkspaceConfiguration; + private static globalFile = "frontmatter.json"; private static globalConfig: any; public static init() { const wsFolder = Folders.getWorkspaceFolder(); if (wsFolder) { - const fmConfig = join(wsFolder.fsPath, 'frontmatter.json'); + const fmConfig = join(wsFolder.fsPath, Settings.globalFile); if (existsSync(fmConfig)) { const localConfig = readFileSync(fmConfig, 'utf8'); - this.globalConfig = JSON.parse(localConfig); + Settings.globalConfig = JSON.parse(localConfig); } } - this.config = vscode.workspace.getConfiguration(CONFIG_KEY); + Settings.config = vscode.workspace.getConfiguration(CONFIG_KEY); Settings.onConfigChange((global?: any) => { if (global) { - this.globalConfig = Object.assign({}, global); + Settings.globalConfig = Object.assign({}, global); } else { - this.config = vscode.workspace.getConfiguration(CONFIG_KEY); + Settings.config = vscode.workspace.getConfiguration(CONFIG_KEY); } }); } @@ -40,10 +41,12 @@ export class Settings { callback(); }); - workspace.onDidChangeTextDocument((e) => { - if (e.document.fileName === "frontmatter.json") { - if (e && e.document.fileName === "frontmatter.json") { - const fileContents = e.document.getText(); + workspace.onDidSaveTextDocument(async (e) => { + const filename = e.uri.fsPath; + if (filename && basename(filename).toLowerCase() === Settings.globalFile.toLowerCase()) { + const file = await workspace.openTextDocument(e.uri); + if (file) { + const fileContents = file.getText(); const json = JSON.parse(fileContents); callback(json); } @@ -55,39 +58,61 @@ export class Settings { * Retrieve a setting from global and local config */ public static get(name: string): T | undefined{ - const configInpection = this.config.inspect(name); + const configInpection = Settings.config.inspect(name); let setting = undefined; const settingKey = `${CONFIG_KEY}.${name}`; - if (typeof this.globalConfig[settingKey] !== "undefined") { - setting = this.globalConfig[settingKey]; + if (typeof Settings.globalConfig[settingKey] !== "undefined") { + setting = Settings.globalConfig[settingKey]; } // Local overrides global - if (configInpection && typeof configInpection.workspaceValue !== undefined) { + if (configInpection && typeof configInpection.workspaceValue !== "undefined") { setting = configInpection.workspaceValue; } + if (setting === undefined) { + setting = Settings.config.get(name); + } + return setting; } + /** + * String update config setting + * @param name + * @param value + */ + public static async update(name: string, value: T, updateGlobal: boolean = false) { + const wsFolder = Folders.getWorkspaceFolder(); + + if (updateGlobal) { + if (wsFolder) { + const fmConfig = join(wsFolder.fsPath, Settings.globalFile); + if (existsSync(fmConfig)) { + const localConfig = readFileSync(fmConfig, 'utf8'); + Settings.globalConfig = JSON.parse(localConfig); + Settings.globalConfig[`${CONFIG_KEY}.${name}`] = value; + writeFileSync(fmConfig, JSON.stringify(Settings.globalConfig, null, 2), 'utf8'); + return; + } + } + } else { + await Settings.config.update(name, value); + return; + } + + // Fallback to the local settings + await Settings.config.update(name, value); + } + /** * Retrieves the config * @returns */ public static getConfig(): vscode.WorkspaceConfiguration { - return this.config; - } - - /** - * Update a setting - * @param name - * @param value - */ - public static async updateSetting(name: string, value: any) { - const config = vscode.workspace.getConfiguration(CONFIG_KEY); - await config.update(name, value); + return Settings.config; } /** @@ -113,7 +138,7 @@ export class Settings { * @param type * @param options */ - static async update(type: TaxonomyType, options: string[]) { + static async updateTaxonomy(type: TaxonomyType, options: string[]) { const config = vscode.workspace.getConfiguration(CONFIG_KEY); const configSetting = type === TaxonomyType.Tag ? SETTING_TAXONOMY_TAGS : SETTING_TAXONOMY_CATEGORIES; options = [...new Set(options)]; diff --git a/src/helpers/TomlEngine.ts b/src/helpers/TomlEngine.ts index fdeda4c3..99839e6d 100644 --- a/src/helpers/TomlEngine.ts +++ b/src/helpers/TomlEngine.ts @@ -1,11 +1,9 @@ -import * as vscode from 'vscode'; import * as toml from '@iarna/toml'; import { SETTING_FRONTMATTER_TYPE } from '../constants'; -import { Settings } from '.'; +import { Settings } from './SettingsHelper'; export const getFmLanguage = (): string => { - const config = Settings.getConfig(); - const language = config.get(SETTING_FRONTMATTER_TYPE) as string || "YAML"; + const language = Settings.get(SETTING_FRONTMATTER_TYPE) as string || "YAML"; return language.toLowerCase(); };