diff --git a/apps/obsidian/src/utils/registerCommands.ts b/apps/obsidian/src/utils/registerCommands.ts index 25d8f0619..4a7a5c044 100644 --- a/apps/obsidian/src/utils/registerCommands.ts +++ b/apps/obsidian/src/utils/registerCommands.ts @@ -26,7 +26,7 @@ type ModifyNodeSubmitParams = { const createModifyNodeModalSubmitHandler = ( plugin: DiscourseGraphPlugin, - editor: Editor, + editor?: Editor, ): ((params: ModifyNodeSubmitParams) => Promise) => { return async ({ nodeType, @@ -36,7 +36,7 @@ const createModifyNodeModalSubmitHandler = ( relationshipTargetFile, }: ModifyNodeSubmitParams) => { if (selectedExistingNode) { - editor.replaceSelection(`[[${selectedExistingNode.basename}]]`); + editor?.replaceSelection(`[[${selectedExistingNode.basename}]]`); await addRelationIfRequested(plugin, selectedExistingNode, { relationshipId, relationshipTargetFile, @@ -91,10 +91,10 @@ export const registerCommands = (plugin: DiscourseGraphPlugin) => { plugin.addCommand({ id: "create-discourse-node", name: "Create discourse node", - editorCallback: (editor: Editor) => { - const currentFile = - plugin.app.workspace.getActiveViewOfType(MarkdownView)?.file || - undefined; + callback: () => { + const activeView = plugin.app.workspace.getActiveViewOfType(MarkdownView); + const editor = activeView?.editor; + const currentFile = activeView?.file || undefined; new ModifyNodeModal(plugin.app, { nodeTypes: plugin.settings.nodeTypes, plugin, diff --git a/apps/obsidian/src/utils/templates.ts b/apps/obsidian/src/utils/templates.ts index 6805c0e33..5e0469dc0 100644 --- a/apps/obsidian/src/utils/templates.ts +++ b/apps/obsidian/src/utils/templates.ts @@ -124,18 +124,17 @@ export const applyTemplate = async ({ const templateFrontmatter = app.metadataCache.getFileCache(templateFile)?.frontmatter || {}; - const currentFrontmatter = - app.metadataCache.getFileCache(targetFile)?.frontmatter || {}; - const mergedFrontmatter = mergeFrontmatter( - templateFrontmatter, - currentFrontmatter, + // Read the actual current frontmatter inside processFrontMatter to avoid + // stale metadata cache (newly created files may not be indexed yet). + await app.fileManager.processFrontMatter( + targetFile, + (fm: Record) => { + const mergedFrontmatter = mergeFrontmatter(templateFrontmatter, fm); + Object.assign(fm, mergedFrontmatter); + }, ); - await app.fileManager.processFrontMatter(targetFile, (fm) => { - Object.assign(fm, mergedFrontmatter); - }); - const frontmatterInfo = getFrontMatterInfo(templateContent); const templateBody = frontmatterInfo.exists ? templateContent.slice(frontmatterInfo.contentStart)