Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
client/snippets/markdown: add support for snippets in the slash commands
Adorian Dorana224afb50ae2
diff --git a/apps/client/src/widgets/type_widgets/code/Markdown.tsx b/apps/client/src/widgets/type_widgets/code/Markdown.tsxindex b170e388d4..23d267165b 100644--- a/apps/client/src/widgets/type_widgets/code/Markdown.tsx+++ b/apps/client/src/widgets/type_widgets/code/Markdown.tsx@@ -30,6 +30,7 @@ import SplitEditor from "../helpers/SplitEditor";import SAMPLE_DIAGRAMS from "../mermaid/sample_diagrams";import { ReadOnlyTextContent } from "../text/ReadOnlyText";import { TypeWidgetProps } from "../type_widget";+import { type CodeSnippet, getCodeSnippets, isCodeSnippetChange } from "./snippets";const marked = new Marked({ breaks: true, gfm: true });@@ -508,10 +509,25 @@ function useSlashCommands(parentComponent: TypeWidgetProps["parentComponent"], e// The user-configured todo task states (from the `_taskStates` subtree), loaded once.// Read inside the autocomplete closure, so `/todo:*` commands reflect the current config.const taskStatesRef = useRef<TaskStateDef[]>([]);+ // Markdown snippets (#snippet code notes with a markdown MIME), inserted via `/snippet:<name>`.+ // Held in a ref and refreshed on entity changes so the slash menu reads the latest list when it+ // opens, without re-registering the autocomplete extension.+ const snippetsRef = useRef<CodeSnippet[]>([]);useEffect(() => { noteRef.current = note; }, [note]);useEffect(() => { parentRef.current = parentComponent; }, [parentComponent]);useEffect(() => { void getTaskStateDefinitions().then((states) => { taskStatesRef.current = states; }); }, []);+ const reloadSnippets = useCallback(() => {+ void getCodeSnippets((candidate) => candidate.isMarkdown()).then((snippets) => { snippetsRef.current = snippets; });+ }, []);+ useEffect(() => { reloadSnippets(); }, [reloadSnippets]);+ useTriliumEvent("entitiesReloaded", ({ loadResults }) => {+ const knownNoteIds = new Set(snippetsRef.current.map((snippet) => snippet.noteId));+ if (isCodeSnippetChange(loadResults, knownNoteIds)) {+ reloadSnippets();+ }+ });+useEffect(() => {if (!editorView) return;@@ -675,7 +691,18 @@ function useSlashCommands(parentComponent: TypeWidgetProps["parentComponent"], eview.dispatch({ changes: { from, to, insert } });}};- })+ }),+ ...snippetsRef.current.map((snippet) => ({+ label: snippet.description+ ? `/snippet:${snippet.title} - ${snippet.description}`+ : `/snippet:${snippet.title}`,+ apply(view: import("@codemirror/view").EditorView, _c: unknown, from: number, to: number) {+ view.dispatch({+ changes: { from, to, insert: snippet.content },+ selection: { anchor: from + snippet.content.length }+ });+ }+ }))]};}],diff --git a/apps/client/src/widgets/type_widgets/code/snippets.ts b/apps/client/src/widgets/type_widgets/code/snippets.tsnew file mode 100644index 0000000000..3d301dd2a1--- /dev/null+++ b/apps/client/src/widgets/type_widgets/code/snippets.ts@@ -0,0 +1,46 @@+import type FNote from "../../../entities/fnote.js";+import type LoadResults from "../../../services/load_results.js";+import search from "../../../services/search.js";++export interface CodeSnippet {+ noteId: string;+ title: string;+ description?: string;+ content: string;+}++/**+ * Loads the code snippets (notes carrying `#snippet`) accepted by `matches`, pre-fetching their+ * content and optional `#snippetDescription` so callers can insert them synchronously. The `matches`+ * predicate selects which snippets are relevant to a given editor (e.g. `note.isMarkdown()` for the+ * Markdown editor, or a MIME comparison for a code editor).+ */+export async function getCodeSnippets(matches: (note: FNote) => boolean): Promise<CodeSnippet[]> {+ const notes = (await search.searchForNotes("#snippet")).filter(matches);++ return Promise.all(notes.map(async (note) => ({+ noteId: note.noteId,+ title: note.title,+ description: note.getLabelValue("snippetDescription") ?? undefined,+ content: (await note.getContent()) ?? ""+ })));+}++/**+ * Whether the reloaded entities could change the snippet list — a snippet was created, deleted,+ * retitled, had its description changed, or its content edited. `knownNoteIds` are the note IDs of+ * the snippets currently held by the caller, used to detect content/title edits.+ */+export function isCodeSnippetChange(loadResults: LoadResults, knownNoteIds: Set<string>): boolean {+ const attributeChanged = loadResults.getAttributeRows().some((attr) => {+ if (attr.type === "label") {+ return attr.name === "snippet" || attr.name === "snippetDescription";+ }+ if (attr.type === "relation") {+ return attr.value === "_template_markdown_snippet" || attr.value === "_template_code_snippet";+ }+ return false;+ });++ return attributeChanged || loadResults.getNoteIds().some((noteId) => knownNoteIds.has(noteId));+}