From e897804f650e4b5c2896477331d675a2bae7fb91 Mon Sep 17 00:00:00 2001 From: tyrese Date: Tue, 26 Nov 2024 14:24:44 +0800 Subject: [PATCH 1/5] fix: prevent creating new tab when file is already opened --- src/engine/CaptureChoiceEngine.ts | 24 +- src/engine/TemplateChoiceEngine.ts | 22 +- src/gui/ChoiceBuilder/captureChoiceBuilder.ts | 27 +- .../ChoiceBuilder/templateChoiceBuilder.ts | 27 +- src/types/choices/CaptureChoice.ts | 2 + src/types/choices/ICaptureChoice.ts | 1 + src/types/choices/ITemplateChoice.ts | 1 + src/types/choices/TemplateChoice.ts | 2 + src/utilityObsidian.ts | 482 ++++++++++-------- 9 files changed, 346 insertions(+), 242 deletions(-) diff --git a/src/engine/CaptureChoiceEngine.ts b/src/engine/CaptureChoiceEngine.ts index 172d8e1c..c69909bf 100644 --- a/src/engine/CaptureChoiceEngine.ts +++ b/src/engine/CaptureChoiceEngine.ts @@ -11,6 +11,7 @@ import { isFolder, getMarkdownFilesInFolder, getMarkdownFilesWithTag, + openExistingFileTab, } from "../utilityObsidian"; import { VALUE_SYNTAX } from "../constants"; import type QuickAdd from "../main"; @@ -88,13 +89,22 @@ export class CaptureChoiceEngine extends QuickAddChoiceEngine { appendToCurrentLine(markdownLink, this.app); } - if (this.choice?.openFile) { - await openFile(this.app, file, { - openInNewTab: this.choice.openFileInNewTab.enabled, - direction: this.choice.openFileInNewTab.direction, - focus: this.choice.openFileInNewTab.focus, - mode: this.choice.openFileInMode, - }); + if (this.choice.openFile && file) { + let openExistingTab=false; + if(this.choice.focusExsitingFileTab) + { + openExistingTab=await openExistingFileTab(this.app, file); + } + + if(!openExistingTab) + { + await openFile(this.app, file, { + openInNewTab: this.choice.openFileInNewTab.enabled, + direction: this.choice.openFileInNewTab.direction, + focus: this.choice.openFileInNewTab.focus, + mode: this.choice.openFileInMode, + }); + } } } catch (e) { log.logError(e as string); diff --git a/src/engine/TemplateChoiceEngine.ts b/src/engine/TemplateChoiceEngine.ts index b4da5be2..76113acc 100644 --- a/src/engine/TemplateChoiceEngine.ts +++ b/src/engine/TemplateChoiceEngine.ts @@ -4,6 +4,7 @@ import { TFile } from "obsidian"; import { appendToCurrentLine, getAllFolderPathsInVault, + openExistingFileTab, openFile, } from "../utilityObsidian"; import { @@ -148,12 +149,21 @@ export class TemplateChoiceEngine extends TemplateEngine { } if (this.choice.openFile && createdFile) { - await openFile(this.app, createdFile, { - openInNewTab: this.choice.openFileInNewTab.enabled, - direction: this.choice.openFileInNewTab.direction, - focus: this.choice.openFileInNewTab.focus, - mode: this.choice.openFileInMode, - }); + let openExistingTab=false; + if(this.choice.focusExsitingFileTab) + { + openExistingTab=await openExistingFileTab(this.app, createdFile); + } + + if(!openExistingTab) + { + await openFile(this.app, createdFile, { + openInNewTab: this.choice.openFileInNewTab.enabled, + direction: this.choice.openFileInNewTab.direction, + focus: this.choice.openFileInNewTab.focus, + mode: this.choice.openFileInMode, + }); + } } } catch (error) { log.logError(error as string); diff --git a/src/gui/ChoiceBuilder/captureChoiceBuilder.ts b/src/gui/ChoiceBuilder/captureChoiceBuilder.ts index 5f5b1ccc..b110dfae 100644 --- a/src/gui/ChoiceBuilder/captureChoiceBuilder.ts +++ b/src/gui/ChoiceBuilder/captureChoiceBuilder.ts @@ -52,9 +52,13 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { this.addInsertAfterSetting(); if (!this.choice.captureToActiveFile) { this.addOpenFileSetting(); - + if (this.choice.openFile) { - this.addOpenFileInNewTabSetting(); + this.addFocusExsitingTabSetting(); + + if (!this.choice.focusExsitingFileTab) { + this.addOpenFileInNewTabSetting(); + } } } @@ -460,6 +464,23 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { }); } + private addFocusExsitingTabSetting(): void { + const exsitingTabSetting = new Setting(this.contentEl); + exsitingTabSetting + .setName("Focus Exsiting Tab") + .setDesc("Focus the tab that have already opened the file.") + .addToggle((toggle) => { + toggle.setValue(this.choice?.focusExsitingFileTab); + toggle.onChange( + (value) => { + this.choice.focusExsitingFileTab = value; + this.reload(); + } + + ); + }); + } + private addOpenFileInNewTabSetting(): void { const newTabSetting = new Setting(this.contentEl); newTabSetting @@ -494,7 +515,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { new Setting(this.contentEl) .setName("Focus new pane") - .setDesc("Focus the opened tab immediately") + .setDesc("Focus the created tab immediately") .addToggle((toggle) => toggle .setValue(this.choice.openFileInNewTab.focus) diff --git a/src/gui/ChoiceBuilder/templateChoiceBuilder.ts b/src/gui/ChoiceBuilder/templateChoiceBuilder.ts index 614c234a..ac4b82c8 100644 --- a/src/gui/ChoiceBuilder/templateChoiceBuilder.ts +++ b/src/gui/ChoiceBuilder/templateChoiceBuilder.ts @@ -45,7 +45,15 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { this.addAppendLinkSetting(); this.addFileAlreadyExistsSetting(); this.addOpenFileSetting(); - if (this.choice.openFile) this.addOpenFileInNewTabSetting(); + + if (this.choice.openFile) { + this.addFocusExsitingTabSetting(); + + if (!this.choice.focusExsitingFileTab) { + this.addOpenFileInNewTabSetting(); + } + + } } private addTemplatePathSetting(): void { @@ -340,6 +348,23 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { }); } + private addFocusExsitingTabSetting(): void { + const exsitingTabSetting = new Setting(this.contentEl); + exsitingTabSetting + .setName("Focus Exsiting Tab") + .setDesc("Focus the tab that have already opened the file.") + .addToggle((toggle) => { + toggle.setValue(this.choice?.focusExsitingFileTab); + toggle.onChange( + (value) => { + this.choice.focusExsitingFileTab = value; + this.reload(); + } + + ); + }); + } + private addOpenFileInNewTabSetting(): void { const newTabSetting = new Setting(this.contentEl); newTabSetting diff --git a/src/types/choices/CaptureChoice.ts b/src/types/choices/CaptureChoice.ts index 3490c337..3b321f5b 100644 --- a/src/types/choices/CaptureChoice.ts +++ b/src/types/choices/CaptureChoice.ts @@ -23,6 +23,7 @@ export class CaptureChoice extends Choice implements ICaptureChoice { }; prepend: boolean; task: boolean; + focusExsitingFileTab:boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; @@ -60,6 +61,7 @@ export class CaptureChoice extends Choice implements ICaptureChoice { }; this.openFile = false; this.openFileInMode = "default"; + this.focusExsitingFileTab=true } public static Load(choice: ICaptureChoice): CaptureChoice { diff --git a/src/types/choices/ICaptureChoice.ts b/src/types/choices/ICaptureChoice.ts index 86d1fea3..351c26f4 100644 --- a/src/types/choices/ICaptureChoice.ts +++ b/src/types/choices/ICaptureChoice.ts @@ -23,6 +23,7 @@ export default interface ICaptureChoice extends IChoice { createIfNotFound: boolean; createIfNotFoundLocation: string; }; + focusExsitingFileTab:boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; diff --git a/src/types/choices/ITemplateChoice.ts b/src/types/choices/ITemplateChoice.ts index a84706cd..64e9e431 100644 --- a/src/types/choices/ITemplateChoice.ts +++ b/src/types/choices/ITemplateChoice.ts @@ -15,6 +15,7 @@ export default interface ITemplateChoice extends IChoice { fileNameFormat: { enabled: boolean; format: string }; appendLink: boolean; openFile: boolean; + focusExsitingFileTab:boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; diff --git a/src/types/choices/TemplateChoice.ts b/src/types/choices/TemplateChoice.ts index 71d4ddd9..70ddf945 100644 --- a/src/types/choices/TemplateChoice.ts +++ b/src/types/choices/TemplateChoice.ts @@ -14,6 +14,7 @@ export class TemplateChoice extends Choice implements ITemplateChoice { createInSameFolderAsActiveFile: boolean; chooseFromSubfolders: boolean; }; + focusExsitingFileTab:boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; @@ -47,6 +48,7 @@ export class TemplateChoice extends Choice implements ITemplateChoice { this.openFileInMode = "default"; this.fileExistsMode = "Increment the file name"; this.setFileExistsBehavior = false; + this.focusExsitingFileTab=true } public static Load(choice: ITemplateChoice): TemplateChoice { diff --git a/src/utilityObsidian.ts b/src/utilityObsidian.ts index 44c91d47..ab73eac4 100644 --- a/src/utilityObsidian.ts +++ b/src/utilityObsidian.ts @@ -1,10 +1,10 @@ import type { - App, - TAbstractFile, - WorkspaceLeaf, - CachedMetadata, + App, + TAbstractFile, + WorkspaceLeaf, + CachedMetadata, } from "obsidian"; -import { MarkdownView, TFile, TFolder } from "obsidian"; +import { FileView, MarkdownView, TFile, TFolder } from "obsidian"; import type { NewTabDirection } from "./types/newTabDirection"; import type { IUserScript } from "./types/macros/IUserScript"; import type { FileViewMode } from "./types/fileViewMode"; @@ -14,297 +14,329 @@ import type { CaptureChoice } from "./types/choices/CaptureChoice"; import type { MacroChoice } from "./types/choices/MacroChoice"; import type IChoice from "./types/choices/IChoice"; import { log } from "./logger/logManager"; +import { resolve } from "path"; export function getTemplater(app: App) { - return app.plugins.plugins["templater-obsidian"]; + return app.plugins.plugins["templater-obsidian"]; } export async function replaceTemplaterTemplatesInCreatedFile( - app: App, - file: TFile, - force = false + app: App, + file: TFile, + force = false ) { - const templater = getTemplater(app); - - if ( - templater && - (force || - !(templater.settings as Record)[ - "trigger_on_file_creation" - ]) - ) { - const impl = templater?.templater as { - overwrite_file_commands?: (file: TFile) => Promise; - }; - if (impl?.overwrite_file_commands) { - await impl.overwrite_file_commands(file); - } - } + const templater = getTemplater(app); + + if ( + templater && + (force || + !(templater.settings as Record)[ + "trigger_on_file_creation" + ]) + ) { + const impl = templater?.templater as { + overwrite_file_commands?: (file: TFile) => Promise; + }; + if (impl?.overwrite_file_commands) { + await impl.overwrite_file_commands(file); + } + } } export async function templaterParseTemplate( - app: App, - templateContent: string, - targetFile: TFile + app: App, + templateContent: string, + targetFile: TFile ) { - const templater = getTemplater(app); - if (!templater) return templateContent; - - return await ( - templater.templater as { - parse_template: ( - opt: { target_file: TFile; run_mode: number }, - content: string - ) => Promise; - } - ).parse_template({ target_file: targetFile, run_mode: 4 }, templateContent); + const templater = getTemplater(app); + if (!templater) return templateContent; + + return await ( + templater.templater as { + parse_template: ( + opt: { target_file: TFile; run_mode: number }, + content: string + ) => Promise; + } + ).parse_template({ target_file: targetFile, run_mode: 4 }, templateContent); } export function getNaturalLanguageDates(app: App) { - // @ts-ignore - return app.plugins.plugins["nldates-obsidian"]; + // @ts-ignore + return app.plugins.plugins["nldates-obsidian"]; } export function getDate(input?: { format?: string; offset?: number }) { - let duration; - - if ( - input?.offset !== null && - input?.offset !== undefined && - typeof input.offset === "number" - ) { - duration = window.moment.duration(input.offset, "days"); - } - - return input?.format - ? window.moment().add(duration).format(input.format) - : window.moment().add(duration).format("YYYY-MM-DD"); + let duration; + + if ( + input?.offset !== null && + input?.offset !== undefined && + typeof input.offset === "number" + ) { + duration = window.moment.duration(input.offset, "days"); + } + + return input?.format + ? window.moment().add(duration).format(input.format) + : window.moment().add(duration).format("YYYY-MM-DD"); } export function appendToCurrentLine(toAppend: string, app: App) { - try { - const activeView = app.workspace.getActiveViewOfType(MarkdownView); - - if (!activeView) { - log.logError(`unable to append '${toAppend}' to current line.`); - return; - } - - activeView.editor.replaceSelection(toAppend); - } catch { - log.logError(`unable to append '${toAppend}' to current line.`); - } + try { + const activeView = app.workspace.getActiveViewOfType(MarkdownView); + + if (!activeView) { + log.logError(`unable to append '${toAppend}' to current line.`); + return; + } + + activeView.editor.replaceSelection(toAppend); + } catch { + log.logError(`unable to append '${toAppend}' to current line.`); + } } export function findObsidianCommand(app: App, commandId: string) { - return app.commands.findCommand(commandId); + return app.commands.findCommand(commandId); } export function deleteObsidianCommand(app: App, commandId: string) { - if (findObsidianCommand(app, commandId)) { - delete app.commands.commands[commandId]; - delete app.commands.editorCommands[commandId]; - } + if (findObsidianCommand(app, commandId)) { + delete app.commands.commands[commandId]; + delete app.commands.editorCommands[commandId]; + } } export function getAllFolderPathsInVault(app: App): string[] { - return app.vault - .getAllLoadedFiles() - .filter((f) => f instanceof TFolder) - .map((folder) => folder.path); + return app.vault + .getAllLoadedFiles() + .filter((f) => f instanceof TFolder) + .map((folder) => folder.path); } export function getUserScriptMemberAccess(fullMemberPath: string): { - basename: string | undefined; - memberAccess: string[] | undefined; + basename: string | undefined; + memberAccess: string[] | undefined; } { - const fullMemberArray: string[] = fullMemberPath.split("::"); - return { - basename: fullMemberArray[0], - memberAccess: fullMemberArray.slice(1), - }; + const fullMemberArray: string[] = fullMemberPath.split("::"); + return { + basename: fullMemberArray[0], + memberAccess: fullMemberArray.slice(1), + }; } export async function openFile( - app: App, - file: TFile, - optional: { - openInNewTab?: boolean; - direction?: NewTabDirection; - mode?: FileViewMode; - focus?: boolean; - } + app: App, + file: TFile, + optional: { + openInNewTab?: boolean; + direction?: NewTabDirection; + mode?: FileViewMode; + focus?: boolean; + } ) { - let leaf: WorkspaceLeaf; - - if (optional.openInNewTab && optional.direction) { - leaf = app.workspace.getLeaf("split", optional.direction); - } else { - leaf = app.workspace.getLeaf("tab"); - } - - await leaf.openFile(file); - - if (optional?.focus) { - app.workspace.setActiveLeaf(leaf, { focus: optional.focus }); - } + let leaf: WorkspaceLeaf; + + if (optional.openInNewTab && optional.direction) { + leaf = app.workspace.getLeaf("split", optional.direction); + } else { + leaf = app.workspace.getLeaf("tab"); + } + + await leaf.openFile(file); + + if (optional?.focus) { + app.workspace.setActiveLeaf(leaf, { focus: optional.focus }); + } + + if (optional?.mode) { + const leafViewState = leaf.getViewState(); + + await leaf.setViewState({ + ...leafViewState, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + state: { + ...leafViewState.state, + mode: optional.mode, + }, + }); + } +} - if (optional?.mode) { - const leafViewState = leaf.getViewState(); - - await leaf.setViewState({ - ...leafViewState, - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - state: { - ...leafViewState.state, - mode: optional.mode, - }, - }); +/** + * If there is no existing tab which opened the file, return false, else return true. + */ +export async function openExistingFileTab( + app: App, + file: TFile +):Promise { + let leaf: WorkspaceLeaf | undefined = undefined; + + app.workspace.iterateRootLeaves( + (m_leaf: WorkspaceLeaf) => { + const view = m_leaf.view; + if (view instanceof FileView) { + if (view.file) { + const normalizedOpeningPath = resolve(file.path); + const normalizedCurrentPath = resolve(view.file.path); + + if (normalizedOpeningPath === normalizedCurrentPath) { + leaf = m_leaf; + return + } + } + } + }) + if (leaf !== undefined) { + app.workspace.setActiveLeaf(leaf); + return true } + return false } // Slightly modified version of Templater's user script import implementation // Source: https://github.com/SilentVoid13/Templater export async function getUserScript(command: IUserScript, app: App) { - // @ts-ignore - const file: TAbstractFile = app.vault.getAbstractFileByPath(command.path); - if (!file) { - log.logError(`failed to load file ${command.path}.`); - return; - } - - if (file instanceof TFile) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - const req = (s: string) => window.require && window.require(s); - const exp: Record = {}; - const mod = { exports: exp }; - - const fileContent = await app.vault.read(file); - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const fn = window.eval( - `(function(require, module, exports) { ${fileContent} \n})` - ); - // eslint-disable-next-line @typescript-eslint/no-unsafe-call - fn(req, mod, exp); - - // @ts-ignore - const userScript = exp["default"] || mod.exports; - if (!userScript) return; - - let script = userScript; - - const { memberAccess } = getUserScriptMemberAccess(command.name); - if (memberAccess && memberAccess.length > 0) { - let member: string; - while ((member = memberAccess.shift() as string)) { - //@ts-ignore - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - script = script[member]; - } - } - - return script; - } + // @ts-ignore + const file: TAbstractFile = app.vault.getAbstractFileByPath(command.path); + if (!file) { + log.logError(`failed to load file ${command.path}.`); + return; + } + + if (file instanceof TFile) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + const req = (s: string) => window.require && window.require(s); + const exp: Record = {}; + const mod = { exports: exp }; + + const fileContent = await app.vault.read(file); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const fn = window.eval( + `(function(require, module, exports) { ${fileContent} \n})` + ); + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + fn(req, mod, exp); + + // @ts-ignore + const userScript = exp["default"] || mod.exports; + if (!userScript) return; + + let script = userScript; + + const { memberAccess } = getUserScriptMemberAccess(command.name); + if (memberAccess && memberAccess.length > 0) { + let member: string; + while ((member = memberAccess.shift() as string)) { + //@ts-ignore + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + script = script[member]; + } + } + + return script; + } } export function excludeKeys( - sourceObj: T, - except: K[] + sourceObj: T, + except: K[] ): Omit { - const obj = structuredClone(sourceObj); + const obj = structuredClone(sourceObj); - for (const key of except) { - delete obj[key]; - } + for (const key of except) { + delete obj[key]; + } - return obj; + return obj; } export function getChoiceType< - T extends TemplateChoice | MultiChoice | CaptureChoice | MacroChoice + T extends TemplateChoice | MultiChoice | CaptureChoice | MacroChoice >(choice: IChoice): choice is T { - const isTemplate = (choice: IChoice): choice is TemplateChoice => - choice.type === "Template"; - const isMacro = (choice: IChoice): choice is MacroChoice => - choice.type === "Macro"; - const isCapture = (choice: IChoice): choice is CaptureChoice => - choice.type === "Capture"; - const isMulti = (choice: IChoice): choice is MultiChoice => - choice.type === "Multi"; - - return ( - isTemplate(choice) || - isMacro(choice) || - isCapture(choice) || - isMulti(choice) - ); + const isTemplate = (choice: IChoice): choice is TemplateChoice => + choice.type === "Template"; + const isMacro = (choice: IChoice): choice is MacroChoice => + choice.type === "Macro"; + const isCapture = (choice: IChoice): choice is CaptureChoice => + choice.type === "Capture"; + const isMulti = (choice: IChoice): choice is MultiChoice => + choice.type === "Multi"; + + return ( + isTemplate(choice) || + isMacro(choice) || + isCapture(choice) || + isMulti(choice) + ); } export function isFolder(path: string): boolean { - const abstractItem = app.vault.getAbstractFileByPath(path); + const abstractItem = app.vault.getAbstractFileByPath(path); - return !!abstractItem && abstractItem instanceof TFolder; + return !!abstractItem && abstractItem instanceof TFolder; } export function getMarkdownFilesInFolder(folderPath: string): TFile[] { - return app.vault - .getMarkdownFiles() - .filter((f) => f.path.startsWith(folderPath)); + return app.vault + .getMarkdownFiles() + .filter((f) => f.path.startsWith(folderPath)); } function getFrontmatterTags(fileCache: CachedMetadata): string[] { - const frontmatter = fileCache.frontmatter; - if (!frontmatter) return []; - - // You can have both a 'tag' and 'tags' key in frontmatter. - const frontMatterValues = Object.entries(frontmatter); - if (!frontMatterValues.length) return []; - - const tagPairs = frontMatterValues.filter(([key, value]) => { - const lowercaseKey = key.toLowerCase(); - - // In Obsidian, these are synonymous. - return lowercaseKey === "tags" || lowercaseKey === "tag"; - }); - - if (!tagPairs) return []; - - const tags = tagPairs - .flatMap(([key, value]) => { - if (typeof value === "string") { - // separator can either be comma or space separated - return value.split(/,|\s+/).map((v) => v.trim()); - } else if (Array.isArray(value)) { - return value as string[]; - } - }) - .filter((v) => !!v) as string[]; // fair to cast after filtering out falsy values - - return tags; + const frontmatter = fileCache.frontmatter; + if (!frontmatter) return []; + + // You can have both a 'tag' and 'tags' key in frontmatter. + const frontMatterValues = Object.entries(frontmatter); + if (!frontMatterValues.length) return []; + + const tagPairs = frontMatterValues.filter(([key, value]) => { + const lowercaseKey = key.toLowerCase(); + + // In Obsidian, these are synonymous. + return lowercaseKey === "tags" || lowercaseKey === "tag"; + }); + + if (!tagPairs) return []; + + const tags = tagPairs + .flatMap(([key, value]) => { + if (typeof value === "string") { + // separator can either be comma or space separated + return value.split(/,|\s+/).map((v) => v.trim()); + } else if (Array.isArray(value)) { + return value as string[]; + } + }) + .filter((v) => !!v) as string[]; // fair to cast after filtering out falsy values + + return tags; } function getFileTags(file: TFile): string[] { - const fileCache = app.metadataCache.getFileCache(file); - if (!fileCache) return []; + const fileCache = app.metadataCache.getFileCache(file); + if (!fileCache) return []; - const tagsInFile: string[] = []; - if (fileCache.frontmatter) { - tagsInFile.push(...getFrontmatterTags(fileCache)); - } + const tagsInFile: string[] = []; + if (fileCache.frontmatter) { + tagsInFile.push(...getFrontmatterTags(fileCache)); + } - if (fileCache.tags && Array.isArray(fileCache.tags)) { - tagsInFile.push(...fileCache.tags.map((v) => v.tag.replace(/^\#/, ""))); - } + if (fileCache.tags && Array.isArray(fileCache.tags)) { + tagsInFile.push(...fileCache.tags.map((v) => v.tag.replace(/^\#/, ""))); + } - return tagsInFile; + return tagsInFile; } export function getMarkdownFilesWithTag(tag: string): TFile[] { - const targetTag = tag.replace(/^\#/, ""); + const targetTag = tag.replace(/^\#/, ""); - return app.vault.getMarkdownFiles().filter((f) => { - const fileTags = getFileTags(f); + return app.vault.getMarkdownFiles().filter((f) => { + const fileTags = getFileTags(f); - return fileTags.includes(targetTag); - }); -} + return fileTags.includes(targetTag); + }); +} \ No newline at end of file From 480e106af1ef8edc0db673f4b6f6f3a9043e770a Mon Sep 17 00:00:00 2001 From: Christian Bager Bach Houmann Date: Wed, 26 Feb 2025 16:21:07 +0100 Subject: [PATCH 2/5] style: correct typos --- src/engine/CaptureChoiceEngine.ts | 10 +- src/engine/TemplateChoiceEngine.ts | 54 +++--- src/gui/ChoiceBuilder/captureChoiceBuilder.ts | 156 +++++++----------- .../ChoiceBuilder/templateChoiceBuilder.ts | 122 ++++++-------- src/types/choices/CaptureChoice.ts | 4 +- src/types/choices/ICaptureChoice.ts | 2 +- src/types/choices/ITemplateChoice.ts | 4 +- src/types/choices/TemplateChoice.ts | 6 +- 8 files changed, 148 insertions(+), 210 deletions(-) diff --git a/src/engine/CaptureChoiceEngine.ts b/src/engine/CaptureChoiceEngine.ts index c69909bf..da639933 100644 --- a/src/engine/CaptureChoiceEngine.ts +++ b/src/engine/CaptureChoiceEngine.ts @@ -90,14 +90,12 @@ export class CaptureChoiceEngine extends QuickAddChoiceEngine { } if (this.choice.openFile && file) { - let openExistingTab=false; - if(this.choice.focusExsitingFileTab) - { - openExistingTab=await openExistingFileTab(this.app, file); + let openExistingTab = false; + if (this.choice.focusExistingFileTab) { + openExistingTab = await openExistingFileTab(this.app, file); } - if(!openExistingTab) - { + if (!openExistingTab) { await openFile(this.app, file, { openInNewTab: this.choice.openFileInNewTab.enabled, direction: this.choice.openFileInNewTab.direction, diff --git a/src/engine/TemplateChoiceEngine.ts b/src/engine/TemplateChoiceEngine.ts index 76113acc..8b0457aa 100644 --- a/src/engine/TemplateChoiceEngine.ts +++ b/src/engine/TemplateChoiceEngine.ts @@ -30,7 +30,7 @@ export class TemplateChoiceEngine extends TemplateEngine { app: App, plugin: QuickAdd, choice: ITemplateChoice, - choiceExecutor: IChoiceExecutor + choiceExecutor: IChoiceExecutor, ) { super(app, plugin, choiceExecutor); this.choice = choice; @@ -52,19 +52,19 @@ export class TemplateChoiceEngine extends TemplateEngine { folderPath = await this.getFolderPath(); } - let filePath; + let filePath: string; if (this.choice.fileNameFormat.enabled) { filePath = await this.getFormattedFilePath( folderPath, this.choice.fileNameFormat.format, - this.choice.name + this.choice.name, ); } else { filePath = await this.getFormattedFilePath( folderPath, VALUE_SYNTAX, - this.choice.name + this.choice.name, ); } @@ -76,19 +76,19 @@ export class TemplateChoiceEngine extends TemplateEngine { const file = this.app.vault.getAbstractFileByPath(filePath); if (!(file instanceof TFile) || file.extension !== "md") { log.logError( - `'${filePath}' already exists and is not a valid markdown file.` + `'${filePath}' already exists and is not a valid markdown file.`, ); return; } - let userChoice: typeof fileExistsChoices[number] = + let userChoice: (typeof fileExistsChoices)[number] = this.choice.fileExistsMode; if (!this.choice.setFileExistsBehavior) { userChoice = await GenericSuggester.Suggest( this.app, [...fileExistsChoices], - [...fileExistsChoices] + [...fileExistsChoices], ); } @@ -97,32 +97,30 @@ export class TemplateChoiceEngine extends TemplateEngine { createdFile = await this.appendToFileWithTemplate( file, this.choice.templatePath, - "top" + "top", ); break; case fileExistsAppendToBottom: createdFile = await this.appendToFileWithTemplate( file, this.choice.templatePath, - "bottom" + "bottom", ); break; case fileExistsOverwriteFile: createdFile = await this.overwriteFileWithTemplate( file, - this.choice.templatePath + this.choice.templatePath, ); break; case fileExistsDoNothing: createdFile = file; break; case fileExistsIncrement: { - const incrementFileName = await this.incrementFileName( - filePath - ); + const incrementFileName = await this.incrementFileName(filePath); createdFile = await this.createFileWithTemplate( incrementFileName, - this.choice.templatePath + this.choice.templatePath, ); break; } @@ -133,7 +131,7 @@ export class TemplateChoiceEngine extends TemplateEngine { } else { createdFile = await this.createFileWithTemplate( filePath, - this.choice.templatePath + this.choice.templatePath, ); if (!createdFile) { log.logWarning(`Could not create file '${filePath}'.`); @@ -144,19 +142,17 @@ export class TemplateChoiceEngine extends TemplateEngine { if (this.choice.appendLink && createdFile) { appendToCurrentLine( this.app.fileManager.generateMarkdownLink(createdFile, ""), - this.app + this.app, ); } if (this.choice.openFile && createdFile) { - let openExistingTab=false; - if(this.choice.focusExsitingFileTab) - { - openExistingTab=await openExistingFileTab(this.app, createdFile); + let openExistingTab = false; + if (this.choice.focusExistingFileTab) { + openExistingTab = await openExistingFileTab(this.app, createdFile); } - if(!openExistingTab) - { + if (!openExistingTab) { await openFile(this.app, createdFile, { openInNewTab: this.choice.openFileInNewTab.enabled, direction: this.choice.openFileInNewTab.direction, @@ -174,7 +170,7 @@ export class TemplateChoiceEngine extends TemplateEngine { const folderPaths = await Promise.all( folders.map(async (folder) => { return await this.formatter.formatFolderPath(folder); - }) + }), ); return folderPaths; @@ -192,9 +188,7 @@ export class TemplateChoiceEngine extends TemplateEngine { this.choice.folder?.createInSameFolderAsActiveFile ) ) { - const allFoldersInVault: string[] = getAllFolderPathsInVault( - this.app - ); + const allFoldersInVault: string[] = getAllFolderPathsInVault(this.app); const subfolders = allFoldersInVault.filter((folder) => { return folders.some((f) => folder.startsWith(f)); @@ -204,9 +198,7 @@ export class TemplateChoiceEngine extends TemplateEngine { } if (this.choice.folder?.chooseWhenCreatingNote) { - const allFoldersInVault: string[] = getAllFolderPathsInVault( - this.app - ); + const allFoldersInVault: string[] = getAllFolderPathsInVault(this.app); return await this.getOrCreateFolder(allFoldersInVault); } @@ -215,11 +207,11 @@ export class TemplateChoiceEngine extends TemplateEngine { if (!activeFile || !activeFile.parent) { log.logWarning( - "No active file or active file has no parent. Cannot create file in same folder as active file. Creating in root folder." + "No active file or active file has no parent. Cannot create file in same folder as active file. Creating in root folder.", ); return ""; } - + return this.getOrCreateFolder([activeFile.parent.path]); } diff --git a/src/gui/ChoiceBuilder/captureChoiceBuilder.ts b/src/gui/ChoiceBuilder/captureChoiceBuilder.ts index b110dfae..88db7e56 100644 --- a/src/gui/ChoiceBuilder/captureChoiceBuilder.ts +++ b/src/gui/ChoiceBuilder/captureChoiceBuilder.ts @@ -25,7 +25,11 @@ import { log } from "src/logger/logManager"; export class CaptureChoiceBuilder extends ChoiceBuilder { choice: ICaptureChoice; - constructor(app: App, choice: ICaptureChoice, private plugin: QuickAdd) { + constructor( + app: App, + choice: ICaptureChoice, + private plugin: QuickAdd, + ) { super(app); this.choice = choice; @@ -54,9 +58,9 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { this.addOpenFileSetting(); if (this.choice.openFile) { - this.addFocusExsitingTabSetting(); + this.addFocusExistingTabSetting(); - if (!this.choice.focusExsitingFileTab) { + if (!this.choice.focusExistingFileTab) { this.addOpenFileInNewTabSetting(); } } @@ -80,7 +84,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { captureToActiveFileContainer.createEl("span"); captureToActiveFileText.textContent = "Capture to active file"; const captureToActiveFileToggle: ToggleComponent = new ToggleComponent( - captureToActiveFileContainer + captureToActiveFileContainer, ); captureToActiveFileToggle.setValue(this.choice?.captureToActiveFile); captureToActiveFileToggle.onChange((value) => { @@ -99,7 +103,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { new FileNameDisplayFormatter(this.app); void (async () => (formatDisplay.textContent = await displayFormatter.format( - this.choice.captureTo + this.choice.captureTo, )))(); const formatInput = new TextComponent(captureToFileContainer); @@ -112,9 +116,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { .setDisabled(this.choice?.captureToActiveFile) .onChange(async (value) => { this.choice.captureTo = value; - formatDisplay.textContent = await displayFormatter.format( - value - ); + formatDisplay.textContent = await displayFormatter.format(value); }); const markdownFilesAndFormatSyntax = [ @@ -125,7 +127,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { this.app, textField.inputEl, markdownFilesAndFormatSyntax, - 50 + 50, ); } } @@ -136,20 +138,15 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { .setName("Write to bottom of file") .setDesc( `Put value at the bottom of the file - otherwise at the ${ - this.choice?.captureToActiveFile - ? "active cursor location" - : "top" - }.` + this.choice?.captureToActiveFile ? "active cursor location" : "top" + }.`, ) .addToggle((toggle) => { toggle.setValue(this.choice.prepend); toggle.onChange((value) => { this.choice.prepend = value; - if ( - this.choice.prepend && - this.choice.insertAfter.enabled - ) { + if (this.choice.prepend && this.choice.insertAfter.enabled) { this.choice.insertAfter.enabled = false; this.reload(); } @@ -173,7 +170,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { appendLinkSetting .setName("Append link") .setDesc( - "Add a link on your current cursor position, linking to the file you're capturing to." + "Add a link on your current cursor position, linking to the file you're capturing to.", ) .addToggle((toggle) => { toggle.setValue(this.choice.appendLink); @@ -187,19 +184,14 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { const insertAfterSetting: Setting = new Setting(this.contentEl); insertAfterSetting .setName("Insert after") - .setDesc( - "Insert capture after specified line. Accepts format syntax." - ) + .setDesc("Insert capture after specified line. Accepts format syntax.") .addToggle((toggle) => { toggle.setValue(this.choice.insertAfter.enabled); toggle.onChange((value) => { this.choice.insertAfter.enabled = value; insertAfterInput.setDisabled(!value); - if ( - this.choice.insertAfter.enabled && - this.choice.prepend - ) { + if (this.choice.insertAfter.enabled && this.choice.prepend) { this.choice.prepend = false; } @@ -209,11 +201,13 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { const insertAfterFormatDisplay: HTMLSpanElement = this.contentEl.createEl("span"); - const displayFormatter: FormatDisplayFormatter = - new FormatDisplayFormatter(this.app, this.plugin); + const displayFormatter: FormatDisplayFormatter = new FormatDisplayFormatter( + this.app, + this.plugin, + ); void (async () => (insertAfterFormatDisplay.innerText = await displayFormatter.format( - this.choice.insertAfter.after + this.choice.insertAfter.after, )))(); insertAfterInput = new TextComponent(this.contentEl); @@ -229,36 +223,27 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { await displayFormatter.format(value); }); - new FormatSyntaxSuggester( - this.app, - insertAfterInput.inputEl, - this.plugin - ); + new FormatSyntaxSuggester(this.app, insertAfterInput.inputEl, this.plugin); if (this.choice.insertAfter.enabled) { const insertAtEndSetting: Setting = new Setting(this.contentEl); insertAtEndSetting .setName("Insert at end of section") .setDesc( - "Insert the text at the end of the section, rather than at the top." + "Insert the text at the end of the section, rather than at the top.", ) .addToggle((toggle) => toggle .setValue(this.choice.insertAfter?.insertAtEnd) - .onChange( - (value) => - (this.choice.insertAfter.insertAtEnd = value) - ) + .onChange((value) => (this.choice.insertAfter.insertAtEnd = value)), ); - const considerSubsectionsSetting: Setting = new Setting( - this.contentEl - ); + const considerSubsectionsSetting: Setting = new Setting(this.contentEl); considerSubsectionsSetting .setName("Consider subsections") .setDesc( "Enabling this will insert the text at the end of the section & its subsections, rather than just at the end of the target section." + - " A section is defined by a heading, and its subsections are all the headings inside that section." + " A section is defined by a heading, and its subsections are all the headings inside that section.", ) .addToggle((toggle) => toggle @@ -266,8 +251,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { .onChange((value) => { // Trying to disable if (!value) { - this.choice.insertAfter.considerSubsections = - false; + this.choice.insertAfter.considerSubsections = false; return; } @@ -275,17 +259,15 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { const targetIsHeading = this.choice.insertAfter.after.startsWith("#"); if (targetIsHeading) { - this.choice.insertAfter.considerSubsections = - value; + this.choice.insertAfter.considerSubsections = value; } else { - this.choice.insertAfter.considerSubsections = - false; + this.choice.insertAfter.considerSubsections = false; log.logError( - "'Consider subsections' can only be enabled if the insert after line starts with a # (heading)." + "'Consider subsections' can only be enabled if the insert after line starts with a # (heading).", ); this.display(); } - }) + }), ); const createLineIfNotFound: Setting = new Setting(this.contentEl); @@ -299,9 +281,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { toggle .setValue(this.choice.insertAfter?.createIfNotFound) .onChange( - (value) => - (this.choice.insertAfter.createIfNotFound = - value) + (value) => (this.choice.insertAfter.createIfNotFound = value), ).toggleEl.style.marginRight = "1em"; }) .addDropdown((dropdown) => { @@ -313,13 +293,10 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { .addOption(CREATE_IF_NOT_FOUND_TOP, "Top") .addOption(CREATE_IF_NOT_FOUND_BOTTOM, "Bottom") .addOption(CREATE_IF_NOT_FOUND_CURSOR, "Cursor") - .setValue( - this.choice.insertAfter?.createIfNotFoundLocation - ) + .setValue(this.choice.insertAfter?.createIfNotFoundLocation) .onChange( (value) => - (this.choice.insertAfter.createIfNotFoundLocation = - value) + (this.choice.insertAfter.createIfNotFoundLocation = value), ); }); } @@ -359,11 +336,13 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { new FormatSyntaxSuggester(this.app, textField.inputEl, this.plugin); const formatDisplay: HTMLSpanElement = this.contentEl.createEl("span"); - const displayFormatter: FormatDisplayFormatter = - new FormatDisplayFormatter(this.app, this.plugin); + const displayFormatter: FormatDisplayFormatter = new FormatDisplayFormatter( + this.app, + this.plugin, + ); void (async () => (formatDisplay.innerText = await displayFormatter.format( - this.choice.format.format + this.choice.format.format, )))(); } @@ -385,7 +364,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { .onChange((value) => { this.choice.createFileIfItDoesntExist.enabled = value; this.reload(); - }) + }), ); } @@ -397,24 +376,18 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { .setName("Create file with given template.") .addToggle((toggle) => toggle - .setValue( - this.choice.createFileIfItDoesntExist - ?.createWithTemplate - ) + .setValue(this.choice.createFileIfItDoesntExist?.createWithTemplate) .onChange((value) => { - this.choice.createFileIfItDoesntExist.createWithTemplate = - value; + this.choice.createFileIfItDoesntExist.createWithTemplate = value; templateSelector.setDisabled(!value); - }) + }), ); templateSelector = new TextComponent(this.contentEl); templateSelector .setValue(this.choice?.createFileIfItDoesntExist?.template ?? "") .setPlaceholder("Template path") - .setDisabled( - !this.choice?.createFileIfItDoesntExist?.createWithTemplate - ); + .setDisabled(!this.choice?.createFileIfItDoesntExist?.createWithTemplate); templateSelector.inputEl.style.width = "100%"; templateSelector.inputEl.style.marginBottom = "8px"; @@ -426,7 +399,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { this.app, templateSelector.inputEl, templateFilePaths, - 50 + 50, ); templateSelector.onChange((value) => { @@ -449,8 +422,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { .addDropdown((dropdown) => { dropdown.selectEl.style.marginLeft = "10px"; - if (!this.choice.openFileInMode) - this.choice.openFileInMode = "default"; + if (!this.choice.openFileInMode) this.choice.openFileInMode = "default"; dropdown .addOption("source", "Source") @@ -458,26 +430,22 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { .addOption("default", "Default") .setValue(this.choice.openFileInMode) .onChange( - (value) => - (this.choice.openFileInMode = value as FileViewMode) + (value) => (this.choice.openFileInMode = value as FileViewMode), ); }); } - private addFocusExsitingTabSetting(): void { - const exsitingTabSetting = new Setting(this.contentEl); - exsitingTabSetting - .setName("Focus Exsiting Tab") + private addFocusExistingTabSetting(): void { + const existingTabSetting = new Setting(this.contentEl); + existingTabSetting + .setName("Focus Existing Tab") .setDesc("Focus the tab that have already opened the file.") .addToggle((toggle) => { - toggle.setValue(this.choice?.focusExsitingFileTab); - toggle.onChange( - (value) => { - this.choice.focusExsitingFileTab = value; - this.reload(); - } - - ); + toggle.setValue(this.choice?.focusExistingFileTab); + toggle.onChange((value) => { + this.choice.focusExistingFileTab = value; + this.reload(); + }); }); } @@ -489,7 +457,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { .addToggle((toggle) => { toggle.setValue(this.choice?.openFileInNewTab?.enabled); toggle.onChange( - (value) => (this.choice.openFileInNewTab.enabled = value) + (value) => (this.choice.openFileInNewTab.enabled = value), ); }) .addDropdown((dropdown) => { @@ -507,9 +475,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { dropdown.setValue(this.choice?.openFileInNewTab?.direction); dropdown.onChange( (value) => - (this.choice.openFileInNewTab.direction = < - NewTabDirection - >value) + (this.choice.openFileInNewTab.direction = value), ); }); @@ -519,9 +485,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { .addToggle((toggle) => toggle .setValue(this.choice.openFileInNewTab.focus) - .onChange( - (value) => (this.choice.openFileInNewTab.focus = value) - ) + .onChange((value) => (this.choice.openFileInNewTab.focus = value)), ); } } diff --git a/src/gui/ChoiceBuilder/templateChoiceBuilder.ts b/src/gui/ChoiceBuilder/templateChoiceBuilder.ts index ac4b82c8..b5f2c813 100644 --- a/src/gui/ChoiceBuilder/templateChoiceBuilder.ts +++ b/src/gui/ChoiceBuilder/templateChoiceBuilder.ts @@ -29,7 +29,11 @@ import { export class TemplateChoiceBuilder extends ChoiceBuilder { choice: ITemplateChoice; - constructor(app: App, choice: ITemplateChoice, private plugin: QuickAdd) { + constructor( + app: App, + choice: ITemplateChoice, + private plugin: QuickAdd, + ) { super(app); this.choice = choice; @@ -45,14 +49,13 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { this.addAppendLinkSetting(); this.addFileAlreadyExistsSetting(); this.addOpenFileSetting(); - + if (this.choice.openFile) { - this.addFocusExsitingTabSetting(); + this.addFocusExistingTabSetting(); - if (!this.choice.focusExsitingFileTab) { + if (!this.choice.focusExistingFileTab) { this.addOpenFileInNewTabSetting(); } - } } @@ -96,7 +99,7 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { new FileNameDisplayFormatter(this.app); void (async () => (formatDisplay.textContent = await displayFormatter.format( - this.choice.fileNameFormat.format + this.choice.fileNameFormat.format, )))(); const formatInput = new TextComponent(this.contentEl); @@ -109,17 +112,10 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { .setDisabled(!this.choice.fileNameFormat.enabled) .onChange(async (value) => { this.choice.fileNameFormat.format = value; - formatDisplay.textContent = await displayFormatter.format( - value - ); + formatDisplay.textContent = await displayFormatter.format(value); }); - new FormatSyntaxSuggester( - this.app, - textField.inputEl, - this.plugin, - true - ); + new FormatSyntaxSuggester(this.app, textField.inputEl, this.plugin, true); } private addFolderSetting(): void { @@ -127,7 +123,7 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { folderSetting .setName("Create in folder") .setDesc( - "Create the file in the specified folder. If multiple folders are specified, you will be prompted for which folder to create the file in." + "Create the file in the specified folder. If multiple folders are specified, you will be prompted for which folder to create the file in.", ) .addToggle((toggle) => { toggle.setValue(this.choice.folder.enabled); @@ -142,15 +138,15 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { } if (!this.choice.folder?.createInSameFolderAsActiveFile) { - const chooseFolderWhenCreatingNoteContainer = - this.contentEl.createDiv( - "chooseFolderWhenCreatingNoteContainer" - ); + const chooseFolderWhenCreatingNoteContainer = this.contentEl.createDiv( + "chooseFolderWhenCreatingNoteContainer", + ); chooseFolderWhenCreatingNoteContainer.createEl("span", { text: "Choose folder when creating a new note", }); - const chooseFolderWhenCreatingNote: ToggleComponent = - new ToggleComponent(chooseFolderWhenCreatingNoteContainer); + const chooseFolderWhenCreatingNote: ToggleComponent = new ToggleComponent( + chooseFolderWhenCreatingNoteContainer, + ); chooseFolderWhenCreatingNote .setValue(this.choice.folder?.chooseWhenCreatingNote) .onChange((value) => { @@ -166,9 +162,10 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { this.contentEl.createDiv("chooseFolderFromSubfolderContainer"); const stn = new Setting(chooseFolderFromSubfolderContainer); - stn.setName("Include subfolders") + stn + .setName("Include subfolders") .setDesc( - "Get prompted to choose from both the selected folders and their subfolders when creating the note." + "Get prompted to choose from both the selected folders and their subfolders when creating the note.", ) .addToggle((toggle) => toggle @@ -176,36 +173,34 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { .onChange((value) => { this.choice.folder.chooseFromSubfolders = value; this.reload(); - }) + }), ); } if (!this.choice.folder?.chooseWhenCreatingNote) { const createInSameFolderAsActiveFileSetting: Setting = new Setting( - this.contentEl + this.contentEl, ); createInSameFolderAsActiveFileSetting .setName("Create in same folder as active file") .setDesc( - "Creates the file in the same folder as the currently active file. Will not create the file if there is no active file." + "Creates the file in the same folder as the currently active file. Will not create the file if there is no active file.", ) .addToggle((toggle) => toggle - .setValue( - this.choice.folder?.createInSameFolderAsActiveFile - ) + .setValue(this.choice.folder?.createInSameFolderAsActiveFile) .onChange((value) => { - this.choice.folder.createInSameFolderAsActiveFile = - value; + this.choice.folder.createInSameFolderAsActiveFile = value; this.reload(); - }) + }), ); } } private addFolderSelector() { - const folderSelectionContainer: HTMLDivElement = - this.contentEl.createDiv("folderSelectionContainer"); + const folderSelectionContainer: HTMLDivElement = this.contentEl.createDiv( + "folderSelectionContainer", + ); const folderList: HTMLDivElement = folderSelectionContainer.createDiv("folderList"); @@ -214,8 +209,9 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { props: { folders: this.choice.folder.folders, deleteFolder: (folder: string) => { - this.choice.folder.folders = - this.choice.folder.folders.filter((f) => f !== folder); + this.choice.folder.folders = this.choice.folder.folders.filter( + (f) => f !== folder, + ); // eslint-disable-next-line @typescript-eslint/no-unsafe-call folderListEl.updateFolders(this.choice.folder.folders); suggester.updateCurrentItems(this.choice.folder.folders); @@ -226,7 +222,7 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { this.svelteElements.push(folderListEl); const inputContainer = folderSelectionContainer.createDiv( - "folderInputContainer" + "folderInputContainer", ); const folderInput = new TextComponent(inputContainer); folderInput.inputEl.style.width = "100%"; @@ -237,7 +233,7 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { this.app, folderInput.inputEl, allFolders, - this.choice.folder.folders + this.choice.folder.folders, ); const addFolder = () => { @@ -287,7 +283,7 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { fileAlreadyExistsSetting .setName("Set default behavior if file already exists") .setDesc( - "Set default behavior rather then prompting user on what to do if a file already exists." + "Set default behavior rather then prompting user on what to do if a file already exists.", ) .addToggle((toggle) => { toggle.setValue(this.choice.setFileExistsBehavior); @@ -302,18 +298,15 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { this.choice.fileExistsMode = fileExistsDoNothing; dropdown - .addOption( - fileExistsAppendToBottom, - fileExistsAppendToBottom - ) + .addOption(fileExistsAppendToBottom, fileExistsAppendToBottom) .addOption(fileExistsAppendToTop, fileExistsAppendToTop) .addOption(fileExistsIncrement, fileExistsIncrement) .addOption(fileExistsOverwriteFile, fileExistsOverwriteFile) .addOption(fileExistsDoNothing, fileExistsDoNothing) .setValue(this.choice.fileExistsMode) .onChange( - (value: typeof fileExistsChoices[number]) => - (this.choice.fileExistsMode = value) + (value: (typeof fileExistsChoices)[number]) => + (this.choice.fileExistsMode = value), ); }); } @@ -333,8 +326,7 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { .addDropdown((dropdown) => { dropdown.selectEl.style.marginLeft = "10px"; - if (!this.choice.openFileInMode) - this.choice.openFileInMode = "default"; + if (!this.choice.openFileInMode) this.choice.openFileInMode = "default"; dropdown .addOption("source", "Source") @@ -342,26 +334,22 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { .addOption("default", "Default") .setValue(this.choice.openFileInMode) .onChange( - (value) => - (this.choice.openFileInMode = value as FileViewMode) + (value) => (this.choice.openFileInMode = value as FileViewMode), ); }); } - private addFocusExsitingTabSetting(): void { - const exsitingTabSetting = new Setting(this.contentEl); - exsitingTabSetting - .setName("Focus Exsiting Tab") + private addFocusExistingTabSetting(): void { + const existingTabSetting = new Setting(this.contentEl); + existingTabSetting + .setName("Focus Existing Tab") .setDesc("Focus the tab that have already opened the file.") .addToggle((toggle) => { - toggle.setValue(this.choice?.focusExsitingFileTab); - toggle.onChange( - (value) => { - this.choice.focusExsitingFileTab = value; - this.reload(); - } - - ); + toggle.setValue(this.choice?.focusExistingFileTab); + toggle.onChange((value) => { + this.choice.focusExistingFileTab = value; + this.reload(); + }); }); } @@ -373,7 +361,7 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { .addToggle((toggle) => { toggle.setValue(this.choice.openFileInNewTab.enabled); toggle.onChange( - (value) => (this.choice.openFileInNewTab.enabled = value) + (value) => (this.choice.openFileInNewTab.enabled = value), ); }) .addDropdown((dropdown) => { @@ -383,9 +371,7 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { dropdown.setValue(this.choice.openFileInNewTab.direction); dropdown.onChange( (value) => - (this.choice.openFileInNewTab.direction = < - NewTabDirection - >value) + (this.choice.openFileInNewTab.direction = value), ); }); @@ -395,9 +381,7 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { .addToggle((toggle) => toggle .setValue(this.choice.openFileInNewTab.focus) - .onChange( - (value) => (this.choice.openFileInNewTab.focus = value) - ) + .onChange((value) => (this.choice.openFileInNewTab.focus = value)), ); } } diff --git a/src/types/choices/CaptureChoice.ts b/src/types/choices/CaptureChoice.ts index 3b321f5b..9fd6aea6 100644 --- a/src/types/choices/CaptureChoice.ts +++ b/src/types/choices/CaptureChoice.ts @@ -23,7 +23,7 @@ export class CaptureChoice extends Choice implements ICaptureChoice { }; prepend: boolean; task: boolean; - focusExsitingFileTab:boolean; + focusExistingFileTab: boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; @@ -61,7 +61,7 @@ export class CaptureChoice extends Choice implements ICaptureChoice { }; this.openFile = false; this.openFileInMode = "default"; - this.focusExsitingFileTab=true + this.focusExistingFileTab = true; } public static Load(choice: ICaptureChoice): CaptureChoice { diff --git a/src/types/choices/ICaptureChoice.ts b/src/types/choices/ICaptureChoice.ts index 351c26f4..de9f36d7 100644 --- a/src/types/choices/ICaptureChoice.ts +++ b/src/types/choices/ICaptureChoice.ts @@ -23,7 +23,7 @@ export default interface ICaptureChoice extends IChoice { createIfNotFound: boolean; createIfNotFoundLocation: string; }; - focusExsitingFileTab:boolean; + focusExistingFileTab: boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; diff --git a/src/types/choices/ITemplateChoice.ts b/src/types/choices/ITemplateChoice.ts index 64e9e431..9995d0c2 100644 --- a/src/types/choices/ITemplateChoice.ts +++ b/src/types/choices/ITemplateChoice.ts @@ -15,13 +15,13 @@ export default interface ITemplateChoice extends IChoice { fileNameFormat: { enabled: boolean; format: string }; appendLink: boolean; openFile: boolean; - focusExsitingFileTab:boolean; + focusExistingFileTab: boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; focus: boolean; }; openFileInMode: FileViewMode; - fileExistsMode: typeof fileExistsChoices[number]; + fileExistsMode: (typeof fileExistsChoices)[number]; setFileExistsBehavior: boolean; } diff --git a/src/types/choices/TemplateChoice.ts b/src/types/choices/TemplateChoice.ts index 70ddf945..de650fd2 100644 --- a/src/types/choices/TemplateChoice.ts +++ b/src/types/choices/TemplateChoice.ts @@ -14,7 +14,7 @@ export class TemplateChoice extends Choice implements ITemplateChoice { createInSameFolderAsActiveFile: boolean; chooseFromSubfolders: boolean; }; - focusExsitingFileTab:boolean; + focusExistingFileTab: boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; @@ -23,7 +23,7 @@ export class TemplateChoice extends Choice implements ITemplateChoice { openFile: boolean; openFileInMode: FileViewMode; templatePath: string; - fileExistsMode: typeof fileExistsChoices[number]; + fileExistsMode: (typeof fileExistsChoices)[number]; setFileExistsBehavior: boolean; constructor(name: string) { @@ -48,7 +48,7 @@ export class TemplateChoice extends Choice implements ITemplateChoice { this.openFileInMode = "default"; this.fileExistsMode = "Increment the file name"; this.setFileExistsBehavior = false; - this.focusExsitingFileTab=true + this.focusExistingFileTab = true; } public static Load(choice: ITemplateChoice): TemplateChoice { From 3cef1886184438b2ad0951c48f58ee4f1cf6ae28 Mon Sep 17 00:00:00 2001 From: Christian Bager Bach Houmann Date: Wed, 26 Feb 2025 16:31:49 +0100 Subject: [PATCH 3/5] style: formatting --- src/utilityObsidian.ts | 491 ++++++++++++++++++++--------------------- 1 file changed, 245 insertions(+), 246 deletions(-) diff --git a/src/utilityObsidian.ts b/src/utilityObsidian.ts index ab73eac4..5e32d8cf 100644 --- a/src/utilityObsidian.ts +++ b/src/utilityObsidian.ts @@ -1,8 +1,8 @@ import type { - App, - TAbstractFile, - WorkspaceLeaf, - CachedMetadata, + App, + TAbstractFile, + WorkspaceLeaf, + CachedMetadata, } from "obsidian"; import { FileView, MarkdownView, TFile, TFolder } from "obsidian"; import type { NewTabDirection } from "./types/newTabDirection"; @@ -17,326 +17,325 @@ import { log } from "./logger/logManager"; import { resolve } from "path"; export function getTemplater(app: App) { - return app.plugins.plugins["templater-obsidian"]; + return app.plugins.plugins["templater-obsidian"]; } export async function replaceTemplaterTemplatesInCreatedFile( - app: App, - file: TFile, - force = false + app: App, + file: TFile, + force = false, ) { - const templater = getTemplater(app); - - if ( - templater && - (force || - !(templater.settings as Record)[ - "trigger_on_file_creation" - ]) - ) { - const impl = templater?.templater as { - overwrite_file_commands?: (file: TFile) => Promise; - }; - if (impl?.overwrite_file_commands) { - await impl.overwrite_file_commands(file); - } - } + const templater = getTemplater(app); + + if ( + templater && + (force || + !(templater.settings as Record)[ + "trigger_on_file_creation" + ]) + ) { + const impl = templater?.templater as { + overwrite_file_commands?: (file: TFile) => Promise; + }; + if (impl?.overwrite_file_commands) { + await impl.overwrite_file_commands(file); + } + } } export async function templaterParseTemplate( - app: App, - templateContent: string, - targetFile: TFile + app: App, + templateContent: string, + targetFile: TFile, ) { - const templater = getTemplater(app); - if (!templater) return templateContent; - - return await ( - templater.templater as { - parse_template: ( - opt: { target_file: TFile; run_mode: number }, - content: string - ) => Promise; - } - ).parse_template({ target_file: targetFile, run_mode: 4 }, templateContent); + const templater = getTemplater(app); + if (!templater) return templateContent; + + return await ( + templater.templater as { + parse_template: ( + opt: { target_file: TFile; run_mode: number }, + content: string, + ) => Promise; + } + ).parse_template({ target_file: targetFile, run_mode: 4 }, templateContent); } export function getNaturalLanguageDates(app: App) { - // @ts-ignore - return app.plugins.plugins["nldates-obsidian"]; + // @ts-ignore + return app.plugins.plugins["nldates-obsidian"]; } export function getDate(input?: { format?: string; offset?: number }) { - let duration; - - if ( - input?.offset !== null && - input?.offset !== undefined && - typeof input.offset === "number" - ) { - duration = window.moment.duration(input.offset, "days"); - } - - return input?.format - ? window.moment().add(duration).format(input.format) - : window.moment().add(duration).format("YYYY-MM-DD"); + let duration; + + if ( + input?.offset !== null && + input?.offset !== undefined && + typeof input.offset === "number" + ) { + duration = window.moment.duration(input.offset, "days"); + } + + return input?.format + ? window.moment().add(duration).format(input.format) + : window.moment().add(duration).format("YYYY-MM-DD"); } export function appendToCurrentLine(toAppend: string, app: App) { - try { - const activeView = app.workspace.getActiveViewOfType(MarkdownView); - - if (!activeView) { - log.logError(`unable to append '${toAppend}' to current line.`); - return; - } - - activeView.editor.replaceSelection(toAppend); - } catch { - log.logError(`unable to append '${toAppend}' to current line.`); - } + try { + const activeView = app.workspace.getActiveViewOfType(MarkdownView); + + if (!activeView) { + log.logError(`unable to append '${toAppend}' to current line.`); + return; + } + + activeView.editor.replaceSelection(toAppend); + } catch { + log.logError(`unable to append '${toAppend}' to current line.`); + } } export function findObsidianCommand(app: App, commandId: string) { - return app.commands.findCommand(commandId); + return app.commands.findCommand(commandId); } export function deleteObsidianCommand(app: App, commandId: string) { - if (findObsidianCommand(app, commandId)) { - delete app.commands.commands[commandId]; - delete app.commands.editorCommands[commandId]; - } + if (findObsidianCommand(app, commandId)) { + delete app.commands.commands[commandId]; + delete app.commands.editorCommands[commandId]; + } } export function getAllFolderPathsInVault(app: App): string[] { - return app.vault - .getAllLoadedFiles() - .filter((f) => f instanceof TFolder) - .map((folder) => folder.path); + return app.vault + .getAllLoadedFiles() + .filter((f) => f instanceof TFolder) + .map((folder) => folder.path); } export function getUserScriptMemberAccess(fullMemberPath: string): { - basename: string | undefined; - memberAccess: string[] | undefined; + basename: string | undefined; + memberAccess: string[] | undefined; } { - const fullMemberArray: string[] = fullMemberPath.split("::"); - return { - basename: fullMemberArray[0], - memberAccess: fullMemberArray.slice(1), - }; + const fullMemberArray: string[] = fullMemberPath.split("::"); + return { + basename: fullMemberArray[0], + memberAccess: fullMemberArray.slice(1), + }; } export async function openFile( - app: App, - file: TFile, - optional: { - openInNewTab?: boolean; - direction?: NewTabDirection; - mode?: FileViewMode; - focus?: boolean; - } + app: App, + file: TFile, + optional: { + openInNewTab?: boolean; + direction?: NewTabDirection; + mode?: FileViewMode; + focus?: boolean; + }, ) { - let leaf: WorkspaceLeaf; - - if (optional.openInNewTab && optional.direction) { - leaf = app.workspace.getLeaf("split", optional.direction); - } else { - leaf = app.workspace.getLeaf("tab"); - } - - await leaf.openFile(file); - - if (optional?.focus) { - app.workspace.setActiveLeaf(leaf, { focus: optional.focus }); - } - - if (optional?.mode) { - const leafViewState = leaf.getViewState(); - - await leaf.setViewState({ - ...leafViewState, - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - state: { - ...leafViewState.state, - mode: optional.mode, - }, - }); - } + let leaf: WorkspaceLeaf; + + if (optional.openInNewTab && optional.direction) { + leaf = app.workspace.getLeaf("split", optional.direction); + } else { + leaf = app.workspace.getLeaf("tab"); + } + + await leaf.openFile(file); + + if (optional?.focus) { + app.workspace.setActiveLeaf(leaf, { focus: optional.focus }); + } + + if (optional?.mode) { + const leafViewState = leaf.getViewState(); + + await leaf.setViewState({ + ...leafViewState, + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + state: { + ...leafViewState.state, + mode: optional.mode, + }, + }); + } } /** * If there is no existing tab which opened the file, return false, else return true. */ export async function openExistingFileTab( - app: App, - file: TFile -):Promise { - let leaf: WorkspaceLeaf | undefined = undefined; - - app.workspace.iterateRootLeaves( - (m_leaf: WorkspaceLeaf) => { - const view = m_leaf.view; - if (view instanceof FileView) { - if (view.file) { - const normalizedOpeningPath = resolve(file.path); - const normalizedCurrentPath = resolve(view.file.path); - - if (normalizedOpeningPath === normalizedCurrentPath) { - leaf = m_leaf; - return - } + app: App, + file: TFile, +): Promise { + let leaf: WorkspaceLeaf | undefined = undefined; + + app.workspace.iterateRootLeaves((m_leaf: WorkspaceLeaf) => { + const view = m_leaf.view; + if (view instanceof FileView) { + if (view.file) { + const normalizedOpeningPath = resolve(file.path); + const normalizedCurrentPath = resolve(view.file.path); + + if (normalizedOpeningPath === normalizedCurrentPath) { + leaf = m_leaf; + return; } } - }) + } + }); if (leaf !== undefined) { app.workspace.setActiveLeaf(leaf); - return true + return true; } - return false + return false; } // Slightly modified version of Templater's user script import implementation // Source: https://github.com/SilentVoid13/Templater export async function getUserScript(command: IUserScript, app: App) { - // @ts-ignore - const file: TAbstractFile = app.vault.getAbstractFileByPath(command.path); - if (!file) { - log.logError(`failed to load file ${command.path}.`); - return; - } - - if (file instanceof TFile) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - const req = (s: string) => window.require && window.require(s); - const exp: Record = {}; - const mod = { exports: exp }; - - const fileContent = await app.vault.read(file); - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - const fn = window.eval( - `(function(require, module, exports) { ${fileContent} \n})` - ); - // eslint-disable-next-line @typescript-eslint/no-unsafe-call - fn(req, mod, exp); - - // @ts-ignore - const userScript = exp["default"] || mod.exports; - if (!userScript) return; - - let script = userScript; - - const { memberAccess } = getUserScriptMemberAccess(command.name); - if (memberAccess && memberAccess.length > 0) { - let member: string; - while ((member = memberAccess.shift() as string)) { - //@ts-ignore - // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment - script = script[member]; - } - } - - return script; - } + // @ts-ignore + const file: TAbstractFile = app.vault.getAbstractFileByPath(command.path); + if (!file) { + log.logError(`failed to load file ${command.path}.`); + return; + } + + if (file instanceof TFile) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + const req = (s: string) => window.require && window.require(s); + const exp: Record = {}; + const mod = { exports: exp }; + + const fileContent = await app.vault.read(file); + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + const fn = window.eval( + `(function(require, module, exports) { ${fileContent} \n})`, + ); + // eslint-disable-next-line @typescript-eslint/no-unsafe-call + fn(req, mod, exp); + + // @ts-ignore + const userScript = exp["default"] || mod.exports; + if (!userScript) return; + + let script = userScript; + + const { memberAccess } = getUserScriptMemberAccess(command.name); + if (memberAccess && memberAccess.length > 0) { + let member: string; + while ((member = memberAccess.shift() as string)) { + //@ts-ignore + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment + script = script[member]; + } + } + + return script; + } } export function excludeKeys( - sourceObj: T, - except: K[] + sourceObj: T, + except: K[], ): Omit { - const obj = structuredClone(sourceObj); + const obj = structuredClone(sourceObj); - for (const key of except) { - delete obj[key]; - } + for (const key of except) { + delete obj[key]; + } - return obj; + return obj; } export function getChoiceType< - T extends TemplateChoice | MultiChoice | CaptureChoice | MacroChoice + T extends TemplateChoice | MultiChoice | CaptureChoice | MacroChoice, >(choice: IChoice): choice is T { - const isTemplate = (choice: IChoice): choice is TemplateChoice => - choice.type === "Template"; - const isMacro = (choice: IChoice): choice is MacroChoice => - choice.type === "Macro"; - const isCapture = (choice: IChoice): choice is CaptureChoice => - choice.type === "Capture"; - const isMulti = (choice: IChoice): choice is MultiChoice => - choice.type === "Multi"; - - return ( - isTemplate(choice) || - isMacro(choice) || - isCapture(choice) || - isMulti(choice) - ); + const isTemplate = (choice: IChoice): choice is TemplateChoice => + choice.type === "Template"; + const isMacro = (choice: IChoice): choice is MacroChoice => + choice.type === "Macro"; + const isCapture = (choice: IChoice): choice is CaptureChoice => + choice.type === "Capture"; + const isMulti = (choice: IChoice): choice is MultiChoice => + choice.type === "Multi"; + + return ( + isTemplate(choice) || + isMacro(choice) || + isCapture(choice) || + isMulti(choice) + ); } export function isFolder(path: string): boolean { - const abstractItem = app.vault.getAbstractFileByPath(path); + const abstractItem = app.vault.getAbstractFileByPath(path); - return !!abstractItem && abstractItem instanceof TFolder; + return !!abstractItem && abstractItem instanceof TFolder; } export function getMarkdownFilesInFolder(folderPath: string): TFile[] { - return app.vault - .getMarkdownFiles() - .filter((f) => f.path.startsWith(folderPath)); + return app.vault + .getMarkdownFiles() + .filter((f) => f.path.startsWith(folderPath)); } function getFrontmatterTags(fileCache: CachedMetadata): string[] { - const frontmatter = fileCache.frontmatter; - if (!frontmatter) return []; - - // You can have both a 'tag' and 'tags' key in frontmatter. - const frontMatterValues = Object.entries(frontmatter); - if (!frontMatterValues.length) return []; - - const tagPairs = frontMatterValues.filter(([key, value]) => { - const lowercaseKey = key.toLowerCase(); - - // In Obsidian, these are synonymous. - return lowercaseKey === "tags" || lowercaseKey === "tag"; - }); - - if (!tagPairs) return []; - - const tags = tagPairs - .flatMap(([key, value]) => { - if (typeof value === "string") { - // separator can either be comma or space separated - return value.split(/,|\s+/).map((v) => v.trim()); - } else if (Array.isArray(value)) { - return value as string[]; - } - }) - .filter((v) => !!v) as string[]; // fair to cast after filtering out falsy values - - return tags; + const frontmatter = fileCache.frontmatter; + if (!frontmatter) return []; + + // You can have both a 'tag' and 'tags' key in frontmatter. + const frontMatterValues = Object.entries(frontmatter); + if (!frontMatterValues.length) return []; + + const tagPairs = frontMatterValues.filter(([key, value]) => { + const lowercaseKey = key.toLowerCase(); + + // In Obsidian, these are synonymous. + return lowercaseKey === "tags" || lowercaseKey === "tag"; + }); + + if (!tagPairs) return []; + + const tags = tagPairs + .flatMap(([key, value]) => { + if (typeof value === "string") { + // separator can either be comma or space separated + return value.split(/,|\s+/).map((v) => v.trim()); + } else if (Array.isArray(value)) { + return value as string[]; + } + }) + .filter((v) => !!v) as string[]; // fair to cast after filtering out falsy values + + return tags; } function getFileTags(file: TFile): string[] { - const fileCache = app.metadataCache.getFileCache(file); - if (!fileCache) return []; + const fileCache = app.metadataCache.getFileCache(file); + if (!fileCache) return []; - const tagsInFile: string[] = []; - if (fileCache.frontmatter) { - tagsInFile.push(...getFrontmatterTags(fileCache)); - } + const tagsInFile: string[] = []; + if (fileCache.frontmatter) { + tagsInFile.push(...getFrontmatterTags(fileCache)); + } - if (fileCache.tags && Array.isArray(fileCache.tags)) { - tagsInFile.push(...fileCache.tags.map((v) => v.tag.replace(/^\#/, ""))); - } + if (fileCache.tags && Array.isArray(fileCache.tags)) { + tagsInFile.push(...fileCache.tags.map((v) => v.tag.replace(/^\#/, ""))); + } - return tagsInFile; + return tagsInFile; } export function getMarkdownFilesWithTag(tag: string): TFile[] { - const targetTag = tag.replace(/^\#/, ""); + const targetTag = tag.replace(/^\#/, ""); - return app.vault.getMarkdownFiles().filter((f) => { - const fileTags = getFileTags(f); + return app.vault.getMarkdownFiles().filter((f) => { + const fileTags = getFileTags(f); - return fileTags.includes(targetTag); - }); -} \ No newline at end of file + return fileTags.includes(targetTag); + }); +} From 9416f7cf7239c8aa2ab6bce2a52bc789d3c3107c Mon Sep 17 00:00:00 2001 From: Christian Bager Bach Houmann Date: Wed, 26 Feb 2025 16:47:04 +0100 Subject: [PATCH 4/5] make opening to existing tab default behavior --- src/engine/CaptureChoiceEngine.ts | 5 +---- src/engine/TemplateChoiceEngine.ts | 8 ++++---- src/gui/ChoiceBuilder/captureChoiceBuilder.ts | 20 +------------------ .../ChoiceBuilder/templateChoiceBuilder.ts | 20 +------------------ src/types/choices/CaptureChoice.ts | 2 -- src/types/choices/ICaptureChoice.ts | 1 - src/types/choices/ITemplateChoice.ts | 1 - src/types/choices/TemplateChoice.ts | 2 -- src/utilityObsidian.ts | 6 +----- 9 files changed, 8 insertions(+), 57 deletions(-) diff --git a/src/engine/CaptureChoiceEngine.ts b/src/engine/CaptureChoiceEngine.ts index da639933..2315bb11 100644 --- a/src/engine/CaptureChoiceEngine.ts +++ b/src/engine/CaptureChoiceEngine.ts @@ -90,10 +90,7 @@ export class CaptureChoiceEngine extends QuickAddChoiceEngine { } if (this.choice.openFile && file) { - let openExistingTab = false; - if (this.choice.focusExistingFileTab) { - openExistingTab = await openExistingFileTab(this.app, file); - } + const openExistingTab = await openExistingFileTab(this.app, file); if (!openExistingTab) { await openFile(this.app, file, { diff --git a/src/engine/TemplateChoiceEngine.ts b/src/engine/TemplateChoiceEngine.ts index 8b0457aa..c3c96694 100644 --- a/src/engine/TemplateChoiceEngine.ts +++ b/src/engine/TemplateChoiceEngine.ts @@ -147,10 +147,10 @@ export class TemplateChoiceEngine extends TemplateEngine { } if (this.choice.openFile && createdFile) { - let openExistingTab = false; - if (this.choice.focusExistingFileTab) { - openExistingTab = await openExistingFileTab(this.app, createdFile); - } + const openExistingTab = await openExistingFileTab( + this.app, + createdFile, + ); if (!openExistingTab) { await openFile(this.app, createdFile, { diff --git a/src/gui/ChoiceBuilder/captureChoiceBuilder.ts b/src/gui/ChoiceBuilder/captureChoiceBuilder.ts index 88db7e56..478a1cc1 100644 --- a/src/gui/ChoiceBuilder/captureChoiceBuilder.ts +++ b/src/gui/ChoiceBuilder/captureChoiceBuilder.ts @@ -58,11 +58,7 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { this.addOpenFileSetting(); if (this.choice.openFile) { - this.addFocusExistingTabSetting(); - - if (!this.choice.focusExistingFileTab) { - this.addOpenFileInNewTabSetting(); - } + this.addOpenFileInNewTabSetting(); } } @@ -435,20 +431,6 @@ export class CaptureChoiceBuilder extends ChoiceBuilder { }); } - private addFocusExistingTabSetting(): void { - const existingTabSetting = new Setting(this.contentEl); - existingTabSetting - .setName("Focus Existing Tab") - .setDesc("Focus the tab that have already opened the file.") - .addToggle((toggle) => { - toggle.setValue(this.choice?.focusExistingFileTab); - toggle.onChange((value) => { - this.choice.focusExistingFileTab = value; - this.reload(); - }); - }); - } - private addOpenFileInNewTabSetting(): void { const newTabSetting = new Setting(this.contentEl); newTabSetting diff --git a/src/gui/ChoiceBuilder/templateChoiceBuilder.ts b/src/gui/ChoiceBuilder/templateChoiceBuilder.ts index b5f2c813..d3d6e5ea 100644 --- a/src/gui/ChoiceBuilder/templateChoiceBuilder.ts +++ b/src/gui/ChoiceBuilder/templateChoiceBuilder.ts @@ -51,11 +51,7 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { this.addOpenFileSetting(); if (this.choice.openFile) { - this.addFocusExistingTabSetting(); - - if (!this.choice.focusExistingFileTab) { - this.addOpenFileInNewTabSetting(); - } + this.addOpenFileInNewTabSetting(); } } @@ -339,20 +335,6 @@ export class TemplateChoiceBuilder extends ChoiceBuilder { }); } - private addFocusExistingTabSetting(): void { - const existingTabSetting = new Setting(this.contentEl); - existingTabSetting - .setName("Focus Existing Tab") - .setDesc("Focus the tab that have already opened the file.") - .addToggle((toggle) => { - toggle.setValue(this.choice?.focusExistingFileTab); - toggle.onChange((value) => { - this.choice.focusExistingFileTab = value; - this.reload(); - }); - }); - } - private addOpenFileInNewTabSetting(): void { const newTabSetting = new Setting(this.contentEl); newTabSetting diff --git a/src/types/choices/CaptureChoice.ts b/src/types/choices/CaptureChoice.ts index 9fd6aea6..3490c337 100644 --- a/src/types/choices/CaptureChoice.ts +++ b/src/types/choices/CaptureChoice.ts @@ -23,7 +23,6 @@ export class CaptureChoice extends Choice implements ICaptureChoice { }; prepend: boolean; task: boolean; - focusExistingFileTab: boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; @@ -61,7 +60,6 @@ export class CaptureChoice extends Choice implements ICaptureChoice { }; this.openFile = false; this.openFileInMode = "default"; - this.focusExistingFileTab = true; } public static Load(choice: ICaptureChoice): CaptureChoice { diff --git a/src/types/choices/ICaptureChoice.ts b/src/types/choices/ICaptureChoice.ts index de9f36d7..86d1fea3 100644 --- a/src/types/choices/ICaptureChoice.ts +++ b/src/types/choices/ICaptureChoice.ts @@ -23,7 +23,6 @@ export default interface ICaptureChoice extends IChoice { createIfNotFound: boolean; createIfNotFoundLocation: string; }; - focusExistingFileTab: boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; diff --git a/src/types/choices/ITemplateChoice.ts b/src/types/choices/ITemplateChoice.ts index 9995d0c2..69cb1df7 100644 --- a/src/types/choices/ITemplateChoice.ts +++ b/src/types/choices/ITemplateChoice.ts @@ -15,7 +15,6 @@ export default interface ITemplateChoice extends IChoice { fileNameFormat: { enabled: boolean; format: string }; appendLink: boolean; openFile: boolean; - focusExistingFileTab: boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; diff --git a/src/types/choices/TemplateChoice.ts b/src/types/choices/TemplateChoice.ts index de650fd2..2918fa3e 100644 --- a/src/types/choices/TemplateChoice.ts +++ b/src/types/choices/TemplateChoice.ts @@ -14,7 +14,6 @@ export class TemplateChoice extends Choice implements ITemplateChoice { createInSameFolderAsActiveFile: boolean; chooseFromSubfolders: boolean; }; - focusExistingFileTab: boolean; openFileInNewTab: { enabled: boolean; direction: NewTabDirection; @@ -48,7 +47,6 @@ export class TemplateChoice extends Choice implements ITemplateChoice { this.openFileInMode = "default"; this.fileExistsMode = "Increment the file name"; this.setFileExistsBehavior = false; - this.focusExistingFileTab = true; } public static Load(choice: ITemplateChoice): TemplateChoice { diff --git a/src/utilityObsidian.ts b/src/utilityObsidian.ts index 5e32d8cf..b5467ef0 100644 --- a/src/utilityObsidian.ts +++ b/src/utilityObsidian.ts @@ -14,7 +14,6 @@ import type { CaptureChoice } from "./types/choices/CaptureChoice"; import type { MacroChoice } from "./types/choices/MacroChoice"; import type IChoice from "./types/choices/IChoice"; import { log } from "./logger/logManager"; -import { resolve } from "path"; export function getTemplater(app: App) { return app.plugins.plugins["templater-obsidian"]; @@ -177,10 +176,7 @@ export async function openExistingFileTab( const view = m_leaf.view; if (view instanceof FileView) { if (view.file) { - const normalizedOpeningPath = resolve(file.path); - const normalizedCurrentPath = resolve(view.file.path); - - if (normalizedOpeningPath === normalizedCurrentPath) { + if (file.path === view.file.path) { leaf = m_leaf; return; } From 1bf50d68d24744ec62162a2e6b0513af5f1b69f9 Mon Sep 17 00:00:00 2001 From: Christian Bager Bach Houmann Date: Wed, 26 Feb 2025 16:52:10 +0100 Subject: [PATCH 5/5] feat: QuickAdd will now reuse the existing tab for files when capturing to them, instead of opening the file again. Thanks to @JayPritchet