Skip to content

Build your personal knowledge base with Trilium Notes

test(codemirror): cover the template extension

Elian Doran2237201e08f3
diff --git a/packages/codemirror/src/extensions/trilium_template.spec.ts b/packages/codemirror/src/extensions/trilium_template.spec.ts
index 0e25401555..8008ef83d7 100644
--- a/packages/codemirror/src/extensions/trilium_template.spec.ts
+++ b/packages/codemirror/src/extensions/trilium_template.spec.ts
@@ -1,6 +1,9 @@
-import { describe, expect, it } from "vitest";
+import { diagnosticCount, forceLinting } from "@codemirror/lint";
+import { EditorSelection } from "@codemirror/state";
+import { describe, expect, it, vi } from "vitest";
-import { diagnoseTemplate, type TemplateLintMessages, tokenizeTemplate } from "./trilium_template.js";
+import { createFieldEditor } from "../field_editor.js";
+import { diagnoseTemplate, type TemplateLintMessages, tokenizeTemplate, triliumTemplate } from "./trilium_template.js";
const MESSAGES: TemplateLintMessages = {
unclosed: "unclosed",
@@ -32,8 +35,63 @@ describe("tokenizeTemplate", () => {
it("colours an expression still being typed, up to the end of the text", () => {
expect(tokensOf("A ${note.")).toStrictEqual([ "delimiter:${", "variable:note", "property:." ]);
});
+
+ it("skips whitespace and characters with no colour, and the text after the last expression", () => {
+ expect(tokensOf("${ note.title } and ${1 + 2} tail")).toStrictEqual([
+ "delimiter:${", "variable:note", "property:.title", "delimiter:}",
+ "delimiter:${", "delimiter:}"
+ ]);
+ });
+});
+
+describe("triliumTemplate", () => {
+ it("colours the expressions in the rendered editor and recolours them after an edit", () => {
+ const parent = document.createElement("div");
+ document.body.appendChild(parent);
+ const view = createFieldEditor({
+ parent,
+ doc: "NEW: ${note.title}",
+ extensions: [ triliumTemplate({ note: "note" }, MESSAGES) ]
+ });
+
+ try {
+ expect(textOf(parent, ".cm-template-variable")).toStrictEqual([ "note" ]);
+ expect(textOf(parent, ".cm-template-property")).toStrictEqual([ ".title" ]);
+
+ view.dispatch({ changes: { from: 12, to: 18, insert: "getLabelValue('x')" } });
+ expect(textOf(parent, ".cm-template-method")).toStrictEqual([ ".getLabelValue" ]);
+ expect(textOf(parent, ".cm-template-string")).toStrictEqual([ "'x'" ]);
+
+ view.dispatch({ selection: EditorSelection.cursor(0) });
+ expect(textOf(parent, ".cm-template-method")).toStrictEqual([ ".getLabelValue" ]);
+ } finally {
+ view.destroy();
+ }
+ });
+
+ it("underlines an expression the evaluator refuses", async () => {
+ const parent = document.createElement("div");
+ document.body.appendChild(parent);
+ const view = createFieldEditor({
+ parent,
+ doc: "NEW: ${other}",
+ extensions: [ triliumTemplate({ note: "note" }, MESSAGES) ]
+ });
+
+ try {
+ forceLinting(view);
+ await vi.waitFor(() => expect(diagnosticCount(view.state)).toBe(1));
+ expect(parent.querySelector(".cm-lintRange-error")?.textContent).toBe("${other}");
+ } finally {
+ view.destroy();
+ }
+ });
});
+function textOf(parent: HTMLElement, selector: string) {
+ return [ ...parent.querySelectorAll(selector) ].map((el) => el.textContent);
+}
+
describe("diagnoseTemplate", () => {
it("underlines each refused expression with the consumer's wording", () => {
const diagnostics = diagnoseTemplate(
diff --git a/packages/codemirror/src/extensions/trilium_template.ts b/packages/codemirror/src/extensions/trilium_template.ts
index 5e800c395c..c9e912c80f 100644
--- a/packages/codemirror/src/extensions/trilium_template.ts
+++ b/packages/codemirror/src/extensions/trilium_template.ts
@@ -88,11 +88,11 @@ export interface TemplateLintMessages {
/** Marks the expressions `evaluateTemplate()` refuses, given the variables it is called with. */
export function diagnoseTemplate(text: string, variables: TemplateVariableTypes, messages: TemplateLintMessages): Diagnostic[] {
- return findTemplateIssues(text, variables).map(({ kind, from, to, name }) => ({
- from,
- to,
+ return findTemplateIssues(text, variables).map((issue) => ({
+ from: issue.from,
+ to: issue.to,
severity: "error",
- message: kind === "unclosed" || kind === "unsupported" ? messages[kind] : messages[kind](name ?? "")
+ message: issue.name === undefined ? messages[issue.kind] : messages[issue.kind](issue.name)
}));
}
diff --git a/packages/commons/src/lib/safe_template.ts b/packages/commons/src/lib/safe_template.ts
index c6ed765b35..38ceeec169 100644
--- a/packages/commons/src/lib/safe_template.ts
+++ b/packages/commons/src/lib/safe_template.ts
@@ -60,18 +60,18 @@ const TEMPLATE_METHODS_OF: Readonly<Record<TemplateValueType, ReadonlySet<string
const NOTE_DATE_PROPERTIES: ReadonlySet<string> = new Set([ "dateCreatedObj", "utcDateCreatedObj" ]);
-/** Why {@link findTemplateIssues} refuses an expression, which `evaluateTemplate()` would throw for. */
-export type TemplateIssueKind =
- | "unclosed" | "unsupported" | "unknownVariable" | "propertyNotAllowed" | "methodNotAllowed" | "methodNotOnValue";
-
-export interface TemplateIssue {
- kind: TemplateIssueKind;
- /** Where the `${...}` expression starts and ends in the template. */
- from: number;
- to: number;
- /** The variable, property or method that is refused, for the kinds that name one. */
- name: string | undefined;
-}
+/**
+ * Why {@link findTemplateIssues} refuses an expression, which `evaluateTemplate()` would throw for,
+ * with the variable, property or method refused for the kinds that name one.
+ */
+export type TemplateProblem =
+ | { kind: "unclosed" | "unsupported"; name: undefined }
+ | { kind: "unknownVariable" | "propertyNotAllowed" | "methodNotAllowed" | "methodNotOnValue"; name: string };
+
+export type TemplateIssueKind = TemplateProblem["kind"];
+
+/** A refused expression, and where its `${...}` starts and ends in the template. */
+export type TemplateIssue = TemplateProblem & { from: number; to: number };
// `{` is excluded too, so a `${` without a closing brace scans only to the next brace.
const EXPRESSION = /\$\{([^{}]+)\}/g;
@@ -145,7 +145,7 @@ function parseExpression(expr: string): ParsedExpression | null {
}
/** What `evaluateExpression()` throws for `parsed` when the variables hold values of `variables`. */
-function checkExpression(parsed: ParsedExpression | null, variables: TemplateVariableTypes): Omit<TemplateIssue, "from" | "to"> | null {
+function checkExpression(parsed: ParsedExpression | null, variables: TemplateVariableTypes): TemplateProblem | null {
if (!parsed) {
return { kind: "unsupported", name: undefined };
}