From c65173ec030912b93d56f0be6e337aacbdd2fd72 Mon Sep 17 00:00:00 2001 From: Zef Hemel Date: Sat, 2 Mar 2024 12:53:31 +0100 Subject: [PATCH] Fixes #723 --- plugs/template/snippet.ts | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/plugs/template/snippet.ts b/plugs/template/snippet.ts index d5fc68d6..bf19bed6 100644 --- a/plugs/template/snippet.ts +++ b/plugs/template/snippet.ts @@ -3,14 +3,18 @@ import { SlashCompletionOption, SlashCompletions, } from "../../plug-api/types.ts"; -import { editor, markdown, space } from "$sb/syscalls.ts"; +import { editor, markdown, space, YAML } from "$sb/syscalls.ts"; import type { AttributeCompletion } from "../index/attributes.ts"; import { queryObjects } from "../index/plug_api.ts"; import { TemplateObject } from "./types.ts"; import { loadPageObject } from "./page.ts"; import { renderTemplate } from "./api.ts"; -import { prepareFrontmatterDispatch } from "$sb/lib/frontmatter.ts"; +import { + extractFrontmatter, + prepareFrontmatterDispatch, +} from "$sb/lib/frontmatter.ts"; import { SnippetConfig } from "./types.ts"; +import { deepObjectMerge } from "$sb/lib/json.ts"; export async function snippetSlashComplete( completeEvent: CompleteEvent, @@ -67,13 +71,39 @@ export async function insertSnippetTemplate( let cursorPos = await editor.getCursor(); if (renderedFrontmatter) { - renderedFrontmatter = renderedFrontmatter.trim(); + let parsedFrontmatter: Record = {}; + try { + parsedFrontmatter = await YAML.parse(renderedFrontmatter); + } catch (e: any) { + console.error( + `Invalid rendered for ${slashCompletion.templatePage}:`, + e.message, + "for frontmatter", + renderedFrontmatter, + ); + await editor.flashNotification( + `Invalid frontmatter for ${slashCompletion.templatePage}, won't insert snippet`, + "error", + ); + return; + } const pageText = await editor.getText(); const tree = await markdown.parseMarkdown(pageText); + const currentFrontmatter = await extractFrontmatter( + tree, + parsedFrontmatter, + ); + if (!currentFrontmatter.tags?.length) { + delete currentFrontmatter.tags; + } + const newFrontmatter = deepObjectMerge( + currentFrontmatter, + parsedFrontmatter, + ); const dispatch = await prepareFrontmatterDispatch( tree, - renderedFrontmatter, + newFrontmatter, ); if (cursorPos === 0) { dispatch.selection = { anchor: renderedFrontmatter.length + 9 };